Blame view

sources/3rdparty/getid3/getid3.lib.php 42.3 KB
03e52840d   Kload   Init
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  <?php
  /////////////////////////////////////////////////////////////////
  /// getID3() by James Heinrich <info@getid3.org>               //
  //  available at http://getid3.sourceforge.net                 //
  //            or http://www.getid3.org                         //
  /////////////////////////////////////////////////////////////////
  //                                                             //
  // getid3.lib.php - part of getID3()                           //
  // See readme.txt for more details                             //
  //                                                            ///
  /////////////////////////////////////////////////////////////////
  
  
  class getid3_lib
  {
31b7f2792   Kload   Upgrade to ownclo...
16
  	public static function PrintHexBytes($string, $hex=true, $spaces=true, $htmlencoding='UTF-8') {
03e52840d   Kload   Init
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  		$returnstring = '';
  		for ($i = 0; $i < strlen($string); $i++) {
  			if ($hex) {
  				$returnstring .= str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
  			} else {
  				$returnstring .= ' '.(preg_match("#[\x20-\x7E]#", $string{$i}) ? $string{$i} : 'ยค');
  			}
  			if ($spaces) {
  				$returnstring .= ' ';
  			}
  		}
  		if (!empty($htmlencoding)) {
  			if ($htmlencoding === true) {
  				$htmlencoding = 'UTF-8'; // prior to getID3 v1.9.0 the function's 4th parameter was boolean
  			}
  			$returnstring = htmlentities($returnstring, ENT_QUOTES, $htmlencoding);
  		}
  		return $returnstring;
  	}
31b7f2792   Kload   Upgrade to ownclo...
36
  	public static function trunc($floatnumber) {
03e52840d   Kload   Init
37
38
39
40
41
42
43
44
45
  		// truncates a floating-point number at the decimal point
  		// returns int (if possible, otherwise float)
  		if ($floatnumber >= 1) {
  			$truncatednumber = floor($floatnumber);
  		} elseif ($floatnumber <= -1) {
  			$truncatednumber = ceil($floatnumber);
  		} else {
  			$truncatednumber = 0;
  		}
31b7f2792   Kload   Upgrade to ownclo...
46
  		if (self::intValueSupported($truncatednumber)) {
03e52840d   Kload   Init
47
48
49
50
  			$truncatednumber = (int) $truncatednumber;
  		}
  		return $truncatednumber;
  	}
31b7f2792   Kload   Upgrade to ownclo...
51
  	public static function safe_inc(&$variable, $increment=1) {
03e52840d   Kload   Init
52
53
54
55
56
57
58
  		if (isset($variable)) {
  			$variable += $increment;
  		} else {
  			$variable = $increment;
  		}
  		return true;
  	}
31b7f2792   Kload   Upgrade to ownclo...
59
  	public static function CastAsInt($floatnum) {
03e52840d   Kload   Init
60
61
62
63
  		// convert to float if not already
  		$floatnum = (float) $floatnum;
  
  		// convert a float to type int, only if possible
31b7f2792   Kload   Upgrade to ownclo...
64
  		if (self::trunc($floatnum) == $floatnum) {
03e52840d   Kload   Init
65
  			// it's not floating point
31b7f2792   Kload   Upgrade to ownclo...
66
  			if (self::intValueSupported($floatnum)) {
03e52840d   Kload   Init
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  				// it's within int range
  				$floatnum = (int) $floatnum;
  			}
  		}
  		return $floatnum;
  	}
  
  	public static function intValueSupported($num) {
  		// check if integers are 64-bit
  		static $hasINT64 = null;
  		if ($hasINT64 === null) { // 10x faster than is_null()
  			$hasINT64 = is_int(pow(2, 31)); // 32-bit int are limited to (2^31)-1
  			if (!$hasINT64 && !defined('PHP_INT_MIN')) {
  				define('PHP_INT_MIN', ~PHP_INT_MAX);
  			}
  		}
  		// if integers are 64-bit - no other check required
  		if ($hasINT64 || (($num <= PHP_INT_MAX) && ($num >= PHP_INT_MIN))) {
  			return true;
  		}
  		return false;
  	}
31b7f2792   Kload   Upgrade to ownclo...
89
  	public static function DecimalizeFraction($fraction) {
03e52840d   Kload   Init
90
91
92
  		list($numerator, $denominator) = explode('/', $fraction);
  		return $numerator / ($denominator ? $denominator : 1);
  	}
31b7f2792   Kload   Upgrade to ownclo...
93
94
95
  	public static function DecimalBinary2Float($binarynumerator) {
  		$numerator   = self::Bin2Dec($binarynumerator);
  		$denominator = self::Bin2Dec('1'.str_repeat('0', strlen($binarynumerator)));
03e52840d   Kload   Init
96
97
  		return ($numerator / $denominator);
  	}
31b7f2792   Kload   Upgrade to ownclo...
98
  	public static function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) {
03e52840d   Kload   Init
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
  		// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
  		if (strpos($binarypointnumber, '.') === false) {
  			$binarypointnumber = '0.'.$binarypointnumber;
  		} elseif ($binarypointnumber{0} == '.') {
  			$binarypointnumber = '0'.$binarypointnumber;
  		}
  		$exponent = 0;
  		while (($binarypointnumber{0} != '1') || (substr($binarypointnumber, 1, 1) != '.')) {
  			if (substr($binarypointnumber, 1, 1) == '.') {
  				$exponent--;
  				$binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3);
  			} else {
  				$pointpos = strpos($binarypointnumber, '.');
  				$exponent += ($pointpos - 1);
  				$binarypointnumber = str_replace('.', '', $binarypointnumber);
  				$binarypointnumber = $binarypointnumber{0}.'.'.substr($binarypointnumber, 1);
  			}
  		}
  		$binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT);
  		return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent);
  	}
31b7f2792   Kload   Upgrade to ownclo...
120
  	public static function Float2BinaryDecimal($floatvalue) {
03e52840d   Kload   Init
121
122
  		// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
  		$maxbits = 128; // to how many bits of precision should the calculations be taken?
31b7f2792   Kload   Upgrade to ownclo...
123
  		$intpart   = self::trunc($floatvalue);
03e52840d   Kload   Init
124
125
126
127
  		$floatpart = abs($floatvalue - $intpart);
  		$pointbitstring = '';
  		while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) {
  			$floatpart *= 2;
31b7f2792   Kload   Upgrade to ownclo...
128
129
  			$pointbitstring .= (string) self::trunc($floatpart);
  			$floatpart -= self::trunc($floatpart);
03e52840d   Kload   Init
130
131
132
133
  		}
  		$binarypointnumber = decbin($intpart).'.'.$pointbitstring;
  		return $binarypointnumber;
  	}
