[ 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                      if ($loader === false && !libxml_disable_entity_loader(true)) {
 751                          // Failed to disable external entity loading โ€” refuse to parse to prevent XXE
 752                          return false;
 753                      }
 754                      $XMLobject = simplexml_load_string($XMLstring, 'SimpleXMLElement', GETID3_LIBXML_OPTIONS);
 755                      $return = self::SimpleXMLelement2array($XMLobject);
 756                      libxml_disable_entity_loader($loader);
 757                      return $return;
 758                  }
 759              } else {
 760                  $allow = false;
 761                  if (defined('LIBXML_VERSION') && (LIBXML_VERSION >= 20900)) {
 762                      // https://www.php.net/manual/en/function.libxml-disable-entity-loader.php
 763                      // "as of libxml 2.9.0 entity substitution is disabled by default, so there is no need to disable the loading
 764                      //  of external entities, unless there is the need to resolve internal entity references with LIBXML_NOENT."
 765                      $allow = true;
 766                  } elseif (function_exists('libxml_set_external_entity_loader')) {
 767                      libxml_set_external_entity_loader(function () { return null; }); // https://www.zend.com/blog/cve-2023-3823
 768                      $allow = true;
 769                  }
 770                  if ($allow) {
 771                      $XMLobject = simplexml_load_string($XMLstring, 'SimpleXMLElement', GETID3_LIBXML_OPTIONS);
 772                      $return = self::SimpleXMLelement2array($XMLobject);
 773                      return $return;
 774                  }
 775              }
 776          }
 777          return false;
 778      }
 779  
 780      /**
 781      * @param SimpleXMLElement|array|mixed $XMLobject
 782      *
 783      * @return mixed
 784      */
 785  	public static function SimpleXMLelement2array($XMLobject) {
 786          if (!is_object($XMLobject) && !is_array($XMLobject)) {
 787              return $XMLobject;
 788          }
 789          $XMLarray = $XMLobject instanceof SimpleXMLElement ? get_object_vars($XMLobject) : $XMLobject;
 790          foreach ($XMLarray as $key => $value) {
 791              $XMLarray[$key] = self::SimpleXMLelement2array($value);
 792          }
 793          return $XMLarray;
 794      }
 795  
 796      /**
 797       * Returns checksum for a file from starting position to absolute end position.
 798       *
 799       * @param string $file
 800       * @param int    $offset
 801       * @param int    $end
 802       * @param string $algorithm
 803       *
 804       * @return string|false
 805       * @throws getid3_exception
 806       */
 807  	public static function hash_data($file, $offset, $end, $algorithm) {
 808          if (!self::intValueSupported($end)) {
 809              return false;
 810          }
 811          if (!in_array($algorithm, array('md5', 'sha1'))) {
 812              throw new getid3_exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
 813          }
 814  
 815          $size = $end - $offset;
 816  
 817          $fp = fopen($file, 'rb');
 818          fseek($fp, $offset);
 819          $ctx = hash_init($algorithm);
 820          while ($size > 0) {
 821              $buffer = fread($fp, min($size, getID3::FREAD_BUFFER_SIZE));
 822              hash_update($ctx, $buffer);
 823              $size -= getID3::FREAD_BUFFER_SIZE;
 824          }
 825          $hash = hash_final($ctx);
 826          fclose($fp);
 827  
 828          return $hash;
 829      }
 830  
 831      /**
 832       * @param string $filename_source
 833       * @param string $filename_dest
 834       * @param int    $offset
 835       * @param int    $length
 836       *
 837       * @return bool
 838       * @throws Exception
 839       *
 840       * @deprecated Unused, may be removed in future versions of getID3
 841       */
 842  	public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
 843          if (!self::intValueSupported($offset + $length)) {
 844              throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
 845          }
 846          if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
 847              if (($fp_dest = fopen($filename_dest, 'wb'))) {
 848                  if (fseek($fp_src, $offset) == 0) {
 849                      $byteslefttowrite = $length;
 850                      while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
 851                          $byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
 852                          $byteslefttowrite -= $byteswritten;
 853                      }
 854                      fclose($fp_dest);
 855                      return true;
 856                  } else {
 857                      fclose($fp_src);
 858                      throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
 859                  }
 860              } else {
 861                  throw new Exception('failed to create file for writing '.$filename_dest);
 862              }
 863          } else {
 864              throw new Exception('failed to open file for reading '.$filename_source);
 865          }
 866      }
 867  
 868      /**
 869       * @param int $charval
 870       *
 871       * @return string
 872       */
 873  	public static function iconv_fallback_int_utf8($charval) {
 874          if ($charval < 128) {
 875              // 0bbbbbbb
 876              $newcharstring = chr($charval);
 877          } elseif ($charval < 2048) {
 878              // 110bbbbb 10bbbbbb
 879              $newcharstring  = chr(($charval >>   6) | 0xC0);
 880              $newcharstring .= chr(($charval & 0x3F) | 0x80);
 881          } elseif ($charval < 65536) {
 882              // 1110bbbb 10bbbbbb 10bbbbbb
 883              $newcharstring  = chr(($charval >>  12) | 0xE0);
 884              $newcharstring .= chr(($charval >>   6) | 0xC0);
 885              $newcharstring .= chr(($charval & 0x3F) | 0x80);
 886          } else {
 887              // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
 888              $newcharstring  = chr(($charval >>  18) | 0xF0);
 889              $newcharstring .= chr(($charval >>  12) | 0xC0);
 890              $newcharstring .= chr(($charval >>   6) | 0xC0);
 891              $newcharstring .= chr(($charval & 0x3F) | 0x80);
 892          }
 893          return $newcharstring;
 894      }
 895  
 896      /**
 897       * ISO-8859-1 => UTF-8
 898       *
 899       * @param string $string
 900       * @param bool   $bom
 901       *
 902       * @return string
 903       */
 904  	public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
 905          $newcharstring = '';
 906          if ($bom) {
 907              $newcharstring .= "\xEF\xBB\xBF";
 908          }
 909          for ($i = 0; $i < strlen($string); $i++) {
 910              $charval = ord($string[$i]);
 911              $newcharstring .= self::iconv_fallback_int_utf8($charval);
 912          }
 913          return $newcharstring;
 914      }
 915  
 916      /**
 917       * ISO-8859-1 => UTF-16BE
 918       *
 919       * @param string $string
 920       * @param bool   $bom
 921       *
 922       * @return string
 923       */
 924  	public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
 925          $newcharstring = '';
 926          if ($bom) {
 927              $newcharstring .= "\xFE\xFF";
 928          }
 929          for ($i = 0; $i < strlen($string); $i++) {
 930              $newcharstring .= "\x00".$string[$i];
 931          }
 932          return $newcharstring;
 933      }
 934  
 935      /**
 936       * ISO-8859-1 => UTF-16LE
 937       *
 938       * @param string $string
 939       * @param bool   $bom
 940       *
 941       * @return string
 942       */
 943  	public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
 944          $newcharstring = '';
 945          if ($bom) {
 946              $newcharstring .= "\xFF\xFE";
 947          }
 948          for ($i = 0; $i < strlen($string); $i++) {
 949              $newcharstring .= $string[$i]."\x00";
 950          }
 951          return $newcharstring;
 952      }
 953  
 954      /**
 955       * ISO-8859-1 => UTF-16LE (BOM)
 956       *
 957       * @param string $string
 958       *
 959       * @return string
 960       */
 961  	public static function iconv_fallback_iso88591_utf16($string) {
 962          return self::iconv_fallback_iso88591_utf16le($string, true);
 963      }
 964  
 965      /**
 966       * UTF-8 => ISO-8859-1
 967       *
 968       * @param string $string
 969       *
 970       * @return string
 971       */
 972  	public static function iconv_fallback_utf8_iso88591($string) {
 973          $newcharstring = '';
 974          $offset = 0;
 975          $stringlength = strlen($string);
 976          while ($offset < $stringlength) {
 977              if ((ord($string[$offset]) | 0x07) == 0xF7) {
 978                  // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
 979                  $charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
 980                             ((ord($string[($offset + 1)]) & 0x3F) << 12) &
 981                             ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
 982                              (ord($string[($offset + 3)]) & 0x3F);
 983                  $offset += 4;
 984              } elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
 985                  // 1110bbbb 10bbbbbb 10bbbbbb
 986                  $charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
 987                             ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
 988                              (ord($string[($offset + 2)]) & 0x3F);
 989                  $offset += 3;
 990              } elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
 991                  // 110bbbbb 10bbbbbb
 992                  $charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
 993                              (ord($string[($offset + 1)]) & 0x3F);
 994                  $offset += 2;
 995              } elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
 996                  // 0bbbbbbb
 997                  $charval = ord($string[$offset]);
 998                  $offset += 1;
 999              } else {
1000                  // error? throw some kind of warning here?
1001                  $charval = false;
1002                  $offset += 1;
1003              }
1004              if ($charval !== false) {
1005                  $newcharstring .= (($charval < 256) ? chr($charval) : '?');
1006              }
1007          }
1008          return $newcharstring;
1009      }
1010  
1011      /**
1012       * UTF-8 => UTF-16BE
1013       *
1014       * @param string $string
1015       * @param bool   $bom
1016       *
1017       * @return string
1018       */
1019  	public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
1020          $newcharstring = '';
1021          if ($bom) {
1022              $newcharstring .= "\xFE\xFF";
1023          }
1024          $offset = 0;
1025          $stringlength = strlen($string);
1026          while ($offset < $stringlength) {
1027              if ((ord($string[$offset]) | 0x07) == 0xF7) {
1028                  // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
1029                  $charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
1030                             ((ord($string[($offset + 1)]) & 0x3F) << 12) &
1031                             ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
1032                              (ord($string[($offset + 3)]) & 0x3F);
1033                  $offset += 4;
1034              } elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
1035                  // 1110bbbb 10bbbbbb 10bbbbbb
1036                  $charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
1037                             ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
1038                              (ord($string[($offset + 2)]) & 0x3F);
1039                  $offset += 3;
1040              } elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
1041                  // 110bbbbb 10bbbbbb
1042                  $charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
1043                              (ord($string[($offset + 1)]) & 0x3F);
1044                  $offset += 2;
1045              } elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
1046                  // 0bbbbbbb
1047                  $charval = ord($string[$offset]);
1048                  $offset += 1;
1049              } else {
1050                  // error? throw some kind of warning here?
1051                  $charval = false;
1052                  $offset += 1;
1053              }
1054              if ($charval !== false) {
1055                  $newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
1056              }
1057          }
1058          return $newcharstring;
1059      }
1060  
1061      /**
1062       * UTF-8 => UTF-16LE
1063       *
1064       * @param string $string
1065       * @param bool   $bom
1066       *
1067       * @return string
1068       */
1069  	public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
1070          $newcharstring = '';
1071          if ($bom) {
1072              $newcharstring .= "\xFF\xFE";
1073          }
1074          $offset = 0;
1075          $stringlength = strlen($string);
1076          while ($offset < $stringlength) {
1077              if ((ord($string[$offset]) | 0x07) == 0xF7) {
1078                  // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
1079                  $charval = ((ord($string[($offset + 0)]) & 0x07) << 18) &
1080                             ((ord($string[($offset + 1)]) & 0x3F) << 12) &
1081                             ((ord($string[($offset + 2)]) & 0x3F) <<  6) &
1082                              (ord($string[($offset + 3)]) & 0x3F);
1083                  $offset += 4;
1084              } elseif ((ord($string[$offset]) | 0x0F) == 0xEF) {
1085                  // 1110bbbb 10bbbbbb 10bbbbbb
1086                  $charval = ((ord($string[($offset + 0)]) & 0x0F) << 12) &
1087                             ((ord($string[($offset + 1)]) & 0x3F) <<  6) &
1088                              (ord($string[($offset + 2)]) & 0x3F);
1089                  $offset += 3;
1090              } elseif ((ord($string[$offset]) | 0x1F) == 0xDF) {
1091                  // 110bbbbb 10bbbbbb
1092                  $charval = ((ord($string[($offset + 0)]) & 0x1F) <<  6) &
1093                              (ord($string[($offset + 1)]) & 0x3F);
1094                  $offset += 2;
1095              } elseif ((ord($string[$offset]) | 0x7F) == 0x7F) {
1096                  // 0bbbbbbb
1097                  $charval = ord($string[$offset]);
1098                  $offset += 1;
1099              } else {
1100                  // error? maybe throw some warning here?
1101                  $charval = false;
1102                  $offset += 1;
1103              }
1104              if ($charval !== false) {
1105                  $newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
1106              }
1107          }
1108          return $newcharstring;
1109      }
1110  
1111      /**
1112       * UTF-8 => UTF-16LE (BOM)
1113       *
1114       * @param string $string
1115       *
1116       * @return string
1117       */
1118  	public static function iconv_fallback_utf8_utf16($string) {
1119          return self::iconv_fallback_utf8_utf16le($string, true);
1120      }
1121  
1122      /**
1123       * UTF-16BE => UTF-8
1124       *
1125       * @param string $string
1126       *
1127       * @return string
1128       */
1129  	public static function iconv_fallback_utf16be_utf8($string) {
1130          if (substr($string, 0, 2) == "\xFE\xFF") {
1131              // strip BOM
1132              $string = substr($string, 2);
1133          }
1134          $newcharstring = '';
1135          for ($i = 0; $i < strlen($string); $i += 2) {
1136              $charval = self::BigEndian2Int(substr($string, $i, 2));
1137              $newcharstring .= self::iconv_fallback_int_utf8($charval);
1138          }
1139          return $newcharstring;
1140      }
1141  
1142      /**
1143       * UTF-16LE => UTF-8
1144       *
1145       * @param string $string
1146       *
1147       * @return string
1148       */
1149  	public static function iconv_fallback_utf16le_utf8($string) {
1150          if (substr($string, 0, 2) == "\xFF\xFE") {
1151              // strip BOM
1152              $string = substr($string, 2);
1153          }
1154          $newcharstring = '';
1155          for ($i = 0; $i < strlen($string); $i += 2) {
1156              $charval = self::LittleEndian2Int(substr($string, $i, 2));
1157              $newcharstring .= self::iconv_fallback_int_utf8($charval);
1158          }
1159          return $newcharstring;
1160      }
1161  
1162      /**
1163       * UTF-16BE => ISO-8859-1
1164       *
1165       * @param string $string
1166       *
1167       * @return string
1168       */
1169  	public static function iconv_fallback_utf16be_iso88591($string) {
1170          if (substr($string, 0, 2) == "\xFE\xFF") {
1171              // strip BOM
1172              $string = substr($string, 2);
1173          }
1174          $newcharstring = '';
1175          for ($i = 0; $i < strlen($string); $i += 2) {
1176              $charval = self::BigEndian2Int(substr($string, $i, 2));
1177              $newcharstring .= (($charval < 256) ? chr($charval) : '?');
1178          }
1179          return $newcharstring;
1180      }
1181  
1182      /**
1183       * UTF-16LE => ISO-8859-1
1184       *
1185       * @param string $string
1186       *
1187       * @return string
1188       */
1189  	public static function iconv_fallback_utf16le_iso88591($string) {
1190          if (substr($string, 0, 2) == "\xFF\xFE") {
1191              // strip BOM
1192              $string = substr($string, 2);
1193          }
1194          $newcharstring = '';
1195          for ($i = 0; $i < strlen($string); $i += 2) {
1196              $charval = self::LittleEndian2Int(substr($string, $i, 2));
1197              $newcharstring .= (($charval < 256) ? chr($charval) : '?');
1198          }
1199          return $newcharstring;
1200      }
1201  
1202      /**
1203       * UTF-16 (BOM) => ISO-8859-1
1204       *
1205       * @param string $string
1206       *
1207       * @return string
1208       */
1209  	public static function iconv_fallback_utf16_iso88591($string) {
1210          $bom = substr($string, 0, 2);
1211          if ($bom == "\xFE\xFF") {
1212              return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
1213          } elseif ($bom == "\xFF\xFE") {
1214              return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
1215          }
1216          return $string;
1217      }
1218  
1219      /**
1220       * UTF-16 (BOM) => UTF-8
1221       *
1222       * @param string $string
1223       *
1224       * @return string
1225       */
1226  	public static function iconv_fallback_utf16_utf8($string) {
1227          $bom = substr($string, 0, 2);
1228          if ($bom == "\xFE\xFF") {
1229              return self::iconv_fallback_utf16be_utf8(substr($string, 2));
1230          } elseif ($bom == "\xFF\xFE") {
1231              return self::iconv_fallback_utf16le_utf8(substr($string, 2));
1232          }
1233          return $string;
1234      }
1235  
1236      /**
1237       * @param string $in_charset
1238       * @param string $out_charset
1239       * @param string $string
1240       *
1241       * @return string
1242       * @throws Exception
1243       */
1244  	public static function iconv_fallback($in_charset, $out_charset, $string) {
1245  
1246          if ($in_charset == $out_charset) {
1247              return $string;
1248          }
1249  
1250          // mb_convert_encoding() available
1251          if (function_exists('mb_convert_encoding')) {
1252              if ((strtoupper($in_charset) == 'UTF-16') && (substr($string, 0, 2) != "\xFE\xFF") && (substr($string, 0, 2) != "\xFF\xFE")) {
1253                  // if BOM missing, mb_convert_encoding will mishandle the conversion, assume UTF-16BE and prepend appropriate BOM
1254                  $string = "\xFF\xFE".$string;
1255              }
1256              if ((strtoupper($in_charset) == 'UTF-16') && (strtoupper($out_charset) == 'UTF-8')) {
1257                  if (($string == "\xFF\xFE") || ($string == "\xFE\xFF")) {
1258                      // if string consists of only BOM, mb_convert_encoding will return the BOM unmodified
1259                      return '';
1260                  }
1261              }
1262              if ($converted_string = @mb_convert_encoding($string, $out_charset, $in_charset)) {
1263                  switch ($out_charset) {
1264                      case 'ISO-8859-1':
1265                          $converted_string = rtrim($converted_string, "\x00");
1266                          break;
1267                  }
1268                  return $converted_string;
1269              }
1270              return $string;
1271  
1272          // iconv() available
1273          } elseif (function_exists('iconv')) {
1274              if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
1275                  switch ($out_charset) {
1276                      case 'ISO-8859-1':
1277                          $converted_string = rtrim($converted_string, "\x00");
1278                          break;
1279                  }
1280                  return $converted_string;
1281              }
1282  
1283              // iconv() may sometimes fail with "illegal character in input string" error message
1284              // and return an empty string, but returning the unconverted string is more useful
1285              return $string;
1286          }
1287  
1288  
1289          // neither mb_convert_encoding or iconv() is available
1290          static $ConversionFunctionList = array();
1291          if (empty($ConversionFunctionList)) {
1292              $ConversionFunctionList['ISO-8859-1']['UTF-8']    = 'iconv_fallback_iso88591_utf8';
1293              $ConversionFunctionList['ISO-8859-1']['UTF-16']   = 'iconv_fallback_iso88591_utf16';
1294              $ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
1295              $ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
1296              $ConversionFunctionList['UTF-8']['ISO-8859-1']    = 'iconv_fallback_utf8_iso88591';
1297              $ConversionFunctionList['UTF-8']['UTF-16']        = 'iconv_fallback_utf8_utf16';
1298              $ConversionFunctionList['UTF-8']['UTF-16BE']      = 'iconv_fallback_utf8_utf16be';
1299              $ConversionFunctionList['UTF-8']['UTF-16LE']      = 'iconv_fallback_utf8_utf16le';
1300              $ConversionFunctionList['UTF-16']['ISO-8859-1']   = 'iconv_fallback_utf16_iso88591';
1301              $ConversionFunctionList['UTF-16']['UTF-8']        = 'iconv_fallback_utf16_utf8';
1302              $ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
1303              $ConversionFunctionList['UTF-16LE']['UTF-8']      = 'iconv_fallback_utf16le_utf8';
1304              $ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
1305              $ConversionFunctionList['UTF-16BE']['UTF-8']      = 'iconv_fallback_utf16be_utf8';
1306          }
1307          if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
1308              $ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
1309              return self::$ConversionFunction($string);
1310          }
1311          throw new Exception('PHP does not has mb_convert_encoding() or iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
1312      }
1313  
1314      /**
1315       * @param mixed  $data
1316       * @param string $charset
1317       *
1318       * @return mixed
1319       */
1320  	public static function recursiveMultiByteCharString2HTML($data, $charset='ISO-8859-1') {
1321          if (is_string($data)) {
1322              return self::MultiByteCharString2HTML($data, $charset);
1323          } elseif (is_array($data)) {
1324              $return_data = array();
1325              foreach ($data as $key => $value) {
1326                  $return_data[$key] = self::recursiveMultiByteCharString2HTML($value, $charset);
1327              }
1328              return $return_data;
1329          }
1330          // integer, float, objects, resources, etc
1331          return $data;
1332      }
1333  
1334      /**
1335       * @param string|int|float $string
1336       * @param string           $charset
1337       *
1338       * @return string
1339       */
1340  	public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
1341          $string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
1342          $HTMLstring = '';
1343  
1344          switch (strtolower($charset)) {
1345              case '1251':
1346              case '1252':
1347              case '866':
1348              case '932':
1349              case '936':
1350              case '950':
1351              case 'big5':
1352              case 'big5-hkscs':
1353              case 'cp1251':
1354              case 'cp1252':
1355              case 'cp866':
1356              case 'euc-jp':
1357              case 'eucjp':
1358              case 'gb2312':
1359              case 'ibm866':
1360              case 'iso-8859-1':
1361              case 'iso-8859-15':
1362              case 'iso8859-1':
1363              case 'iso8859-15':
1364              case 'koi8-r':
1365              case 'koi8-ru':
1366              case 'koi8r':
1367              case 'shift_jis':
1368              case 'sjis':
1369              case 'win-1251':
1370              case 'windows-1251':
1371              case 'windows-1252':
1372                  $HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
1373                  break;
1374  
1375              case 'utf-8':
1376                  $strlen = strlen($string);
1377                  for ($i = 0; $i < $strlen; $i++) {
1378                      $char_ord_val = ord($string[$i]);
1379                      $charval = 0;
1380                      if ($char_ord_val < 0x80) {
1381                          $charval = $char_ord_val;
1382                      } elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F  &&  $i+3 < $strlen) {
1383                          $charval  = (($char_ord_val & 0x07) << 18);
1384                          $charval += ((ord($string[++$i]) & 0x3F) << 12);
1385                          $charval += ((ord($string[++$i]) & 0x3F) << 6);
1386                          $charval +=  (ord($string[++$i]) & 0x3F);
1387                      } elseif ((($char_ord_val & 0xE0) >> 5) == 0x07  &&  $i+2 < $strlen) {
1388                          $charval  = (($char_ord_val & 0x0F) << 12);
1389                          $charval += ((ord($string[++$i]) & 0x3F) << 6);
1390                          $charval +=  (ord($string[++$i]) & 0x3F);
1391                      } elseif ((($char_ord_val & 0xC0) >> 6) == 0x03  &&  $i+1 < $strlen) {
1392                          $charval  = (($char_ord_val & 0x1F) << 6);
1393                          $charval += (ord($string[++$i]) & 0x3F);
1394                      }
1395                      if (($charval >= 32) && ($charval <= 127)) {
1396                          $HTMLstring .= htmlentities(chr($charval));
1397                      } else {
1398                          $HTMLstring .= '&#'.$charval.';';
1399                      }
1400                  }
1401                  break;
1402  
1403              case 'utf-16le':
1404                  for ($i = 0; $i < strlen($string); $i += 2) {
1405                      $charval = self::LittleEndian2Int(substr($string, $i, 2));
1406                      if (($charval >= 32) && ($charval <= 127)) {
1407                          $HTMLstring .= chr($charval);
1408                      } else {
1409                          $HTMLstring .= '&#'.$charval.';';
1410                      }
1411                  }
1412                  break;
1413  
1414              case 'utf-16be':
1415                  for ($i = 0; $i < strlen($string); $i += 2) {
1416                      $charval = self::BigEndian2Int(substr($string, $i, 2));
1417                      if (($charval >= 32) && ($charval <= 127)) {
1418                          $HTMLstring .= chr($charval);
1419                      } else {
1420                          $HTMLstring .= '&#'.$charval.';';
1421                      }
1422                  }
1423                  break;
1424  
1425              default:
1426                  $HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
1427                  break;
1428          }
1429          return $HTMLstring;
1430      }
1431  
1432      /**
1433       * @param int $namecode
1434       *
1435       * @return string
1436       */
1437  	public static function RGADnameLookup($namecode) {
1438          static $RGADname = array();
1439          if (empty($RGADname)) {
1440              $RGADname[0] = 'not set';
1441              $RGADname[1] = 'Track Gain Adjustment';
1442              $RGADname[2] = 'Album Gain Adjustment';
1443          }
1444  
1445          return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
1446      }
1447  
1448      /**
1449       * @param int $originatorcode
1450       *
1451       * @return string
1452       */
1453  	public static function RGADoriginatorLookup($originatorcode) {
1454          static $RGADoriginator = array();
1455          if (empty($RGADoriginator)) {
1456              $RGADoriginator[0] = 'unspecified';
1457              $RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
1458              $RGADoriginator[2] = 'set by user';
1459              $RGADoriginator[3] = 'determined automatically';
1460          }
1461  
1462          return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
1463      }
1464  
1465      /**
1466       * @param int $rawadjustment
1467       * @param int $signbit
1468       *
1469       * @return float
1470       */
1471  	public static function RGADadjustmentLookup($rawadjustment, $signbit) {
1472          $adjustment = (float) $rawadjustment / 10;
1473          if ($signbit == 1) {
1474              $adjustment *= -1;
1475          }
1476          return $adjustment;
1477      }
1478  
1479      /**
1480       * @param int $namecode
1481       * @param int $originatorcode
1482       * @param int $replaygain
1483       *
1484       * @return string
1485       */
1486  	public static function RGADgainString($namecode, $originatorcode, $replaygain) {
1487          if ($replaygain < 0) {
1488              $signbit = '1';
1489          } else {
1490              $signbit = '0';
1491          }
1492          $storedreplaygain = intval(round($replaygain * 10));
1493          $gainstring  = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
1494          $gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
1495          $gainstring .= $signbit;
1496          $gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
1497  
1498          return $gainstring;
1499      }
1500  
1501      /**
1502       * @param float $amplitude
1503       *
1504       * @return float
1505       */
1506  	public static function RGADamplitude2dB($amplitude) {
1507          return 20 * log10($amplitude);
1508      }
1509  
1510      /**
1511       * @param string $imgData
1512       * @param array  $imageinfo
1513       *
1514       * @return array|false
1515       */
1516  	public static function GetDataImageSize($imgData, &$imageinfo=array()) {
1517          if (PHP_VERSION_ID >= 50400) {
1518              $GetDataImageSize = @getimagesizefromstring($imgData, $imageinfo);
1519              if ($GetDataImageSize === false) {
1520                  return false;
1521              }
1522              $GetDataImageSize['height'] = $GetDataImageSize[0];
1523              $GetDataImageSize['width'] = $GetDataImageSize[1];
1524              return $GetDataImageSize;
1525          }
1526          static $tempdir = '';
1527          if (empty($tempdir)) {
1528              if (function_exists('sys_get_temp_dir')) {
1529                  $tempdir = sys_get_temp_dir(); // https://github.com/JamesHeinrich/getID3/issues/52
1530              }
1531  
1532              // yes this is ugly, feel free to suggest a better way
1533              if (include_once(dirname(__FILE__).'/getid3.php')) {
1534                  $getid3_temp = new getID3();
1535                  if ($getid3_temp_tempdir = $getid3_temp->tempdir) {
1536                      $tempdir = $getid3_temp_tempdir;
1537                  }
1538                  unset($getid3_temp, $getid3_temp_tempdir);
1539              }
1540          }
1541          $GetDataImageSize = false;
1542          if ($tempfilename = tempnam($tempdir, 'gI3')) {
1543              if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
1544                  fwrite($tmp, $imgData);
1545                  fclose($tmp);
1546                  $GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
1547                  if ($GetDataImageSize === false) {
1548                      return false;
1549                  }
1550                  $GetDataImageSize['height'] = $GetDataImageSize[0];
1551                  $GetDataImageSize['width']  = $GetDataImageSize[1];
1552              }
1553              unlink($tempfilename);
1554          }
1555          return $GetDataImageSize;
1556      }
1557  
1558      /**
1559       * @param string $mime_type
1560       *
1561       * @return string
1562       */
1563  	public static function ImageExtFromMime($mime_type) {
1564          // temporary way, works OK for now, but should be reworked in the future
1565          return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
1566      }
1567  
1568      /**
1569       * @param array $ThisFileInfo
1570       * @param bool  $option_tags_html default true (just as in the main getID3 class)
1571       *
1572       * @return bool
1573       */
1574  	public static function CopyTagsToComments(&$ThisFileInfo, $option_tags_html=true) {
1575          // Copy all entries from ['tags'] into common ['comments']
1576          if (!empty($ThisFileInfo['tags'])) {
1577  
1578              // Some tag types can only support limited character sets and may contain data in non-standard encoding (usually ID3v1)
1579              // and/or poorly-transliterated tag values that are also in tag formats that do support full-range character sets
1580              // To make the output more user-friendly, process the potentially-problematic tag formats last to enhance the chance that
1581              // the first entries in [comments] are the most correct and the "bad" ones (if any) come later.
1582              // https://github.com/JamesHeinrich/getID3/issues/338
1583              $processLastTagTypes = array('id3v1','riff');
1584              foreach ($processLastTagTypes as $processLastTagType) {
1585                  if (isset($ThisFileInfo['tags'][$processLastTagType])) {
1586                      // bubble ID3v1 to the end, if present to aid in detecting bad ID3v1 encodings
1587                      $temp = $ThisFileInfo['tags'][$processLastTagType];
1588                      unset($ThisFileInfo['tags'][$processLastTagType]);
1589                      $ThisFileInfo['tags'][$processLastTagType] = $temp;
1590                      unset($temp);
1591                  }
1592              }
1593              foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
1594                  foreach ($tagarray as $tagname => $tagdata) {
1595                      foreach ($tagdata as $key => $value) {
1596                          if (!empty($value)) {
1597                              if (empty($ThisFileInfo['comments'][$tagname])) {
1598  
1599                                  // fall through and append value
1600  
1601                              } elseif ($tagtype == 'id3v1') {
1602  
1603                                  $newvaluelength = strlen(trim($value));
1604                                  foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1605                                      $oldvaluelength = strlen(trim($existingvalue));
1606                                      if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
1607                                          // new value is identical but shorter-than (or equal-length to) one already in comments - skip
1608                                          break 2;
1609                                      }
1610  
1611                                      if (function_exists('mb_convert_encoding')) {
1612                                          if (trim($value) == trim(substr(mb_convert_encoding($existingvalue, $ThisFileInfo['id3v1']['encoding'], $ThisFileInfo['encoding']), 0, 30))) {
1613                                              // value stored in ID3v1 appears to be probably the multibyte value transliterated (badly) into ISO-8859-1 in ID3v1.
1614                                              // 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
1615                                              break 2;
1616                                          }
1617                                      }
1618                                  }
1619  
1620                              } elseif (!is_array($value)) {
1621  
1622                                  $newvaluelength   =    strlen(trim($value));
1623                                  $newvaluelengthMB = mb_strlen(trim($value));
1624                                  foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
1625                                      $oldvaluelength   =    strlen(trim($existingvalue));
1626                                      $oldvaluelengthMB = mb_strlen(trim($existingvalue));
1627                                      if (($newvaluelengthMB == $oldvaluelengthMB) && ($existingvalue == getid3_lib::iconv_fallback('UTF-8', 'ASCII', $value))) {
1628                                          // https://github.com/JamesHeinrich/getID3/issues/338
1629                                          // check for tags containing extended characters that may have been forced into limited-character storage (e.g. UTF8 values into ASCII)
1630                                          // which will usually display unrepresentable characters as "?"
1631                                          $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
1632                                          break;
1633                                      }
1634                                      if ((strlen($existingvalue) > 10) && ($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
1635                                          $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
1636                                          break;
1637                                      }
1638                                  }
1639  
1640                              }
1641                              if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
1642                                  $value = (is_string($value) ? trim($value) : $value);
1643                                  if (!is_int($key) && !ctype_digit($key)) {
1644                                      $ThisFileInfo['comments'][$tagname][$key] = $value;
1645                                  } else {
1646                                      if (!isset($ThisFileInfo['comments'][$tagname])) {
1647                                          $ThisFileInfo['comments'][$tagname] = array($value);
1648                                      } else {
1649                                          $ThisFileInfo['comments'][$tagname][] = $value;
1650                                      }
1651                                  }
1652                              }
1653                          }
1654                      }
1655                  }
1656              }
1657  
1658              // attempt to standardize spelling of returned keys
1659              if (!empty($ThisFileInfo['comments'])) {
1660                  $StandardizeFieldNames = array(
1661                      'tracknumber' => 'track_number',
1662                      'track'       => 'track_number',
1663                  );
1664                  foreach ($StandardizeFieldNames as $badkey => $goodkey) {
1665                      if (array_key_exists($badkey, $ThisFileInfo['comments']) && !array_key_exists($goodkey, $ThisFileInfo['comments'])) {
1666                          $ThisFileInfo['comments'][$goodkey] = $ThisFileInfo['comments'][$badkey];
1667                          unset($ThisFileInfo['comments'][$badkey]);
1668                      }
1669                  }
1670              }
1671  
1672              if ($option_tags_html) {
1673                  // Copy ['comments'] to ['comments_html']
1674                  if (!empty($ThisFileInfo['comments'])) {
1675                      foreach ($ThisFileInfo['comments'] as $field => $values) {
1676                          if ($field == 'picture') {
1677                              // pictures can take up a lot of space, and we don't need multiple copies of them
1678                              // let there be a single copy in [comments][picture], and not elsewhere
1679                              continue;
1680                          }
1681                          foreach ($values as $index => $value) {
1682                              if (is_array($value)) {
1683                                  $ThisFileInfo['comments_html'][$field][$index] = $value;
1684                              } else {
1685                                  $ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
1686                              }
1687                          }
1688                      }
1689                  }
1690              }
1691  
1692          }
1693          return true;
1694      }
1695  
1696      /**
1697       * @param string $key
1698       * @param int    $begin
1699       * @param int    $end
1700       * @param string $file
1701       * @param string $name
1702       *
1703       * @return string
1704       */
1705  	public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
1706  
1707          // Cached
1708          static $cache;
1709          if (isset($cache[$file][$name])) {
1710              return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1711          }
1712  
1713          // Init
1714          $keylength  = strlen($key);
1715          $line_count = $end - $begin - 7;
1716  
1717          // Open php file
1718          $fp = fopen($file, 'r');
1719  
1720          // Discard $begin lines
1721          for ($i = 0; $i < ($begin + 3); $i++) {
1722              fgets($fp, 1024);
1723          }
1724  
1725          // Loop thru line
1726          while (0 < $line_count--) {
1727  
1728              // Read line
1729              $line = ltrim(fgets($fp, 1024), "\t ");
1730  
1731              // METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
1732              //$keycheck = substr($line, 0, $keylength);
1733              //if ($key == $keycheck)  {
1734              //    $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
1735              //    break;
1736              //}
1737  
1738              // METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
1739              //$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
1740              $explodedLine = explode("\t", $line, 2);
1741              $ThisKey   = $explodedLine[0];
1742              $ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
1743              $cache[$file][$name][$ThisKey] = trim($ThisValue);
1744          }
1745  
1746          // Close and return
1747          fclose($fp);
1748          return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
1749      }
1750  
1751      /**
1752       * @param string $filename
1753       * @param string $sourcefile
1754       * @param bool   $DieOnFailure
1755       *
1756       * @return bool
1757       * @throws Exception
1758       */
1759  	public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
1760          global $GETID3_ERRORARRAY;
1761  
1762          if (file_exists($filename)) {
1763              if (include_once($filename)) {
1764                  return true;
1765              } else {
1766                  $diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
1767              }
1768          } else {
1769              $diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
1770          }
1771          if ($DieOnFailure) {
1772              throw new Exception($diemessage);
1773          } else {
1774              $GETID3_ERRORARRAY[] = $diemessage;
1775          }
1776          return false;
1777      }
1778  
1779      /**
1780       * @param string $string
1781       *
1782       * @return string
1783       */
1784  	public static function trimNullByte($string) {
1785          return trim($string, "\x00");
1786      }
1787  
1788      /**
1789       * @param string $path
1790       *
1791       * @return float|bool
1792       */
1793  	public static function getFileSizeSyscall($path) {
1794          $commandline = null;
1795          $filesize = false;
1796  
1797          if (GETID3_OS_ISWINDOWS) {
1798              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:
1799                  $filesystem = new COM('Scripting.FileSystemObject');
1800                  $file = $filesystem->GetFile($path);
1801                  $filesize = $file->Size();
1802                  unset($filesystem, $file);
1803              } else {
1804                  $commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
1805              }
1806          } else {
1807              $commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
1808          }
1809          if (isset($commandline)) {
1810              $output = trim(shell_exec($commandline));
1811              if (ctype_digit($output)) {
1812                  $filesize = (float) $output;
1813              }
1814          }
1815          return $filesize;
1816      }
1817  
1818      /**
1819       * @param string $filename
1820       *
1821       * @return string|false
1822       */
1823  	public static function truepath($filename) {
1824          // 2017-11-08: this could use some improvement, patches welcome
1825          if (preg_match('#^(\\\\\\\\|//)[a-z0-9]#i', $filename, $matches)) {
1826              // PHP's built-in realpath function does not work on UNC Windows shares
1827              $goodpath = array();
1828              foreach (explode('/', str_replace('\\', '/', $filename)) as $part) {
1829                  if ($part == '.') {
1830                      continue;
1831                  }
1832                  if ($part == '..') {
1833                      if (count($goodpath)) {
1834                          array_pop($goodpath);
1835                      } else {
1836                          // cannot step above this level, already at top level
1837                          return false;
1838                      }
1839                  } else {
1840                      $goodpath[] = $part;
1841                  }
1842              }
1843              return implode(DIRECTORY_SEPARATOR, $goodpath);
1844          }
1845          return realpath($filename);
1846      }
1847  
1848      /**
1849       * Workaround for Bug #37268 (https://bugs.php.net/bug.php?id=37268)
1850       *
1851       * @param string $path A path.
1852       * @param string $suffix If the name component ends in suffix this will also be cut off.
1853       *
1854       * @return string
1855       */
1856  	public static function mb_basename($path, $suffix = '') {
1857          $splited = preg_split('#/#', rtrim($path, '/ '));
1858          return substr(basename('X'.$splited[count($splited) - 1], $suffix), 1);
1859      }
1860  
1861  }


Generated : Fri Nov 13 08:20:01 2026 Cross-referenced by PHPXref