1<?php
2
3/////////////////////////////////////////////////////////////////
4/// getID3() by James Heinrich <info@getid3.org>               //
5//  available at https://github.com/JamesHeinrich/getID3       //
6//            or https://www.getid3.org                        //
7//            or http://getid3.sourceforge.net                 //
8//                                                             //
9// getid3.lib.php - part of getID3()                           //
10//  see readme.txt for more details                            //
11//                                                            ///
12/////////////////////////////////////////////////////////////////
13
14
15class getid3_lib
16{
17	/**
18	 * @param string      $string
19	 * @param bool        $hex
20	 * @param bool        $spaces
21	 * @param string|bool $htmlencoding
22	 *
23	 * @return string
24	 */
25	public static function PrintHexBytes($string, $hex=true, $spaces=true, $htmlencoding='UTF-8') {
26		$returnstring = '';
27		for ($i = 0; $i < strlen($string); $i++) {
28			if ($hex) {
29				$returnstring .= str_pad(dechex(ord($string[$i])), 2, '0', STR_PAD_LEFT);
30			} else {
31				$returnstring .= ' '.(preg_match("#[\x20-\x7E]#", $string[$i]) ? $string[$i] : '¤');
32			}
33			if ($spaces) {
34				$returnstring .= ' ';
35			}
36		}
37		if (!empty($htmlencoding)) {
38			if ($htmlencoding === true) {
39				$htmlencoding = 'UTF-8'; // prior to getID3 v1.9.0 the function's 4th parameter was boolean
40			}
41			$returnstring = htmlentities($returnstring, ENT_QUOTES, $htmlencoding);
42		}
43		return $returnstring;
44	}
45
46	/**
47	 * Truncates a floating-point number at the decimal point.
48	 *
49	 * @param float $floatnumber
50	 *
51	 * @return float|int returns int (if possible, otherwise float)
52	 */
53	public static function trunc($floatnumber) {
54		if ($floatnumber >= 1) {
55			$truncatednumber = floor($floatnumber);
56		} elseif ($floatnumber <= -1) {
57			$truncatednumber = ceil($floatnumber);
58		} else {
59			$truncatednumber = 0;
60		}
61		if (self::intValueSupported($truncatednumber)) {
62			$truncatednumber = (int) $truncatednumber;
63		}
64		return $truncatednumber;
65	}
66
67	/**
68	 * @param int|null $variable
69	 * @param int      $increment
70	 *
71	 * @return bool
72	 */
73	public static function safe_inc(&$variable, $increment=1) {
74		if (isset($variable)) {
75			$variable += $increment;
76		} else {
77			$variable = $increment;
78		}
79		return true;
80	}
81
82	/**
83	 * @param int|float $floatnum
84	 *
85	 * @return int|float
86	 */
87	public static function CastAsInt($floatnum) {
88		// convert to float if not already
89		$floatnum = (float) $floatnum;
90
91		// convert a float to type int, only if possible
92		if (self::trunc($floatnum) == $floatnum) {
93			// it's not floating point
94			if (self::intValueSupported($floatnum)) {
95				// it's within int range
96				$floatnum = (int) $floatnum;
97			}
98		}
99		return $floatnum;
100	}
101
102	/**
103	 * @param int $num
104	 *
105	 * @return bool
106	 */
107	public static function intValueSupported($num) {
108		// check if integers are 64-bit
109		static $hasINT64 = null;
110		if ($hasINT64 === null) { // 10x faster than is_null()
111			$hasINT64 = is_int(pow(2, 31)); // 32-bit int are limited to (2^31)-1
112			if (!$hasINT64 && !defined('PHP_INT_MIN')) {
113				define('PHP_INT_MIN', ~PHP_INT_MAX);
114			}
115		}
116		// if integers are 64-bit - no other check required
117		if ($hasINT64 || (($num <= PHP_INT_MAX) && ($num >= PHP_INT_MIN))) {
118			return true;
119		}
120		return false;
121	}
122
123	/**
124	 * @param string $fraction
125	 *
126	 * @return float
127	 */
128	public static function DecimalizeFraction($fraction) {
129		list($numerator, $denominator) = explode('/', $fraction);
130		return $numerator / ($denominator ? $denominator : 1);
131	}
132
133	/**
134	 * @param string $binarynumerator
135	 *
136	 * @return float
137	 */
138	public static function DecimalBinary2Float($binarynumerator) {
139		$numerator   = self::Bin2Dec($binarynumerator);
140		$denominator = self::Bin2Dec('1'.str_repeat('0', strlen($binarynumerator)));
141		return ($numerator / $denominator);
142	}
143
144	/**
145	 * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
146	 *
147	 * @param string $binarypointnumber
148	 * @param int    $maxbits
149	 *
150	 * @return array
151	 */
152	public static function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) {
153		if (strpos($binarypointnumber, '.') === false) {
154			$binarypointnumber = '0.'.$binarypointnumber;
155		} elseif ($binarypointnumber[0] == '.') {
156			$binarypointnumber = '0'.$binarypointnumber;
157		}
158		$exponent = 0;
159		while (($binarypointnumber[0] != '1') || (substr($binarypointnumber, 1, 1) != '.')) {
160			if (substr($binarypointnumber, 1, 1) == '.') {
161				$exponent--;
162				$binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3);
163			} else {
164				$pointpos = strpos($binarypointnumber, '.');
165				$exponent += ($pointpos - 1);
166				$binarypointnumber = str_replace('.', '', $binarypointnumber);
167				$binarypointnumber = $binarypointnumber[0].'.'.substr($binarypointnumber, 1);
168			}
169		}
170		$binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT);
171		return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent);
172	}
173
174	/**
175	 * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
176	 *
177	 * @param float $floatvalue
178	 *
179	 * @return string
180	 */
181	public static function Float2BinaryDecimal($floatvalue) {
182		$maxbits = 128; // to how many bits of precision should the calculations be taken?
183		$intpart   = self::trunc($floatvalue);
184		$floatpart = abs($floatvalue - $intpart);
185		$pointbitstring = '';
186		while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) {
187			$floatpart *= 2;
188			$pointbitstring .= (string) self::trunc($floatpart);
189			$floatpart -= self::trunc($floatpart);
190		}
191		$binarypointnumber = decbin($intpart).'.'.$pointbitstring;
192		return $binarypointnumber;
193	}
194
195	/**
196	 * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html
197	 *
198	 * @param float $floatvalue
199	 * @param int $bits
200	 *
201	 * @return string|false
202	 */
203	public static function Float2String($floatvalue, $bits) {
204		$exponentbits = 0;
205		$fractionbits = 0;
206		switch ($bits) {
207			case 32:
208				$exponentbits = 8;
209				$fractionbits = 23;
210				break;
211
212			case 64:
213				$exponentbits = 11;
214				$fractionbits = 52;
215				break;
216
217			default:
218				return false;
219		}
220		if ($floatvalue >= 0) {
221			$signbit = '0';
222		} else {
223			$signbit = '1';
224		}
225		$normalizedbinary  = self::NormalizeBinaryPoint(self::Float2BinaryDecimal($floatvalue), $fractionbits);
226		$biasedexponent    = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent
227		$exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT);
228		$fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT);
229
230		return self::BigEndian2String(self::Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false);
231	}
232
233	/**
234	 * @param string $byteword
235	 *
236	 * @return float|false
237	 */
238	public static function LittleEndian2Float($byteword) {
239		return self::BigEndian2Float(strrev($byteword));
240	}
241
242	/**
243	 * ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic
244	 *
245	 * @link http://www.psc.edu/general/software/packages/ieee/ieee.html
246	 * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html
247	 *
248	 * @param string $byteword
249	 *
250	 * @return float|false
251	 */
252	public static function BigEndian2Float($byteword) {
253		$bitword = self::BigEndian2Bin($byteword);
254		if (!$bitword) {
255			return 0;
256		}
257		$signbit = $bitword[0];
258		$floatvalue = 0;
259		$exponentbits = 0;
260		$fractionbits = 0;
261
262		switch (strlen($byteword) * 8) {
263			case 32:
264				$exponentbits = 8;
265				$fractionbits = 23;
266				break;
267
268			case 64:
269				$exponentbits = 11;
270				$fractionbits = 52;
271				break;
272
273			case 80:
274				// 80-bit Apple SANE format
275				// http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/
276				$exponentstring = substr($bitword, 1, 15);
277				$isnormalized = intval($bitword[16]);
278				$fractionstring = substr($bitword, 17, 63);
279				$exponent = pow(2, self::Bin2Dec($exponentstring) - 16383);
280				$fraction = $isnormalized + self::DecimalBinary2Float($fractionstring);
281				$floatvalue = $exponent * $fraction;
282				if ($signbit == '1') {
283					$floatvalue *= -1;
284				}
285				return $floatvalue;
286
287			default:
288				return false;
289		}
290		$exponentstring = substr($bitword, 1, $exponentbits);
291		$fractionstring = substr($bitword, $exponentbits + 1, $fractionbits);
292		$exponent = self::Bin2Dec($exponentstring);
293		$fraction = self::Bin2Dec($fractionstring);
294
295		if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) {
296			// Not a Number
297			$floatvalue = false;
298		} elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) {
299			if ($signbit == '1') {
300				$floatvalue = '-infinity';
301			} else {
302				$floatvalue = '+infinity';
303			}
304		} elseif (($exponent == 0) && ($fraction == 0)) {
305			if ($signbit == '1') {
306				$floatvalue = -0;
307			} else {
308				$floatvalue = 0;
309			}
310			$floatvalue = ($signbit ? 0 : -0);
311		} elseif (($exponent == 0) && ($fraction != 0)) {
312			// These are 'unnormalized' values
313			$floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * self::DecimalBinary2Float($fractionstring);
314			if ($signbit == '1') {
315				$floatvalue *= -1;
316			}
317		} elseif ($exponent != 0) {
318			$floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + self::DecimalBinary2Float($fractionstring));
319			if ($signbit == '1') {
320				$floatvalue *= -1;
321			}
322		}
323		return (float) $floatvalue;
324	}
325
326	/**
327	 * @param string $byteword
328	 * @param bool   $synchsafe
329	 * @param bool   $signed
330	 *
331	 * @return int|float|false
332	 * @throws Exception
333	 */
334	public static function BigEndian2Int($byteword, $synchsafe=false, $signed=false) {
335		$intvalue = 0;
336		$bytewordlen = strlen($byteword);
337		if ($bytewordlen == 0) {
338			return false;
339		}
340		for ($i = 0; $i < $bytewordlen; $i++) {
341			if ($synchsafe) { // disregard MSB, effectively 7-bit bytes
342				//$intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); // faster, but runs into problems past 2^31 on 32-bit systems
343				$intvalue += (ord($byteword[$i]) & 0x7F) * pow(2, ($bytewordlen - 1 - $i) * 7);
344			} else {
345				$intvalue += ord($byteword[$i]) * pow(256, ($bytewordlen - 1 - $i));
346			}
347		}
348		if ($signed && !$synchsafe) {
349			// synchsafe ints are not allowed to be signed
350			if ($bytewordlen <= PHP_INT_SIZE) {
351				$signMaskBit = 0x80 << (8 * ($bytewordlen - 1));
352				if ($intvalue & $signMaskBit) {
353					$intvalue = 0 - ($intvalue & ($signMaskBit - 1));
354				}
355			} else {
356				throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits ('.strlen($byteword).') in self::BigEndian2Int()');
357			}
358		}
359		return self::CastAsInt($intvalue);
360	}
361
362	/**
363	 * @param string $byteword
364	 * @param bool   $signed
365	 *
366	 * @return int|float|false
367	 */
368	public static function LittleEndian2Int($byteword, $signed=false) {
369		return self::BigEndian2Int(strrev($byteword), false, $signed);
370	}
371
372	/**
373	 * @param string $byteword
374	 *
375	 * @return string
376	 */
377	public static function LittleEndian2Bin($byteword) {
378		return self::BigEndian2Bin(strrev($byteword));
379	}
380
381	/**
382	 * @param string $byteword
383	 *
384	 * @return string
385	 */
386	public static function BigEndian2Bin($byteword) {
387		$binvalue = '';
388		$bytewordlen = strlen($byteword);
389		for ($i = 0; $i < $bytewordlen; $i++) {
390			$binvalue .= str_pad(decbin(ord($byteword[$i])), 8, '0', STR_PAD_LEFT);
391		}
392		return $binvalue;
393	}
394
395	/**
396	 * @param int  $number
397	 * @param int  $minbytes
398	 * @param bool $synchsafe
399	 * @param bool $signed
400	 *
401	 * @return string
402	 * @throws Exception
403	 */
404	public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
405		if ($number < 0) {
406			throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
407		}
408		$maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
409		$intstring = '';
410		if ($signed) {
411			if ($minbytes > PHP_INT_SIZE) {
412				throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
413			}
414			$number = $number & (0x80 << (8 * ($minbytes - 1)));
415		}
416		while ($number != 0) {
417			$quotient = ($number / ($maskbyte + 1));
418			$intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
419			$number = floor($quotient);
420		}
421		return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
422	}
423
424	/**
425	 * @param int $number
426	 *
427	 * @return string
428	 */
429	public static function Dec2Bin($number) {
430		$bytes = array();
431		while ($number >= 256) {
432			$bytes[] = (($number / 256) - (floor($number / 256))) * 256;
433			$number = floor($number / 256);
434		}
435		$bytes[] = $number;
436		$binstring = '';
437		foreach ($bytes as $i => $byte) {
438			$binstring = (($i == count($bytes) - 1) ? decbin($byte) : str_pad(decbin($byte), 8, '0', STR_PAD_LEFT)).$binstring;
439		}
440		return $binstring;
441	}
442
443	/**
444	 * @param string $binstring
445	 * @param bool   $signed
446	 *
447	 * @return int|float
448	 */
449	public static function Bin2Dec($binstring, $signed=false) {
450		$signmult = 1;
451		if ($signed) {
452			if ($binstring[0] == '1') {
453				$signmult = -1;
454			}
455			$binstring = substr($binstring, 1);
456		}
457		$decvalue = 0;
458		for ($i = 0; $i < strlen($binstring); $i++) {
459			$decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
460		}
461		return self::CastAsInt($decvalue * $signmult);
462	}
463
464	/**
465	 * @param string $binstring
466	 *
467	 * @return string
468	 */
469	public static function Bin2String($binstring) {
470		// return 'hi' for input of '0110100001101001'
471		$string = '';
472		$binstringreversed = strrev($binstring);
473		for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
474			$string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
475		}
476		return $string;
477	}
478
479	/**
480	 * @param int  $number
481	 * @param int  $minbytes
482	 * @param bool $synchsafe
483	 *
484	 * @return string
485	 */
486	public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
487		$intstring = '';
488		while ($number > 0) {
489			if ($synchsafe) {
490				$intstring = $intstring.chr($number & 127);
491				$number >>= 7;
492			} else {
493				$intstring = $intstring.chr($number & 255);
494				$number >>= 8;
495			}
496		}
497		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
498	}
499
500	/**
501	 * @param mixed $array1
502	 * @param mixed $array2
503	 *
504	 * @return array|false
505	 */
506	public static function array_merge_clobber($array1, $array2) {
507		// written by kcØhireability*com
508		// taken from http://www.php.net/manual/en/function.array-merge-recursive.php
509		if (!is_array($array1) || !is_array($array2)) {
510			return false;
511		}
512		$newarray = $array1;
513		foreach ($array2 as $key => $val) {
514			if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
515				$newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
516			} else {
517				$newarray[$key] = $val;
518			}
519		}
520		return $newarray;
521	}
522
523	/**
524	 * @param mixed $array1
525	 * @param mixed $array2
526	 *
527	 * @return array|false
528	 */
529	public static function array_merge_noclobber($array1, $array2) {
530		if (!is_array($array1) || !is_array($array2)) {
531			return false;
532		}
533		$newarray = $array1;
534		foreach ($array2 as $key => $val) {
535			if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
536				$newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
537			} elseif (!isset($newarray[$key])) {
538				$newarray[$key] = $val;
539			}
540		}
541		return $newarray;
542	}
543
544	/**
545	 * @param mixed $array1
546	 * @param mixed $array2
547	 *
548	 * @return array|false|null
549	 */
550	public static function flipped_array_merge_noclobber($array1, $array2) {
551		if (!is_array($array1) || !is_array($array2)) {
552			return false;
553		}
554		# naturally, this only works non-recursively
555		$newarray = array_flip($array1);
556		foreach (array_flip($array2) as $key => $val) {
557			if (!isset($newarray[$key])) {
558				$newarray[$key] = count($newarray);
559			}
560		}
561		return array_flip($newarray);
562	}
563
564	/**
565	 * @param array $theArray
566	 *
567	 * @return bool
568	 */
569	public static function ksort_recursive(&$theArray) {
570		ksort($theArray);
571		foreach ($theArray as $key => $value) {
572			if (is_array($value)) {
573				self::ksort_recursive($theArray[$key]);
574			}
575		}
576		return true;
577	}
578
579	/**
580	 * @param string $filename
581	 * @param int    $numextensions
582	 *
583	 * @return string
584	 */
585	public static function fileextension($filename, $numextensions=1) {
586		if (strstr($filename, '.')) {
587			$reversedfilename = strrev($filename);
588			$offset = 0;
589			for ($i = 0; $i < $numextensions; $i++) {
590				$offset = strpos($reversedfilename, '.', $offset + 1);
591				if ($offset === false) {
592					return '';
593				}
594			}
595			return strrev(substr($reversedfilename, 0, $offset));
596		}
597		return '';
598	}
599
600	/**
601	 * @param int $seconds
602	 *
603	 * @return string
604	 */
605	public static function PlaytimeString($seconds) {
606		$sign = (($seconds < 0) ? '-' : '');
607		$seconds = round(abs($seconds));
608		$H = (int) floor( $seconds                            / 3600);
609		$M = (int) floor(($seconds - (3600 * $H)            ) /   60);
610		$S = (int) round( $seconds - (3600 * $H) - (60 * $M)        );
611		return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
612	}
613
614	/**
615	 * @param int $macdate
616	 *
617	 * @return int|float
618	 */
619	public static function DateMac2Unix($macdate) {
620		// Macintosh timestamp: seconds since 00:00h January 1, 1904
621		// UNIX timestamp:      seconds since 00:00h January 1, 1970
622		return self::CastAsInt($macdate - 2082844800);
623	}
624
625	/**
626	 * @param string $rawdata
627	 *
628	 * @return float
629	 */
630	public static function FixedPoint8_8($rawdata) {
631		return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
632	}
633
634	/**
635	 * @param string $rawdata
636	 *
637	 * @return float
638	 */
639	public static function FixedPoint16_16($rawdata) {
640		return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
641	}
642
643	/**
644	 * @param string $rawdata
645	 *
646	 * @return float
647	 */
648	public static function FixedPoint2_30($rawdata) {
649		$binarystring = self::BigEndian2Bin($rawdata);
650		return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
651	}
652
653
654	/**
655	 * @param string $ArrayPath
656	 * @param string $Separator
657	 * @param mixed $Value
658	 *
659	 * @return array
660	 */
661	public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
662		// assigns $Value to a nested array path:
663		//   $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
664		// is the same as:
665		//   $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
666		// or
667		//   $foo['path']['to']['my'] = 'file.txt';
668		$ArrayPath = ltrim($ArrayPath, $Separator);
669		$ReturnedArray = array();
670		if (($pos = strpos($ArrayPath, $Separator)) !== false) {
671			$ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
672		} else {
673			$ReturnedArray[$ArrayPath] = $Value;
674		}
675		return $ReturnedArray;
676	}
677
678	/**
679	 * @param array $arraydata
680	 * @param bool  $returnkey
681	 *
682	 * @return int|false
683	 */
684	public static function array_max($arraydata, $returnkey=false) {
685		$maxvalue = false;
686		$maxkey   = false;
687		foreach ($arraydata as $key => $value) {
688			if (!is_array($value)) {
689				if (($maxvalue === false) || ($value > $maxvalue)) {
690					$maxvalue = $value;
691					$maxkey = $key;
692				}
693			}
694		}
695		return ($returnkey ? $maxkey : $maxvalue);
696	}
697
698	/**
699	 * @param array $arraydata
700	 * @param bool  $returnkey
701	 *
702	 * @return int|false
703	 */
704	public static function array_min($arraydata, $returnkey=false) {
705		$minvalue = false;
706		$minkey   = false;
707		foreach ($arraydata as $key => $value) {
708			if (!is_array($value)) {
709				if (($minvalue === false) || ($value < $minvalue)) {
710					$minvalue = $value;
711					$minkey = $key;
712				}
713			}
714		}
715		return ($returnkey ? $minkey : $minvalue);
716	}
717
718	/**
719	 * @param string $XMLstring
720	 *
721	 * @return array|false
722	 */
723	public static function XML2array($XMLstring) {
724		if (function_exists('simplexml_load_string') && function_exists('libxml_disable_entity_loader')) {
725			// http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html
726			// https://core.trac.wordpress.org/changeset/29378
727			// This function has been deprecated in PHP 8.0 because in libxml 2.9.0, external entity loading is
728			// disabled by default, but is still needed when LIBXML_NOENT is used.
729			$loader = @libxml_disable_entity_loader(true);
730			$XMLobject = simplexml_load_string($XMLstring, 'SimpleXMLElement', LIBXML_NOENT);
731			$return = self::SimpleXMLelement2array($XMLobject);
732			@libxml_disable_entity_loader($loader);
733			return $return;
734		}
735		return false;
736	}
737
738	/**
739	* @param SimpleXMLElement|array|mixed $XMLobject
740	*
741	* @return mixed
742	*/
743	public static function SimpleXMLelement2array($XMLobject) {
744		if (!is_object($XMLobject) && !is_array($XMLobject)) {
745			return $XMLobject;
746		}
747		$XMLarray = $XMLobject instanceof SimpleXMLElement ? get_object_vars($XMLobject) : $XMLobject;
748		foreach ($XMLarray as $key => $value) {
749			$XMLarray[$key] = self::SimpleXMLelement2array($value);
750		}
751		return $XMLarray;
752	}
753
754	/**
755	 * Returns checksum for a file from starting position to absolute end position.
756	 *
757	 * @param string $file
758	 * @param int    $offset
759	 * @param int    $end
760	 * @param string $algorithm
761	 *
762	 * @return string|false
763	 * @throws getid3_exception
764	 */
765	public static function hash_data($file, $offset, $end, $algorithm) {
766		if (!self::intValueSupported($end)) {
767			return false;
768		}
769		if (!in_array($algorithm, array('md5', 'sha1'))) {
770			throw new getid3_exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
771		}
772
773		$size = $end - $offset;
774
775		$fp = fopen($file, 'rb');
776		fseek($fp, $offset);
777		$ctx = hash_init($algorithm);
778		while ($size > 0) {
779			$buffer = fread($fp, min($size, getID3::FREAD_BUFFER_SIZE));
780			hash_update($ctx, $buffer);
781			$size -= getID3::FREAD_BUFFER_SIZE;
782		}
783		$hash = hash_final($ctx);
784		fclose($fp);
785
786		return $hash;
787	}
788
789	/**
790	 * @param string $filename_source
791	 * @param string $filename_dest
792	 * @param int    $offset
793	 * @param int    $length
794	 *
795	 * @return bool
796	 * @throws Exception
797	 *
798	 * @deprecated Unused, may be removed in future versions of getID3
799	 */
800	public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
801		if (!self::intValueSupported($offset + $length)) {
802			throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
803		}
804		if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
805			if (($fp_dest = fopen($filename_dest, 'wb'))) {
806				if (fseek($fp_src, $offset) == 0) {
807					$byteslefttowrite = $length;
808					while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
809						$byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
810						$byteslefttowrite -= $byteswritten;
811					}
812					fclose($fp_dest);
813					return true;
814				} else {
815					fclose($fp_src);
816					throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
817				}
818			} else {
819				throw new Exception('failed to create file for writing '.$filename_dest);
820			}
821		} else {
822			throw new Exception('failed to open file for reading '.$filename_source);
823		}
824	}
825
826	/**
827	 * @param int $charval
828	 *
829	 * @return string
830	 */
831	public static function iconv_fallback_int_utf8($charval) {
832		if ($charval < 128) {
833			// 0bbbbbbb
834			$newcharstring = chr($charval);
835		} elseif ($charval < 2048) {
836			// 110bbbbb 10bbbbbb
837			$newcharstring  = chr(($charval >>   6) | 0xC0);
838			$newcharstring .= chr(($charval & 0x3F) | 0x80);
839		} elseif ($charval < 65536) {
840			// 1110bbbb 10bbbbbb 10bbbbbb
841			$newcharstring  = chr(($charval >>  12) | 0xE0);
842			$newcharstring .= chr(($charval >>   6) | 0xC0);
843			$newcharstring .= chr(($charval & 0x3F) | 0x80);
844		} else {
845			// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
846			$newcharstring  = chr(($charval >>  18) | 0xF0);
847			$newcharstring .= chr(($charval >>  12) | 0xC0);
848			$newcharstring .= chr(($charval >>   6) | 0xC0);
849			$newcharstring .= chr(($charval & 0x3F) | 0x80);
850		}
851		return $newcharstring;
852	}
853
854	/**
855	 * ISO-8859-1 => UTF-8
856	 *
857	 * @param string $string
858	 * @param bool   $bom
859	 *
860	 * @return string
861	 */
862	public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
863		if (function_exists('utf8_encode')) {
864			return utf8_encode($string);
865		}
866		// utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
867		$newcharstring = '';
868		if ($bom) {
869			$newcharstring .= "\xEF\xBB\xBF";
870		}
871		for ($i = 0; $i < strlen($string); $i++) {
872			$charval = ord($string[$i]);
873			$newcharstring .= self::iconv_fallback_int_utf8($charval);
874		}
875		return $newcharstring;
876	}
877
878	/**
879	 * ISO-8859-1 => UTF-16BE
880	 *
881	 * @param string $string
882	 * @param bool   $bom
883	 *
884	 * @return string
885	 */
886	public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
887		$newcharstring = '';
888		if ($bom) {
889			$newcharstring .= "\xFE\xFF";
890		}
891		for ($i = 0; $i < strlen($string); $i++) {
892			$newcharstring .= "\x00".$string[$i];
893		}
894		return $newcharstring;
895	}
896
897	/**
898	 * ISO-8859-1 => UTF-16LE
899	 *
900	 * @param string $string
901	 * @param bool   $bom
902	 *
903	 * @return string
904	 */
905	public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
906		$newcharstring = '';
907		if ($bom) {
908			$newcharstring .= "\xFF\xFE";
909		}
910		for ($i = 0; $i < strlen($string); $i++) {
911			$newcharstring .= $string[$i]."\x00";
912		}
913		return $newcharstring;
914	}
915
916	/**
917	 * ISO-8859-1 => UTF-16LE (BOM)
918	 *
919	 * @param string $string
920	 *
921	 * @return string
922	 */
923	public static function iconv_fallback_iso88591_utf16($string) {
924		return self::iconv_fallback_iso88591_utf16le($string, true);
925	}
926
927	/**
928	 * UTF-8 => ISO-8859-1
929	 *
930	 * @param string $string
931	 *
932	 * @return string
933	 */
934	public static function iconv_fallback_utf8_iso88591($string) {
935		if (function_exists('utf8_decode')) {
936			return utf8_decode($string);
937		}
938		// utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
939		$newcharstring = '';
940		$offset = 0;
941		$stringlength = strlen($string);
942		while ($offset < $stringlength) {
943			if ((ord($string[$offset]) | 0x07) == 0xF7) {
944				// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
945				$charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
946						   ((ord($string[($offset + 1)]) & 0x3F) << 12) &
947						   ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
948							(ord($string[($offset + 3)]) & 0x3F);
949				$offset += 4;
950			} elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
951				// 1110bbbb 10bbbbbb 10bbbbbb
952				$charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
953						   ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
954							(ord($string[($offset + 2)]) & 0x3F);
955				$offset += 3;
956			} elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
957				// 110bbbbb 10bbbbbb
958				$charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
959							(ord($string[($offset + 1)]) & 0x3F);
960				$offset += 2;
961			} elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
962				// 0bbbbbbb
963				$charval = ord($string[$offset]);
964				$offset += 1;
965			} else {
966				// error? throw some kind of warning here?
967				$charval = false;
968				$offset += 1;
969			}
970			if ($charval !== false) {
971				$newcharstring .= (($charval < 256) ? chr($charval) : '?');
972			}
973		}
974		return $newcharstring;
975	}
976
977	/**
978	 * UTF-8 => UTF-16BE
979	 *
980	 * @param string $string
981	 * @param bool   $bom
982	 *
983	 * @return string
984	 */
985	public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
986		$newcharstring = '';
987		if ($bom) {
988			$newcharstring .= "\xFE\xFF";
989		}
990		$offset = 0;
991		$stringlength = strlen($string);
992		while ($offset < $stringlength) {
993			if ((ord($string[$offset]) | 0x07) == 0xF7) {
994				// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
995				$charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
996						   ((ord($string[($offset + 1)]) & 0x3F) << 12) &
997						   ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
998							(ord($string[($offset + 3)]) & 0x3F);
999				$offset += 4;
1000			} elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
1001				// 1110bbbb 10bbbbbb 10bbbbbb
1002				$charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
1003						   ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
1004							(ord($string[($offset + 2)]) & 0x3F);
1005				$offset += 3;
1006			} elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
1007				// 110bbbbb 10bbbbbb
1008				$charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
1009							(ord($string[($offset + 1)]) & 0x3F);
1010				$offset += 2;
1011			} elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
1012				// 0bbbbbbb
1013				$charval = ord($string[$offset]);
1014				$offset += 1;
1015			} else {
1016				// error? throw some kind of warning here?
1017				$charval = false;
1018				$offset += 1;
1019			}
1020			if ($charval !== false) {
1021				$newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
1022			}
1023		}
1024		return $newcharstring;
1025	}
1026
1027	/**
1028	 * UTF-8 => UTF-16LE
1029	 *
1030	 * @param string $string
1031	 * @param bool   $bom
1032	 *
1033	 * @return string
1034	 */
1035	public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
1036		$newcharstring = '';
1037		if ($bom) {
1038			$newcharstring .= "\xFF\xFE";
1039		}
1040		$offset = 0;
1041		$stringlength = strlen($string);
1042		while ($offset < $stringlength) {
1043			if ((ord($string[$offset]) | 0x07) == 0xF7) {
1044				// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
1045				$charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
1046						   ((ord($string[($offset + 1)]) & 0x3F) << 12) &
1047						   ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
1048							(ord($string[($offset + 3)]) & 0x3F);
1049				$offset += 4;
1050			} elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
1051				// 1110bbbb 10bbbbbb 10bbbbbb
1052				$charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
1053						   ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
1054							(ord($string[($offset + 2)]) & 0x3F);
1055				$offset += 3;
1056			} elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
1057				// 110bbbbb 10bbbbbb
1058				$charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
1059							(ord($string[($offset + 1)]) & 0x3F);
1060				$offset += 2;
1061			} elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
1062				// 0bbbbbbb
1063				$charval = ord($string[$offset]);
1064				$offset += 1;
1065			} else {
1066				// error? maybe throw some warning here?
1067				$charval = false;
1068				$offset += 1;
1069			}
1070			if ($charval !== false) {
1071				$newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
1072			}
1073		}
1074		return $newcharstring;
1075	}
1076
1077	/**
1078	 * UTF-8 => UTF-16LE (BOM)
1079	 *
1080	 * @param string $string
1081	 *
1082	 * @return string
1083	 */
1084	public static function iconv_fallback_utf8_utf16($string) {
1085		return self::iconv_fallback_utf8_utf16le($string, true);
1086	}
1087
1088	/**
1089	 * UTF-16BE => UTF-8
1090	 *
1091	 * @param string $string
1092	 *
1093	 * @return string
1094	 */
1095	public static function iconv_fallback_utf16be_utf8($string) {
1096		if (substr($string, 0, 2) == "\xFE\xFF") {
1097			// strip BOM
1098			$string = substr($string, 2);
1099		}
1100		$newcharstring = '';
1101		for ($i = 0; $i < strlen($string); $i += 2) {
1102			$charval = self::BigEndian2Int(substr($string, $i, 2));
1103			$newcharstring .= self::iconv_fallback_int_utf8($charval);
1104		}
1105		return $newcharstring;
1106	}
1107
1108	/**
1109	 * UTF-16LE => UTF-8
1110	 *
1111	 * @param string $string
1112	 *
1113	 * @return string
1114	 */
1115	public static function iconv_fallback_utf16le_utf8($string) {
1116		if (substr($string, 0, 2) == "\xFF\xFE") {
1117			// strip BOM
1118			$string = substr($string, 2);
1119		}
1120		$newcharstring = '';
1121		for ($i = 0; $i < strlen($string); $i += 2) {
1122			$charval = self::LittleEndian2Int(substr($string, $i, 2));
1123			$newcharstring .= self::iconv_fallback_int_utf8($charval);
1124		}
1125		return $newcharstring;
1126	}
1127
1128	/**
1129	 * UTF-16BE => ISO-8859-1
1130	 *
1131	 * @param string $string
1132	 *
1133	 * @return string
1134	 */
1135	public static function iconv_fallback_utf16be_iso88591($string) {
1136		if (substr($string, 0, 2) == "\xFE\xFF") {
1137			// strip BOM
1138			$string = substr($string, 2);
1139		}
1140		$newcharstring = '';
1141		for ($i = 0; $i < strlen($string); $i += 2) {
1142			$charval = self::BigEndian2Int(substr($string, $i, 2));
1143			$newcharstring .= (($charval < 256) ? chr($charval) : '?');
1144		}
1145		return $newcharstring;
1146	}
1147
1148	/**
1149	 * UTF-16LE => ISO-8859-1
1150	 *
1151	 * @param string $string
1152	 *
1153	 * @return string
1154	 */
1155	public static function iconv_fallback_utf16le_iso88591($string) {
1156		if (substr($string, 0, 2) == "\xFF\xFE") {
1157			// strip BOM
1158			$string = substr($string, 2);
1159		}
1160		$newcharstring = '';
1161		for ($i = 0; $i < strlen($string); $i += 2) {
1162			$charval = self::LittleEndian2Int(substr($string, $i, 2));
1163			$newcharstring .= (($charval < 256) ? chr($charval) : '?');
1164		}
1165		return $newcharstring;
1166	}
1167
1168	/**
1169	 * UTF-16 (BOM) => ISO-8859-1
1170	 *
1171	 * @param string $string
1172	 *
1173	 * @return string
1174	 */
1175	public static function iconv_fallback_utf16_iso88591($string) {
1176		$bom = substr($string, 0, 2);
1177		if ($bom == "\xFE\xFF") {
1178			return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
1179		} elseif ($bom == "\xFF\xFE") {
1180			return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
1181		}
1182		return $string;
1183	}
1184
1185	/**
1186	 * UTF-16 (BOM) => UTF-8
1187	 *
1188	 * @param string $string
1189	 *
1190	 * @return string
1191	 */
1192	public static function iconv_fallback_utf16_utf8($string) {
1193		$bom = substr($string, 0, 2);
1194		if ($bom == "\xFE\xFF") {
1195			return self::iconv_fallback_utf16be_utf8(substr($string, 2));
1196		} elseif ($bom == "\xFF\xFE") {
1197			return self::iconv_fallback_utf16le_utf8(substr($string, 2));
1198		}
1199		return $string;
1200	}
1201
1202	/**
1203	 * @param string $in_charset
1204	 * @param string $out_charset
1205	 * @param string $string
1206	 *
1207	 * @return string
1208	 * @throws Exception
1209	 */
1210	public static function iconv_fallback($in_charset, $out_charset, $string) {
1211
1212		if ($in_charset == $out_charset) {
1213			return $string;
1214		}
1215
1216		// mb_convert_encoding() available
1217		if (function_exists('mb_convert_encoding')) {
1218			if ((strtoupper($in_charset) == 'UTF-16') && (substr($string, 0, 2) != "\xFE\xFF") && (substr($string, 0, 2) != "\xFF\xFE")) {
1219				// if BOM missing, mb_convert_encoding will mishandle the conversion, assume UTF-16BE and prepend appropriate BOM
1220				$string = "\xFF\xFE".$string;
1221			}
1222			if ((strtoupper($in_charset) == 'UTF-16') && (strtoupper($out_charset) == 'UTF-8')) {
1223				if (($string == "\xFF\xFE") || ($string == "\xFE\xFF")) {
1224					// if string consists of only BOM, mb_convert_encoding will return the BOM unmodified
1225					return '';
1226				}
1227			}
1228			if ($converted_string = @mb_convert_encoding($string, $out_charset, $in_charset)) {
1229				switch ($out_charset) {
1230					case 'ISO-8859-1':
1231						$converted_string = rtrim($converted_string, "\x00");
1232						break;
1233				}
1234				return $converted_string;
1235			}
1236			return $string;
1237
1238		// iconv() available
1239		} elseif (function_exists('iconv')) {
1240			if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
1241				switch ($out_charset) {
1242					case 'ISO-8859-1':
1243						$converted_string = rtrim($converted_string, "\x00");
1244						break;
1245				}
1246				return $converted_string;
1247			}
1248
1249			// iconv() may sometimes fail with "illegal character in input string" error message
1250			// and return an empty string, but returning the unconverted string is more useful
1251			return $string;
1252		}
1253
1254
1255		// neither mb_convert_encoding or iconv() is available
1256		static $ConversionFunctionList = array();
1257		if (empty($ConversionFunctionList)) {
1258			$ConversionFunctionList['ISO-8859-1']['UTF-8']    = 'iconv_fallback_iso88591_utf8';
1259			$ConversionFunctionList['ISO-8859-1']['UTF-16']   = 'iconv_fallback_iso88591_utf16';
1260			$ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
1261			$ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
1262			$ConversionFunctionList['UTF-8']['ISO-8859-1']    = 'iconv_fallback_utf8_iso88591';
1263			$ConversionFunctionList['UTF-8']['UTF-16']        = 'iconv_fallback_utf8_utf16';
1264			$ConversionFunctionList['UTF-8']['UTF-16BE']      = 'iconv_fallback_utf8_utf16be';
1265			$ConversionFunctionList['UTF-8']['UTF-16LE']      = 'iconv_fallback_utf8_utf16le';
1266			$ConversionFunctionList['UTF-16']['ISO-8859-1']   = 'iconv_fallback_utf16_iso88591';
1267			$ConversionFunctionList['UTF-16']['UTF-8']        = 'iconv_fallback_utf16_utf8';
1268			$ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
1269			$ConversionFunctionList['UTF-16LE']['UTF-8']      = 'iconv_fallback_utf16le_utf8';
1270			$ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
1271			$ConversionFunctionList['UTF-16BE']['UTF-8']      = 'iconv_fallback_utf16be_utf8';
1272		}
1273		if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
1274			$ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
1275			return self::$ConversionFunction($string);
1276		}
1277		throw new Exception('PHP does not has mb_convert_encoding() or iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
1278	}
1279
1280	/**
1281	 * @param mixed  $data
1282	 * @param string $charset
1283	 *
1284	 * @return mixed
1285	 */
1286	public static function recursiveMultiByteCharString2HTML($data, $charset='ISO-8859-1') {
1287		if (is_string($data)) {
1288			return self::MultiByteCharString2HTML($data, $charset);
1289		} elseif (is_array($data)) {
1290			$return_data = array();
1291			foreach ($data as $key => $value) {
1292				$return_data[$key] = self::recursiveMultiByteCharString2HTML($value, $charset);
1293			}
1294			return $return_data;
1295		}
1296		// integer, float, objects, resources, etc
1297		return $data;
1298	}
1299
1300	/**
1301	 * @param string|int|float $string
1302	 * @param string           $charset
1303	 *
1304	 * @return string
1305	 */
1306	public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
1307		$string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
1308		$HTMLstring = '';
1309
1310		switch (strtolower($charset)) {
1311			case '1251':
1312			case '1252':
1313			case '866':
1314			case '932':
1315			case '936':
1316			case '950':
1317			case 'big5':
1318			case 'big5-hkscs':
1319			case 'cp1251':
1320			case 'cp1252':
1321			case 'cp866':
1322			case 'euc-jp':
1323			case 'eucjp':
1324			case 'gb2312':
1325			case 'ibm866':
1326			case 'iso-8859-1':
1327			case 'iso-8859-15':
1328			case 'iso8859-1':
1329			case 'iso8859-15':
1330			case 'koi8-r':
1331			case 'koi8-ru':
1332			case 'koi8r':
1333			case 'shift_jis':
1334			case 'sjis':
1335			case 'win-1251':
1336			case 'windows-1251':
1337			case 'windows-1252':
1338				$HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
1339				break;
1340
1341			case 'utf-8':
1342				$strlen = strlen($string);
1343				for ($i = 0; $i < $strlen; $i++) {
1344					$char_ord_val = ord($string[$i]);
1345					$charval = 0;
1346					if ($char_ord_val < 0x80) {
1347						$charval = $char_ord_val;
1348					} elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F  &&  $i+3 < $strlen) {
1349						$charval  = (($char_ord_val & 0x07) << 18);
1350						$charval += ((ord($string[++$i]) & 0x3F) << 12);
1351						$charval += ((ord($string[++$i]) & 0x3F) << 6);
1352						$charval +=  (ord($string[++$i]) & 0x3F);
1353					} elseif ((($char_ord_val & 0xE0) >> 5) == 0x07  &&  $i+2 < $strlen) {
1354						$charval  = (($char_ord_val & 0x0F) << 12);
1355						$charval += ((ord($string[++$i]) & 0x3F) << 6);
1356						$charval +=  (ord($string[++$i]) & 0x3F);
1357					} elseif ((($char_ord_val & 0xC0) >> 6) == 0x03  &&  $i+1 < $strlen) {
1358						$charval  = (($char_ord_val & 0x1F) << 6);
1359						$charval += (ord($string[++$i]) & 0x3F);
1360					}
1361					if (($charval >= 32) && ($charval <= 127)) {
1362						$HTMLstring .= htmlentities(chr($charval));
1363					} else {
1364						$HTMLstring .= '&#'.$charval.';';
1365					}
1366				}
1367				break;
1368
1369			case 'utf-16le':
1370				for ($i = 0; $i < strlen($string); $i += 2) {
1371					$charval = self::LittleEndian2Int(substr($string, $i, 2));
1372					if (($charval >= 32) && ($charval <= 127)) {
1373						$HTMLstring .= chr($charval);
1374					} else {
1375						$HTMLstring .= '&#'.$charval.';';
1376					}
1377				}
1378				break;
1379
1380			case 'utf-16be':
1381				for ($i = 0; $i < strlen($string); $i += 2) {
1382					$charval = self::BigEndian2Int(substr($string, $i, 2));
1383					if (($charval >= 32) && ($charval <= 127)) {
1384						$HTMLstring .= chr($charval);
1385					} else {
1386						$HTMLstring .= '&#'.$charval.';';
1387					}
1388				}
1389				break;
1390
1391			default:
1392				$HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
1393				break;
1394		}
1395		return $HTMLstring;
1396	}
1397
1398	/**
1399	 * @param int $namecode
1400	 *
1401	 * @return string
1402	 */
1403	public static function RGADnameLookup($namecode) {
1404		static $RGADname = array();
1405		if (empty($RGADname)) {
1406			$RGADname[0] = 'not set';
1407			$RGADname[1] = 'Track Gain Adjustment';
1408			$RGADname[2] = 'Album Gain Adjustment';
1409		}
1410
1411		return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
1412	}
1413
1414	/**
1415	 * @param int $originatorcode
1416	 *
1417	 * @return string
1418	 */
1419	public static function RGADoriginatorLookup($originatorcode) {
1420		static $RGADoriginator = array();
1421		if (empty($RGADoriginator)) {
1422			$RGADoriginator[0] = 'unspecified';
1423			$RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
1424			$RGADoriginator[2] = 'set by user';
1425			$RGADoriginator[3] = 'determined automatically';
1426		}
1427
1428		return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
1429	}
1430
1431	/**
1432	 * @param int $rawadjustment
1433	 * @param int $signbit
1434	 *
1435	 * @return float
1436	 */
1437	public static function RGADadjustmentLookup($rawadjustment, $signbit) {
1438		$adjustment = (float) $rawadjustment / 10;
1439		if ($signbit == 1) {
1440			$adjustment *= -1;
1441		}
1442		return $adjustment;
1443	}
1444
1445	/**
1446	 * @param int $namecode
1447	 * @param int $originatorcode
1448	 * @param int $replaygain
1449	 *
1450	 * @return string
1451	 */
1452	public static function RGADgainString($namecode, $originatorcode, $replaygain) {
1453		if ($replaygain < 0) {
1454			$signbit = '1';
1455		} else {
1456			$signbit = '0';
1457		}
1458		$storedreplaygain = intval(round($replaygain * 10));
1459		$gainstring  = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
1460		$gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
1461		$gainstring .= $signbit;
1462		$gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
1463
1464		return $gainstring;
1465	}
1466
1467	/**
1468	 * @param float $amplitude
1469	 *
1470	 * @return float
1471	 */
1472	public static function RGADamplitude2dB($amplitude) {
1473		return 20 * log10($amplitude);
1474	}
1475
1476	/**
1477	 * @param string $imgData
1478	 * @param array  $imageinfo
1479	 *
1480	 * @return array|false
1481	 */
1482	public static function GetDataImageSize($imgData, &$imageinfo=array()) {
1483		if (PHP_VERSION_ID >= 50400) {
1484			$GetDataImageSize = @getimagesizefromstring($imgData, $imageinfo);
1485			if ($GetDataImageSize === false || !isset($GetDataImageSize[0], $GetDataImageSize[1])) {
1486				return false;
1487			}
1488			$GetDataImageSize['height'] = $GetDataImageSize[0];
1489			$GetDataImageSize['width'] = $GetDataImageSize[1];
1490			return $GetDataImageSize;
1491		}
1492		static $tempdir = '';
1493		if (empty($tempdir)) {
1494			if (function_exists('sys_get_temp_dir')) {
1495				$tempdir = sys_get_temp_dir(); // https://github.com/JamesHeinrich/getID3/issues/52
1496			}
1497
1498			// yes this is ugly, feel free to suggest a better way
1499			if (include_once(dirname(__FILE__).'/getid3.php')) {
1500				$getid3_temp = new getID3();
1501				if ($getid3_temp_tempdir = $getid3_temp->tempdir) {
1502					$tempdir = $getid3_temp_tempdir;
1503				}
1504				unset($getid3_temp, $getid3_temp_tempdir);
1505			}
1506		}
1507		$GetDataImageSize = false;
1508		if ($tempfilename = tempnam($tempdir, 'gI3')) {
1509			if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
1510				fwrite($tmp, $imgData);
1511				fclose($tmp);
1512				$GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
1513				if (($GetDataImageSize === false) || !isset($GetDataImageSize[0]) || !isset($GetDataImageSize[1])) {
1514					return false;
1515				}
1516				$GetDataImageSize['height'] = $GetDataImageSize[0];
1517				$GetDataImageSize['width']  = $GetDataImageSize[1];
1518			}
1519			unlink($tempfilename);
1520		}
1521		return $GetDataImageSize;
1522	}
1523
1524	/**
1525	 * @param string $mime_type
1526	 *
1527	 * @return string
1528	 */
1529	public static function ImageExtFromMime($mime_type) {
1530		// temporary way, works OK for now, but should be reworked in the future
1531		return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
1532	}
1533
1534	/**
1535	 * @param array $ThisFileInfo
1536	 * @param bool  $option_tags_html default true (just as in the main getID3 class)
1537	 *
1538	 * @return bool
1539	 */
1540	public static function CopyTagsToComments(&$ThisFileInfo, $option_tags_html=true) {
1541		// Copy all entries from ['tags'] into common ['comments']
1542		if (!empty($ThisFileInfo['tags'])) {
1543			if (isset($ThisFileInfo['tags']['id3v1'])) {
1544				// bubble ID3v1 to the end, if present to aid in detecting bad ID3v1 encodings
1545				$ID3v1 = $ThisFileInfo['tags']['id3v1'];
1546				unset($ThisFileInfo['tags']['id3v1']);
1547				$ThisFileInfo['tags']['id3v1'] = $ID3v1;
1548				unset($ID3v1);
1549			}
1550			foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
1551				foreach ($tagarray as $tagname => $tagdata) {
1552					foreach ($tagdata as $key => $value) {
1553						if (!empty($value)) {
1554							if (empty($ThisFileInfo['comments'][$tagname])) {
1555
1556								// fall through and append value
1557
1558							} elseif ($tagtype == 'id3v1') {
1559
1560								$newvaluelength = strlen(trim($value));
1561								foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1562									$oldvaluelength = strlen(trim($existingvalue));
1563									if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
1564										// new value is identical but shorter-than (or equal-length to) one already in comments - skip
1565										break 2;
1566									}
1567
1568									if (function_exists('mb_convert_encoding')) {
1569										if (trim($value) == trim(substr(mb_convert_encoding($existingvalue, $ThisFileInfo['id3v1']['encoding'], $ThisFileInfo['encoding']), 0, 30))) {
1570											// value stored in ID3v1 appears to be probably the multibyte value transliterated (badly) into ISO-8859-1 in ID3v1.
1571											// As an example, Foobar2000 will do this if you tag a file with Chinese or Arabic or Cyrillic or something that doesn't fit into ISO-8859-1 the ID3v1 will consist of mostly "?" characters, one per multibyte unrepresentable character
1572											break 2;
1573										}
1574									}
1575								}
1576
1577							} elseif (!is_array($value)) {
1578
1579								$newvaluelength = strlen(trim($value));
1580								foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1581									$oldvaluelength = strlen(trim($existingvalue));
1582									if ((strlen($existingvalue) > 10) && ($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
1583										$ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
1584										break;
1585									}
1586								}
1587
1588							}
1589							if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
1590								$value = (is_string($value) ? trim($value) : $value);
1591								if (!is_int($key) && !ctype_digit($key)) {
1592									$ThisFileInfo['comments'][$tagname][$key] = $value;
1593								} else {
1594									if (!isset($ThisFileInfo['comments'][$tagname])) {
1595										$ThisFileInfo['comments'][$tagname] = array($value);
1596									} else {
1597										$ThisFileInfo['comments'][$tagname][] = $value;
1598									}
1599								}
1600							}
1601						}
1602					}
1603				}
1604			}
1605
1606			// attempt to standardize spelling of returned keys
1607			if (!empty($ThisFileInfo['comments'])) {
1608				$StandardizeFieldNames = array(
1609					'tracknumber' => 'track_number',
1610					'track'       => 'track_number',
1611				);
1612				foreach ($StandardizeFieldNames as $badkey => $goodkey) {
1613					if (array_key_exists($badkey, $ThisFileInfo['comments']) && !array_key_exists($goodkey, $ThisFileInfo['comments'])) {
1614						$ThisFileInfo['comments'][$goodkey] = $ThisFileInfo['comments'][$badkey];
1615						unset($ThisFileInfo['comments'][$badkey]);
1616					}
1617				}
1618			}
1619
1620			if ($option_tags_html) {
1621				// Copy ['comments'] to ['comments_html']
1622				if (!empty($ThisFileInfo['comments'])) {
1623					foreach ($ThisFileInfo['comments'] as $field => $values) {
1624						if ($field == 'picture') {
1625							// pictures can take up a lot of space, and we don't need multiple copies of them
1626							// let there be a single copy in [comments][picture], and not elsewhere
1627							continue;
1628						}
1629						foreach ($values as $index => $value) {
1630							if (is_array($value)) {
1631								$ThisFileInfo['comments_html'][$field][$index] = $value;
1632							} else {
1633								$ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
1634							}
1635						}
1636					}
1637				}
1638			}
1639
1640		}
1641		return true;
1642	}
1643
1644	/**
1645	 * @param string $key
1646	 * @param int    $begin
1647	 * @param int    $end
1648	 * @param string $file
1649	 * @param string $name
1650	 *
1651	 * @return string
1652	 */
1653	public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
1654
1655		// Cached
1656		static $cache;
1657		if (isset($cache[$file][$name])) {
1658			return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1659		}
1660
1661		// Init
1662		$keylength  = strlen($key);
1663		$line_count = $end - $begin - 7;
1664
1665		// Open php file
1666		$fp = fopen($file, 'r');
1667
1668		// Discard $begin lines
1669		for ($i = 0; $i < ($begin + 3); $i++) {
1670			fgets($fp, 1024);
1671		}
1672
1673		// Loop thru line
1674		while (0 < $line_count--) {
1675
1676			// Read line
1677			$line = ltrim(fgets($fp, 1024), "\t ");
1678
1679			// METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
1680			//$keycheck = substr($line, 0, $keylength);
1681			//if ($key == $keycheck)  {
1682			//	$cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
1683			//	break;
1684			//}
1685
1686			// METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
1687			//$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
1688			$explodedLine = explode("\t", $line, 2);
1689			$ThisKey   = (isset($explodedLine[0]) ? $explodedLine[0] : '');
1690			$ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
1691			$cache[$file][$name][$ThisKey] = trim($ThisValue);
1692		}
1693
1694		// Close and return
1695		fclose($fp);
1696		return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1697	}
1698
1699	/**
1700	 * @param string $filename
1701	 * @param string $sourcefile
1702	 * @param bool   $DieOnFailure
1703	 *
1704	 * @return bool
1705	 * @throws Exception
1706	 */
1707	public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
1708		global $GETID3_ERRORARRAY;
1709
1710		if (file_exists($filename)) {
1711			if (include_once($filename)) {
1712				return true;
1713			} else {
1714				$diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
1715			}
1716		} else {
1717			$diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
1718		}
1719		if ($DieOnFailure) {
1720			throw new Exception($diemessage);
1721		} else {
1722			$GETID3_ERRORARRAY[] = $diemessage;
1723		}
1724		return false;
1725	}
1726
1727	/**
1728	 * @param string $string
1729	 *
1730	 * @return string
1731	 */
1732	public static function trimNullByte($string) {
1733		return trim($string, "\x00");
1734	}
1735
1736	/**
1737	 * @param string $path
1738	 *
1739	 * @return float|bool
1740	 */
1741	public static function getFileSizeSyscall($path) {
1742		$commandline = null;
1743		$filesize = false;
1744
1745		if (GETID3_OS_ISWINDOWS) {
1746			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:
1747				$filesystem = new COM('Scripting.FileSystemObject');
1748				$file = $filesystem->GetFile($path);
1749				$filesize = $file->Size();
1750				unset($filesystem, $file);
1751			} else {
1752				$commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
1753			}
1754		} else {
1755			$commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
1756		}
1757		if (isset($commandline)) {
1758			$output = trim(`$commandline`);
1759			if (ctype_digit($output)) {
1760				$filesize = (float) $output;
1761			}
1762		}
1763		return $filesize;
1764	}
1765
1766	/**
1767	 * @param string $filename
1768	 *
1769	 * @return string|false
1770	 */
1771	public static function truepath($filename) {
1772		// 2017-11-08: this could use some improvement, patches welcome
1773		if (preg_match('#^(\\\\\\\\|//)[a-z0-9]#i', $filename, $matches)) {
1774			// PHP's built-in realpath function does not work on UNC Windows shares
1775			$goodpath = array();
1776			foreach (explode('/', str_replace('\\', '/', $filename)) as $part) {
1777				if ($part == '.') {
1778					continue;
1779				}
1780				if ($part == '..') {
1781					if (count($goodpath)) {
1782						array_pop($goodpath);
1783					} else {
1784						// cannot step above this level, already at top level
1785						return false;
1786					}
1787				} else {
1788					$goodpath[] = $part;
1789				}
1790			}
1791			return implode(DIRECTORY_SEPARATOR, $goodpath);
1792		}
1793		return realpath($filename);
1794	}
1795
1796	/**
1797	 * Workaround for Bug #37268 (https://bugs.php.net/bug.php?id=37268)
1798	 *
1799	 * @param string $path A path.
1800	 * @param string $suffix If the name component ends in suffix this will also be cut off.
1801	 *
1802	 * @return string
1803	 */
1804	public static function mb_basename($path, $suffix = null) {
1805		$splited = preg_split('#/#', rtrim($path, '/ '));
1806		return substr(basename('X'.$splited[count($splited) - 1], $suffix), 1);
1807	}
1808
1809}
1810