File indexing completed on 2024-05-12 17:25:54

0001 <?php
0002 /////////////////////////////////////////////////////////////////
0003 /// getID3() by James Heinrich <info@getid3.org>               //
0004 //  available at http://getid3.sourceforge.net                 //
0005 //            or http://www.getid3.org                         //
0006 //          also https://github.com/JamesHeinrich/getID3       //
0007 /////////////////////////////////////////////////////////////////
0008 //                                                             //
0009 // getid3.lib.php - part of getID3()                           //
0010 // See readme.txt for more details                             //
0011 //                                                            ///
0012 /////////////////////////////////////////////////////////////////
0013 
0014 
0015 class getid3_lib
0016 {
0017 
0018   public static function PrintHexBytes($string, $hex=true, $spaces=true, $htmlencoding='UTF-8') {
0019     $returnstring = '';
0020     for ($i = 0; $i < strlen($string); $i++) {
0021       if ($hex) {
0022         $returnstring .= str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
0023       } else {
0024         $returnstring .= ' '.(preg_match("#[\x20-\x7E]#", $string{$i}) ? $string{$i} : 'ยค');
0025       }
0026       if ($spaces) {
0027         $returnstring .= ' ';
0028       }
0029     }
0030     if (!empty($htmlencoding)) {
0031       if ($htmlencoding === true) {
0032         $htmlencoding = 'UTF-8'; // prior to getID3 v1.9.0 the function's 4th parameter was boolean
0033       }
0034       $returnstring = htmlentities($returnstring, ENT_QUOTES, $htmlencoding);
0035     }
0036     return $returnstring;
0037   }
0038 
0039   public static function trunc($floatnumber) {
0040     // truncates a floating-point number at the decimal point
0041     // returns int (if possible, otherwise float)
0042     if ($floatnumber >= 1) {
0043       $truncatednumber = floor($floatnumber);
0044     } elseif ($floatnumber <= -1) {
0045       $truncatednumber = ceil($floatnumber);
0046     } else {
0047       $truncatednumber = 0;
0048     }
0049     if (self::intValueSupported($truncatednumber)) {
0050       $truncatednumber = (int) $truncatednumber;
0051     }
0052     return $truncatednumber;
0053   }
0054 
0055 
0056   public static function safe_inc(&$variable, $increment=1) {
0057     if (isset($variable)) {
0058       $variable += $increment;
0059     } else {
0060       $variable = $increment;
0061     }
0062     return true;
0063   }
0064 
0065   public static function CastAsInt($floatnum) {
0066     // convert to float if not already
0067     $floatnum = (float) $floatnum;
0068 
0069     // convert a float to type int, only if possible
0070     if (self::trunc($floatnum) == $floatnum) {
0071       // it's not floating point
0072       if (self::intValueSupported($floatnum)) {
0073         // it's within int range
0074         $floatnum = (int) $floatnum;
0075       }
0076     }
0077     return $floatnum;
0078   }
0079 
0080   public static function intValueSupported($num) {
0081     // check if integers are 64-bit
0082     static $hasINT64 = null;
0083     if ($hasINT64 === null) { // 10x faster than is_null()
0084       $hasINT64 = is_int(pow(2, 31)); // 32-bit int are limited to (2^31)-1
0085       if (!$hasINT64 && !defined('PHP_INT_MIN')) {
0086         define('PHP_INT_MIN', ~PHP_INT_MAX);
0087       }
0088     }
0089     // if integers are 64-bit - no other check required
0090     if ($hasINT64 || (($num <= PHP_INT_MAX) && ($num >= PHP_INT_MIN))) {
0091       return true;
0092     }
0093     return false;
0094   }
0095 
0096   public static function DecimalizeFraction($fraction) {
0097     list($numerator, $denominator) = explode('/', $fraction);
0098     return $numerator / ($denominator ? $denominator : 1);
0099   }
0100 
0101 
0102   public static function DecimalBinary2Float($binarynumerator) {
0103     $numerator   = self::Bin2Dec($binarynumerator);
0104     $denominator = self::Bin2Dec('1'.str_repeat('0', strlen($binarynumerator)));
0105     return ($numerator / $denominator);
0106   }
0107 
0108 
0109   public static function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) {
0110     // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
0111     if (strpos($binarypointnumber, '.') === false) {
0112       $binarypointnumber = '0.'.$binarypointnumber;
0113     } elseif ($binarypointnumber{0} == '.') {
0114       $binarypointnumber = '0'.$binarypointnumber;
0115     }
0116     $exponent = 0;
0117     while (($binarypointnumber{0} != '1') || (substr($binarypointnumber, 1, 1) != '.')) {
0118       if (substr($binarypointnumber, 1, 1) == '.') {
0119         $exponent--;
0120         $binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3);
0121       } else {
0122         $pointpos = strpos($binarypointnumber, '.');
0123         $exponent += ($pointpos - 1);
0124         $binarypointnumber = str_replace('.', '', $binarypointnumber);
0125         $binarypointnumber = $binarypointnumber{0}.'.'.substr($binarypointnumber, 1);
0126       }
0127     }
0128     $binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT);
0129     return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent);
0130   }
0131 
0132 
0133   public static function Float2BinaryDecimal($floatvalue) {
0134     // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
0135     $maxbits = 128; // to how many bits of precision should the calculations be taken?
0136     $intpart   = self::trunc($floatvalue);
0137     $floatpart = abs($floatvalue - $intpart);
0138     $pointbitstring = '';
0139     while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) {
0140       $floatpart *= 2;
0141       $pointbitstring .= (string) self::trunc($floatpart);
0142       $floatpart -= self::trunc($floatpart);
0143     }
0144     $binarypointnumber = decbin($intpart).'.'.$pointbitstring;
0145     return $binarypointnumber;
0146   }
0147 
0148 
0149   public static function Float2String($floatvalue, $bits) {
0150     // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html
0151     switch ($bits) {
0152       case 32:
0153         $exponentbits = 8;
0154         $fractionbits = 23;
0155         break;
0156 
0157       case 64:
0158         $exponentbits = 11;
0159         $fractionbits = 52;
0160         break;
0161 
0162       default:
0163         return false;
0164         break;
0165     }
0166     if ($floatvalue >= 0) {
0167       $signbit = '0';
0168     } else {
0169       $signbit = '1';
0170     }
0171     $normalizedbinary  = self::NormalizeBinaryPoint(self::Float2BinaryDecimal($floatvalue), $fractionbits);
0172     $biasedexponent    = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent
0173     $exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT);
0174     $fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT);
0175 
0176     return self::BigEndian2String(self::Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false);
0177   }
0178 
0179 
0180   public static function LittleEndian2Float($byteword) {
0181     return self::BigEndian2Float(strrev($byteword));
0182   }
0183 
0184 
0185   public static function BigEndian2Float($byteword) {
0186     // ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic
0187     // http://www.psc.edu/general/software/packages/ieee/ieee.html
0188     // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html
0189 
0190     $bitword = self::BigEndian2Bin($byteword);
0191     if (!$bitword) {
0192       return 0;
0193     }
0194     $signbit = $bitword{0};
0195 
0196     switch (strlen($byteword) * 8) {
0197       case 32:
0198         $exponentbits = 8;
0199         $fractionbits = 23;
0200         break;
0201 
0202       case 64:
0203         $exponentbits = 11;
0204         $fractionbits = 52;
0205         break;
0206 
0207       case 80:
0208         // 80-bit Apple SANE format
0209         // http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/
0210         $exponentstring = substr($bitword, 1, 15);
0211         $isnormalized = intval($bitword{16});
0212         $fractionstring = substr($bitword, 17, 63);
0213         $exponent = pow(2, self::Bin2Dec($exponentstring) - 16383);
0214         $fraction = $isnormalized + self::DecimalBinary2Float($fractionstring);
0215         $floatvalue = $exponent * $fraction;
0216         if ($signbit == '1') {
0217           $floatvalue *= -1;
0218         }
0219         return $floatvalue;
0220         break;
0221 
0222       default:
0223         return false;
0224         break;
0225     }
0226     $exponentstring = substr($bitword, 1, $exponentbits);
0227     $fractionstring = substr($bitword, $exponentbits + 1, $fractionbits);
0228     $exponent = self::Bin2Dec($exponentstring);
0229     $fraction = self::Bin2Dec($fractionstring);
0230 
0231     if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) {
0232       // Not a Number
0233       $floatvalue = false;
0234     } elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) {
0235       if ($signbit == '1') {
0236         $floatvalue = '-infinity';
0237       } else {
0238         $floatvalue = '+infinity';
0239       }
0240     } elseif (($exponent == 0) && ($fraction == 0)) {
0241       if ($signbit == '1') {
0242         $floatvalue = -0;
0243       } else {
0244         $floatvalue = 0;
0245       }
0246       $floatvalue = ($signbit ? 0 : -0);
0247     } elseif (($exponent == 0) && ($fraction != 0)) {
0248       // These are 'unnormalized' values
0249       $floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * self::DecimalBinary2Float($fractionstring);
0250       if ($signbit == '1') {
0251         $floatvalue *= -1;
0252       }
0253     } elseif ($exponent != 0) {
0254       $floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + self::DecimalBinary2Float($fractionstring));
0255       if ($signbit == '1') {
0256         $floatvalue *= -1;
0257       }
0258     }
0259     return (float) $floatvalue;
0260   }
0261 
0262 
0263   public static function BigEndian2Int($byteword, $synchsafe=false, $signed=false) {
0264     $intvalue = 0;
0265     $bytewordlen = strlen($byteword);
0266     if ($bytewordlen == 0) {
0267       return false;
0268     }
0269     for ($i = 0; $i < $bytewordlen; $i++) {
0270       if ($synchsafe) { // disregard MSB, effectively 7-bit bytes
0271         //$intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); // faster, but runs into problems past 2^31 on 32-bit systems
0272         $intvalue += (ord($byteword{$i}) & 0x7F) * pow(2, ($bytewordlen - 1 - $i) * 7);
0273       } else {
0274         $intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i));
0275       }
0276     }
0277     if ($signed && !$synchsafe) {
0278       // synchsafe ints are not allowed to be signed
0279       if ($bytewordlen <= PHP_INT_SIZE) {
0280         $signMaskBit = 0x80 << (8 * ($bytewordlen - 1));
0281         if ($intvalue & $signMaskBit) {
0282           $intvalue = 0 - ($intvalue & ($signMaskBit - 1));
0283         }
0284       } else {
0285         throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits ('.strlen($byteword).') in self::BigEndian2Int()');
0286       }
0287     }
0288     return self::CastAsInt($intvalue);
0289   }
0290 
0291 
0292   public static function LittleEndian2Int($byteword, $signed=false) {
0293     return self::BigEndian2Int(strrev($byteword), false, $signed);
0294   }
0295 
0296 
0297   public static function BigEndian2Bin($byteword) {
0298     $binvalue = '';
0299     $bytewordlen = strlen($byteword);
0300     for ($i = 0; $i < $bytewordlen; $i++) {
0301       $binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
0302     }
0303     return $binvalue;
0304   }
0305 
0306 
0307   public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
0308     if ($number < 0) {
0309       throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
0310     }
0311     $maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
0312     $intstring = '';
0313     if ($signed) {
0314       if ($minbytes > PHP_INT_SIZE) {
0315         throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
0316       }
0317       $number = $number & (0x80 << (8 * ($minbytes - 1)));
0318     }
0319     while ($number != 0) {
0320       $quotient = ($number / ($maskbyte + 1));
0321       $intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
0322       $number = floor($quotient);
0323     }
0324     return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
0325   }
0326 
0327 
0328   public static function Dec2Bin($number) {
0329     while ($number >= 256) {
0330       $bytes[] = (($number / 256) - (floor($number / 256))) * 256;
0331       $number = floor($number / 256);
0332     }
0333     $bytes[] = $number;
0334     $binstring = '';
0335     for ($i = 0; $i < count($bytes); $i++) {
0336       $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring;
0337     }
0338     return $binstring;
0339   }
0340 
0341 
0342   public static function Bin2Dec($binstring, $signed=false) {
0343     $signmult = 1;
0344     if ($signed) {
0345       if ($binstring{0} == '1') {
0346         $signmult = -1;
0347       }
0348       $binstring = substr($binstring, 1);
0349     }
0350     $decvalue = 0;
0351     for ($i = 0; $i < strlen($binstring); $i++) {
0352       $decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
0353     }
0354     return self::CastAsInt($decvalue * $signmult);
0355   }
0356 
0357 
0358   public static function Bin2String($binstring) {
0359     // return 'hi' for input of '0110100001101001'
0360     $string = '';
0361     $binstringreversed = strrev($binstring);
0362     for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
0363       $string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
0364     }
0365     return $string;
0366   }
0367 
0368 
0369   public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
0370     $intstring = '';
0371     while ($number > 0) {
0372       if ($synchsafe) {
0373         $intstring = $intstring.chr($number & 127);
0374         $number >>= 7;
0375       } else {
0376         $intstring = $intstring.chr($number & 255);
0377         $number >>= 8;
0378       }
0379     }
0380     return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
0381   }
0382 
0383 
0384   public static function array_merge_clobber($array1, $array2) {
0385     // written by kcร˜hireability*com
0386     // taken from http://www.php.net/manual/en/function.array-merge-recursive.php
0387     if (!is_array($array1) || !is_array($array2)) {
0388       return false;
0389     }
0390     $newarray = $array1;
0391     foreach ($array2 as $key => $val) {
0392       if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
0393         $newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
0394       } else {
0395         $newarray[$key] = $val;
0396       }
0397     }
0398     return $newarray;
0399   }
0400 
0401 
0402   public static function array_merge_noclobber($array1, $array2) {
0403     if (!is_array($array1) || !is_array($array2)) {
0404       return false;
0405     }
0406     $newarray = $array1;
0407     foreach ($array2 as $key => $val) {
0408       if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
0409         $newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
0410       } elseif (!isset($newarray[$key])) {
0411         $newarray[$key] = $val;
0412       }
0413     }
0414     return $newarray;
0415   }
0416 
0417 
0418   public static function ksort_recursive(&$theArray) {
0419     ksort($theArray);
0420     foreach ($theArray as $key => $value) {
0421       if (is_array($value)) {
0422         self::ksort_recursive($theArray[$key]);
0423       }
0424     }
0425     return true;
0426   }
0427 
0428   public static function fileextension($filename, $numextensions=1) {
0429     if (strstr($filename, '.')) {
0430       $reversedfilename = strrev($filename);
0431       $offset = 0;
0432       for ($i = 0; $i < $numextensions; $i++) {
0433         $offset = strpos($reversedfilename, '.', $offset + 1);
0434         if ($offset === false) {
0435           return '';
0436         }
0437       }
0438       return strrev(substr($reversedfilename, 0, $offset));
0439     }
0440     return '';
0441   }
0442 
0443 
0444   public static function PlaytimeString($seconds) {
0445     $sign = (($seconds < 0) ? '-' : '');
0446     $seconds = round(abs($seconds));
0447     $H = (int) floor( $seconds                            / 3600);
0448     $M = (int) floor(($seconds - (3600 * $H)            ) /   60);
0449     $S = (int) round( $seconds - (3600 * $H) - (60 * $M)        );
0450     return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
0451   }
0452 
0453 
0454   public static function DateMac2Unix($macdate) {
0455     // Macintosh timestamp: seconds since 00:00h January 1, 1904
0456     // UNIX timestamp:      seconds since 00:00h January 1, 1970
0457     return self::CastAsInt($macdate - 2082844800);
0458   }
0459 
0460 
0461   public static function FixedPoint8_8($rawdata) {
0462     return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
0463   }
0464 
0465 
0466   public static function FixedPoint16_16($rawdata) {
0467     return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
0468   }
0469 
0470 
0471   public static function FixedPoint2_30($rawdata) {
0472     $binarystring = self::BigEndian2Bin($rawdata);
0473     return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
0474   }
0475 
0476 
0477   public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
0478     // assigns $Value to a nested array path:
0479     //   $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
0480     // is the same as:
0481     //   $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
0482     // or
0483     //   $foo['path']['to']['my'] = 'file.txt';
0484     $ArrayPath = ltrim($ArrayPath, $Separator);
0485     if (($pos = strpos($ArrayPath, $Separator)) !== false) {
0486       $ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
0487     } else {
0488       $ReturnedArray[$ArrayPath] = $Value;
0489     }
0490     return $ReturnedArray;
0491   }
0492 
0493   public static function array_max($arraydata, $returnkey=false) {
0494     $maxvalue = false;
0495     $maxkey = false;
0496     foreach ($arraydata as $key => $value) {
0497       if (!is_array($value)) {
0498         if ($value > $maxvalue) {
0499           $maxvalue = $value;
0500           $maxkey = $key;
0501         }
0502       }
0503     }
0504     return ($returnkey ? $maxkey : $maxvalue);
0505   }
0506 
0507   public static function array_min($arraydata, $returnkey=false) {
0508     $minvalue = false;
0509     $minkey = false;
0510     foreach ($arraydata as $key => $value) {
0511       if (!is_array($value)) {
0512         if ($value > $minvalue) {
0513           $minvalue = $value;
0514           $minkey = $key;
0515         }
0516       }
0517     }
0518     return ($returnkey ? $minkey : $minvalue);
0519   }
0520 
0521   public static function XML2array($XMLstring) {
0522     if (function_exists('simplexml_load_string')) {
0523       if (function_exists('get_object_vars')) {
0524         if (function_exists('libxml_disable_entity_loader')) { // (PHP 5 >= 5.2.11)
0525           // http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html
0526           libxml_disable_entity_loader(true);
0527         }
0528         $XMLobject = simplexml_load_string($XMLstring);
0529         return self::SimpleXMLelement2array($XMLobject);
0530       }
0531     }
0532     return false;
0533   }
0534 
0535   public static function SimpleXMLelement2array($XMLobject) {
0536     if (!is_object($XMLobject) && !is_array($XMLobject)) {
0537       return $XMLobject;
0538     }
0539     $XMLarray = (is_object($XMLobject) ? get_object_vars($XMLobject) : $XMLobject);
0540     foreach ($XMLarray as $key => $value) {
0541       $XMLarray[$key] = self::SimpleXMLelement2array($value);
0542     }
0543     return $XMLarray;
0544   }
0545 
0546 
0547   // Allan Hansen <ahร˜artemis*dk>
0548   // self::md5_data() - returns md5sum for a file from startuing position to absolute end position
0549   public static function hash_data($file, $offset, $end, $algorithm) {
0550     static $tempdir = '';
0551     if (!self::intValueSupported($end)) {
0552       return false;
0553     }
0554     switch ($algorithm) {
0555       case 'md5':
0556         $hash_function = 'md5_file';
0557         $unix_call     = 'md5sum';
0558         $windows_call  = 'md5sum.exe';
0559         $hash_length   = 32;
0560         break;
0561 
0562       case 'sha1':
0563         $hash_function = 'sha1_file';
0564         $unix_call     = 'sha1sum';
0565         $windows_call  = 'sha1sum.exe';
0566         $hash_length   = 40;
0567         break;
0568 
0569       default:
0570         throw new Exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
0571         break;
0572     }
0573     $size = $end - $offset;
0574     while (true) {
0575       if (GETID3_OS_ISWINDOWS) {
0576 
0577         // It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
0578         // Fall back to create-temp-file method:
0579         if ($algorithm == 'sha1') {
0580           break;
0581         }
0582 
0583         $RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
0584         foreach ($RequiredFiles as $required_file) {
0585           if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
0586             // helper apps not available - fall back to old method
0587             break 2;
0588           }
0589         }
0590         $commandline  = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' '.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).' | ';
0591         $commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
0592         $commandline .= GETID3_HELPERAPPSDIR.$windows_call;
0593 
0594       } else {
0595 
0596         $commandline  = 'head -c'.$end.' '.escapeshellarg($file).' | ';
0597         $commandline .= 'tail -c'.$size.' | ';
0598         $commandline .= $unix_call;
0599 
0600       }
0601       if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
0602         //throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
0603         break;
0604       }
0605       return substr(`$commandline`, 0, $hash_length);
0606     }
0607 
0608     if (empty($tempdir)) {
0609       // yes this is ugly, feel free to suggest a better way
0610       require_once(dirname(__FILE__).'/getid3.php');
0611       $getid3_temp = new getID3();
0612       $tempdir = $getid3_temp->tempdir;
0613       unset($getid3_temp);
0614     }
0615     // try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
0616     if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
0617       // can't find anywhere to create a temp file, just fail
0618       return false;
0619     }
0620 
0621     // Init
0622     $result = false;
0623 
0624     // copy parts of file
0625     try {
0626       self::CopyFileParts($file, $data_filename, $offset, $end - $offset);
0627       $result = $hash_function($data_filename);
0628     } catch (Exception $e) {
0629       throw new Exception('self::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
0630     }
0631     unlink($data_filename);
0632     return $result;
0633   }
0634 
0635   public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
0636     if (!self::intValueSupported($offset + $length)) {
0637       throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
0638     }
0639     if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
0640       if (($fp_dest = fopen($filename_dest, 'wb'))) {
0641         if (fseek($fp_src, $offset) == 0) {
0642           $byteslefttowrite = $length;
0643           while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
0644             $byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
0645             $byteslefttowrite -= $byteswritten;
0646           }
0647           return true;
0648         } else {
0649           throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
0650         }
0651         fclose($fp_dest);
0652       } else {
0653         throw new Exception('failed to create file for writing '.$filename_dest);
0654       }
0655       fclose($fp_src);
0656     } else {
0657       throw new Exception('failed to open file for reading '.$filename_source);
0658     }
0659     return false;
0660   }
0661 
0662   public static function iconv_fallback_int_utf8($charval) {
0663     if ($charval < 128) {
0664       // 0bbbbbbb
0665       $newcharstring = chr($charval);
0666     } elseif ($charval < 2048) {
0667       // 110bbbbb 10bbbbbb
0668       $newcharstring  = chr(($charval >>   6) | 0xC0);
0669       $newcharstring .= chr(($charval & 0x3F) | 0x80);
0670     } elseif ($charval < 65536) {
0671       // 1110bbbb 10bbbbbb 10bbbbbb
0672       $newcharstring  = chr(($charval >>  12) | 0xE0);
0673       $newcharstring .= chr(($charval >>   6) | 0xC0);
0674       $newcharstring .= chr(($charval & 0x3F) | 0x80);
0675     } else {
0676       // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
0677       $newcharstring  = chr(($charval >>  18) | 0xF0);
0678       $newcharstring .= chr(($charval >>  12) | 0xC0);
0679       $newcharstring .= chr(($charval >>   6) | 0xC0);
0680       $newcharstring .= chr(($charval & 0x3F) | 0x80);
0681     }
0682     return $newcharstring;
0683   }
0684 
0685   // ISO-8859-1 => UTF-8
0686   public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
0687     if (function_exists('utf8_encode')) {
0688       return utf8_encode($string);
0689     }
0690     // utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
0691     $newcharstring = '';
0692     if ($bom) {
0693       $newcharstring .= "\xEF\xBB\xBF";
0694     }
0695     for ($i = 0; $i < strlen($string); $i++) {
0696       $charval = ord($string{$i});
0697       $newcharstring .= self::iconv_fallback_int_utf8($charval);
0698     }
0699     return $newcharstring;
0700   }
0701 
0702   // ISO-8859-1 => UTF-16BE
0703   public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
0704     $newcharstring = '';
0705     if ($bom) {
0706       $newcharstring .= "\xFE\xFF";
0707     }
0708     for ($i = 0; $i < strlen($string); $i++) {
0709       $newcharstring .= "\x00".$string{$i};
0710     }
0711     return $newcharstring;
0712   }
0713 
0714   // ISO-8859-1 => UTF-16LE
0715   public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
0716     $newcharstring = '';
0717     if ($bom) {
0718       $newcharstring .= "\xFF\xFE";
0719     }
0720     for ($i = 0; $i < strlen($string); $i++) {
0721       $newcharstring .= $string{$i}."\x00";
0722     }
0723     return $newcharstring;
0724   }
0725 
0726   // ISO-8859-1 => UTF-16LE (BOM)
0727   public static function iconv_fallback_iso88591_utf16($string) {
0728     return self::iconv_fallback_iso88591_utf16le($string, true);
0729   }
0730 
0731   // UTF-8 => ISO-8859-1
0732   public static function iconv_fallback_utf8_iso88591($string) {
0733     if (function_exists('utf8_decode')) {
0734       return utf8_decode($string);
0735     }
0736     // utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
0737     $newcharstring = '';
0738     $offset = 0;
0739     $stringlength = strlen($string);
0740     while ($offset < $stringlength) {
0741       if ((ord($string{$offset}) | 0x07) == 0xF7) {
0742         // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
0743         $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
0744                ((ord($string{($offset + 1)}) & 0x3F) << 12) &
0745                ((ord($string{($offset + 2)}) & 0x3F) <<  6) &
0746               (ord($string{($offset + 3)}) & 0x3F);
0747         $offset += 4;
0748       } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
0749         // 1110bbbb 10bbbbbb 10bbbbbb
0750         $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
0751                ((ord($string{($offset + 1)}) & 0x3F) <<  6) &
0752               (ord($string{($offset + 2)}) & 0x3F);
0753         $offset += 3;
0754       } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
0755         // 110bbbbb 10bbbbbb
0756         $charval = ((ord($string{($offset + 0)}) & 0x1F) <<  6) &
0757               (ord($string{($offset + 1)}) & 0x3F);
0758         $offset += 2;
0759       } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
0760         // 0bbbbbbb
0761         $charval = ord($string{$offset});
0762         $offset += 1;
0763       } else {
0764         // error? throw some kind of warning here?
0765         $charval = false;
0766         $offset += 1;
0767       }
0768       if ($charval !== false) {
0769         $newcharstring .= (($charval < 256) ? chr($charval) : '?');
0770       }
0771     }
0772     return $newcharstring;
0773   }
0774 
0775   // UTF-8 => UTF-16BE
0776   public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
0777     $newcharstring = '';
0778     if ($bom) {
0779       $newcharstring .= "\xFE\xFF";
0780     }
0781     $offset = 0;
0782     $stringlength = strlen($string);
0783     while ($offset < $stringlength) {
0784       if ((ord($string{$offset}) | 0x07) == 0xF7) {
0785         // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
0786         $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
0787                ((ord($string{($offset + 1)}) & 0x3F) << 12) &
0788                ((ord($string{($offset + 2)}) & 0x3F) <<  6) &
0789               (ord($string{($offset + 3)}) & 0x3F);
0790         $offset += 4;
0791       } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
0792         // 1110bbbb 10bbbbbb 10bbbbbb
0793         $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
0794                ((ord($string{($offset + 1)}) & 0x3F) <<  6) &
0795               (ord($string{($offset + 2)}) & 0x3F);
0796         $offset += 3;
0797       } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
0798         // 110bbbbb 10bbbbbb
0799         $charval = ((ord($string{($offset + 0)}) & 0x1F) <<  6) &
0800               (ord($string{($offset + 1)}) & 0x3F);
0801         $offset += 2;
0802       } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
0803         // 0bbbbbbb
0804         $charval = ord($string{$offset});
0805         $offset += 1;
0806       } else {
0807         // error? throw some kind of warning here?
0808         $charval = false;
0809         $offset += 1;
0810       }
0811       if ($charval !== false) {
0812         $newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
0813       }
0814     }
0815     return $newcharstring;
0816   }
0817 
0818   // UTF-8 => UTF-16LE
0819   public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
0820     $newcharstring = '';
0821     if ($bom) {
0822       $newcharstring .= "\xFF\xFE";
0823     }
0824     $offset = 0;
0825     $stringlength = strlen($string);
0826     while ($offset < $stringlength) {
0827       if ((ord($string{$offset}) | 0x07) == 0xF7) {
0828         // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
0829         $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
0830                ((ord($string{($offset + 1)}) & 0x3F) << 12) &
0831                ((ord($string{($offset + 2)}) & 0x3F) <<  6) &
0832               (ord($string{($offset + 3)}) & 0x3F);
0833         $offset += 4;
0834       } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
0835         // 1110bbbb 10bbbbbb 10bbbbbb
0836         $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
0837                ((ord($string{($offset + 1)}) & 0x3F) <<  6) &
0838               (ord($string{($offset + 2)}) & 0x3F);
0839         $offset += 3;
0840       } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
0841         // 110bbbbb 10bbbbbb
0842         $charval = ((ord($string{($offset + 0)}) & 0x1F) <<  6) &
0843               (ord($string{($offset + 1)}) & 0x3F);
0844         $offset += 2;
0845       } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
0846         // 0bbbbbbb
0847         $charval = ord($string{$offset});
0848         $offset += 1;
0849       } else {
0850         // error? maybe throw some warning here?
0851         $charval = false;
0852         $offset += 1;
0853       }
0854       if ($charval !== false) {
0855         $newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
0856       }
0857     }
0858     return $newcharstring;
0859   }
0860 
0861   // UTF-8 => UTF-16LE (BOM)
0862   public static function iconv_fallback_utf8_utf16($string) {
0863     return self::iconv_fallback_utf8_utf16le($string, true);
0864   }
0865 
0866   // UTF-16BE => UTF-8
0867   public static function iconv_fallback_utf16be_utf8($string) {
0868     if (substr($string, 0, 2) == "\xFE\xFF") {
0869       // strip BOM
0870       $string = substr($string, 2);
0871     }
0872     $newcharstring = '';
0873     for ($i = 0; $i < strlen($string); $i += 2) {
0874       $charval = self::BigEndian2Int(substr($string, $i, 2));
0875       $newcharstring .= self::iconv_fallback_int_utf8($charval);
0876     }
0877     return $newcharstring;
0878   }
0879 
0880   // UTF-16LE => UTF-8
0881   public static function iconv_fallback_utf16le_utf8($string) {
0882     if (substr($string, 0, 2) == "\xFF\xFE") {
0883       // strip BOM
0884       $string = substr($string, 2);
0885     }
0886     $newcharstring = '';
0887     for ($i = 0; $i < strlen($string); $i += 2) {
0888       $charval = self::LittleEndian2Int(substr($string, $i, 2));
0889       $newcharstring .= self::iconv_fallback_int_utf8($charval);
0890     }
0891     return $newcharstring;
0892   }
0893 
0894   // UTF-16BE => ISO-8859-1
0895   public static function iconv_fallback_utf16be_iso88591($string) {
0896     if (substr($string, 0, 2) == "\xFE\xFF") {
0897       // strip BOM
0898       $string = substr($string, 2);
0899     }
0900     $newcharstring = '';
0901     for ($i = 0; $i < strlen($string); $i += 2) {
0902       $charval = self::BigEndian2Int(substr($string, $i, 2));
0903       $newcharstring .= (($charval < 256) ? chr($charval) : '?');
0904     }
0905     return $newcharstring;
0906   }
0907 
0908   // UTF-16LE => ISO-8859-1
0909   public static function iconv_fallback_utf16le_iso88591($string) {
0910     if (substr($string, 0, 2) == "\xFF\xFE") {
0911       // strip BOM
0912       $string = substr($string, 2);
0913     }
0914     $newcharstring = '';
0915     for ($i = 0; $i < strlen($string); $i += 2) {
0916       $charval = self::LittleEndian2Int(substr($string, $i, 2));
0917       $newcharstring .= (($charval < 256) ? chr($charval) : '?');
0918     }
0919     return $newcharstring;
0920   }
0921 
0922   // UTF-16 (BOM) => ISO-8859-1
0923   public static function iconv_fallback_utf16_iso88591($string) {
0924     $bom = substr($string, 0, 2);
0925     if ($bom == "\xFE\xFF") {
0926       return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
0927     } elseif ($bom == "\xFF\xFE") {
0928       return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
0929     }
0930     return $string;
0931   }
0932 
0933   // UTF-16 (BOM) => UTF-8
0934   public static function iconv_fallback_utf16_utf8($string) {
0935     $bom = substr($string, 0, 2);
0936     if ($bom == "\xFE\xFF") {
0937       return self::iconv_fallback_utf16be_utf8(substr($string, 2));
0938     } elseif ($bom == "\xFF\xFE") {
0939       return self::iconv_fallback_utf16le_utf8(substr($string, 2));
0940     }
0941     return $string;
0942   }
0943 
0944   public static function iconv_fallback($in_charset, $out_charset, $string) {
0945 
0946     if ($in_charset == $out_charset) {
0947       return $string;
0948     }
0949 
0950     // iconv() availble
0951     if (function_exists('iconv')) {
0952       if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
0953         switch ($out_charset) {
0954           case 'ISO-8859-1':
0955             $converted_string = rtrim($converted_string, "\x00");
0956             break;
0957         }
0958         return $converted_string;
0959       }
0960 
0961       // iconv() may sometimes fail with "illegal character in input string" error message
0962       // and return an empty string, but returning the unconverted string is more useful
0963       return $string;
0964     }
0965 
0966 
0967     // iconv() not available
0968     static $ConversionFunctionList = array();
0969     if (empty($ConversionFunctionList)) {
0970       $ConversionFunctionList['ISO-8859-1']['UTF-8']    = 'iconv_fallback_iso88591_utf8';
0971       $ConversionFunctionList['ISO-8859-1']['UTF-16']   = 'iconv_fallback_iso88591_utf16';
0972       $ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
0973       $ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
0974       $ConversionFunctionList['UTF-8']['ISO-8859-1']    = 'iconv_fallback_utf8_iso88591';
0975       $ConversionFunctionList['UTF-8']['UTF-16']        = 'iconv_fallback_utf8_utf16';
0976       $ConversionFunctionList['UTF-8']['UTF-16BE']      = 'iconv_fallback_utf8_utf16be';
0977       $ConversionFunctionList['UTF-8']['UTF-16LE']      = 'iconv_fallback_utf8_utf16le';
0978       $ConversionFunctionList['UTF-16']['ISO-8859-1']   = 'iconv_fallback_utf16_iso88591';
0979       $ConversionFunctionList['UTF-16']['UTF-8']        = 'iconv_fallback_utf16_utf8';
0980       $ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
0981       $ConversionFunctionList['UTF-16LE']['UTF-8']      = 'iconv_fallback_utf16le_utf8';
0982       $ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
0983       $ConversionFunctionList['UTF-16BE']['UTF-8']      = 'iconv_fallback_utf16be_utf8';
0984     }
0985     if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
0986       $ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
0987       return self::$ConversionFunction($string);
0988     }
0989     throw new Exception('PHP does not have iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
0990   }
0991 
0992   public static function recursiveMultiByteCharString2HTML($data, $charset='ISO-8859-1') {
0993     if (is_string($data)) {
0994       return self::MultiByteCharString2HTML($data, $charset);
0995     } elseif (is_array($data)) {
0996       $return_data = array();
0997       foreach ($data as $key => $value) {
0998         $return_data[$key] = self::recursiveMultiByteCharString2HTML($value, $charset);
0999       }
1000       return $return_data;
1001     }
1002     // integer, float, objects, resources, etc
1003     return $data;
1004   }
1005 
1006   public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
1007     $string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
1008     $HTMLstring = '';
1009 
1010     switch ($charset) {
1011       case '1251':
1012       case '1252':
1013       case '866':
1014       case '932':
1015       case '936':
1016       case '950':
1017       case 'BIG5':
1018       case 'BIG5-HKSCS':
1019       case 'cp1251':
1020       case 'cp1252':
1021       case 'cp866':
1022       case 'EUC-JP':
1023       case 'EUCJP':
1024       case 'GB2312':
1025       case 'ibm866':
1026       case 'ISO-8859-1':
1027       case 'ISO-8859-15':
1028       case 'ISO8859-1':
1029       case 'ISO8859-15':
1030       case 'KOI8-R':
1031       case 'koi8-ru':
1032       case 'koi8r':
1033       case 'Shift_JIS':
1034       case 'SJIS':
1035       case 'win-1251':
1036       case 'Windows-1251':
1037       case 'Windows-1252':
1038         $HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
1039         break;
1040 
1041       case 'UTF-8':
1042         $strlen = strlen($string);
1043         for ($i = 0; $i < $strlen; $i++) {
1044           $char_ord_val = ord($string{$i});
1045           $charval = 0;
1046           if ($char_ord_val < 0x80) {
1047             $charval = $char_ord_val;
1048           } elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F  &&  $i+3 < $strlen) {
1049             $charval  = (($char_ord_val & 0x07) << 18);
1050             $charval += ((ord($string{++$i}) & 0x3F) << 12);
1051             $charval += ((ord($string{++$i}) & 0x3F) << 6);
1052             $charval +=  (ord($string{++$i}) & 0x3F);
1053           } elseif ((($char_ord_val & 0xE0) >> 5) == 0x07  &&  $i+2 < $strlen) {
1054             $charval  = (($char_ord_val & 0x0F) << 12);
1055             $charval += ((ord($string{++$i}) & 0x3F) << 6);
1056             $charval +=  (ord($string{++$i}) & 0x3F);
1057           } elseif ((($char_ord_val & 0xC0) >> 6) == 0x03  &&  $i+1 < $strlen) {
1058             $charval  = (($char_ord_val & 0x1F) << 6);
1059             $charval += (ord($string{++$i}) & 0x3F);
1060           }
1061           if (($charval >= 32) && ($charval <= 127)) {
1062             $HTMLstring .= htmlentities(chr($charval));
1063           } else {
1064             $HTMLstring .= '&#'.$charval.';';
1065           }
1066         }
1067         break;
1068 
1069       case 'UTF-16LE':
1070         for ($i = 0; $i < strlen($string); $i += 2) {
1071           $charval = self::LittleEndian2Int(substr($string, $i, 2));
1072           if (($charval >= 32) && ($charval <= 127)) {
1073             $HTMLstring .= chr($charval);
1074           } else {
1075             $HTMLstring .= '&#'.$charval.';';
1076           }
1077         }
1078         break;
1079 
1080       case 'UTF-16BE':
1081         for ($i = 0; $i < strlen($string); $i += 2) {
1082           $charval = self::BigEndian2Int(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       default:
1092         $HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
1093         break;
1094     }
1095     return $HTMLstring;
1096   }
1097 
1098 
1099 
1100   public static function RGADnameLookup($namecode) {
1101     static $RGADname = array();
1102     if (empty($RGADname)) {
1103       $RGADname[0] = 'not set';
1104       $RGADname[1] = 'Track Gain Adjustment';
1105       $RGADname[2] = 'Album Gain Adjustment';
1106     }
1107 
1108     return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
1109   }
1110 
1111 
1112   public static function RGADoriginatorLookup($originatorcode) {
1113     static $RGADoriginator = array();
1114     if (empty($RGADoriginator)) {
1115       $RGADoriginator[0] = 'unspecified';
1116       $RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
1117       $RGADoriginator[2] = 'set by user';
1118       $RGADoriginator[3] = 'determined automatically';
1119     }
1120 
1121     return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
1122   }
1123 
1124 
1125   public static function RGADadjustmentLookup($rawadjustment, $signbit) {
1126     $adjustment = $rawadjustment / 10;
1127     if ($signbit == 1) {
1128       $adjustment *= -1;
1129     }
1130     return (float) $adjustment;
1131   }
1132 
1133 
1134   public static function RGADgainString($namecode, $originatorcode, $replaygain) {
1135     if ($replaygain < 0) {
1136       $signbit = '1';
1137     } else {
1138       $signbit = '0';
1139     }
1140     $storedreplaygain = intval(round($replaygain * 10));
1141     $gainstring  = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
1142     $gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
1143     $gainstring .= $signbit;
1144     $gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
1145 
1146     return $gainstring;
1147   }
1148 
1149   public static function RGADamplitude2dB($amplitude) {
1150     return 20 * log10($amplitude);
1151   }
1152 
1153 
1154   public static function GetDataImageSize($imgData, &$imageinfo=array()) {
1155     static $tempdir = '';
1156     if (empty($tempdir)) {
1157       // yes this is ugly, feel free to suggest a better way
1158       require_once(dirname(__FILE__).'/getid3.php');
1159       $getid3_temp = new getID3();
1160       $tempdir = $getid3_temp->tempdir;
1161       unset($getid3_temp);
1162     }
1163     $GetDataImageSize = false;
1164     if ($tempfilename = tempnam($tempdir, 'gI3')) {
1165       if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
1166         fwrite($tmp, $imgData);
1167         fclose($tmp);
1168         $GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
1169       }
1170       unlink($tempfilename);
1171     }
1172     return $GetDataImageSize;
1173   }
1174 
1175   public static function ImageExtFromMime($mime_type) {
1176     // temporary way, works OK for now, but should be reworked in the future
1177     return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
1178   }
1179 
1180   public static function ImageTypesLookup($imagetypeid) {
1181     static $ImageTypesLookup = array();
1182     if (empty($ImageTypesLookup)) {
1183       $ImageTypesLookup[1]  = 'gif';
1184       $ImageTypesLookup[2]  = 'jpeg';
1185       $ImageTypesLookup[3]  = 'png';
1186       $ImageTypesLookup[4]  = 'swf';
1187       $ImageTypesLookup[5]  = 'psd';
1188       $ImageTypesLookup[6]  = 'bmp';
1189       $ImageTypesLookup[7]  = 'tiff (little-endian)';
1190       $ImageTypesLookup[8]  = 'tiff (big-endian)';
1191       $ImageTypesLookup[9]  = 'jpc';
1192       $ImageTypesLookup[10] = 'jp2';
1193       $ImageTypesLookup[11] = 'jpx';
1194       $ImageTypesLookup[12] = 'jb2';
1195       $ImageTypesLookup[13] = 'swc';
1196       $ImageTypesLookup[14] = 'iff';
1197     }
1198     return (isset($ImageTypesLookup[$imagetypeid]) ? $ImageTypesLookup[$imagetypeid] : '');
1199   }
1200 
1201   public static function CopyTagsToComments(&$ThisFileInfo) {
1202 
1203     // Copy all entries from ['tags'] into common ['comments']
1204     if (!empty($ThisFileInfo['tags'])) {
1205       foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
1206         foreach ($tagarray as $tagname => $tagdata) {
1207           foreach ($tagdata as $key => $value) {
1208             if (!empty($value)) {
1209               if (empty($ThisFileInfo['comments'][$tagname])) {
1210 
1211                 // fall through and append value
1212 
1213               } elseif ($tagtype == 'id3v1') {
1214 
1215                 $newvaluelength = strlen(trim($value));
1216                 foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1217                   $oldvaluelength = strlen(trim($existingvalue));
1218                   if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
1219                     // new value is identical but shorter-than (or equal-length to) one already in comments - skip
1220                     break 2;
1221                   }
1222                 }
1223 
1224               } elseif (!is_array($value)) {
1225 
1226                 $newvaluelength = strlen(trim($value));
1227                 foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1228                   $oldvaluelength = strlen(trim($existingvalue));
1229                   if ((strlen($existingvalue) > 10) && ($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
1230                     $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
1231                     //break 2;
1232                     break;
1233                   }
1234                 }
1235 
1236               }
1237               if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
1238                 $value = (is_string($value) ? trim($value) : $value);
1239                 if (!is_numeric($key)) {
1240                   $ThisFileInfo['comments'][$tagname][$key] = $value;
1241                 } else {
1242                   $ThisFileInfo['comments'][$tagname][]     = $value;
1243                 }
1244               }
1245             }
1246           }
1247         }
1248       }
1249 
1250       // Copy to ['comments_html']
1251       if (!empty($ThisFileInfo['comments'])) {
1252         foreach ($ThisFileInfo['comments'] as $field => $values) {
1253           if ($field == 'picture') {
1254             // pictures can take up a lot of space, and we don't need multiple copies of them
1255             // let there be a single copy in [comments][picture], and not elsewhere
1256             continue;
1257           }
1258           foreach ($values as $index => $value) {
1259             if (is_array($value)) {
1260               $ThisFileInfo['comments_html'][$field][$index] = $value;
1261             } else {
1262               $ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
1263             }
1264           }
1265         }
1266       }
1267 
1268     }
1269     return true;
1270   }
1271 
1272 
1273   public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
1274 
1275     // Cached
1276     static $cache;
1277     if (isset($cache[$file][$name])) {
1278       return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1279     }
1280 
1281     // Init
1282     $keylength  = strlen($key);
1283     $line_count = $end - $begin - 7;
1284 
1285     // Open php file
1286     $fp = fopen($file, 'r');
1287 
1288     // Discard $begin lines
1289     for ($i = 0; $i < ($begin + 3); $i++) {
1290       fgets($fp, 1024);
1291     }
1292 
1293     // Loop thru line
1294     while (0 < $line_count--) {
1295 
1296       // Read line
1297       $line = ltrim(fgets($fp, 1024), "\t ");
1298 
1299       // METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
1300       //$keycheck = substr($line, 0, $keylength);
1301       //if ($key == $keycheck)  {
1302       //  $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
1303       //  break;
1304       //}
1305 
1306       // METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
1307       //$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
1308       $explodedLine = explode("\t", $line, 2);
1309       $ThisKey   = (isset($explodedLine[0]) ? $explodedLine[0] : '');
1310       $ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
1311       $cache[$file][$name][$ThisKey] = trim($ThisValue);
1312     }
1313 
1314     // Close and return
1315     fclose($fp);
1316     return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1317   }
1318 
1319   public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
1320     global $GETID3_ERRORARRAY;
1321 
1322     if (file_exists($filename)) {
1323       if (include_once($filename)) {
1324         return true;
1325       } else {
1326         $diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
1327       }
1328     } else {
1329       $diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
1330     }
1331     if ($DieOnFailure) {
1332       throw new Exception($diemessage);
1333     } else {
1334       $GETID3_ERRORARRAY[] = $diemessage;
1335     }
1336     return false;
1337   }
1338 
1339   public static function trimNullByte($string) {
1340     return trim($string, "\x00");
1341   }
1342 
1343   public static function getFileSizeSyscall($path) {
1344     $filesize = false;
1345 
1346     if (GETID3_OS_ISWINDOWS) {
1347       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:
1348         $filesystem = new COM('Scripting.FileSystemObject');
1349         $file = $filesystem->GetFile($path);
1350         $filesize = $file->Size();
1351         unset($filesystem, $file);
1352       } else {
1353         $commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
1354       }
1355     } else {
1356       $commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
1357     }
1358     if (isset($commandline)) {
1359       $output = trim(`$commandline`);
1360       if (ctype_digit($output)) {
1361         $filesize = (float) $output;
1362       }
1363     }
1364     return $filesize;
1365   }
1366 
1367 
1368   /**
1369   * Workaround for Bug #37268 (https://bugs.php.net/bug.php?id=37268)
1370   * @param string $path A path.
1371   * @param string $suffix If the name component ends in suffix this will also be cut off.
1372   * @return string
1373   */
1374   public static function mb_basename($path, $suffix = null) {
1375     $splited = preg_split('#/#', rtrim($path, '/ '));
1376     return substr(basename('X'.$splited[count($splited) - 1], $suffix), 1);
1377   }
1378 
1379 }