[ Index ]

PHP Cross Reference of WordPress

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


Generated: Fri Jul 30 01:00:09 2021 Cross-referenced by PHPXref 0.7.1