PageRenderTime 70ms CodeModel.GetById 11ms app.highlight 48ms RepoModel.GetById 1ms app.codeStats 1ms

/MediaGallery-master/include/lib/getid3/getid3.lib.php

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