31b7f2792   Kload   Upgrade to ownclo...
134
  	public static function Float2String($floatvalue, $bits) {
03e52840d   Kload   Init
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
  		// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html
  		switch ($bits) {
  			case 32:
  				$exponentbits = 8;
  				$fractionbits = 23;
  				break;
  
  			case 64:
  				$exponentbits = 11;
  				$fractionbits = 52;
  				break;
  
  			default:
  				return false;
  				break;
  		}
  		if ($floatvalue >= 0) {
  			$signbit = '0';
  		} else {
  			$signbit = '1';
  		}
31b7f2792   Kload   Upgrade to ownclo...
156
  		$normalizedbinary  = self::NormalizeBinaryPoint(self::Float2BinaryDecimal($floatvalue), $fractionbits);
03e52840d   Kload   Init
157
158
159
  		$biasedexponent    = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent
  		$exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT);
  		$fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT);
31b7f2792   Kload   Upgrade to ownclo...
160
  		return self::BigEndian2String(self::Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false);
03e52840d   Kload   Init
161
  	}
31b7f2792   Kload   Upgrade to ownclo...
162
163
  	public static function LittleEndian2Float($byteword) {
  		return self::BigEndian2Float(strrev($byteword));
03e52840d   Kload   Init
164
  	}
31b7f2792   Kload   Upgrade to ownclo...
165
  	public static function BigEndian2Float($byteword) {
03e52840d   Kload   Init
166
167
168
  		// ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic
  		// http://www.psc.edu/general/software/packages/ieee/ieee.html
  		// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html
31b7f2792   Kload   Upgrade to ownclo...
169
  		$bitword = self::BigEndian2Bin($byteword);
03e52840d   Kload   Init
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
  		if (!$bitword) {
  			return 0;
  		}
  		$signbit = $bitword{0};
  
  		switch (strlen($byteword) * 8) {
  			case 32:
  				$exponentbits = 8;
  				$fractionbits = 23;
  				break;
  
  			case 64:
  				$exponentbits = 11;
  				$fractionbits = 52;
  				break;
  
  			case 80:
  				// 80-bit Apple SANE format
  				// http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/
  				$exponentstring = substr($bitword, 1, 15);
  				$isnormalized = intval($bitword{16});
  				$fractionstring = substr($bitword, 17, 63);
31b7f2792   Kload   Upgrade to ownclo...
192
193
  				$exponent = pow(2, self::Bin2Dec($exponentstring) - 16383);
  				$fraction = $isnormalized + self::DecimalBinary2Float($fractionstring);
03e52840d   Kload   Init
194
195
196
197
198
199
200
201
202
203
204
205
206
  				$floatvalue = $exponent * $fraction;
  				if ($signbit == '1') {
  					$floatvalue *= -1;
  				}
  				return $floatvalue;
  				break;
  
  			default:
  				return false;
  				break;
  		}
  		$exponentstring = substr($bitword, 1, $exponentbits);
  		$fractionstring = substr($bitword, $exponentbits + 1, $fractionbits);
31b7f2792   Kload   Upgrade to ownclo...
207
208
  		$exponent = self::Bin2Dec($exponentstring);
  		$fraction = self::Bin2Dec($fractionstring);
03e52840d   Kload   Init
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
  
  		if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) {
  			// Not a Number
  			$floatvalue = false;
  		} elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) {
  			if ($signbit == '1') {
  				$floatvalue = '-infinity';
  			} else {
  				$floatvalue = '+infinity';
  			}
  		} elseif (($exponent == 0) && ($fraction == 0)) {
  			if ($signbit == '1') {
  				$floatvalue = -0;
  			} else {
  				$floatvalue = 0;
  			}
  			$floatvalue = ($signbit ? 0 : -0);
  		} elseif (($exponent == 0) && ($fraction != 0)) {
  			// These are 'unnormalized' values
31b7f2792   Kload   Upgrade to ownclo...
228
  			$floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * self::DecimalBinary2Float($fractionstring);
03e52840d   Kload   Init
229
230
231
232
  			if ($signbit == '1') {
  				$floatvalue *= -1;
  			}
  		} elseif ($exponent != 0) {
31b7f2792   Kload   Upgrade to ownclo...
233
  			$floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + self::DecimalBinary2Float($fractionstring));
03e52840d   Kload   Init
234
235
236
237
238
239
  			if ($signbit == '1') {
  				$floatvalue *= -1;
  			}
  		}
  		return (float) $floatvalue;
  	}
31b7f2792   Kload   Upgrade to ownclo...
240
  	public static function BigEndian2Int($byteword, $synchsafe=false, $signed=false) {
03e52840d   Kload   Init
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
  		$intvalue = 0;
  		$bytewordlen = strlen($byteword);
  		if ($bytewordlen == 0) {
  			return false;
  		}
  		for ($i = 0; $i < $bytewordlen; $i++) {
  			if ($synchsafe) { // disregard MSB, effectively 7-bit bytes
  				//$intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); // faster, but runs into problems past 2^31 on 32-bit systems
  				$intvalue += (ord($byteword{$i}) & 0x7F) * pow(2, ($bytewordlen - 1 - $i) * 7);
  			} else {
  				$intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i));
  			}
  		}
  		if ($signed && !$synchsafe) {
  			// synchsafe ints are not allowed to be signed
  			if ($bytewordlen <= PHP_INT_SIZE) {
  				$signMaskBit = 0x80 << (8 * ($bytewordlen - 1));
  				if ($intvalue & $signMaskBit) {
  					$intvalue = 0 - ($intvalue & ($signMaskBit - 1));
  				}
  			} else {
31b7f2792   Kload   Upgrade to ownclo...
262
  				throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits ('.strlen($byteword).') in self::BigEndian2Int()');
03e52840d   Kload   Init
263
264
265
  				break;
  			}
  		}
31b7f2792   Kload   Upgrade to ownclo...
266
  		return self::CastAsInt($intvalue);
03e52840d   Kload   Init
267
  	}
31b7f2792   Kload   Upgrade to ownclo...
268
269
  	public static function LittleEndian2Int($byteword, $signed=false) {
  		return self::BigEndian2Int(strrev($byteword), false, $signed);
03e52840d   Kload   Init
270
  	}
31b7f2792   Kload   Upgrade to ownclo...
271
  	public static function BigEndian2Bin($byteword) {
03e52840d   Kload   Init
272
273
274
275
276
277
278
  		$binvalue = '';
  		$bytewordlen = strlen($byteword);
  		for ($i = 0; $i < $bytewordlen; $i++) {
  			$binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
  		}
  		return $binvalue;
  	}
31b7f2792   Kload   Upgrade to ownclo...
279
  	public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
03e52840d   Kload   Init
280
  		if ($number < 0) {
31b7f2792   Kload   Upgrade to ownclo...
281
  			throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
03e52840d   Kload   Init
282
283
284
285
286
  		}
  		$maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
  		$intstring = '';
  		if ($signed) {
  			if ($minbytes > PHP_INT_SIZE) {
31b7f2792   Kload   Upgrade to ownclo...
287
  				throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
03e52840d   Kload   Init
288
289
290
291
292
293
294
295
296
297
  			}
  			$number = $number & (0x80 << (8 * ($minbytes - 1)));
  		}
  		while ($number != 0) {
  			$quotient = ($number / ($maskbyte + 1));
  			$intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
  			$number = floor($quotient);
  		}
  		return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
  	}
