PageRenderTime 89ms CodeModel.GetById 10ms app.highlight 69ms RepoModel.GetById 2ms app.codeStats 0ms

/blog/wp-content/plugins/podpress/getid3/getid3.lib.php

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