PageRenderTime 51ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/wp-includes/ID3/getid3.lib.php

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