31b7f2792   Kload   Upgrade to ownclo...
298
  	public static function Dec2Bin($number) {
03e52840d   Kload   Init
299
300
301
302
303
304
305
306
307
308
309
  		while ($number >= 256) {
  			$bytes[] = (($number / 256) - (floor($number / 256))) * 256;
  			$number = floor($number / 256);
  		}
  		$bytes[] = $number;
  		$binstring = '';
  		for ($i = 0; $i < count($bytes); $i++) {
  			$binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring;
  		}
  		return $binstring;
  	}
31b7f2792   Kload   Upgrade to ownclo...
310
  	public static function Bin2Dec($binstring, $signed=false) {
03e52840d   Kload   Init
311
312
313
314
315
316
317
318
319
320
321
  		$signmult = 1;
  		if ($signed) {
  			if ($binstring{0} == '1') {
  				$signmult = -1;
  			}
  			$binstring = substr($binstring, 1);
  		}
  		$decvalue = 0;
  		for ($i = 0; $i < strlen($binstring); $i++) {
  			$decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
  		}
31b7f2792   Kload   Upgrade to ownclo...
322
  		return self::CastAsInt($decvalue * $signmult);
03e52840d   Kload   Init
323
  	}
31b7f2792   Kload   Upgrade to ownclo...
324
  	public static function Bin2String($binstring) {
03e52840d   Kload   Init
325
326
327
328
  		// return 'hi' for input of '0110100001101001'
  		$string = '';
  		$binstringreversed = strrev($binstring);
  		for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
31b7f2792   Kload   Upgrade to ownclo...
329
  			$string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
03e52840d   Kload   Init
330
331
332
  		}
  		return $string;
  	}
31b7f2792   Kload   Upgrade to ownclo...
333
  	public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
03e52840d   Kload   Init
334
335
336
337
338
339
340
341
342
343
344
345
  		$intstring = '';
  		while ($number > 0) {
  			if ($synchsafe) {
  				$intstring = $intstring.chr($number & 127);
  				$number >>= 7;
  			} else {
  				$intstring = $intstring.chr($number & 255);
  				$number >>= 8;
  			}
  		}
  		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
  	}
31b7f2792   Kload   Upgrade to ownclo...
346
  	public static function array_merge_clobber($array1, $array2) {
03e52840d   Kload   Init
347
348
349
350
351
352
353
354
  		// written by kcล˜hireability*com
  		// taken from http://www.php.net/manual/en/function.array-merge-recursive.php
  		if (!is_array($array1) || !is_array($array2)) {
  			return false;
  		}
  		$newarray = $array1;
  		foreach ($array2 as $key => $val) {
  			if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
31b7f2792   Kload   Upgrade to ownclo...
355
  				$newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
03e52840d   Kload   Init
356
357
358
359
360
361
  			} else {
  				$newarray[$key] = $val;
  			}
  		}
  		return $newarray;
  	}
31b7f2792   Kload   Upgrade to ownclo...
362
  	public static function array_merge_noclobber($array1, $array2) {
03e52840d   Kload   Init
363
364
365
366
367
368
  		if (!is_array($array1) || !is_array($array2)) {
  			return false;
  		}
  		$newarray = $array1;
  		foreach ($array2 as $key => $val) {
  			if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
31b7f2792   Kload   Upgrade to ownclo...
369
  				$newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
03e52840d   Kload   Init
370
371
372
373
374
375
  			} elseif (!isset($newarray[$key])) {
  				$newarray[$key] = $val;
  			}
  		}
  		return $newarray;
  	}
31b7f2792   Kload   Upgrade to ownclo...
376
  	public static function ksort_recursive(&$theArray) {
03e52840d   Kload   Init
377
378
379
380
381
382
383
384
  		ksort($theArray);
  		foreach ($theArray as $key => $value) {
  			if (is_array($value)) {
  				self::ksort_recursive($theArray[$key]);
  			}
  		}
  		return true;
  	}
31b7f2792   Kload   Upgrade to ownclo...
385
  	public static function fileextension($filename, $numextensions=1) {
03e52840d   Kload   Init
386
387
388
389
390
391
392
393
394
395
396
397
398
  		if (strstr($filename, '.')) {
  			$reversedfilename = strrev($filename);
  			$offset = 0;
  			for ($i = 0; $i < $numextensions; $i++) {
  				$offset = strpos($reversedfilename, '.', $offset + 1);
  				if ($offset === false) {
  					return '';
  				}
  			}
  			return strrev(substr($reversedfilename, 0, $offset));
  		}
  		return '';
  	}
31b7f2792   Kload   Upgrade to ownclo...
399
  	public static function PlaytimeString($seconds) {
03e52840d   Kload   Init
400
  		$sign = (($seconds < 0) ? '-' : '');
31b7f2792   Kload   Upgrade to ownclo...
401
402
403
404
  		$seconds = round(abs($seconds));
  		$H = (int) floor( $seconds                            / 3600);
  		$M = (int) floor(($seconds - (3600 * $H)            ) /   60);
  		$S = (int) round( $seconds - (3600 * $H) - (60 * $M)        );
03e52840d   Kload   Init
405
406
  		return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
  	}
31b7f2792   Kload   Upgrade to ownclo...
407
  	public static function DateMac2Unix($macdate) {
03e52840d   Kload   Init
408
409
  		// Macintosh timestamp: seconds since 00:00h January 1, 1904
  		// UNIX timestamp:      seconds since 00:00h January 1, 1970
31b7f2792   Kload   Upgrade to ownclo...
410
  		return self::CastAsInt($macdate - 2082844800);
03e52840d   Kload   Init
411
  	}
31b7f2792   Kload   Upgrade to ownclo...
412
413
  	public static function FixedPoint8_8($rawdata) {
  		return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
03e52840d   Kload   Init
414
  	}
31b7f2792   Kload   Upgrade to ownclo...
415
416
  	public static function FixedPoint16_16($rawdata) {
  		return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
03e52840d   Kload   Init
417
  	}
31b7f2792   Kload   Upgrade to ownclo...
418
419
420
  	public static function FixedPoint2_30($rawdata) {
  		$binarystring = self::BigEndian2Bin($rawdata);
  		return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
03e52840d   Kload   Init
421
  	}
31b7f2792   Kload   Upgrade to ownclo...
422
  	public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
03e52840d   Kload   Init
423
  		// assigns $Value to a nested array path:
31b7f2792   Kload   Upgrade to ownclo...
424
  		//   $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
03e52840d   Kload   Init
425
426
427
428
  		// is the same as:
  		//   $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
  		// or
  		//   $foo['path']['to']['my'] = 'file.txt';
