[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ID3/ -> getid3.lib.php (source)

   1  <?php
   2  
   3  /////////////////////////////////////////////////////////////////
   4  /// getID3() by James Heinrich <info@getid3.org>               //
   5  //  available at https://github.com/JamesHeinrich/getID3       //
   6  //            or https://www.getid3.org                        //
   7  //            or http://getid3.sourceforge.net                 //
   8  //                                                             //
   9  // getid3.lib.php - part of getID3()                           //
  10  //  see readme.txt for more details                            //
  11  //                                                            ///
  12  /////////////////////////////////////////////////////////////////
  13  
  14  if (!defined('GETID3_LIBXML_OPTIONS') && defined('LIBXML_VERSION')) {
  15      if (LIBXML_VERSION >= 20621) {
  16          define('GETID3_LIBXML_OPTIONS', LIBXML_NONET | LIBXML_NOWARNING | LIBXML_COMPACT);
  17      } else {
  18          define('GETID3_LIBXML_OPTIONS', LIBXML_NONET | LIBXML_NOWARNING);
  19      }
  20  }
  21  
  22  // Available since PHP 7.0 (2015-Dec-03 https://www.php.net/ChangeLog-7.php)
  23  if (!defined('PHP_INT_MIN')) {
  24      define('PHP_INT_MIN', ~PHP_INT_MAX);
  25  }
  26  
  27  class getid3_lib
  28  {
  29      /**
  30       * @param string      $string
  31       * @param bool        $hex
  32       * @param bool        $spaces
  33       * @param string|bool $htmlencoding
  34       *
  35       * @return string
  36       */
  37  	public static function PrintHexBytes($string, $hex=true, $spaces=true, $htmlencoding='UTF-8') {
  38          $returnstring = '';
  39          for ($i = 0; $i < strlen($string); $i++) {
  40              if ($hex) {
  41                  $returnstring .= str_pad(dechex(ord($string[$i])), 2, '0', STR_PAD_LEFT);
  42              } else {
  43                  $returnstring .= ' '.(preg_match("#[\x20-\x7E]#", $string[$i]) ? $string[$i] : 'ยค');
  44              }
  45              if ($spaces) {
  46                  $returnstring .= ' ';
  47              }
  48          }
  49          if (!empty($htmlencoding)) {
  50              if ($htmlencoding === true) {
  51                  $htmlencoding = 'UTF-8'; // prior to getID3 v1.9.0 the function's 4th parameter was boolean
  52              }
  53              $returnstring = htmlentities($returnstring, ENT_QUOTES, $htmlencoding);
  54          }
  55          return $returnstring;
  56      }
  57  
  58      /**
  59       * Truncates a floating-point number at the decimal point.
  60       *
  61       * @param float $floatnumber
  62       *
  63       * @return float|int returns int (if possible, otherwise float)
  64       */
  65  	public static function trunc($floatnumber) {
  66          if ($floatnumber >= 1) {
  67              $truncatednumber = floor($floatnumber);
  68          } elseif ($floatnumber <= -1) {
  69              $truncatednumber = ceil($floatnumber);
  70          } else {
  71              $truncatednumber = 0;
  72          }
  73          if (self::intValueSupported($truncatednumber)) {
  74              $truncatednumber = (int) $truncatednumber;
  75          }
  76          return $truncatednumber;
  77      }
  78  
  79      /**
  80       * @param int|null $variable
  81       * @param-out int  $variable
  82       * @param int      $increment
  83       *
  84       * @return bool
  85       */
  86  	public static function safe_inc(&$variable, $increment=1) {
  87          if (isset($variable)) {
  88              $variable += $increment;
  89          } else {
  90              $variable = $increment;
  91          }
  92          return true;
  93      }
  94  
  95      /**
  96       * @param int|float $floatnum
  97       *
  98       * @return int|float
  99       */
 100  	public static function CastAsInt($floatnum) {
 101          // convert to float if not already
 102          $floatnum = (float) $floatnum;
 103  
 104          // convert a float to type int, only if possible
 105          if (self::trunc($floatnum) == $floatnum) {
 106              // it's not floating point
 107              if (self::intValueSupported($floatnum)) {
 108                  // it's within int range
 109                  $floatnum = (int) $floatnum;
 110              }
 111          }
 112          return $floatnum;
 113      }
 114  
 115      /**
 116       * @param int $num
 117       *
 118       * @return bool
 119       */
 120  	public static function intValueSupported($num) {
 121          // really should be <= and >= but trying "(int)9.2233720368548E+18" results in PHP warning "The float 9.2233720368548E+18 is not representable as an int, cast occurred"
 122          return (($num < PHP_INT_MAX) && ($num > PHP_INT_MIN));
 123      }
 124  
 125      /**
 126       * Perform a division, guarding against division by zero
 127       *
 128       * @param float|int $numerator
 129       * @param float|int $denominator
 130       * @param float|int $fallback
 131       * @return float|int
 132       */
 133  	public static function SafeDiv($numerator, $denominator, $fallback = 0) {
 134          return $denominator ? $numerator / $denominator : $fallback;
 135      }
 136  
 137      /**
 138       * @param string $fraction
 139       *
 140       * @return float
 141       */
 142  	public static function DecimalizeFraction($fraction) {
 143          list($numerator, $denominator) = explode('/', $fraction);
 144          return (int) $numerator / ($denominator ? $denominator : 1);
 145      }
 146  
 147      /**
 148       * @param string $binarynumerator
 149       *
 150       * @return float
 151       */
 152  	public static function DecimalBinary2Float($binarynumerator) {
 153          $numerator   = self::Bin2Dec($binarynumerator);
 154          $denominator = self::Bin2Dec('1'.str_repeat('0', strlen($binarynumerator)));
 155          return ($numerator / $denominator);
 156      }
 157  
 158      /**
 159       * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
 160       *
 161       * @param string $binarypointnumber
 162       * @param int    $maxbits
 163       *
 164       * @return array
 165       */
 166  	public static function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) {
 167          if (strpos($binarypointnumber, '.') === false) {
 168              $binarypointnumber = '0.'.$binarypointnumber;
 169          } elseif ($binarypointnumber[0] == '.') {
 170              $binarypointnumber = '0'.$binarypointnumber;
 171          }
 172          $exponent = 0;
 173          while (($binarypointnumber[0] != '1') || (substr($binarypointnumber, 1, 1) != '.')) {
 174              if (substr($binarypointnumber, 1, 1) == '.') {
 175                  $exponent--;
 176                  $binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3);
 177              } else {
 178                  $pointpos = strpos($binarypointnumber, '.');
 179                  $exponent += ($pointpos - 1);
 180                  $binarypointnumber = str_replace('.', '', $binarypointnumber);
 181                  $binarypointnumber = $binarypointnumber[0].'.'.substr($binarypointnumber, 1);
 182              }
 183          }
 184          $binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT);
 185          return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent);
 186      }
 187  
 188      /**
 189       * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
 190       *
 191       * @param float $floatvalue
 192       *
 193       * @return string
 194       */
 195  	public static function Float2BinaryDecimal($floatvalue) {
 196          $maxbits = 128; // to how many bits of precision should the calculations be taken?
 197          $intpart   = self::trunc($floatvalue);
 198          $floatpart = abs($floatvalue - $intpart);
 199          $pointbitstring = '';
 200          while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) {
 201              $floatpart *= 2;
 202              $pointbitstring .= (string) self::trunc($floatpart);
 203              $floatpart -= self::trunc($floatpart);
 204          }
 205          $binarypointnumber = decbin($intpart).'.'.$pointbitstring;
 206          return $binarypointnumber;
 207      }
 208  
 209      /**
 210       * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html
 211       *
 212       * @param float $floatvalue
 213       * @param int $bits
 214       *
 215       * @return string|false
 216       */
 217  	public static function Float2String($floatvalue, $bits) {
 218          $exponentbits = 0;
 219          $fractionbits = 0;
 220          switch ($bits) {
 221              case 32:
 222                  $exponentbits = 8;
 223                  $fractionbits = 23;
 224                  break;
 225  
 226              case 64:
 227                  $exponentbits = 11;
 228                  $fractionbits = 52;
 229                  break;
 230  
 231              default:
 232                  return false;
 233          }
 234          if ($floatvalue >= 0) {
 235              $signbit = '0';
 236          } else {
 237              $signbit = '1';
 238          }
 239          $normalizedbinary  = self::NormalizeBinaryPoint(self::Float2BinaryDecimal($floatvalue), $fractionbits);
 240          $biasedexponent    = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent
 241          $exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT);
 242          $fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT);
 243  
 244          return self::BigEndian2String(self::Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false);
 245      }
 246  
 247      /**
 248       * @param string $byteword
 249       *
 250       * @return float|false
 251       */
 252  	public static function LittleEndian2Float($byteword) {
 253          return self::BigEndian2Float(strrev($byteword));
 254      }
 255  
 256      /**
 257       * ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic
 258       *
 259       * @link https://web.archive.org/web/20120325162206/http://www.psc.edu/general/software/packages/ieee/ieee.php
 260       * @link http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html
 261       *
 262       * @param string $byteword
 263       *
 264       * @return float|false
 265       */
 266  	public static function BigEndian2Float($byteword) {
 267          $bitword = self::BigEndian2Bin($byteword);
 268          if (!$bitword) {
 269              return 0;
 270          }
 271          $signbit = $bitword[0];
 272          $floatvalue = 0;
 273          $exponentbits = 0;
 274          $fractionbits = 0;
 275  
 276          switch (strlen($byteword) * 8) {
 277              case 32:
 278                  $exponentbits = 8;
 279                  $fractionbits = 23;
 280                  break;
 281  
 282              case 64:
 283                  $exponentbits = 11;
 284                  $fractionbits = 52;
 285                  break;
 286  
 287              case 80:
 288                  // 80-bit Apple SANE format
 289                  // http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/
 290                  $exponentstring = substr($bitword, 1, 15);
 291                  $isnormalized = intval($bitword[16]);
 292                  $fractionstring = substr($bitword, 17, 63);
 293                  $exponent = pow(2, self::Bin2Dec($exponentstring) - 16383);
 294                  $fraction = $isnormalized + self::DecimalBinary2Float($fractionstring);
 295                  $floatvalue = $exponent * $fraction;
 296                  if ($signbit == '1') {
 297                      $floatvalue *= -1;
 298                  }
 299                  return $floatvalue;
 300  
 301              default:
 302                  return false;
 303          }
 304          $exponentstring = substr($bitword, 1, $exponentbits);
 305          $fractionstring = substr($bitword, $exponentbits + 1, $fractionbits);
 306          $exponent = self::Bin2Dec($exponentstring);
 307          $fraction = self::Bin2Dec($fractionstring);
 308  
 309          if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) {
 310              // Not a Number
 311              $floatvalue = NAN;
 312          } elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) {
 313              if ($signbit == '1') {
 314                  $floatvalue = -INF;
 315              } else {
 316                  $floatvalue = INF;
 317              }
 318          } elseif (($exponent == 0) && ($fraction == 0)) {
 319              if ($signbit == '1') {
 320                  $floatvalue = -0.0;
 321              } else {
 322                  $floatvalue = 0.0;
 323              }
 324          } elseif (($exponent == 0) && ($fraction != 0)) {
 325              // These are 'unnormalized' values
 326              $floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * self::DecimalBinary2Float($fractionstring);
 327              if ($signbit == '1') {
 328                  $floatvalue *= -1;
 329              }
 330          } elseif ($exponent != 0) {
 331              $floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + self::DecimalBinary2Float($fractionstring));
 332              if ($signbit == '1') {
 333                  $floatvalue *= -1;
 334              }
 335          }
 336          return (float) $floatvalue;
 337      }
 338  
 339      /**
 340       * @param string $byteword
 341       * @param bool   $synchsafe
 342       * @param bool   $signed
 343       *
 344       * @return int|float|false
 345       * @throws Exception
 346       */
 347  	public static function BigEndian2Int($byteword, $synchsafe=false, $signed=false) {
 348          $intvalue = 0;
 349          $bytewordlen = strlen($byteword);
 350          if ($bytewordlen == 0) {
 351              return false;
 352          }
 353          for ($i = 0; $i < $bytewordlen; $i++) {
 354              if ($synchsafe) { // disregard MSB, effectively 7-bit bytes
 355                  //$intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); // faster, but runs into problems past 2^31 on 32-bit systems
 356                  $intvalue += (ord($byteword[$i]) & 0x7F) * pow(2, ($bytewordlen - 1 - $i) * 7);
 357              } else {
 358                  $intvalue += ord($byteword[$i]) * pow(256, ($bytewordlen - 1 - $i));
 359              }
 360          }
 361          if ($signed && !$synchsafe) {
 362              // synchsafe ints are not allowed to be signed
 363              if ($bytewordlen <= PHP_INT_SIZE) {
 364                  $signMaskBit = 0x80 << (8 * ($bytewordlen - 1));
 365                  if ($intvalue & $signMaskBit) {
 366                      $intvalue = 0 - ($intvalue & ($signMaskBit - 1));
 367                  }
 368              } else {
 369                  throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits ('.strlen($byteword).') in self::BigEndian2Int()');
 370              }
 371          }
 372          return self::CastAsInt($intvalue);
 373      }
 374  
 375      /**
 376       * @param string $byteword
 377       * @param bool   $signed
 378       *
 379       * @return int|float|false
 380       */
 381  	public static function LittleEndian2Int($byteword, $signed=false) {
 382          return self::BigEndian2Int(strrev($byteword), false, $signed);
 383      }
 384  
 385      /**
 386       * @param string $byteword
 387       *
 388       * @return string
 389       */
 390  	public static function LittleEndian2Bin($byteword) {
 391          return self::BigEndian2Bin(strrev($byteword));
 392      }
 393  
 394      /**
 395       * @param string $byteword
 396       *
 397       * @return string
 398       */
 399  	public static function BigEndian2Bin($byteword) {
 400          $binvalue = '';
 401          $bytewordlen = strlen($byteword);
 402          for ($i = 0; $i < $bytewordlen; $i++) {
 403              $binvalue .= str_pad(decbin(ord($byteword[$i])), 8, '0', STR_PAD_LEFT);
 404          }
 405          return $binvalue;
 406      }
 407  
 408      /**
 409       * @param int  $number
 410       * @param int  $minbytes
 411       * @param bool $synchsafe
 412       * @param bool $signed
 413       *
 414       * @return string
 415       * @throws Exception
 416       */
 417  	public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
 418          if ($number < 0) {
 419              throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
 420          }
 421          $maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
 422          $intstring = '';
 423          if ($signed) {
 424              if ($minbytes > PHP_INT_SIZE) {
 425                  throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
 426              }
 427              $number = $number & (0x80 << (8 * ($minbytes - 1)));
 428          }
 429          while ($number != 0) {
 430              $quotient = ($number / ($maskbyte + 1));
 431              $intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
 432              $number = floor($quotient);
 433          }
 434          return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
 435      }
 436  
 437      /**
 438       * @param int|string $number
 439       *
 440       * @return string
 441       */
 442  	public static function Dec2Bin($number) {
 443          if (!is_numeric($number)) {
 444              // https://github.com/JamesHeinrich/getID3/issues/299
 445              trigger_error('TypeError: Dec2Bin(): Argument #1 ($number) must be numeric, '.gettype($number).' given', E_USER_WARNING);
 446              return '';
 447          }
 448          $bytes = array();
 449          while ($number >= 256) {
 450              $bytes[] = (int) (($number / 256) - (floor($number / 256))) * 256;
 451              $number = floor($number / 256);
 452          }
 453          $bytes[] = (int) $number;
 454          $binstring = '';
 455          foreach ($bytes as $i => $byte) {
 456              $binstring = (($i == count($bytes) - 1) ? decbin($byte) : str_pad(decbin($byte), 8, '0', STR_PAD_LEFT)).$binstring;
 457          }
 458          return $binstring;
 459      }
 460  
 461      /**
 462       * @param string $binstring
 463       * @param bool   $signed
 464       *
 465       * @return int|float
 466       */
 467  	public static function Bin2Dec($binstring, $signed=false) {
 468          $signmult = 1;
 469          if ($signed) {
 470              if ($binstring[0] == '1') {
 471                  $signmult = -1;
 472              }
 473              $binstring = substr($binstring, 1);
 474          }
 475          $decvalue = 0;
 476          for ($i = 0; $i < strlen($binstring); $i++) {
 477              $decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
 478          }
 479          return self::CastAsInt($decvalue * $signmult);
 480      }
 481  
 482      /**
 483       * @param string $binstring
 484       *
 485       * @return string
 486       */
 487  	public static function Bin2String($binstring) {
 488          // return 'hi' for input of '0110100001101001'
 489          $string = '';
 490          $binstringreversed = strrev($binstring);
 491          for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
 492              $string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
 493          }
 494          return $string;
 495      }
 496  
 497      /**
 498       * @param int  $number
 499       * @param int  $minbytes
 500       * @param bool $synchsafe
 501       *
 502       * @return string
 503       */
 504  	public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
 505          $intstring = '';
 506          while ($number > 0) {
 507              if ($synchsafe) {
 508                  $intstring = $intstring.chr($number & 127);
 509                  $number >>= 7;
 510              } else {
 511                  $intstring = $intstring.chr($number & 255);
 512                  $number >>= 8;
 513              }
 514          }
 515          return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
 516      }
 517  
 518      /**
 519       * @param mixed $array1
 520       * @param mixed $array2
 521       *
 522       * @return array|false
 523       */
 524  	public static function array_merge_clobber($array1, $array2) {
 525          // written by kcร˜hireability*com
 526          // taken from http://www.php.net/manual/en/function.array-merge-recursive.php
 527          if (!is_array($array1) || !is_array($array2)) {
 528              return false;
 529          }
 530          $newarray = $array1;
 531          foreach ($array2 as $key => $val) {
 532              if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
 533                  $newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
 534              } else {
 535                  $newarray[$key] = $val;
 536              }
 537          }
 538          return $newarray;
 539      }
 540  
 541      /**
 542       * @param mixed $array1
 543       * @param mixed $array2
 544       *
 545       * @return array|false
 546       */
 547  	public static function array_merge_noclobber($array1, $array2) {
 548          if (!is_array($array1) || !is_array($array2)) {
 549              return false;
 550          }
 551          $newarray = $array1;
 552          foreach ($array2 as $key => $val) {
 553              if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
 554                  $newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
 555              } elseif (!isset($newarray[$key])) {
 556                  $newarray[$key] = $val;
 557              }
 558          }
 559          return $newarray;
 560      }
 561  
 562      /**
 563       * @param mixed $array1
 564       * @param mixed $array2
 565       *
 566       * @return array|false|null
 567       */
 568  	public static function flipped_array_merge_noclobber($array1, $array2) {
 569          if (!is_array($array1) || !is_array($array2)) {
 570              return false;
 571          }
 572          # naturally, this only works non-recursively
 573          $newarray = array_flip($array1);
 574          foreach (array_flip($array2) as $key => $val) {
 575              if (!isset($newarray[$key])) {
 576                  $newarray[$key] = count($newarray);
 577              }
 578          }
 579          return array_flip($newarray);
 580      }
 581  
 582      /**
 583       * @param array $theArray
 584       *
 585       * @return bool
 586       */
 587  	public static function ksort_recursive(&$theArray) {
 588          ksort($theArray);
 589          foreach ($theArray as $key => $value) {
 590              if (is_array($value)) {
 591                  self::ksort_recursive($theArray[$key]);
 592              }
 593          }
 594          return true;
 595      }
 596  
 597      /**
 598       * @param string $filename
 599       * @param int    $numextensions
 600       *
 601       * @return string
 602       */
 603  	public static function fileextension($filename, $numextensions=1) {
 604          if (strstr($filename, '.')) {
 605              $reversedfilename = strrev($filename);
 606              $offset = 0;
 607              for ($i = 0; $i < $numextensions; $i++) {
 608                  $offset = strpos($reversedfilename, '.', $offset + 1);
 609                  if ($offset === false) {
 610                      return '';
 611                  }
 612              }
 613              return strrev(substr($reversedfilename, 0, $offset));
 614          }
 615          return '';
 616      }
 617  
 618      /**
 619       * @param int $seconds
 620       *
 621       * @return string
 622       */
 623  	public static function PlaytimeString($seconds) {
 624          $sign = (($seconds < 0) ? '-' : '');
 625          $seconds = round(abs($seconds));
 626          $H = (int) floor( $seconds                            / 3600);
 627          $M = (int) floor(($seconds - (3600 * $H)            ) /   60);
 628          $S = (int) round( $seconds - (3600 * $H) - (60 * $M)        );
 629          return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
 630      }
 631  
 632      /**
 633       * @param int $macdate
 634       *
 635       * @return int|float
 636       */
 637  	public static function DateMac2Unix($macdate) {
 638          // Macintosh timestamp: seconds since 00:00h January 1, 1904
 639          // UNIX timestamp:      seconds since 00:00h January 1, 1970
 640          return self::CastAsInt($macdate - 2082844800);
 641      }
 642  
 643      /**
 644       * @param string $rawdata
 645       *
 646       * @return float
 647       */
 648  	public static function FixedPoint8_8($rawdata) {
 649          return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
 650      }
 651  
 652      /**
 653       * @param string $rawdata
 654       *
 655       * @return float
 656       */
 657  	public static function FixedPoint16_16($rawdata) {
 658          return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
 659      }
 660  
 661      /**
 662       * @param string $rawdata
 663       *
 664       * @return float
 665       */
 666  	public static function FixedPoint2_30($rawdata) {
 667          $binarystring = self::BigEndian2Bin($rawdata);
 668          return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
 669      }
 670  
 671  
 672      /**
 673       * @param string $ArrayPath
 674       * @param string $Separator
 675       * @param mixed $Value
 676       *
 677       * @return array
 678       */
 679  	public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
 680          // assigns $Value to a nested array path:
 681          //   $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
 682          // is the same as:
 683          //   $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
 684          // or
 685          //   $foo['path']['to']['my'] = 'file.txt';
 686          $ArrayPath = ltrim($ArrayPath, $Separator);
 687          $ReturnedArray = array();
 688          if (($pos = strpos($ArrayPath, $Separator)) !== false) {
 689              $ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
 690          } else {
 691              $ReturnedArray[$ArrayPath] = $Value;
 692          }
 693          return $ReturnedArray;
 694      }
 695  
 696      /**
 697       * @param array $arraydata
 698       * @param bool  $returnkey
 699       *
 700       * @return int|false
 701       */
 702  	public static function array_max($arraydata, $returnkey=false) {
 703          $maxvalue = false;
 704          $maxkey   = false;
 705          foreach ($arraydata as $key => $value) {
 706              if (!is_array($value)) {
 707                  if (($maxvalue === false) || ($value > $maxvalue)) {
 708                      $maxvalue = $value;
 709                      $maxkey = $key;
 710                  }
 711              }
 712          }
 713          return ($returnkey ? $maxkey : $maxvalue);
 714      }
 715  
 716      /**
 717       * @param array $arraydata
 718       * @param bool  $returnkey
 719       *
 720       * @return int|false
 721       */
 722  	public static function array_min($arraydata, $returnkey=false) {
 723          $minvalue = false;
 724          $minkey   = false;
 725          foreach ($arraydata as $key => $value) {
 726              if (!is_array($value)) {
 727                  if (($minvalue === false) || ($value < $minvalue)) {
 728                      $minvalue = $value;
 729                      $minkey = $key;
 730                  }
 731              }
 732          }
 733          return ($returnkey ? $minkey : $minvalue);
 734      }
 735  
 736      /**
 737       * @param string $XMLstring
 738       *
 739       * @return array|false
 740       */
 741  	public static function XML2array($XMLstring) {
 742          if (function_exists('simplexml_load_string')) {
 743              if (PHP_VERSION_ID < 80000) {
 744                  if (function_exists('libxml_disable_entity_loader')) {
 745                      // http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html
 746                      // https://core.trac.wordpress.org/changeset/29378
 747                      // This function has been deprecated in PHP 8.0 because in libxml 2.9.0, external entity loading is
 748                      // disabled by default, but is still needed when LIBXML_NOENT is used.
 749                      $loader = @libxml_disable_entity_loader(true);
 750                      $XMLobject = simplexml_load_string($XMLstring, 'SimpleXMLElement', GETID3_LIBXML_OPTIONS);
 751                      $return = self::SimpleXMLelement2array($XMLobject);
 752                      @libxml_disable_entity_loader($loader);
 753                      return $return;
 754                  }
 755              } else {
 756                  $allow = false;
 757                  if (defined('LIBXML_VERSION') && (LIBXML_VERSION >= 20900)) {
 758                      // https://www.php.net/manual/en/function.libxml-disable-entity-loader.php
 759                      // "as of libxml 2.9.0 entity substitution is disabled by default, so there is no need to disable the loading
 760                      //  of external entities, unless there is the need to resolve internal entity references with LIBXML_NOENT."
 761                      $allow = true;
 762                  } elseif (function_exists('libxml_set_external_entity_loader')) {
 763                      libxml_set_external_entity_loader(function () { return null; }); // https://www.zend.com/blog/cve-2023-3823
 764                      $allow = true;
 765                  }
 766                  if ($allow) {
 767                      $XMLobject = simplexml_load_string($XMLstring, 'SimpleXMLElement', GETID3_LIBXML_OPTIONS);
 768                      $return = self::SimpleXMLelement2array($XMLobject);
 769                      return $return;
 770                  }
 771              }
 772          }
 773          return false;
 774      }
 775  
 776      /**
 777      * @param SimpleXMLElement|array|mixed $XMLobject
 778      *
 779      * @return mixed
 780      */
 781  	public static function SimpleXMLelement2array($XMLobject) {
 782          if (!is_object($XMLobject) && !is_array($XMLobject)) {
 783              return $XMLobject;
 784          }
 785          $XMLarray = $XMLobject instanceof SimpleXMLElement ? get_object_vars($XMLobject) : $XMLobject;
 786          foreach ($XMLarray as $key => $value) {
 787              $XMLarray[$key] = self::SimpleXMLelement2array($value);
 788          }
 789          return $XMLarray;
 790      }
 791  
 792      /**
 793       * Returns checksum for a file from starting position to absolute end position.
 794       *
 795       * @param string $file
 796       * @param int    $offset
 797       * @param int    $end
 798       * @param string $algorithm
 799       *
 800       * @return string|false
 801       * @throws getid3_exception
 802       */
 803  	public static function hash_data($file, $offset, $end, $algorithm) {
 804          if (!self::intValueSupported($end)) {
 805              return false;
 806          }
 807          if (!in_array($algorithm, array('md5', 'sha1'))) {
 808              throw new getid3_exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
 809          }
 810  
 811          $size = $end - $offset;
 812  
 813          $fp = fopen($file, 'rb');
 814          fseek($fp, $offset);
 815          $ctx = hash_init($algorithm);
 816          while ($size > 0) {
 817              $buffer = fread($fp, min($size, getID3::FREAD_BUFFER_SIZE));
 818              hash_update($ctx, $buffer);
 819              $size -= getID3::FREAD_BUFFER_SIZE;
 820          }
 821          $hash = hash_final($ctx);
 822          fclose($fp);
 823  
 824          return $hash;
 825      }
 826  
 827      /**
 828       * @param string $filename_source
 829       * @param string $filename_dest
 830       * @param int    $offset
 831       * @param int    $length
 832       *
 833       * @return bool
 834       * @throws Exception
 835       *
 836       * @deprecated Unused, may be removed in future versions of getID3
 837       */
 838  	public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
 839          if (!self::intValueSupported($offset + $length)) {
 840              throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
 841          }
 842          if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
 843              if (($fp_dest = fopen($filename_dest, 'wb'))) {
 844                  if (fseek($fp_src, $offset) == 0) {
 845                      $byteslefttowrite = $length;
 846                      while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
 847                          $byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
 848                          $byteslefttowrite -= $byteswritten;
 849                      }
 850                      fclose($fp_dest);
 851                      return true;
 852                  } else {
 853                      fclose($fp_src);
 854                      throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
 855                  }
 856              } else {
 857                  throw new Exception('failed to create file for writing '.$filename_dest);
 858              }
 859          } else {
 860              throw new Exception('failed to open file for reading '.$filename_source);
 861          }
 862      }
 863  
 864      /**
 865       * @param int $charval
 866       *
 867       * @return string
 868       */
 869  	public static function iconv_fallback_int_utf8($charval) {
 870          if ($charval < 128) {
 871              // 0bbbbbbb
 872              $newcharstring = chr($charval);
 873          } elseif ($charval < 2048) {
 874              // 110bbbbb 10bbbbbb
 875              $newcharstring  = chr(($charval >>   6) | 0xC0);
 876              $newcharstring .= chr(($charval & 0x3F) | 0x80);
 877          } elseif ($charval < 65536) {
 878              // 1110bbbb 10bbbbbb 10bbbbbb
 879              $newcharstring  = chr(($charval >>  12) | 0xE0);
 880              $newcharstring .= chr(($charval >>   6) | 0xC0);
 881              $newcharstring .= chr(($charval & 0x3F) | 0x80);
 882          } else {
 883              // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
 884              $newcharstring  = chr(($charval >>  18) | 0xF0);
 885              $newcharstring .= chr(($charval >>  12) | 0xC0);
 886              $newcharstring .= chr(($charval >>   6) | 0xC0);
 887              $newcharstring .= chr(($charval & 0x3F) | 0x80);
 888          }
 889          return $newcharstring;
 890      }
 891  
 892      /**
 893       * ISO-8859-1 => UTF-8
 894       *
 895       * @param string $string
 896       * @param bool   $bom
 897       *
 898       * @return string
 899       */
 900  	public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
 901          $newcharstring = '';
 902          if ($bom) {
 903              $newcharstring .= "\xEF\xBB\xBF";
 904          }
 905          for ($i = 0; $i < strlen($string); $i++) {
 906              $charval = ord($string[$i]);
 907              $newcharstring .= self::iconv_fallback_int_utf8($charval);
 908          }
 909          return $newcharstring;
 910      }
 911  
 912      /**
 913       * ISO-8859-1 => UTF-16BE
 914       *
 915       * @param string $string
 916       * @param bool   $bom
 917       *
 918       * @return string
 919       */
 920  	public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
 921          $newcharstring = '';
 922          if ($bom) {
 923              $newcharstring .= "\xFE\xFF";
 924          }
 925          for ($i = 0; $i < strlen($string); $i++) {
 926              $newcharstring .= "\x00".$string[$i];
 927          }
 928          return $newcharstring;
 929      }
 930  
 931      /**
 932       * ISO-8859-1 => UTF-16LE
 933       *
 934       * @param string $string
 935       * @param bool   $bom
 936       *
 937       * @return string
 938       */
 939  	public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
 940          $newcharstring = '';
 941          if ($bom) {
 942              $newcharstring .= "\xFF\xFE";
 943          }
 944          for ($i = 0; $i < strlen($string); $i++) {
 945              $newcharstring .= $string[$i]."\x00";
 946          }
 947          return $newcharstring;
 948      }
 949  
 950      /**
 951       * ISO-8859-1 => UTF-16LE (BOM)
 952       *
 953       * @param string $string
 954       *
 955       * @return string
 956       */
 957  	public static function iconv_fallback_iso88591_utf16($string) {
 958          return self::iconv_fallback_iso88591_utf16le($string, true);
 959      }
 960  
 961      /**
 962       * UTF-8 => ISO-8859-1
 963       *
 964       * @param string $string
 965       *
 966       * @return string
 967       */
 968  	public static function iconv_fallback_utf8_iso88591($string) {
 969          $newcharstring = '';
 970          $offset = 0;
 971          $stringlength = strlen($string);
 972          while ($offset < $stringlength) {
 973              if ((ord($string[$offset]) | 0x07) == 0xF7) {
 974                  // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
 975                  $charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
 976                             ((ord($string[($offset + 1)]) & 0x3F) << 12) &
 977                             ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
 978                              (ord($string[($offset + 3)]) & 0x3F);
 979                  $offset += 4;
 980              } elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
 981                  // 1110bbbb 10bbbbbb 10bbbbbb
 982                  $charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
 983                             ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
 984                              (ord($string[($offset + 2)]) & 0x3F);
 985                  $offset += 3;
 986              } elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
 987                  // 110bbbbb 10bbbbbb
 988                  $charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
 989                              (ord($string[($offset + 1)]) & 0x3F);
 990                  $offset += 2;
 991              } elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
 992                  // 0bbbbbbb
 993                  $charval = ord($string[$offset]);
 994                  $offset += 1;
 995              } else {
 996                  // error? throw some kind of warning here?
 997                  $charval = false;
 998                  $offset += 1;
 999              }
