2
/////////////////////////////////////////////////////////////////
3
/// getID3() by James Heinrich <info@getid3.org> //
4
// available at http://getid3.sourceforge.net //
5
// or http://www.getid3.org //
6
/////////////////////////////////////////////////////////////////
8
// getid3.lib.php - part of getID3() //
9
// See readme.txt for more details //
11
/////////////////////////////////////////////////////////////////
17
public static function PrintHexBytes($string, $hex=true, $spaces=true, $htmlencoding='UTF-8') {
19
for ($i = 0; $i < strlen($string); $i++) {
21
$returnstring .= str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
23
$returnstring .= ' '.(preg_match("#[\x20-\x7E]#", $string{$i}) ? $string{$i} : '¤');
29
if (!empty($htmlencoding)) {
30
if ($htmlencoding === true) {
31
$htmlencoding = 'UTF-8'; // prior to getID3 v1.9.0 the function's 4th parameter was boolean
33
$returnstring = htmlentities($returnstring, ENT_QUOTES, $htmlencoding);
38
public static function trunc($floatnumber) {
39
// truncates a floating-point number at the decimal point
40
// returns int (if possible, otherwise float)
41
if ($floatnumber >= 1) {
42
$truncatednumber = floor($floatnumber);
43
} elseif ($floatnumber <= -1) {
44
$truncatednumber = ceil($floatnumber);
48
if (self::intValueSupported($truncatednumber)) {
49
$truncatednumber = (int) $truncatednumber;
51
return $truncatednumber;
55
public static function safe_inc(&$variable, $increment=1) {
56
if (isset($variable)) {
57
$variable += $increment;
59
$variable = $increment;
64
public static function CastAsInt($floatnum) {
65
// convert to float if not already
66
$floatnum = (float) $floatnum;
68
// convert a float to type int, only if possible
69
if (self::trunc($floatnum) == $floatnum) {
70
// it's not floating point
71
if (self::intValueSupported($floatnum)) {
72
// it's within int range
73
$floatnum = (int) $floatnum;
79
public static function intValueSupported($num) {
80
// check if integers are 64-bit
81
static $hasINT64 = null;
82
if ($hasINT64 === null) { // 10x faster than is_null()
83
$hasINT64 = is_int(pow(2, 31)); // 32-bit int are limited to (2^31)-1
84
if (!$hasINT64 && !defined('PHP_INT_MIN')) {
85
define('PHP_INT_MIN', ~PHP_INT_MAX);
88
// if integers are 64-bit - no other check required
89
if ($hasINT64 || (($num <= PHP_INT_MAX) && ($num >= PHP_INT_MIN))) {
95
public static function DecimalizeFraction($fraction) {
96
list($numerator, $denominator) = explode('/', $fraction);
97
return $numerator / ($denominator ? $denominator : 1);
101
public static function DecimalBinary2Float($binarynumerator) {
102
$numerator = self::Bin2Dec($binarynumerator);
103
$denominator = self::Bin2Dec('1'.str_repeat('0', strlen($binarynumerator)));
104
return ($numerator / $denominator);
108
public static function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) {
109
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
110
if (strpos($binarypointnumber, '.') === false) {
111
$binarypointnumber = '0.'.$binarypointnumber;
112
} elseif ($binarypointnumber{0} == '.') {
113
$binarypointnumber = '0'.$binarypointnumber;
116
while (($binarypointnumber{0} != '1') || (substr($binarypointnumber, 1, 1) != '.')) {
117
if (substr($binarypointnumber, 1, 1) == '.') {
119
$binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3);
121
$pointpos = strpos($binarypointnumber, '.');
122
$exponent += ($pointpos - 1);
123
$binarypointnumber = str_replace('.', '', $binarypointnumber);
124
$binarypointnumber = $binarypointnumber{0}.'.'.substr($binarypointnumber, 1);
127
$binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT);
128
return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent);
132
public static function Float2BinaryDecimal($floatvalue) {
133
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
134
$maxbits = 128; // to how many bits of precision should the calculations be taken?
135
$intpart = self::trunc($floatvalue);
136
$floatpart = abs($floatvalue - $intpart);
137
$pointbitstring = '';
138
while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) {
140
$pointbitstring .= (string) self::trunc($floatpart);
141
$floatpart -= self::trunc($floatpart);
143
$binarypointnumber = decbin($intpart).'.'.$pointbitstring;
144
return $binarypointnumber;
148
public static function Float2String($floatvalue, $bits) {
149
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html
165
if ($floatvalue >= 0) {
170
$normalizedbinary = self::NormalizeBinaryPoint(self::Float2BinaryDecimal($floatvalue), $fractionbits);
171
$biasedexponent = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent
172
$exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT);
173
$fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT);
175
return self::BigEndian2String(self::Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false);
179
public static function LittleEndian2Float($byteword) {
180
return self::BigEndian2Float(strrev($byteword));
184
public static function BigEndian2Float($byteword) {
185
// ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic
186
// http://www.psc.edu/general/software/packages/ieee/ieee.html
187
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html
189
$bitword = self::BigEndian2Bin($byteword);
193
$signbit = $bitword{0};
195
switch (strlen($byteword) * 8) {
207
// 80-bit Apple SANE format
208
// http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/
209
$exponentstring = substr($bitword, 1, 15);
210
$isnormalized = intval($bitword{16});
211
$fractionstring = substr($bitword, 17, 63);
212
$exponent = pow(2, self::Bin2Dec($exponentstring) - 16383);
213
$fraction = $isnormalized + self::DecimalBinary2Float($fractionstring);
214
$floatvalue = $exponent * $fraction;
215
if ($signbit == '1') {
225
$exponentstring = substr($bitword, 1, $exponentbits);
226
$fractionstring = substr($bitword, $exponentbits + 1, $fractionbits);
227
$exponent = self::Bin2Dec($exponentstring);
228
$fraction = self::Bin2Dec($fractionstring);
230
if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) {
233
} elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) {
234
if ($signbit == '1') {
235
$floatvalue = '-infinity';
237
$floatvalue = '+infinity';
239
} elseif (($exponent == 0) && ($fraction == 0)) {
240
if ($signbit == '1') {
245
$floatvalue = ($signbit ? 0 : -0);
246
} elseif (($exponent == 0) && ($fraction != 0)) {
247
// These are 'unnormalized' values
248
$floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * self::DecimalBinary2Float($fractionstring);
249
if ($signbit == '1') {
252
} elseif ($exponent != 0) {
253
$floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + self::DecimalBinary2Float($fractionstring));
254
if ($signbit == '1') {
258
return (float) $floatvalue;
262
public static function BigEndian2Int($byteword, $synchsafe=false, $signed=false) {
264
$bytewordlen = strlen($byteword);
265
if ($bytewordlen == 0) {
268
for ($i = 0; $i < $bytewordlen; $i++) {
269
if ($synchsafe) { // disregard MSB, effectively 7-bit bytes
270
//$intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); // faster, but runs into problems past 2^31 on 32-bit systems
271
$intvalue += (ord($byteword{$i}) & 0x7F) * pow(2, ($bytewordlen - 1 - $i) * 7);
273
$intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i));
276
if ($signed && !$synchsafe) {
277
// synchsafe ints are not allowed to be signed
278
if ($bytewordlen <= PHP_INT_SIZE) {
279
$signMaskBit = 0x80 << (8 * ($bytewordlen - 1));
280
if ($intvalue & $signMaskBit) {
281
$intvalue = 0 - ($intvalue & ($signMaskBit - 1));
284
throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits ('.strlen($byteword).') in self::BigEndian2Int()');
288
return self::CastAsInt($intvalue);
292
public static function LittleEndian2Int($byteword, $signed=false) {
293
return self::BigEndian2Int(strrev($byteword), false, $signed);
297
public static function BigEndian2Bin($byteword) {
299
$bytewordlen = strlen($byteword);
300
for ($i = 0; $i < $bytewordlen; $i++) {
301
$binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
307
public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
309
throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
311
$maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
314
if ($minbytes > PHP_INT_SIZE) {
315
throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
317
$number = $number & (0x80 << (8 * ($minbytes - 1)));
319
while ($number != 0) {
320
$quotient = ($number / ($maskbyte + 1));
321
$intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
322
$number = floor($quotient);
324
return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
328
public static function Dec2Bin($number) {
329
while ($number >= 256) {
330
$bytes[] = (($number / 256) - (floor($number / 256))) * 256;
331
$number = floor($number / 256);
335
for ($i = 0; $i < count($bytes); $i++) {
336
$binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring;
342
public static function Bin2Dec($binstring, $signed=false) {
345
if ($binstring{0} == '1') {
348
$binstring = substr($binstring, 1);
351
for ($i = 0; $i < strlen($binstring); $i++) {
352
$decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
354
return self::CastAsInt($decvalue * $signmult);
358
public static function Bin2String($binstring) {
359
// return 'hi' for input of '0110100001101001'
361
$binstringreversed = strrev($binstring);
362
for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
363
$string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
369
public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
371
while ($number > 0) {
373
$intstring = $intstring.chr($number & 127);
376
$intstring = $intstring.chr($number & 255);
380
return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
384
public static function array_merge_clobber($array1, $array2) {
385
// written by kcØhireability*com
386
// taken from http://www.php.net/manual/en/function.array-merge-recursive.php
387
if (!is_array($array1) || !is_array($array2)) {
391
foreach ($array2 as $key => $val) {
392
if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
393
$newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
395
$newarray[$key] = $val;
402
public static function array_merge_noclobber($array1, $array2) {
403
if (!is_array($array1) || !is_array($array2)) {
407
foreach ($array2 as $key => $val) {
408
if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
409
$newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
410
} elseif (!isset($newarray[$key])) {
411
$newarray[$key] = $val;
418
public static function ksort_recursive(&$theArray) {
420
foreach ($theArray as $key => $value) {
421
if (is_array($value)) {
422
self::ksort_recursive($theArray[$key]);
428
public static function fileextension($filename, $numextensions=1) {
429
if (strstr($filename, '.')) {
430
$reversedfilename = strrev($filename);
432
for ($i = 0; $i < $numextensions; $i++) {
433
$offset = strpos($reversedfilename, '.', $offset + 1);
434
if ($offset === false) {
438
return strrev(substr($reversedfilename, 0, $offset));
444
public static function PlaytimeString($seconds) {
445
$sign = (($seconds < 0) ? '-' : '');
446
$seconds = round(abs($seconds));
447
$H = (int) floor( $seconds / 3600);
448
$M = (int) floor(($seconds - (3600 * $H) ) / 60);
449
$S = (int) round( $seconds - (3600 * $H) - (60 * $M) );
450
return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
454
public static function DateMac2Unix($macdate) {
455
// Macintosh timestamp: seconds since 00:00h January 1, 1904
456
// UNIX timestamp: seconds since 00:00h January 1, 1970
457
return self::CastAsInt($macdate - 2082844800);
461
public static function FixedPoint8_8($rawdata) {
462
return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
466
public static function FixedPoint16_16($rawdata) {
467
return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
471
public static function FixedPoint2_30($rawdata) {
472
$binarystring = self::BigEndian2Bin($rawdata);
473
return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
477
public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
478
// assigns $Value to a nested array path:
479
// $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
481
// $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
483
// $foo['path']['to']['my'] = 'file.txt';
484
$ArrayPath = ltrim($ArrayPath, $Separator);
485
if (($pos = strpos($ArrayPath, $Separator)) !== false) {
486
$ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
488
$ReturnedArray[$ArrayPath] = $Value;
490
return $ReturnedArray;
493
public static function array_max($arraydata, $returnkey=false) {
496
foreach ($arraydata as $key => $value) {
497
if (!is_array($value)) {
498
if ($value > $maxvalue) {
504
return ($returnkey ? $maxkey : $maxvalue);
507
public static function array_min($arraydata, $returnkey=false) {
510
foreach ($arraydata as $key => $value) {
511
if (!is_array($value)) {
512
if ($value > $minvalue) {
518
return ($returnkey ? $minkey : $minvalue);
521
public static function XML2array($XMLstring) {
522
if ( function_exists( 'simplexml_load_string' ) && function_exists( 'libxml_disable_entity_loader' ) ) {
523
$loader = libxml_disable_entity_loader( true );
524
$XMLobject = simplexml_load_string( $XMLstring, 'SimpleXMLElement', LIBXML_NOENT );
525
$return = self::SimpleXMLelement2array( $XMLobject );
526
libxml_disable_entity_loader( $loader );
532
public static function SimpleXMLelement2array($XMLobject) {
533
if (!is_object($XMLobject) && !is_array($XMLobject)) {
536
$XMLarray = (is_object($XMLobject) ? get_object_vars($XMLobject) : $XMLobject);
537
foreach ($XMLarray as $key => $value) {
538
$XMLarray[$key] = self::SimpleXMLelement2array($value);
544
// Allan Hansen <ahØartemis*dk>
545
// self::md5_data() - returns md5sum for a file from startuing position to absolute end position
546
public static function hash_data($file, $offset, $end, $algorithm) {
547
static $tempdir = '';
548
if (!self::intValueSupported($end)) {
551
switch ($algorithm) {
553
$hash_function = 'md5_file';
554
$unix_call = 'md5sum';
555
$windows_call = 'md5sum.exe';
560
$hash_function = 'sha1_file';
561
$unix_call = 'sha1sum';
562
$windows_call = 'sha1sum.exe';
567
throw new Exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
570
$size = $end - $offset;
572
if (GETID3_OS_ISWINDOWS) {
574
// It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
575
// Fall back to create-temp-file method:
576
if ($algorithm == 'sha1') {
580
$RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
581
foreach ($RequiredFiles as $required_file) {
582
if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
583
// helper apps not available - fall back to old method
587
$commandline = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' '.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).' | ';
588
$commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
589
$commandline .= GETID3_HELPERAPPSDIR.$windows_call;
593
$commandline = 'head -c'.$end.' '.escapeshellarg($file).' | ';
594
$commandline .= 'tail -c'.$size.' | ';
595
$commandline .= $unix_call;
598
if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
599
//throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
602
return substr(`$commandline`, 0, $hash_length);
605
if (empty($tempdir)) {
606
// yes this is ugly, feel free to suggest a better way
607
require_once(dirname(__FILE__).'/getid3.php');
608
$getid3_temp = new getID3();
609
$tempdir = $getid3_temp->tempdir;
612
// try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
613
if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
614
// can't find anywhere to create a temp file, just fail
621
// copy parts of file
623
self::CopyFileParts($file, $data_filename, $offset, $end - $offset);
624
$result = $hash_function($data_filename);
625
} catch (Exception $e) {
626
throw new Exception('self::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
628
unlink($data_filename);
632
public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
633
if (!self::intValueSupported($offset + $length)) {
634
throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
636
if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
637
if (($fp_dest = fopen($filename_dest, 'wb'))) {
638
if (fseek($fp_src, $offset, SEEK_SET) == 0) {
639
$byteslefttowrite = $length;
640
while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
641
$byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
642
$byteslefttowrite -= $byteswritten;
646
throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
650
throw new Exception('failed to create file for writing '.$filename_dest);
654
throw new Exception('failed to open file for reading '.$filename_source);
659
public static function iconv_fallback_int_utf8($charval) {
660
if ($charval < 128) {
662
$newcharstring = chr($charval);
663
} elseif ($charval < 2048) {
665
$newcharstring = chr(($charval >> 6) | 0xC0);
666
$newcharstring .= chr(($charval & 0x3F) | 0x80);
667
} elseif ($charval < 65536) {
668
// 1110bbbb 10bbbbbb 10bbbbbb
669
$newcharstring = chr(($charval >> 12) | 0xE0);
670
$newcharstring .= chr(($charval >> 6) | 0xC0);
671
$newcharstring .= chr(($charval & 0x3F) | 0x80);
673
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
674
$newcharstring = chr(($charval >> 18) | 0xF0);
675
$newcharstring .= chr(($charval >> 12) | 0xC0);
676
$newcharstring .= chr(($charval >> 6) | 0xC0);
677
$newcharstring .= chr(($charval & 0x3F) | 0x80);
679
return $newcharstring;
682
// ISO-8859-1 => UTF-8
683
public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
684
if (function_exists('utf8_encode')) {
685
return utf8_encode($string);
687
// utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
690
$newcharstring .= "\xEF\xBB\xBF";
692
for ($i = 0; $i < strlen($string); $i++) {
693
$charval = ord($string{$i});
694
$newcharstring .= self::iconv_fallback_int_utf8($charval);
696
return $newcharstring;
699
// ISO-8859-1 => UTF-16BE
700
public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
703
$newcharstring .= "\xFE\xFF";
705
for ($i = 0; $i < strlen($string); $i++) {
706
$newcharstring .= "\x00".$string{$i};
708
return $newcharstring;
711
// ISO-8859-1 => UTF-16LE
712
public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
715
$newcharstring .= "\xFF\xFE";
717
for ($i = 0; $i < strlen($string); $i++) {
718
$newcharstring .= $string{$i}."\x00";
720
return $newcharstring;
723
// ISO-8859-1 => UTF-16LE (BOM)
724
public static function iconv_fallback_iso88591_utf16($string) {
725
return self::iconv_fallback_iso88591_utf16le($string, true);
728
// UTF-8 => ISO-8859-1
729
public static function iconv_fallback_utf8_iso88591($string) {
730
if (function_exists('utf8_decode')) {
731
return utf8_decode($string);
733
// utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
736
$stringlength = strlen($string);
737
while ($offset < $stringlength) {
738
if ((ord($string{$offset}) | 0x07) == 0xF7) {
739
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
740
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
741
((ord($string{($offset + 1)}) & 0x3F) << 12) &
742
((ord($string{($offset + 2)}) & 0x3F) << 6) &
743
(ord($string{($offset + 3)}) & 0x3F);
745
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
746
// 1110bbbb 10bbbbbb 10bbbbbb
747
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
748
((ord($string{($offset + 1)}) & 0x3F) << 6) &
749
(ord($string{($offset + 2)}) & 0x3F);
751
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
753
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
754
(ord($string{($offset + 1)}) & 0x3F);
756
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
758
$charval = ord($string{$offset});
761
// error? throw some kind of warning here?
765
if ($charval !== false) {
766
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
769
return $newcharstring;
773
public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
776
$newcharstring .= "\xFE\xFF";
779
$stringlength = strlen($string);
780
while ($offset < $stringlength) {
781
if ((ord($string{$offset}) | 0x07) == 0xF7) {
782
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
783
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
784
((ord($string{($offset + 1)}) & 0x3F) << 12) &
785
((ord($string{($offset + 2)}) & 0x3F) << 6) &
786
(ord($string{($offset + 3)}) & 0x3F);
788
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
789
// 1110bbbb 10bbbbbb 10bbbbbb
790
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
791
((ord($string{($offset + 1)}) & 0x3F) << 6) &
792
(ord($string{($offset + 2)}) & 0x3F);
794
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
796
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
797
(ord($string{($offset + 1)}) & 0x3F);
799
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
801
$charval = ord($string{$offset});
804
// error? throw some kind of warning here?
808
if ($charval !== false) {
809
$newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
812
return $newcharstring;
816
public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
819
$newcharstring .= "\xFF\xFE";
822
$stringlength = strlen($string);
823
while ($offset < $stringlength) {
824
if ((ord($string{$offset}) | 0x07) == 0xF7) {
825
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
826
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
827
((ord($string{($offset + 1)}) & 0x3F) << 12) &
828
((ord($string{($offset + 2)}) & 0x3F) << 6) &
829
(ord($string{($offset + 3)}) & 0x3F);
831
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
832
// 1110bbbb 10bbbbbb 10bbbbbb
833
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
834
((ord($string{($offset + 1)}) & 0x3F) << 6) &
835
(ord($string{($offset + 2)}) & 0x3F);
837
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
839
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
840
(ord($string{($offset + 1)}) & 0x3F);
842
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
844
$charval = ord($string{$offset});
847
// error? maybe throw some warning here?
851
if ($charval !== false) {
852
$newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
855
return $newcharstring;
858
// UTF-8 => UTF-16LE (BOM)
859
public static function iconv_fallback_utf8_utf16($string) {
860
return self::iconv_fallback_utf8_utf16le($string, true);
864
public static function iconv_fallback_utf16be_utf8($string) {
865
if (substr($string, 0, 2) == "\xFE\xFF") {
867
$string = substr($string, 2);
870
for ($i = 0; $i < strlen($string); $i += 2) {
871
$charval = self::BigEndian2Int(substr($string, $i, 2));
872
$newcharstring .= self::iconv_fallback_int_utf8($charval);
874
return $newcharstring;
878
public static function iconv_fallback_utf16le_utf8($string) {
879
if (substr($string, 0, 2) == "\xFF\xFE") {
881
$string = substr($string, 2);
884
for ($i = 0; $i < strlen($string); $i += 2) {
885
$charval = self::LittleEndian2Int(substr($string, $i, 2));
886
$newcharstring .= self::iconv_fallback_int_utf8($charval);
888
return $newcharstring;
891
// UTF-16BE => ISO-8859-1
892
public static function iconv_fallback_utf16be_iso88591($string) {
893
if (substr($string, 0, 2) == "\xFE\xFF") {
895
$string = substr($string, 2);
898
for ($i = 0; $i < strlen($string); $i += 2) {
899
$charval = self::BigEndian2Int(substr($string, $i, 2));
900
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
902
return $newcharstring;
905
// UTF-16LE => ISO-8859-1
906
public static function iconv_fallback_utf16le_iso88591($string) {
907
if (substr($string, 0, 2) == "\xFF\xFE") {
909
$string = substr($string, 2);
912
for ($i = 0; $i < strlen($string); $i += 2) {
913
$charval = self::LittleEndian2Int(substr($string, $i, 2));
914
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
916
return $newcharstring;
919
// UTF-16 (BOM) => ISO-8859-1
920
public static function iconv_fallback_utf16_iso88591($string) {
921
$bom = substr($string, 0, 2);
922
if ($bom == "\xFE\xFF") {
923
return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
924
} elseif ($bom == "\xFF\xFE") {
925
return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
930
// UTF-16 (BOM) => UTF-8
931
public static function iconv_fallback_utf16_utf8($string) {
932
$bom = substr($string, 0, 2);
933
if ($bom == "\xFE\xFF") {
934
return self::iconv_fallback_utf16be_utf8(substr($string, 2));
935
} elseif ($bom == "\xFF\xFE") {
936
return self::iconv_fallback_utf16le_utf8(substr($string, 2));
941
public static function iconv_fallback($in_charset, $out_charset, $string) {
943
if ($in_charset == $out_charset) {
948
if (function_exists('iconv')) {
949
if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
950
switch ($out_charset) {
952
$converted_string = rtrim($converted_string, "\x00");
955
return $converted_string;
958
// iconv() may sometimes fail with "illegal character in input string" error message
959
// and return an empty string, but returning the unconverted string is more useful
964
// iconv() not available
965
static $ConversionFunctionList = array();
966
if (empty($ConversionFunctionList)) {
967
$ConversionFunctionList['ISO-8859-1']['UTF-8'] = 'iconv_fallback_iso88591_utf8';
968
$ConversionFunctionList['ISO-8859-1']['UTF-16'] = 'iconv_fallback_iso88591_utf16';
969
$ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
970
$ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
971
$ConversionFunctionList['UTF-8']['ISO-8859-1'] = 'iconv_fallback_utf8_iso88591';
972
$ConversionFunctionList['UTF-8']['UTF-16'] = 'iconv_fallback_utf8_utf16';
973
$ConversionFunctionList['UTF-8']['UTF-16BE'] = 'iconv_fallback_utf8_utf16be';
974
$ConversionFunctionList['UTF-8']['UTF-16LE'] = 'iconv_fallback_utf8_utf16le';
975
$ConversionFunctionList['UTF-16']['ISO-8859-1'] = 'iconv_fallback_utf16_iso88591';
976
$ConversionFunctionList['UTF-16']['UTF-8'] = 'iconv_fallback_utf16_utf8';
977
$ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
978
$ConversionFunctionList['UTF-16LE']['UTF-8'] = 'iconv_fallback_utf16le_utf8';
979
$ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
980
$ConversionFunctionList['UTF-16BE']['UTF-8'] = 'iconv_fallback_utf16be_utf8';
982
if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
983
$ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
984
return self::$ConversionFunction($string);
986
throw new Exception('PHP does not have iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
990
public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
991
$string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
1020
case 'Windows-1251':
1021
case 'Windows-1252':
1022
$HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
1026
$strlen = strlen($string);
1027
for ($i = 0; $i < $strlen; $i++) {
1028
$char_ord_val = ord($string{$i});
1030
if ($char_ord_val < 0x80) {
1031
$charval = $char_ord_val;
1032
} elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F && $i+3 < $strlen) {
1033
$charval = (($char_ord_val & 0x07) << 18);
1034
$charval += ((ord($string{++$i}) & 0x3F) << 12);
1035
$charval += ((ord($string{++$i}) & 0x3F) << 6);
1036
$charval += (ord($string{++$i}) & 0x3F);
1037
} elseif ((($char_ord_val & 0xE0) >> 5) == 0x07 && $i+2 < $strlen) {
1038
$charval = (($char_ord_val & 0x0F) << 12);
1039
$charval += ((ord($string{++$i}) & 0x3F) << 6);
1040
$charval += (ord($string{++$i}) & 0x3F);
1041
} elseif ((($char_ord_val & 0xC0) >> 6) == 0x03 && $i+1 < $strlen) {
1042
$charval = (($char_ord_val & 0x1F) << 6);
1043
$charval += (ord($string{++$i}) & 0x3F);
1045
if (($charval >= 32) && ($charval <= 127)) {
1046
$HTMLstring .= htmlentities(chr($charval));
1048
$HTMLstring .= '&#'.$charval.';';
1054
for ($i = 0; $i < strlen($string); $i += 2) {
1055
$charval = self::LittleEndian2Int(substr($string, $i, 2));
1056
if (($charval >= 32) && ($charval <= 127)) {
1057
$HTMLstring .= chr($charval);
1059
$HTMLstring .= '&#'.$charval.';';
1065
for ($i = 0; $i < strlen($string); $i += 2) {
1066
$charval = self::BigEndian2Int(substr($string, $i, 2));
1067
if (($charval >= 32) && ($charval <= 127)) {
1068
$HTMLstring .= chr($charval);
1070
$HTMLstring .= '&#'.$charval.';';
1076
$HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
1084
public static function RGADnameLookup($namecode) {
1085
static $RGADname = array();
1086
if (empty($RGADname)) {
1087
$RGADname[0] = 'not set';
1088
$RGADname[1] = 'Track Gain Adjustment';
1089
$RGADname[2] = 'Album Gain Adjustment';
1092
return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
1096
public static function RGADoriginatorLookup($originatorcode) {
1097
static $RGADoriginator = array();
1098
if (empty($RGADoriginator)) {
1099
$RGADoriginator[0] = 'unspecified';
1100
$RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
1101
$RGADoriginator[2] = 'set by user';
1102
$RGADoriginator[3] = 'determined automatically';
1105
return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
1109
public static function RGADadjustmentLookup($rawadjustment, $signbit) {
1110
$adjustment = $rawadjustment / 10;
1111
if ($signbit == 1) {
1114
return (float) $adjustment;
1118
public static function RGADgainString($namecode, $originatorcode, $replaygain) {
1119
if ($replaygain < 0) {
1124
$storedreplaygain = intval(round($replaygain * 10));
1125
$gainstring = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
1126
$gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
1127
$gainstring .= $signbit;
1128
$gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
1133
public static function RGADamplitude2dB($amplitude) {
1134
return 20 * log10($amplitude);
1138
public static function GetDataImageSize($imgData, &$imageinfo=array()) {
1139
static $tempdir = '';
1140
if (empty($tempdir)) {
1141
// yes this is ugly, feel free to suggest a better way
1142
require_once(dirname(__FILE__).'/getid3.php');
1143
$getid3_temp = new getID3();
1144
$tempdir = $getid3_temp->tempdir;
1145
unset($getid3_temp);
1147
$GetDataImageSize = false;
1148
if ($tempfilename = tempnam($tempdir, 'gI3')) {
1149
if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
1150
fwrite($tmp, $imgData);
1152
$GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
1154
unlink($tempfilename);
1156
return $GetDataImageSize;
1159
public static function ImageExtFromMime($mime_type) {
1160
// temporary way, works OK for now, but should be reworked in the future
1161
return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
1164
public static function ImageTypesLookup($imagetypeid) {
1165
static $ImageTypesLookup = array();
1166
if (empty($ImageTypesLookup)) {
1167
$ImageTypesLookup[1] = 'gif';
1168
$ImageTypesLookup[2] = 'jpeg';
1169
$ImageTypesLookup[3] = 'png';
1170
$ImageTypesLookup[4] = 'swf';
1171
$ImageTypesLookup[5] = 'psd';
1172
$ImageTypesLookup[6] = 'bmp';
1173
$ImageTypesLookup[7] = 'tiff (little-endian)';
1174
$ImageTypesLookup[8] = 'tiff (big-endian)';
1175
$ImageTypesLookup[9] = 'jpc';
1176
$ImageTypesLookup[10] = 'jp2';
1177
$ImageTypesLookup[11] = 'jpx';
1178
$ImageTypesLookup[12] = 'jb2';
1179
$ImageTypesLookup[13] = 'swc';
1180
$ImageTypesLookup[14] = 'iff';
1182
return (isset($ImageTypesLookup[$imagetypeid]) ? $ImageTypesLookup[$imagetypeid] : '');
1185
public static function CopyTagsToComments(&$ThisFileInfo) {
1187
// Copy all entries from ['tags'] into common ['comments']
1188
if (!empty($ThisFileInfo['tags'])) {
1189
foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
1190
foreach ($tagarray as $tagname => $tagdata) {
1191
foreach ($tagdata as $key => $value) {
1192
if (!empty($value)) {
1193
if (empty($ThisFileInfo['comments'][$tagname])) {
1195
// fall through and append value
1197
} elseif ($tagtype == 'id3v1') {
1199
$newvaluelength = strlen(trim($value));
1200
foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1201
$oldvaluelength = strlen(trim($existingvalue));
1202
if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
1203
// new value is identical but shorter-than (or equal-length to) one already in comments - skip
1208
} elseif (!is_array($value)) {
1210
$newvaluelength = strlen(trim($value));
1211
foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1212
$oldvaluelength = strlen(trim($existingvalue));
1213
if (($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
1214
$ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
1220
if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
1221
$value = (is_string($value) ? trim($value) : $value);
1222
$ThisFileInfo['comments'][$tagname][] = $value;
1229
// Copy to ['comments_html']
1230
foreach ($ThisFileInfo['comments'] as $field => $values) {
1231
if ($field == 'picture') {
1232
// pictures can take up a lot of space, and we don't need multiple copies of them
1233
// let there be a single copy in [comments][picture], and not elsewhere
1236
foreach ($values as $index => $value) {
1237
if (is_array($value)) {
1238
$ThisFileInfo['comments_html'][$field][$index] = $value;
1240
$ThisFileInfo['comments_html'][$field][$index] = str_replace('�', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
1249
public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
1253
if (isset($cache[$file][$name])) {
1254
return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1258
$keylength = strlen($key);
1259
$line_count = $end - $begin - 7;
1262
$fp = fopen($file, 'r');
1264
// Discard $begin lines
1265
for ($i = 0; $i < ($begin + 3); $i++) {
1270
while (0 < $line_count--) {
1273
$line = ltrim(fgets($fp, 1024), "\t ");
1275
// METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
1276
//$keycheck = substr($line, 0, $keylength);
1277
//if ($key == $keycheck) {
1278
// $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
1282
// METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
1283
//$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
1284
$explodedLine = explode("\t", $line, 2);
1285
$ThisKey = (isset($explodedLine[0]) ? $explodedLine[0] : '');
1286
$ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
1287
$cache[$file][$name][$ThisKey] = trim($ThisValue);
1292
return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1295
public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
1296
global $GETID3_ERRORARRAY;
1298
if (file_exists($filename)) {
1299
if (include_once($filename)) {
1302
$diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
1305
$diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
1307
if ($DieOnFailure) {
1308
throw new Exception($diemessage);
1310
$GETID3_ERRORARRAY[] = $diemessage;
1315
public static function trimNullByte($string) {
1316
return trim($string, "\x00");
1319
public static function getFileSizeSyscall($path) {
1322
if (GETID3_OS_ISWINDOWS) {
1323
if (class_exists('COM')) { // From PHP 5.3.15 and 5.4.5, COM and DOTNET is no longer built into the php core.you have to add COM support in php.ini:
1324
$filesystem = new COM('Scripting.FileSystemObject');
1325
$file = $filesystem->GetFile($path);
1326
$filesize = $file->Size();
1327
unset($filesystem, $file);
1329
$commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
1332
$commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
1334
if (isset($commandline)) {
1335
$output = trim(`$commandline`);
1336
if (ctype_digit($output)) {
1337
$filesize = (float) $output;
b'\\ No newline at end of file'