31b7f2792   Kload   Upgrade to ownclo...
429
  		$ArrayPath = ltrim($ArrayPath, $Separator);
03e52840d   Kload   Init
430
  		if (($pos = strpos($ArrayPath, $Separator)) !== false) {
31b7f2792   Kload   Upgrade to ownclo...
431
  			$ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
03e52840d   Kload   Init
432
433
434
435
436
  		} else {
  			$ReturnedArray[$ArrayPath] = $Value;
  		}
  		return $ReturnedArray;
  	}
31b7f2792   Kload   Upgrade to ownclo...
437
  	public static function array_max($arraydata, $returnkey=false) {
03e52840d   Kload   Init
438
439
440
441
442
443
444
445
446
447
448
449
  		$maxvalue = false;
  		$maxkey = false;
  		foreach ($arraydata as $key => $value) {
  			if (!is_array($value)) {
  				if ($value > $maxvalue) {
  					$maxvalue = $value;
  					$maxkey = $key;
  				}
  			}
  		}
  		return ($returnkey ? $maxkey : $maxvalue);
  	}
31b7f2792   Kload   Upgrade to ownclo...
450
  	public static function array_min($arraydata, $returnkey=false) {
03e52840d   Kload   Init
451
452
453
454
455
456
457
458
459
460
461
462
  		$minvalue = false;
  		$minkey = false;
  		foreach ($arraydata as $key => $value) {
  			if (!is_array($value)) {
  				if ($value > $minvalue) {
  					$minvalue = $value;
  					$minkey = $key;
  				}
  			}
  		}
  		return ($returnkey ? $minkey : $minvalue);
  	}
31b7f2792   Kload   Upgrade to ownclo...
463
  	public static function XML2array($XMLstring) {
03e52840d   Kload   Init
464
465
466
467
468
469
470
471
  		if (function_exists('simplexml_load_string')) {
  			if (function_exists('get_object_vars')) {
  				$XMLobject = simplexml_load_string($XMLstring);
  				return self::SimpleXMLelement2array($XMLobject);
  			}
  		}
  		return false;
  	}
31b7f2792   Kload   Upgrade to ownclo...
472
  	public static function SimpleXMLelement2array($XMLobject) {
03e52840d   Kload   Init
473
474
475
476
477
478
479
480
481
482
483
484
  		if (!is_object($XMLobject) && !is_array($XMLobject)) {
  			return $XMLobject;
  		}
  		$XMLarray = (is_object($XMLobject) ? get_object_vars($XMLobject) : $XMLobject);
  		foreach ($XMLarray as $key => $value) {
  			$XMLarray[$key] = self::SimpleXMLelement2array($value);
  		}
  		return $XMLarray;
  	}
  
  
  	// Allan Hansen <ahล˜artemis*dk>
31b7f2792   Kload   Upgrade to ownclo...
485
486
  	// self::md5_data() - returns md5sum for a file from startuing position to absolute end position
  	public static function hash_data($file, $offset, $end, $algorithm) {
03e52840d   Kload   Init
487
  		static $tempdir = '';
31b7f2792   Kload   Upgrade to ownclo...
488
  		if (!self::intValueSupported($end)) {
03e52840d   Kload   Init
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
  			return false;
  		}
  		switch ($algorithm) {
  			case 'md5':
  				$hash_function = 'md5_file';
  				$unix_call     = 'md5sum';
  				$windows_call  = 'md5sum.exe';
  				$hash_length   = 32;
  				break;
  
  			case 'sha1':
  				$hash_function = 'sha1_file';
  				$unix_call     = 'sha1sum';
  				$windows_call  = 'sha1sum.exe';
  				$hash_length   = 40;
  				break;
  
  			default:
31b7f2792   Kload   Upgrade to ownclo...
507
  				throw new Exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
03e52840d   Kload   Init
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
  				break;
  		}
  		$size = $end - $offset;
  		while (true) {
  			if (GETID3_OS_ISWINDOWS) {
  
  				// It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
  				// Fall back to create-temp-file method:
  				if ($algorithm == 'sha1') {
  					break;
  				}
  
  				$RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
  				foreach ($RequiredFiles as $required_file) {
  					if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
  						// helper apps not available - fall back to old method
31b7f2792   Kload   Upgrade to ownclo...
524
  						break 2;
03e52840d   Kload   Init
525
526
  					}
  				}
31b7f2792   Kload   Upgrade to ownclo...
527
  				$commandline  = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' '.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).' | ';
03e52840d   Kload   Init
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
  				$commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
  				$commandline .= GETID3_HELPERAPPSDIR.$windows_call;
  
  			} else {
  
  				$commandline  = 'head -c'.$end.' '.escapeshellarg($file).' | ';
  				$commandline .= 'tail -c'.$size.' | ';
  				$commandline .= $unix_call;
  
  			}
  			if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
  				//throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
  				break;
  			}
  			return substr(`$commandline`, 0, $hash_length);
  		}
  
  		if (empty($tempdir)) {
  			// yes this is ugly, feel free to suggest a better way
  			require_once(dirname(__FILE__).'/getid3.php');
  			$getid3_temp = new getID3();
  			$tempdir = $getid3_temp->tempdir;
  			unset($getid3_temp);
  		}
  		// try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
  		if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
  			// can't find anywhere to create a temp file, just fail
  			return false;
  		}
  
  		// Init
  		$result = false;
  
  		// copy parts of file
  		try {
31b7f2792   Kload   Upgrade to ownclo...
563
  			self::CopyFileParts($file, $data_filename, $offset, $end - $offset);
03e52840d   Kload   Init
564
565
  			$result = $hash_function($data_filename);
  		} catch (Exception $e) {
31b7f2792   Kload   Upgrade to ownclo...
566
  			throw new Exception('self::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
03e52840d   Kload   Init
567
568
569
570
  		}
  		unlink($data_filename);
  		return $result;
  	}
31b7f2792   Kload   Upgrade to ownclo...
571
572
  	public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
  		if (!self::intValueSupported($offset + $length)) {
03e52840d   Kload   Init
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
  			throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
  		}
  		if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
  			if (($fp_dest = fopen($filename_dest, 'wb'))) {
  				if (fseek($fp_src, $offset, SEEK_SET) == 0) {
  					$byteslefttowrite = $length;
  					while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
  						$byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
  						$byteslefttowrite -= $byteswritten;
  					}
  					return true;
  				} else {
  					throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
  				}
  				fclose($fp_dest);
  			} else {
  				throw new Exception('failed to create file for writing '.$filename_dest);
  			}
  			fclose($fp_src);
  		} else {
  			throw new Exception('failed to open file for reading '.$filename_source);
  		}
  		return false;
  	}
