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