1000              if ($charval !== false) {
1001                  $newcharstring .= (($charval < 256) ? chr($charval) : '?');
1002              }
1003          }
1004          return $newcharstring;
1005      }
1006  
1007      /**
1008       * UTF-8 => UTF-16BE
1009       *
1010       * @param string $string
1011       * @param bool   $bom
1012       *
1013       * @return string
1014       */
1015  	public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
1016          $newcharstring = '';
1017          if ($bom) {
1018              $newcharstring .= "\xFE\xFF";
1019          }
1020          $offset = 0;
1021          $stringlength = strlen($string);
1022          while ($offset < $stringlength) {
1023              if ((ord($string[$offset]) | 0x07) == 0xF7) {
1024                  // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
1025                  $charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
1026                             ((ord($string[($offset + 1)]) & 0x3F) << 12) &
1027                             ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
1028                              (ord($string[($offset + 3)]) & 0x3F);
1029                  $offset += 4;
1030              } elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
1031                  // 1110bbbb 10bbbbbb 10bbbbbb
1032                  $charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
1033                             ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
1034                              (ord($string[($offset + 2)]) & 0x3F);
1035                  $offset += 3;
1036              } elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
1037                  // 110bbbbb 10bbbbbb
1038                  $charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
1039                              (ord($string[($offset + 1)]) & 0x3F);
1040                  $offset += 2;
1041              } elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
1042                  // 0bbbbbbb
1043                  $charval = ord($string[$offset]);
1044                  $offset += 1;
1045              } else {
1046                  // error? throw some kind of warning here?
1047                  $charval = false;
1048                  $offset += 1;
1049              }
1050              if ($charval !== false) {
1051                  $newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
1052              }
1053          }
1054          return $newcharstring;
1055      }
1056  
1057      /**
1058       * UTF-8 => UTF-16LE
1059       *
1060       * @param string $string
1061       * @param bool   $bom
1062       *
1063       * @return string
1064       */
1065  	public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
1066          $newcharstring = '';
1067          if ($bom) {
1068              $newcharstring .= "\xFF\xFE";
1069          }
1070          $offset = 0;
1071          $stringlength = strlen($string);
1072          while ($offset < $stringlength) {
1073              if ((ord($string[$offset]) | 0x07) == 0xF7) {
1074                  // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
1075                  $charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
1076                             ((ord($string[($offset + 1)]) & 0x3F) << 12) &
1077                             ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
1078                              (ord($string[($offset + 3)]) & 0x3F);
1079                  $offset += 4;
1080              } elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
1081                  // 1110bbbb 10bbbbbb 10bbbbbb
1082                  $charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
1083                             ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
1084                              (ord($string[($offset + 2)]) & 0x3F);
1085                  $offset += 3;
1086              } elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
1087                  // 110bbbbb 10bbbbbb
1088                  $charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
1089                              (ord($string[($offset + 1)]) & 0x3F);
1090                  $offset += 2;
1091              } elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
1092                  // 0bbbbbbb
1093                  $charval = ord($string[$offset]);
1094                  $offset += 1;
1095              } else {
1096                  // error? maybe throw some warning here?
1097                  $charval = false;
1098                  $offset += 1;
1099              }
1100              if ($charval !== false) {
1101                  $newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
1102              }
1103          }
1104          return $newcharstring;
1105      }
1106  
1107      /**
1108       * UTF-8 => UTF-16LE (BOM)
1109       *
1110       * @param string $string
1111       *
1112       * @return string
1113       */
1114  	public static function iconv_fallback_utf8_utf16($string) {
1115          return self::iconv_fallback_utf8_utf16le($string, true);
1116      }
1117  
1118      /**
1119       * UTF-16BE => UTF-8
1120       *
1121       * @param string $string
1122       *
1123       * @return string
1124       */
1125  	public static function iconv_fallback_utf16be_utf8($string) {
1126          if (substr($string, 0, 2) == "\xFE\xFF") {
1127              // strip BOM
1128              $string = substr($string, 2);
1129          }
1130          $newcharstring = '';
1131          for ($i = 0; $i < strlen($string); $i += 2) {
1132              $charval = self::BigEndian2Int(substr($string, $i, 2));
1133              $newcharstring .= self::iconv_fallback_int_utf8($charval);
1134          }
1135          return $newcharstring;
1136      }
1137  
1138      /**
1139       * UTF-16LE => UTF-8
1140       *
1141       * @param string $string
1142       *
1143       * @return string
1144       */
1145  	public static function iconv_fallback_utf16le_utf8($string) {
1146          if (substr($string, 0, 2) == "\xFF\xFE") {
1147              // strip BOM
1148              $string = substr($string, 2);
1149          }
1150          $newcharstring = '';
1151          for ($i = 0; $i < strlen($string); $i += 2) {
1152              $charval = self::LittleEndian2Int(substr($string, $i, 2));
1153              $newcharstring .= self::iconv_fallback_int_utf8($charval);
1154          }
1155          return $newcharstring;
1156      }
1157  
1158      /**
1159       * UTF-16BE => ISO-8859-1
1160       *
1161       * @param string $string
1162       *
1163       * @return string
1164       */
1165  	public static function iconv_fallback_utf16be_iso88591($string) {
1166          if (substr($string, 0, 2) == "\xFE\xFF") {
1167              // strip BOM
1168              $string = substr($string, 2);
1169          }
1170          $newcharstring = '';
1171          for ($i = 0; $i < strlen($string); $i += 2) {
1172              $charval = self::BigEndian2Int(substr($string, $i, 2));
1173              $newcharstring .= (($charval < 256) ? chr($charval) : '?');
1174          }
1175          return $newcharstring;
1176      }
1177  
1178      /**
1179       * UTF-16LE => ISO-8859-1
1180       *
1181       * @param string $string
1182       *
1183       * @return string
1184       */
1185  	public static function iconv_fallback_utf16le_iso88591($string) {
1186          if (substr($string, 0, 2) == "\xFF\xFE") {
1187              // strip BOM
1188              $string = substr($string, 2);
1189          }
1190          $newcharstring = '';
1191          for ($i = 0; $i < strlen($string); $i += 2) {
1192              $charval = self::LittleEndian2Int(substr($string, $i, 2));
1193              $newcharstring .= (($charval < 256) ? chr($charval) : '?');
1194          }
1195          return $newcharstring;
1196      }
1197  
1198      /**
1199       * UTF-16 (BOM) => ISO-8859-1
1200       *
1201       * @param string $string
1202       *
1203       * @return string
1204       */
1205  	public static function iconv_fallback_utf16_iso88591($string) {
1206          $bom = substr($string, 0, 2);
1207          if ($bom == "\xFE\xFF") {
1208              return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
1209          } elseif ($bom == "\xFF\xFE") {
1210              return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
1211          }
1212          return $string;
1213      }
1214  
1215      /**
1216       * UTF-16 (BOM) => UTF-8
1217       *
1218       * @param string $string
1219       *
1220       * @return string
1221       */
1222  	public static function iconv_fallback_utf16_utf8($string) {
1223          $bom = substr($string, 0, 2);
1224          if ($bom == "\xFE\xFF") {
1225              return self::iconv_fallback_utf16be_utf8(substr($string, 2));
1226          } elseif ($bom == "\xFF\xFE") {
1227              return self::iconv_fallback_utf16le_utf8(substr($string, 2));
1228          }
1229          return $string;
1230      }
1231  
1232      /**
1233       * @param string $in_charset
1234       * @param string $out_charset
1235       * @param string $string
1236       *
1237       * @return string
1238       * @throws Exception
1239       */
1240  	public static function iconv_fallback($in_charset, $out_charset, $string) {
1241  
1242          if ($in_charset == $out_charset) {
1243              return $string;
1244          }
1245  
1246          // mb_convert_encoding() available
1247          if (function_exists('mb_convert_encoding')) {
1248              if ((strtoupper($in_charset) == 'UTF-16') && (substr($string, 0, 2) != "\xFE\xFF") && (substr($string, 0, 2) != "\xFF\xFE")) {
1249                  // if BOM missing, mb_convert_encoding will mishandle the conversion, assume UTF-16BE and prepend appropriate BOM
1250                  $string = "\xFF\xFE".$string;
1251              }
1252              if ((strtoupper($in_charset) == 'UTF-16') && (strtoupper($out_charset) == 'UTF-8')) {
1253                  if (($string == "\xFF\xFE") || ($string == "\xFE\xFF")) {
1254                      // if string consists of only BOM, mb_convert_encoding will return the BOM unmodified
1255                      return '';
1256                  }
1257              }
1258              if ($converted_string = @mb_convert_encoding($string, $out_charset, $in_charset)) {
1259                  switch ($out_charset) {
1260                      case 'ISO-8859-1':
1261                          $converted_string = rtrim($converted_string, "\x00");
1262                          break;
1263                  }
1264                  return $converted_string;
1265              }
1266              return $string;
1267  
1268          // iconv() available
1269          } elseif (function_exists('iconv')) {
1270              if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
1271                  switch ($out_charset) {
1272                      case 'ISO-8859-1':
1273                          $converted_string = rtrim($converted_string, "\x00");
1274                          break;
1275                  }
1276                  return $converted_string;
1277              }
1278  
1279              // iconv() may sometimes fail with "illegal character in input string" error message
1280              // and return an empty string, but returning the unconverted string is more useful
1281              return $string;
1282          }
1283  
1284  
1285          // neither mb_convert_encoding or iconv() is available
1286          static $ConversionFunctionList = array();
1287          if (empty($ConversionFunctionList)) {
1288              $ConversionFunctionList['ISO-8859-1']['UTF-8']    = 'iconv_fallback_iso88591_utf8';
1289              $ConversionFunctionList['ISO-8859-1']['UTF-16']   = 'iconv_fallback_iso88591_utf16';
1290              $ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
1291              $ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
1292              $ConversionFunctionList['UTF-8']['ISO-8859-1']    = 'iconv_fallback_utf8_iso88591';
1293              $ConversionFunctionList['UTF-8']['UTF-16']        = 'iconv_fallback_utf8_utf16';
1294              $ConversionFunctionList['UTF-8']['UTF-16BE']      = 'iconv_fallback_utf8_utf16be';
1295              $ConversionFunctionList['UTF-8']['UTF-16LE']      = 'iconv_fallback_utf8_utf16le';
1296              $ConversionFunctionList['UTF-16']['ISO-8859-1']   = 'iconv_fallback_utf16_iso88591';
1297              $ConversionFunctionList['UTF-16']['UTF-8']        = 'iconv_fallback_utf16_utf8';
1298              $ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
1299              $ConversionFunctionList['UTF-16LE']['UTF-8']      = 'iconv_fallback_utf16le_utf8';
1300              $ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
1301              $ConversionFunctionList['UTF-16BE']['UTF-8']      = 'iconv_fallback_utf16be_utf8';
1302          }
1303          if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
1304              $ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
1305              return self::$ConversionFunction($string);
1306          }
1307          throw new Exception('PHP does not has mb_convert_encoding() or iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
1308      }
1309  
1310      /**
1311       * @param mixed  $data
1312       * @param string $charset
1313       *
1314       * @return mixed
1315       */
1316  	public static function recursiveMultiByteCharString2HTML($data, $charset='ISO-8859-1') {
1317          if (is_string($data)) {
1318              return self::MultiByteCharString2HTML($data, $charset);
1319          } elseif (is_array($data)) {
1320              $return_data = array();
1321              foreach ($data as $key => $value) {
1322                  $return_data[$key] = self::recursiveMultiByteCharString2HTML($value, $charset);
1323              }
1324              return $return_data;
1325          }
1326          // integer, float, objects, resources, etc
1327          return $data;
1328      }
1329  
1330      /**
1331       * @param string|int|float $string
1332       * @param string           $charset
1333       *
1334       * @return string
1335       */
1336  	public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
1337          $string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
1338          $HTMLstring = '';
1339  
1340          switch (strtolower($charset)) {
1341              case '1251':
1342              case '1252':
1343              case '866':
1344              case '932':
1345              case '936':
1346              case '950':
1347              case 'big5':
1348              case 'big5-hkscs':
1349              case 'cp1251':
1350              case 'cp1252':
1351              case 'cp866':
1352              case 'euc-jp':
1353              case 'eucjp':
1354              case 'gb2312':
1355              case 'ibm866':
1356              case 'iso-8859-1':
1357              case 'iso-8859-15':
1358              case 'iso8859-1':
1359              case 'iso8859-15':
1360              case 'koi8-r':
1361              case 'koi8-ru':
1362              case 'koi8r':
1363              case 'shift_jis':
1364              case 'sjis':
1365              case 'win-1251':
1366              case 'windows-1251':
1367              case 'windows-1252':
1368                  $HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
1369                  break;
1370  
1371              case 'utf-8':
1372                  $strlen = strlen($string);
1373                  for ($i = 0; $i < $strlen; $i++) {
1374                      $char_ord_val = ord($string[$i]);
1375                      $charval = 0;
1376                      if ($char_ord_val < 0x80) {
1377                          $charval = $char_ord_val;
1378                      } elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F  &&  $i+3 < $strlen) {
1379                          $charval  = (($char_ord_val & 0x07) << 18);
1380                          $charval += ((ord($string[++$i]) & 0x3F) << 12);
1381                          $charval += ((ord($string[++$i]) & 0x3F) << 6);
1382                          $charval +=  (ord($string[++$i]) & 0x3F);
1383                      } elseif ((($char_ord_val & 0xE0) >> 5) == 0x07  &&  $i+2 < $strlen) {
1384                          $charval  = (($char_ord_val & 0x0F) << 12);
1385                          $charval += ((ord($string[++$i]) & 0x3F) << 6);
1386                          $charval +=  (ord($string[++$i]) & 0x3F);
1387                      } elseif ((($char_ord_val & 0xC0) >> 6) == 0x03  &&  $i+1 < $strlen) {
1388                          $charval  = (($char_ord_val & 0x1F) << 6);
1389                          $charval += (ord($string[++$i]) & 0x3F);
1390                      }
1391                      if (($charval >= 32) && ($charval <= 127)) {
1392                          $HTMLstring .= htmlentities(chr($charval));
1393                      } else {
1394                          $HTMLstring .= '&#'.$charval.';';
1395                      }
1396                  }
1397                  break;
1398  
1399              case 'utf-16le':
1400                  for ($i = 0; $i < strlen($string); $i += 2) {
1401                      $charval = self::LittleEndian2Int(substr($string, $i, 2));
1402                      if (($charval >= 32) && ($charval <= 127)) {
1403                          $HTMLstring .= chr($charval);
1404                      } else {
1405                          $HTMLstring .= '&#'.$charval.';';
1406                      }
1407                  }
1408                  break;
1409  
1410              case 'utf-16be':
1411                  for ($i = 0; $i < strlen($string); $i += 2) {
1412                      $charval = self::BigEndian2Int(substr($string, $i, 2));
1413                      if (($charval >= 32) && ($charval <= 127)) {
1414                          $HTMLstring .= chr($charval);
1415                      } else {
1416                          $HTMLstring .= '&#'.$charval.';';
1417                      }
1418                  }
1419                  break;
1420  
1421              default:
1422                  $HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
1423                  break;
1424          }
1425          return $HTMLstring;
1426      }
1427  
1428      /**
1429       * @param int $namecode
1430       *
1431       * @return string
1432       */
1433  	public static function RGADnameLookup($namecode) {
1434          static $RGADname = array();
1435          if (empty($RGADname)) {
1436              $RGADname[0] = 'not set';
1437              $RGADname[1] = 'Track Gain Adjustment';
1438              $RGADname[2] = 'Album Gain Adjustment';
1439          }
1440  
1441          return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
1442      }
1443  
1444      /**
1445       * @param int $originatorcode
1446       *
1447       * @return string
1448       */
1449  	public static function RGADoriginatorLookup($originatorcode) {
1450          static $RGADoriginator = array();
1451          if (empty($RGADoriginator)) {
1452              $RGADoriginator[0] = 'unspecified';
1453              $RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
1454              $RGADoriginator[2] = 'set by user';
1455              $RGADoriginator[3] = 'determined automatically';
1456          }
1457  
1458          return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
1459      }
1460  
1461      /**
1462       * @param int $rawadjustment
1463       * @param int $signbit
1464       *
1465       * @return float
1466       */
1467  	public static function RGADadjustmentLookup($rawadjustment, $signbit) {
1468          $adjustment = (float) $rawadjustment / 10;
1469          if ($signbit == 1) {
1470              $adjustment *= -1;
1471          }
1472          return $adjustment;
1473      }
1474  
1475      /**
1476       * @param int $namecode
1477       * @param int $originatorcode
1478       * @param int $replaygain
1479       *
1480       * @return string
1481       */
1482  	public static function RGADgainString($namecode, $originatorcode, $replaygain) {
1483          if ($replaygain < 0) {
1484              $signbit = '1';
1485          } else {
1486              $signbit = '0';
1487          }
1488          $storedreplaygain = intval(round($replaygain * 10));
1489          $gainstring  = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
1490          $gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
1491          $gainstring .= $signbit;
1492          $gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
1493  
1494          return $gainstring;
1495      }
1496  
1497      /**
1498       * @param float $amplitude
1499       *
1500       * @return float
1501       */
1502  	public static function RGADamplitude2dB($amplitude) {
1503          return 20 * log10($amplitude);
1504      }
1505  
1506      /**
1507       * @param string $imgData
1508       * @param array  $imageinfo
1509       *
1510       * @return array|false
1511       */
1512  	public static function GetDataImageSize($imgData, &$imageinfo=array()) {
1513          if (PHP_VERSION_ID >= 50400) {
1514              $GetDataImageSize = @getimagesizefromstring($imgData, $imageinfo);
1515              if ($GetDataImageSize === false) {
1516                  return false;
1517              }
1518              $GetDataImageSize['height'] = $GetDataImageSize[0];
1519              $GetDataImageSize['width'] = $GetDataImageSize[1];
1520              return $GetDataImageSize;
1521          }
1522          static $tempdir = '';
1523          if (empty($tempdir)) {
1524              if (function_exists('sys_get_temp_dir')) {
1525                  $tempdir = sys_get_temp_dir(); // https://github.com/JamesHeinrich/getID3/issues/52
1526              }
1527  
1528              // yes this is ugly, feel free to suggest a better way
1529              if (include_once(dirname(__FILE__).'/getid3.php')) {
1530                  $getid3_temp = new getID3();
1531                  if ($getid3_temp_tempdir = $getid3_temp->tempdir) {
1532                      $tempdir = $getid3_temp_tempdir;
1533                  }
1534                  unset($getid3_temp, $getid3_temp_tempdir);
1535              }
1536          }
1537          $GetDataImageSize = false;
1538          if ($tempfilename = tempnam($tempdir, 'gI3')) {
1539              if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
1540                  fwrite($tmp, $imgData);
1541                  fclose($tmp);
1542                  $GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
1543                  if ($GetDataImageSize === false) {
1544                      return false;
1545                  }
1546                  $GetDataImageSize['height'] = $GetDataImageSize[0];
1547                  $GetDataImageSize['width']  = $GetDataImageSize[1];
1548              }
1549              unlink($tempfilename);
1550          }
1551          return $GetDataImageSize;
1552      }
1553  
1554      /**
1555       * @param string $mime_type
1556       *
1557       * @return string
1558       */
1559  	public static function ImageExtFromMime($mime_type) {
1560          // temporary way, works OK for now, but should be reworked in the future
1561          return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
1562      }
1563  
1564      /**
1565       * @param array $ThisFileInfo
1566       * @param bool  $option_tags_html default true (just as in the main getID3 class)
1567       *
1568       * @return bool
1569       */
1570  	public static function CopyTagsToComments(&$ThisFileInfo, $option_tags_html=true) {
1571          // Copy all entries from ['tags'] into common ['comments']
1572          if (!empty($ThisFileInfo['tags'])) {
1573  
1574              // Some tag types can only support limited character sets and may contain data in non-standard encoding (usually ID3v1)
1575              // and/or poorly-transliterated tag values that are also in tag formats that do support full-range character sets
1576              // To make the output more user-friendly, process the potentially-problematic tag formats last to enhance the chance that
1577              // the first entries in [comments] are the most correct and the "bad" ones (if any) come later.
1578              // https://github.com/JamesHeinrich/getID3/issues/338
1579              $processLastTagTypes = array('id3v1','riff');
1580              foreach ($processLastTagTypes as $processLastTagType) {
1581                  if (isset($ThisFileInfo['tags'][$processLastTagType])) {
1582                      // bubble ID3v1 to the end, if present to aid in detecting bad ID3v1 encodings
1583                      $temp = $ThisFileInfo['tags'][$processLastTagType];
1584                      unset($ThisFileInfo['tags'][$processLastTagType]);
1585                      $ThisFileInfo['tags'][$processLastTagType] = $temp;
1586                      unset($temp);
1587                  }
1588              }
1589              foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
1590                  foreach ($tagarray as $tagname => $tagdata) {
1591                      foreach ($tagdata as $key => $value) {
1592                          if (!empty($value)) {
1593                              if (empty($ThisFileInfo['comments'][$tagname])) {
1594  
1595                                  // fall through and append value
1596  
1597                              } elseif ($tagtype == 'id3v1') {
1598  
1599                                  $newvaluelength = strlen(trim($value));
1600                                  foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1601                                      $oldvaluelength = strlen(trim($existingvalue));
1602                                      if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
1603                                          // new value is identical but shorter-than (or equal-length to) one already in comments - skip
1604                                          break 2;
1605                                      }
1606  
1607                                      if (function_exists('mb_convert_encoding')) {
1608                                          if (trim($value) == trim(substr(mb_convert_encoding($existingvalue, $ThisFileInfo['id3v1']['encoding'], $ThisFileInfo['encoding']), 0, 30))) {
1609                                              // value stored in ID3v1 appears to be probably the multibyte value transliterated (badly) into ISO-8859-1 in ID3v1.
1610                                              // As an example, Foobar2000 will do this if you tag a file with Chinese or Arabic or Cyrillic or something that doesn't fit into ISO-8859-1 the ID3v1 will consist of mostly "?" characters, one per multibyte unrepresentable character
1611                                              break 2;
1612                                          }
1613                                      }
1614                                  }
1615  
1616                              } elseif (!is_array($value)) {
1617  
1618                                  $newvaluelength   =    strlen(trim($value));
1619                                  $newvaluelengthMB = mb_strlen(trim($value));
1620                                  foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1621                                      $oldvaluelength   =    strlen(trim($existingvalue));
1622                                      $oldvaluelengthMB = mb_strlen(trim($existingvalue));
1623                                      if (($newvaluelengthMB == $oldvaluelengthMB) && ($existingvalue == getid3_lib::iconv_fallback('UTF-8', 'ASCII', $value))) {
1624                                          // https://github.com/JamesHeinrich/getID3/issues/338
1625                                          // check for tags containing extended characters that may have been forced into limited-character storage (e.g. UTF8 values into ASCII)
1626                                          // which will usually display unrepresentable characters as "?"
1627                                          $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
1628                                          break;
1629                                      }
1630                                      if ((strlen($existingvalue) > 10) && ($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
1631                                          $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
1632                                          break;
1633                                      }
1634                                  }
1635  
1636                              }
1637                              if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
1638                                  $value = (is_string($value) ? trim($value) : $value);
1639                                  if (!is_int($key) && !ctype_digit($key)) {
1640                                      $ThisFileInfo['comments'][$tagname][$key] = $value;
1641                                  } else {
1642                                      if (!isset($ThisFileInfo['comments'][$tagname])) {
1643                                          $ThisFileInfo['comments'][$tagname] = array($value);
1644                                      } else {
1645                                          $ThisFileInfo['comments'][$tagname][] = $value;
1646                                      }
1647                                  }
1648                              }
1649                          }
1650                      }
1651                  }
1652              }
1653  
1654              // attempt to standardize spelling of returned keys
1655              if (!empty($ThisFileInfo['comments'])) {
1656                  $StandardizeFieldNames = array(
1657                      'tracknumber' => 'track_number',
1658                      'track'       => 'track_number',
1659                  );
1660                  foreach ($StandardizeFieldNames as $badkey => $goodkey) {
1661                      if (array_key_exists($badkey, $ThisFileInfo['comments']) && !array_key_exists($goodkey, $ThisFileInfo['comments'])) {
1662                          $ThisFileInfo['comments'][$goodkey] = $ThisFileInfo['comments'][$badkey];
1663                          unset($ThisFileInfo['comments'][$badkey]);
1664                      }
1665                  }
1666              }
1667  
1668              if ($option_tags_html) {
1669                  // Copy ['comments'] to ['comments_html']
1670                  if (!empty($ThisFileInfo['comments'])) {
1671                      foreach ($ThisFileInfo['comments'] as $field => $values) {
1672                          if ($field == 'picture') {
1673                              // pictures can take up a lot of space, and we don't need multiple copies of them
1674                              // let there be a single copy in [comments][picture], and not elsewhere
1675                              continue;
1676                          }
1677                          foreach ($values as $index => $value) {
1678                              if (is_array($value)) {
1679                                  $ThisFileInfo['comments_html'][$field][$index] = $value;
1680                              } else {
1681                                  $ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
1682                              }
1683                          }
1684                      }
1685                  }
1686              }
1687  
1688          }
1689          return true;
1690      }
1691  
1692      /**
1693       * @param string $key
1694       * @param int    $begin
1695       * @param int    $end
1696       * @param string $file
1697       * @param string $name
1698       *
1699       * @return string
1700       */
1701  	public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
1702  
1703          // Cached
1704          static $cache;
1705          if (isset($cache[$file][$name])) {
1706              return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1707          }
1708  
1709          // Init
1710          $keylength  = strlen($key);
1711          $line_count = $end - $begin - 7;
1712  
1713          // Open php file
1714          $fp = fopen($file, 'r');
1715  
1716          // Discard $begin lines
1717          for ($i = 0; $i < ($begin + 3); $i++) {
1718              fgets($fp, 1024);
1719          }
1720  
1721          // Loop thru line
1722          while (0 < $line_count--) {
1723  
1724              // Read line
1725              $line = ltrim(fgets($fp, 1024), "\t ");
1726  
1727              // METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
1728              //$keycheck = substr($line, 0, $keylength);
1729              //if ($key == $keycheck)  {
1730              //    $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
1731              //    break;
1732              //}
1733  
1734              // METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
1735              //$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
1736              $explodedLine = explode("\t", $line, 2);
1737              $ThisKey   = $explodedLine[0];
1738              $ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
1739              $cache[$file][$name][$ThisKey] = trim($ThisValue);
1740          }
1741  
1742          // Close and return
1743          fclose($fp);
1744          return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1745      }
1746  
1747      /**
1748       * @param string $filename
1749       * @param string $sourcefile
1750       * @param bool   $DieOnFailure
1751       *
1752       * @return bool
1753       * @throws Exception
1754       */
1755  	public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
1756          global $GETID3_ERRORARRAY;
1757  
1758          if (file_exists($filename)) {
1759              if (include_once($filename)) {
1760                  return true;
1761              } else {
1762                  $diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
1763              }
1764          } else {
1765              $diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
1766          }
1767          if ($DieOnFailure) {
1768              throw new Exception($diemessage);
1769          } else {
1770              $GETID3_ERRORARRAY[] = $diemessage;
1771          }
1772          return false;
1773      }
1774  
1775      /**
1776       * @param string $string
1777       *
1778       * @return string
1779       */
1780  	public static function trimNullByte($string) {
1781          return trim($string, "\x00");
1782      }
1783  
1784      /**
1785       * @param string $path
1786       *
1787       * @return float|bool
1788       */
1789  	public static function getFileSizeSyscall($path) {
1790          $commandline = null;
1791          $filesize = false;
1792  
1793          if (GETID3_OS_ISWINDOWS) {
1794              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:
1795                  $filesystem = new COM('Scripting.FileSystemObject');
1796                  $file = $filesystem->GetFile($path);
1797                  $filesize = $file->Size();
1798                  unset($filesystem, $file);
1799              } else {
1800                  $commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
1801              }
1802          } else {
1803              $commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
1804          }
1805          if (isset($commandline)) {
1806              $output = trim(shell_exec($commandline));
1807              if (ctype_digit($output)) {
1808                  $filesize = (float) $output;
1809              }
1810          }
1811          return $filesize;
1812      }
1813  
1814      /**
1815       * @param string $filename
1816       *
1817       * @return string|false
1818       */
1819  	public static function truepath($filename) {
1820          // 2017-11-08: this could use some improvement, patches welcome
1821          if (preg_match('#^(\\\\\\\\|//)[a-z0-9]#i', $filename, $matches)) {
1822              // PHP's built-in realpath function does not work on UNC Windows shares
1823              $goodpath = array();
1824              foreach (explode('/', str_replace('\\', '/', $filename)) as $part) {
1825                  if ($part == '.') {
1826                      continue;
1827                  }
1828                  if ($part == '..') {
1829                      if (count($goodpath)) {
1830                          array_pop($goodpath);
1831                      } else {
1832                          // cannot step above this level, already at top level
1833                          return false;
1834                      }
1835                  } else {
1836                      $goodpath[] = $part;
1837                  }
1838              }
1839              return implode(DIRECTORY_SEPARATOR, $goodpath);
1840          }
1841          return realpath($filename);
1842      }
1843  
1844      /**
1845       * Workaround for Bug #37268 (https://bugs.php.net/bug.php?id=37268)
1846       *
1847       * @param string $path A path.
1848       * @param string $suffix If the name component ends in suffix this will also be cut off.
1849       *
1850       * @return string
1851       */
1852  	public static function mb_basename($path, $suffix = '') {
1853          $splited = preg_split('#/#', rtrim($path, '/ '));
1854          return substr(basename('X'.$splited[count($splited) - 1], $suffix), 1);
1855      }
1856  
1857  }


Generated : Sat Jun 27 08:20:12 2026 Cross-referenced by PHPXref