31b7f2792   Kload   Upgrade to ownclo...
597
  	public static function iconv_fallback_int_utf8($charval) {
03e52840d   Kload   Init
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
  		if ($charval < 128) {
  			// 0bbbbbbb
  			$newcharstring = chr($charval);
  		} elseif ($charval < 2048) {
  			// 110bbbbb 10bbbbbb
  			$newcharstring  = chr(($charval >>   6) | 0xC0);
  			$newcharstring .= chr(($charval & 0x3F) | 0x80);
  		} elseif ($charval < 65536) {
  			// 1110bbbb 10bbbbbb 10bbbbbb
  			$newcharstring  = chr(($charval >>  12) | 0xE0);
  			$newcharstring .= chr(($charval >>   6) | 0xC0);
  			$newcharstring .= chr(($charval & 0x3F) | 0x80);
  		} else {
  			// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  			$newcharstring  = chr(($charval >>  18) | 0xF0);
  			$newcharstring .= chr(($charval >>  12) | 0xC0);
  			$newcharstring .= chr(($charval >>   6) | 0xC0);
  			$newcharstring .= chr(($charval & 0x3F) | 0x80);
  		}
  		return $newcharstring;
  	}
  
  	// ISO-8859-1 => UTF-8
31b7f2792   Kload   Upgrade to ownclo...
621
  	public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
03e52840d   Kload   Init
622
623
624
625
626
627
628
629
630
631
  		if (function_exists('utf8_encode')) {
  			return utf8_encode($string);
  		}
  		// utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
  		$newcharstring = '';
  		if ($bom) {
  			$newcharstring .= "\xEF\xBB\xBF";
  		}
  		for ($i = 0; $i < strlen($string); $i++) {
  			$charval = ord($string{$i});
31b7f2792   Kload   Upgrade to ownclo...
632
  			$newcharstring .= self::iconv_fallback_int_utf8($charval);
03e52840d   Kload   Init
633
634
635
636
637
  		}
  		return $newcharstring;
  	}
  
  	// ISO-8859-1 => UTF-16BE
31b7f2792   Kload   Upgrade to ownclo...
638
  	public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
03e52840d   Kload   Init
639
640
641
642
643
644
645
646
647
648
649
  		$newcharstring = '';
  		if ($bom) {
  			$newcharstring .= "\xFE\xFF";
  		}
  		for ($i = 0; $i < strlen($string); $i++) {
  			$newcharstring .= "\x00".$string{$i};
  		}
  		return $newcharstring;
  	}
  
  	// ISO-8859-1 => UTF-16LE
31b7f2792   Kload   Upgrade to ownclo...
650
  	public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
03e52840d   Kload   Init
651
652
653
654
655
656
657
658
659
660
661
  		$newcharstring = '';
  		if ($bom) {
  			$newcharstring .= "\xFF\xFE";
  		}
  		for ($i = 0; $i < strlen($string); $i++) {
  			$newcharstring .= $string{$i}."\x00";
  		}
  		return $newcharstring;
  	}
  
  	// ISO-8859-1 => UTF-16LE (BOM)
31b7f2792   Kload   Upgrade to ownclo...
662
663
  	public static function iconv_fallback_iso88591_utf16($string) {
  		return self::iconv_fallback_iso88591_utf16le($string, true);
03e52840d   Kload   Init
664
665
666
  	}
  
  	// UTF-8 => ISO-8859-1
31b7f2792   Kload   Upgrade to ownclo...
667
  	public static function iconv_fallback_utf8_iso88591($string) {
03e52840d   Kload   Init
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
  		if (function_exists('utf8_decode')) {
  			return utf8_decode($string);
  		}
  		// utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
  		$newcharstring = '';
  		$offset = 0;
  		$stringlength = strlen($string);
  		while ($offset < $stringlength) {
  			if ((ord($string{$offset}) | 0x07) == 0xF7) {
  				// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  						   ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  						   ((ord($string{($offset + 2)}) & 0x3F) <<  6) &
  							(ord($string{($offset + 3)}) & 0x3F);
  				$offset += 4;
  			} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  				// 1110bbbb 10bbbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  						   ((ord($string{($offset + 1)}) & 0x3F) <<  6) &
  							(ord($string{($offset + 2)}) & 0x3F);
  				$offset += 3;
  			} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  				// 110bbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x1F) <<  6) &
  							(ord($string{($offset + 1)}) & 0x3F);
  				$offset += 2;
  			} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  				// 0bbbbbbb
  				$charval = ord($string{$offset});
  				$offset += 1;
  			} else {
  				// error? throw some kind of warning here?
  				$charval = false;
  				$offset += 1;
  			}
  			if ($charval !== false) {
  				$newcharstring .= (($charval < 256) ? chr($charval) : '?');
  			}
  		}
  		return $newcharstring;
  	}
  
  	// UTF-8 => UTF-16BE
31b7f2792   Kload   Upgrade to ownclo...
711
  	public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
03e52840d   Kload   Init
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
  		$newcharstring = '';
  		if ($bom) {
  			$newcharstring .= "\xFE\xFF";
  		}
  		$offset = 0;
  		$stringlength = strlen($string);
  		while ($offset < $stringlength) {
  			if ((ord($string{$offset}) | 0x07) == 0xF7) {
  				// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  						   ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  						   ((ord($string{($offset + 2)}) & 0x3F) <<  6) &
  							(ord($string{($offset + 3)}) & 0x3F);
  				$offset += 4;
  			} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  				// 1110bbbb 10bbbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  						   ((ord($string{($offset + 1)}) & 0x3F) <<  6) &
  							(ord($string{($offset + 2)}) & 0x3F);
  				$offset += 3;
  			} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  				// 110bbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x1F) <<  6) &
  							(ord($string{($offset + 1)}) & 0x3F);
  				$offset += 2;
  			} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  				// 0bbbbbbb
  				$charval = ord($string{$offset});
  				$offset += 1;
  			} else {
  				// error? throw some kind of warning here?
  				$charval = false;
  				$offset += 1;
  			}
  			if ($charval !== false) {
31b7f2792   Kload   Upgrade to ownclo...
747
  				$newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
03e52840d   Kload   Init
748
749
750
751
752
753
  			}
  		}
  		return $newcharstring;
  	}
  
  	// UTF-8 => UTF-16LE
31b7f2792   Kload   Upgrade to ownclo...
754
  	public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
03e52840d   Kload   Init
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
  		$newcharstring = '';
  		if ($bom) {
  			$newcharstring .= "\xFF\xFE";
  		}
  		$offset = 0;
  		$stringlength = strlen($string);
  		while ($offset < $stringlength) {
  			if ((ord($string{$offset}) | 0x07) == 0xF7) {
  				// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  						   ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  						   ((ord($string{($offset + 2)}) & 0x3F) <<  6) &
  							(ord($string{($offset + 3)}) & 0x3F);
  				$offset += 4;
  			} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  				// 1110bbbb 10bbbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  						   ((ord($string{($offset + 1)}) & 0x3F) <<  6) &
  							(ord($string{($offset + 2)}) & 0x3F);
  				$offset += 3;
  			} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  				// 110bbbbb 10bbbbbb
  				$charval = ((ord($string{($offset + 0)}) & 0x1F) <<  6) &
  							(ord($string{($offset + 1)}) & 0x3F);
  				$offset += 2;
  			} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  				// 0bbbbbbb
  				$charval = ord($string{$offset});
  				$offset += 1;
  			} else {
  				// error? maybe throw some warning here?
  				$charval = false;
  				$offset += 1;
  			}
  			if ($charval !== false) {
31b7f2792   Kload   Upgrade to ownclo...
790
  				$newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
03e52840d   Kload   Init
791
792
793
794
795
796
  			}
  		}
  		return $newcharstring;
  	}
  
  	// UTF-8 => UTF-16LE (BOM)
31b7f2792   Kload   Upgrade to ownclo...
797
798
  	public static function iconv_fallback_utf8_utf16($string) {
  		return self::iconv_fallback_utf8_utf16le($string, true);
03e52840d   Kload   Init
799
800
801
  	}
  
  	// UTF-16BE => UTF-8
31b7f2792   Kload   Upgrade to ownclo...
802
  	public static function iconv_fallback_utf16be_utf8($string) {
03e52840d   Kload   Init
803
804
805
806
807
808
  		if (substr($string, 0, 2) == "\xFE\xFF") {
  			// strip BOM
  			$string = substr($string, 2);
  		}
  		$newcharstring = '';
  		for ($i = 0; $i < strlen($string); $i += 2) {
31b7f2792   Kload   Upgrade to ownclo...
809
810
  			$charval = self::BigEndian2Int(substr($string, $i, 2));
  			$newcharstring .= self::iconv_fallback_int_utf8($charval);
03e52840d   Kload   Init
811
812
813
814
815
  		}
  		return $newcharstring;
  	}
  
  	// UTF-16LE => UTF-8
31b7f2792   Kload   Upgrade to ownclo...
816
  	public static function iconv_fallback_utf16le_utf8($string) {
03e52840d   Kload   Init
817
818
819
820
821
822
  		if (substr($string, 0, 2) == "\xFF\xFE") {
  			// strip BOM
  			$string = substr($string, 2);
  		}
  		$newcharstring = '';
  		for ($i = 0; $i < strlen($string); $i += 2) {
31b7f2792   Kload   Upgrade to ownclo...
823
824
  			$charval = self::LittleEndian2Int(substr($string, $i, 2));
  			$newcharstring .= self::iconv_fallback_int_utf8($charval);
03e52840d   Kload   Init
825
826
827
828
829
  		}
  		return $newcharstring;
  	}
  
  	// UTF-16BE => ISO-8859-1
31b7f2792   Kload   Upgrade to ownclo...
830
  	public static function iconv_fallback_utf16be_iso88591($string) {
03e52840d   Kload   Init
831
832
833
834
835
836
  		if (substr($string, 0, 2) == "\xFE\xFF") {
  			// strip BOM
  			$string = substr($string, 2);
  		}
  		$newcharstring = '';
  		for ($i = 0; $i < strlen($string); $i += 2) {
31b7f2792   Kload   Upgrade to ownclo...
837
  			$charval = self::BigEndian2Int(substr($string, $i, 2));
03e52840d   Kload   Init
838
839
840
841
842
843
  			$newcharstring .= (($charval < 256) ? chr($charval) : '?');
  		}
  		return $newcharstring;
  	}
  
  	// UTF-16LE => ISO-8859-1
31b7f2792   Kload   Upgrade to ownclo...
844
  	public static function iconv_fallback_utf16le_iso88591($string) {
03e52840d   Kload   Init
845
846
847
848
849
850
  		if (substr($string, 0, 2) == "\xFF\xFE") {
  			// strip BOM
  			$string = substr($string, 2);
  		}
  		$newcharstring = '';
  		for ($i = 0; $i < strlen($string); $i += 2) {
31b7f2792   Kload   Upgrade to ownclo...
851
  			$charval = self::LittleEndian2Int(substr($string, $i, 2));
03e52840d   Kload   Init
852
853
854
855
856
857
  			$newcharstring .= (($charval < 256) ? chr($charval) : '?');
  		}
  		return $newcharstring;
  	}
  
  	// UTF-16 (BOM) => ISO-8859-1
31b7f2792   Kload   Upgrade to ownclo...
858
  	public static function iconv_fallback_utf16_iso88591($string) {
03e52840d   Kload   Init
859
860
  		$bom = substr($string, 0, 2);
  		if ($bom == "\xFE\xFF") {
31b7f2792   Kload   Upgrade to ownclo...
861
  			return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
03e52840d   Kload   Init
862
  		} elseif ($bom == "\xFF\xFE") {
31b7f2792   Kload   Upgrade to ownclo...
863
  			return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
03e52840d   Kload   Init
864
865
866
867
868
  		}
  		return $string;
  	}
  
  	// UTF-16 (BOM) => UTF-8
31b7f2792   Kload   Upgrade to ownclo...
869
  	public static function iconv_fallback_utf16_utf8($string) {
03e52840d   Kload   Init
870
871
  		$bom = substr($string, 0, 2);
  		if ($bom == "\xFE\xFF") {
31b7f2792   Kload   Upgrade to ownclo...
872
  			return self::iconv_fallback_utf16be_utf8(substr($string, 2));
03e52840d   Kload   Init
873
  		} elseif ($bom == "\xFF\xFE") {
31b7f2792   Kload   Upgrade to ownclo...
874
  			return self::iconv_fallback_utf16le_utf8(substr($string, 2));
03e52840d   Kload   Init
875
876
877
  		}
  		return $string;
  	}
31b7f2792   Kload   Upgrade to ownclo...
878
  	public static function iconv_fallback($in_charset, $out_charset, $string) {
03e52840d   Kload   Init
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
  
  		if ($in_charset == $out_charset) {
  			return $string;
  		}
  
  		// iconv() availble
  		if (function_exists('iconv')) {
  			if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
  				switch ($out_charset) {
  					case 'ISO-8859-1':
  						$converted_string = rtrim($converted_string, "\x00");
  						break;
  				}
  				return $converted_string;
  			}
  
  			// iconv() may sometimes fail with "illegal character in input string" error message
  			// and return an empty string, but returning the unconverted string is more useful
  			return $string;
  		}
  
  
  		// iconv() not available
  		static $ConversionFunctionList = array();
  		if (empty($ConversionFunctionList)) {
  			$ConversionFunctionList['ISO-8859-1']['UTF-8']    = 'iconv_fallback_iso88591_utf8';
  			$ConversionFunctionList['ISO-8859-1']['UTF-16']   = 'iconv_fallback_iso88591_utf16';
  			$ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
  			$ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
  			$ConversionFunctionList['UTF-8']['ISO-8859-1']    = 'iconv_fallback_utf8_iso88591';
  			$ConversionFunctionList['UTF-8']['UTF-16']        = 'iconv_fallback_utf8_utf16';
  			$ConversionFunctionList['UTF-8']['UTF-16BE']      = 'iconv_fallback_utf8_utf16be';
  			$ConversionFunctionList['UTF-8']['UTF-16LE']      = 'iconv_fallback_utf8_utf16le';
  			$ConversionFunctionList['UTF-16']['ISO-8859-1']   = 'iconv_fallback_utf16_iso88591';
  			$ConversionFunctionList['UTF-16']['UTF-8']        = 'iconv_fallback_utf16_utf8';
  			$ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
  			$ConversionFunctionList['UTF-16LE']['UTF-8']      = 'iconv_fallback_utf16le_utf8';
  			$ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
  			$ConversionFunctionList['UTF-16BE']['UTF-8']      = 'iconv_fallback_utf16be_utf8';
  		}
  		if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
  			$ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
31b7f2792   Kload   Upgrade to ownclo...
921
  			return self::$ConversionFunction($string);
03e52840d   Kload   Init
922
923
924
  		}
  		throw new Exception('PHP does not have iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
  	}
31b7f2792   Kload   Upgrade to ownclo...
925
  	public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
03e52840d   Kload   Init
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
  		$string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
  		$HTMLstring = '';
  
  		switch ($charset) {
  			case '1251':
  			case '1252':
  			case '866':
  			case '932':
  			case '936':
  			case '950':
  			case 'BIG5':
  			case 'BIG5-HKSCS':
  			case 'cp1251':
  			case 'cp1252':
  			case 'cp866':
  			case 'EUC-JP':
  			case 'EUCJP':
  			case 'GB2312':
  			case 'ibm866':
  			case 'ISO-8859-1':
  			case 'ISO-8859-15':
  			case 'ISO8859-1':
  			case 'ISO8859-15':
  			case 'KOI8-R':
  			case 'koi8-ru':
  			case 'koi8r':
  			case 'Shift_JIS':
  			case 'SJIS':
  			case 'win-1251':
  			case 'Windows-1251':
  			case 'Windows-1252':
  				$HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
  				break;
  
  			case 'UTF-8':
  				$strlen = strlen($string);
  				for ($i = 0; $i < $strlen; $i++) {
  					$char_ord_val = ord($string{$i});
  					$charval = 0;
  					if ($char_ord_val < 0x80) {
  						$charval = $char_ord_val;
  					} elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F  &&  $i+3 < $strlen) {
  						$charval  = (($char_ord_val & 0x07) << 18);
  						$charval += ((ord($string{++$i}) & 0x3F) << 12);
  						$charval += ((ord($string{++$i}) & 0x3F) << 6);
  						$charval +=  (ord($string{++$i}) & 0x3F);
  					} elseif ((($char_ord_val & 0xE0) >> 5) == 0x07  &&  $i+2 < $strlen) {
  						$charval  = (($char_ord_val & 0x0F) << 12);
  						$charval += ((ord($string{++$i}) & 0x3F) << 6);
  						$charval +=  (ord($string{++$i}) & 0x3F);
  					} elseif ((($char_ord_val & 0xC0) >> 6) == 0x03  &&  $i+1 < $strlen) {
  						$charval  = (($char_ord_val & 0x1F) << 6);
  						$charval += (ord($string{++$i}) & 0x3F);
  					}
  					if (($charval >= 32) && ($charval <= 127)) {
  						$HTMLstring .= htmlentities(chr($charval));
  					} else {
  						$HTMLstring .= '&#'.$charval.';';
  					}
  				}
  				break;
  
  			case 'UTF-16LE':
  				for ($i = 0; $i < strlen($string); $i += 2) {
31b7f2792   Kload   Upgrade to ownclo...
990
  					$charval = self::LittleEndian2Int(substr($string, $i, 2));
03e52840d   Kload   Init
991
992
993
994
995
996
997
998
999
1000
  					if (($charval >= 32) && ($charval <= 127)) {
  						$HTMLstring .= chr($charval);
  					} else {
  						$HTMLstring .= '&#'.$charval.';';
  					}
  				}
  				break;
  
  			case 'UTF-16BE':
  				for ($i = 0; $i < strlen($string); $i += 2) {
31b7f2792   Kload   Upgrade to ownclo...
1001
  					$charval = self::BigEndian2Int(substr($string, $i, 2));
03e52840d   Kload   Init
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
  					if (($charval >= 32) && ($charval <= 127)) {
  						$HTMLstring .= chr($charval);
  					} else {
  						$HTMLstring .= '&#'.$charval.';';
  					}
  				}
  				break;
  
  			default:
  				$HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
  				break;
  		}
  		return $HTMLstring;
  	}
31b7f2792   Kload   Upgrade to ownclo...
1016
  	public static function RGADnameLookup($namecode) {
03e52840d   Kload   Init
1017
1018
1019
1020
1021
1022
1023
1024
1025
  		static $RGADname = array();
  		if (empty($RGADname)) {
  			$RGADname[0] = 'not set';
  			$RGADname[1] = 'Track Gain Adjustment';
  			$RGADname[2] = 'Album Gain Adjustment';
  		}
  
  		return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
  	}
31b7f2792   Kload   Upgrade to ownclo...
1026
  	public static function RGADoriginatorLookup($originatorcode) {
03e52840d   Kload   Init
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
  		static $RGADoriginator = array();
  		if (empty($RGADoriginator)) {
  			$RGADoriginator[0] = 'unspecified';
  			$RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
  			$RGADoriginator[2] = 'set by user';
  			$RGADoriginator[3] = 'determined automatically';
  		}
  
  		return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
  	}
31b7f2792   Kload   Upgrade to ownclo...
1037
  	public static function RGADadjustmentLookup($rawadjustment, $signbit) {
03e52840d   Kload   Init
1038
1039
1040
1041
1042
1043
  		$adjustment = $rawadjustment / 10;
  		if ($signbit == 1) {
  			$adjustment *= -1;
  		}
  		return (float) $adjustment;
  	}
31b7f2792   Kload   Upgrade to ownclo...
1044
  	public static function RGADgainString($namecode, $originatorcode, $replaygain) {
03e52840d   Kload   Init
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
  		if ($replaygain < 0) {
  			$signbit = '1';
  		} else {
  			$signbit = '0';
  		}
  		$storedreplaygain = intval(round($replaygain * 10));
  		$gainstring  = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
  		$gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
  		$gainstring .= $signbit;
  		$gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
  
  		return $gainstring;
  	}
31b7f2792   Kload   Upgrade to ownclo...
1058
  	public static function RGADamplitude2dB($amplitude) {
03e52840d   Kload   Init
1059
1060
  		return 20 * log10($amplitude);
  	}
31b7f2792   Kload   Upgrade to ownclo...
1061
  	public static function GetDataImageSize($imgData, &$imageinfo=array()) {
03e52840d   Kload   Init
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
  		static $tempdir = '';
  		if (empty($tempdir)) {
  			// yes this is ugly, feel free to suggest a better way
  			require_once(dirname(__FILE__).'/getid3.php');
  			$getid3_temp = new getID3();
  			$tempdir = $getid3_temp->tempdir;
  			unset($getid3_temp);
  		}
  		$GetDataImageSize = false;
  		if ($tempfilename = tempnam($tempdir, 'gI3')) {
  			if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
  				fwrite($tmp, $imgData);
  				fclose($tmp);
31b7f2792   Kload   Upgrade to ownclo...
1075
  				$GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
03e52840d   Kload   Init
1076
1077
1078
1079
1080
  			}
  			unlink($tempfilename);
  		}
  		return $GetDataImageSize;
  	}
31b7f2792   Kload   Upgrade to ownclo...
1081
1082
1083
1084
1085
1086
  	public static function ImageExtFromMime($mime_type) {
  		// temporary way, works OK for now, but should be reworked in the future
  		return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
  	}
  
  	public static function ImageTypesLookup($imagetypeid) {
03e52840d   Kload   Init
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
  		static $ImageTypesLookup = array();
  		if (empty($ImageTypesLookup)) {
  			$ImageTypesLookup[1]  = 'gif';
  			$ImageTypesLookup[2]  = 'jpeg';
  			$ImageTypesLookup[3]  = 'png';
  			$ImageTypesLookup[4]  = 'swf';
  			$ImageTypesLookup[5]  = 'psd';
  			$ImageTypesLookup[6]  = 'bmp';
  			$ImageTypesLookup[7]  = 'tiff (little-endian)';
  			$ImageTypesLookup[8]  = 'tiff (big-endian)';
  			$ImageTypesLookup[9]  = 'jpc';
  			$ImageTypesLookup[10] = 'jp2';
  			$ImageTypesLookup[11] = 'jpx';
  			$ImageTypesLookup[12] = 'jb2';
  			$ImageTypesLookup[13] = 'swc';
  			$ImageTypesLookup[14] = 'iff';
  		}
  		return (isset($ImageTypesLookup[$imagetypeid]) ? $ImageTypesLookup[$imagetypeid] : '');
  	}
31b7f2792   Kload   Upgrade to ownclo...
1106
  	public static function CopyTagsToComments(&$ThisFileInfo) {
03e52840d   Kload   Init
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
  
  		// Copy all entries from ['tags'] into common ['comments']
  		if (!empty($ThisFileInfo['tags'])) {
  			foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
  				foreach ($tagarray as $tagname => $tagdata) {
  					foreach ($tagdata as $key => $value) {
  						if (!empty($value)) {
  							if (empty($ThisFileInfo['comments'][$tagname])) {
  
  								// fall through and append value
  
  							} elseif ($tagtype == 'id3v1') {
  
  								$newvaluelength = strlen(trim($value));
  								foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  									$oldvaluelength = strlen(trim($existingvalue));
  									if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
  										// new value is identical but shorter-than (or equal-length to) one already in comments - skip
  										break 2;
  									}
  								}
  
  							} elseif (!is_array($value)) {
  
  								$newvaluelength = strlen(trim($value));
  								foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  									$oldvaluelength = strlen(trim($existingvalue));
  									if (($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
  										$ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
  										break 2;
  									}
  								}
  
  							}
  							if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
  								$value = (is_string($value) ? trim($value) : $value);
  								$ThisFileInfo['comments'][$tagname][] = $value;
  							}
  						}
  					}
  				}
  			}
  
  			// Copy to ['comments_html']
  			foreach ($ThisFileInfo['comments'] as $field => $values) {
  				if ($field == 'picture') {
  					// pictures can take up a lot of space, and we don't need multiple copies of them
  					// let there be a single copy in [comments][picture], and not elsewhere
  					continue;
  				}
  				foreach ($values as $index => $value) {
  					if (is_array($value)) {
  						$ThisFileInfo['comments_html'][$field][$index] = $value;
  					} else {
31b7f2792   Kload   Upgrade to ownclo...
1161
  						$ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
03e52840d   Kload   Init
1162
1163
1164
1165
1166
1167
  					}
  				}
  			}
  		}
  		return true;
  	}
31b7f2792   Kload   Upgrade to ownclo...
1168
  	public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
03e52840d   Kload   Init
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
  
  		// Cached
  		static $cache;
  		if (isset($cache[$file][$name])) {
  			return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  		}
  
  		// Init
  		$keylength  = strlen($key);
  		$line_count = $end - $begin - 7;
  
  		// Open php file
  		$fp = fopen($file, 'r');
  
  		// Discard $begin lines
  		for ($i = 0; $i < ($begin + 3); $i++) {
  			fgets($fp, 1024);
  		}
  
  		// Loop thru line
  		while (0 < $line_count--) {
  
  			// Read line
  			$line = ltrim(fgets($fp, 1024), "\t ");
  
  			// METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
  			//$keycheck = substr($line, 0, $keylength);
  			//if ($key == $keycheck)  {
  			//	$cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
  			//	break;
  			//}
  
  			// METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
  			//$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
  			$explodedLine = explode("\t", $line, 2);
  			$ThisKey   = (isset($explodedLine[0]) ? $explodedLine[0] : '');
  			$ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
  			$cache[$file][$name][$ThisKey] = trim($ThisValue);
  		}
  
  		// Close and return
  		fclose($fp);
  		return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  	}
31b7f2792   Kload   Upgrade to ownclo...
1213
  	public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
03e52840d   Kload   Init
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
  		global $GETID3_ERRORARRAY;
  
  		if (file_exists($filename)) {
  			if (include_once($filename)) {
  				return true;
  			} else {
  				$diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
  			}
  		} else {
  			$diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
  		}
  		if ($DieOnFailure) {
  			throw new Exception($diemessage);
  		} else {
  			$GETID3_ERRORARRAY[] = $diemessage;
  		}
  		return false;
  	}
  
  	public static function trimNullByte($string) {
  		return trim($string, "\x00");
  	}
31b7f2792   Kload   Upgrade to ownclo...
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
  	public static function getFileSizeSyscall($path) {
  		$filesize = false;
  
  		if (GETID3_OS_ISWINDOWS) {
  			if (class_exists('COM')) { // From PHP 5.3.15 and 5.4.5, COM and DOTNET is no longer built into the php core.you have to add COM support in php.ini:
  				$filesystem = new COM('Scripting.FileSystemObject');
  				$file = $filesystem->GetFile($path);
  				$filesize = $file->Size();
  				unset($filesystem, $file);
  			} else {
  				$commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
  			}
  		} else {
  			$commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
  		}
  		if (isset($commandline)) {
  			$output = trim(`$commandline`);
  			if (ctype_digit($output)) {
  				$filesize = (float) $output;
  			}
  		}
  		return $filesize;
  	}
03e52840d   Kload   Init
1259

31b7f2792   Kload   Upgrade to ownclo...
1260
  }