getid3.lib.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. <?php
  2. /////////////////////////////////////////////////////////////////
  3. /// getID3() by James Heinrich <info@getid3.org> //
  4. // available at http://getid3.sourceforge.net //
  5. // or http://www.getid3.org //
  6. // also https://github.com/JamesHeinrich/getID3 //
  7. /////////////////////////////////////////////////////////////////
  8. // //
  9. // getid3.lib.php - part of getID3() //
  10. // See readme.txt for more details //
  11. // ///
  12. /////////////////////////////////////////////////////////////////
  13. class getid3_lib
  14. {
  15. public static function PrintHexBytes($string, $hex=true, $spaces=true, $htmlencoding='UTF-8') {
  16. $returnstring = '';
  17. for ($i = 0; $i < strlen($string); $i++) {
  18. if ($hex) {
  19. $returnstring .= str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
  20. } else {
  21. $returnstring .= ' '.(preg_match("#[\x20-\x7E]#", $string{$i}) ? $string{$i} : '¤');
  22. }
  23. if ($spaces) {
  24. $returnstring .= ' ';
  25. }
  26. }
  27. if (!empty($htmlencoding)) {
  28. if ($htmlencoding === true) {
  29. $htmlencoding = 'UTF-8'; // prior to getID3 v1.9.0 the function's 4th parameter was boolean
  30. }
  31. $returnstring = htmlentities($returnstring, ENT_QUOTES, $htmlencoding);
  32. }
  33. return $returnstring;
  34. }
  35. public static function trunc($floatnumber) {
  36. // truncates a floating-point number at the decimal point
  37. // returns int (if possible, otherwise float)
  38. if ($floatnumber >= 1) {
  39. $truncatednumber = floor($floatnumber);
  40. } elseif ($floatnumber <= -1) {
  41. $truncatednumber = ceil($floatnumber);
  42. } else {
  43. $truncatednumber = 0;
  44. }
  45. if (self::intValueSupported($truncatednumber)) {
  46. $truncatednumber = (int) $truncatednumber;
  47. }
  48. return $truncatednumber;
  49. }
  50. public static function safe_inc(&$variable, $increment=1) {
  51. if (isset($variable)) {
  52. $variable += $increment;
  53. } else {
  54. $variable = $increment;
  55. }
  56. return true;
  57. }
  58. public static function CastAsInt($floatnum) {
  59. // convert to float if not already
  60. $floatnum = (float) $floatnum;
  61. // convert a float to type int, only if possible
  62. if (self::trunc($floatnum) == $floatnum) {
  63. // it's not floating point
  64. if (self::intValueSupported($floatnum)) {
  65. // it's within int range
  66. $floatnum = (int) $floatnum;
  67. }
  68. }
  69. return $floatnum;
  70. }
  71. public static function intValueSupported($num) {
  72. // check if integers are 64-bit
  73. static $hasINT64 = null;
  74. if ($hasINT64 === null) { // 10x faster than is_null()
  75. $hasINT64 = is_int(pow(2, 31)); // 32-bit int are limited to (2^31)-1
  76. if (!$hasINT64 && !defined('PHP_INT_MIN')) {
  77. define('PHP_INT_MIN', ~PHP_INT_MAX);
  78. }
  79. }
  80. // if integers are 64-bit - no other check required
  81. if ($hasINT64 || (($num <= PHP_INT_MAX) && ($num >= PHP_INT_MIN))) {
  82. return true;
  83. }
  84. return false;
  85. }
  86. public static function DecimalizeFraction($fraction) {
  87. list($numerator, $denominator) = explode('/', $fraction);
  88. return $numerator / ($denominator ? $denominator : 1);
  89. }
  90. public static function DecimalBinary2Float($binarynumerator) {
  91. $numerator = self::Bin2Dec($binarynumerator);
  92. $denominator = self::Bin2Dec('1'.str_repeat('0', strlen($binarynumerator)));
  93. return ($numerator / $denominator);
  94. }
  95. public static function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) {
  96. // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
  97. if (strpos($binarypointnumber, '.') === false) {
  98. $binarypointnumber = '0.'.$binarypointnumber;
  99. } elseif ($binarypointnumber{0} == '.') {
  100. $binarypointnumber = '0'.$binarypointnumber;
  101. }
  102. $exponent = 0;
  103. while (($binarypointnumber{0} != '1') || (substr($binarypointnumber, 1, 1) != '.')) {
  104. if (substr($binarypointnumber, 1, 1) == '.') {
  105. $exponent--;
  106. $binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3);
  107. } else {
  108. $pointpos = strpos($binarypointnumber, '.');
  109. $exponent += ($pointpos - 1);
  110. $binarypointnumber = str_replace('.', '', $binarypointnumber);
  111. $binarypointnumber = $binarypointnumber{0}.'.'.substr($binarypointnumber, 1);
  112. }
  113. }
  114. $binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT);
  115. return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent);
  116. }
  117. public static function Float2BinaryDecimal($floatvalue) {
  118. // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
  119. $maxbits = 128; // to how many bits of precision should the calculations be taken?
  120. $intpart = self::trunc($floatvalue);
  121. $floatpart = abs($floatvalue - $intpart);
  122. $pointbitstring = '';
  123. while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) {
  124. $floatpart *= 2;
  125. $pointbitstring .= (string) self::trunc($floatpart);
  126. $floatpart -= self::trunc($floatpart);
  127. }
  128. $binarypointnumber = decbin($intpart).'.'.$pointbitstring;
  129. return $binarypointnumber;
  130. }
  131. public static function Float2String($floatvalue, $bits) {
  132. // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html
  133. switch ($bits) {
  134. case 32:
  135. $exponentbits = 8;
  136. $fractionbits = 23;
  137. break;
  138. case 64:
  139. $exponentbits = 11;
  140. $fractionbits = 52;
  141. break;
  142. default:
  143. return false;
  144. break;
  145. }
  146. if ($floatvalue >= 0) {
  147. $signbit = '0';
  148. } else {
  149. $signbit = '1';
  150. }
  151. $normalizedbinary = self::NormalizeBinaryPoint(self::Float2BinaryDecimal($floatvalue), $fractionbits);
  152. $biasedexponent = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent
  153. $exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT);
  154. $fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT);
  155. return self::BigEndian2String(self::Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false);
  156. }
  157. public static function LittleEndian2Float($byteword) {
  158. return self::BigEndian2Float(strrev($byteword));
  159. }
  160. public static function BigEndian2Float($byteword) {
  161. // ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic
  162. // http://www.psc.edu/general/software/packages/ieee/ieee.html
  163. // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html
  164. $bitword = self::BigEndian2Bin($byteword);
  165. if (!$bitword) {
  166. return 0;
  167. }
  168. $signbit = $bitword{0};
  169. switch (strlen($byteword) * 8) {
  170. case 32:
  171. $exponentbits = 8;
  172. $fractionbits = 23;
  173. break;
  174. case 64:
  175. $exponentbits = 11;
  176. $fractionbits = 52;
  177. break;
  178. case 80:
  179. // 80-bit Apple SANE format
  180. // http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/
  181. $exponentstring = substr($bitword, 1, 15);
  182. $isnormalized = intval($bitword{16});
  183. $fractionstring = substr($bitword, 17, 63);
  184. $exponent = pow(2, self::Bin2Dec($exponentstring) - 16383);
  185. $fraction = $isnormalized + self::DecimalBinary2Float($fractionstring);
  186. $floatvalue = $exponent * $fraction;
  187. if ($signbit == '1') {
  188. $floatvalue *= -1;
  189. }
  190. return $floatvalue;
  191. break;
  192. default:
  193. return false;
  194. break;
  195. }
  196. $exponentstring = substr($bitword, 1, $exponentbits);
  197. $fractionstring = substr($bitword, $exponentbits + 1, $fractionbits);
  198. $exponent = self::Bin2Dec($exponentstring);
  199. $fraction = self::Bin2Dec($fractionstring);
  200. if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) {
  201. // Not a Number
  202. $floatvalue = false;
  203. } elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) {
  204. if ($signbit == '1') {
  205. $floatvalue = '-infinity';
  206. } else {
  207. $floatvalue = '+infinity';
  208. }
  209. } elseif (($exponent == 0) && ($fraction == 0)) {
  210. if ($signbit == '1') {
  211. $floatvalue = -0;
  212. } else {
  213. $floatvalue = 0;
  214. }
  215. $floatvalue = ($signbit ? 0 : -0);
  216. } elseif (($exponent == 0) && ($fraction != 0)) {
  217. // These are 'unnormalized' values
  218. $floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * self::DecimalBinary2Float($fractionstring);
  219. if ($signbit == '1') {
  220. $floatvalue *= -1;
  221. }
  222. } elseif ($exponent != 0) {
  223. $floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + self::DecimalBinary2Float($fractionstring));
  224. if ($signbit == '1') {
  225. $floatvalue *= -1;
  226. }
  227. }
  228. return (float) $floatvalue;
  229. }
  230. public static function BigEndian2Int($byteword, $synchsafe=false, $signed=false) {
  231. $intvalue = 0;
  232. $bytewordlen = strlen($byteword);
  233. if ($bytewordlen == 0) {
  234. return false;
  235. }
  236. for ($i = 0; $i < $bytewordlen; $i++) {
  237. if ($synchsafe) { // disregard MSB, effectively 7-bit bytes
  238. //$intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); // faster, but runs into problems past 2^31 on 32-bit systems
  239. $intvalue += (ord($byteword{$i}) & 0x7F) * pow(2, ($bytewordlen - 1 - $i) * 7);
  240. } else {
  241. $intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i));
  242. }
  243. }
  244. if ($signed && !$synchsafe) {
  245. // synchsafe ints are not allowed to be signed
  246. if ($bytewordlen <= PHP_INT_SIZE) {
  247. $signMaskBit = 0x80 << (8 * ($bytewordlen - 1));
  248. if ($intvalue & $signMaskBit) {
  249. $intvalue = 0 - ($intvalue & ($signMaskBit - 1));
  250. }
  251. } else {
  252. throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits ('.strlen($byteword).') in self::BigEndian2Int()');
  253. }
  254. }
  255. return self::CastAsInt($intvalue);
  256. }
  257. public static function LittleEndian2Int($byteword, $signed=false) {
  258. return self::BigEndian2Int(strrev($byteword), false, $signed);
  259. }
  260. public static function BigEndian2Bin($byteword) {
  261. $binvalue = '';
  262. $bytewordlen = strlen($byteword);
  263. for ($i = 0; $i < $bytewordlen; $i++) {
  264. $binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
  265. }
  266. return $binvalue;
  267. }
  268. public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
  269. if ($number < 0) {
  270. throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
  271. }
  272. $maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
  273. $intstring = '';
  274. if ($signed) {
  275. if ($minbytes > PHP_INT_SIZE) {
  276. throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
  277. }
  278. $number = $number & (0x80 << (8 * ($minbytes - 1)));
  279. }
  280. while ($number != 0) {
  281. $quotient = ($number / ($maskbyte + 1));
  282. $intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
  283. $number = floor($quotient);
  284. }
  285. return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
  286. }
  287. public static function Dec2Bin($number) {
  288. while ($number >= 256) {
  289. $bytes[] = (($number / 256) - (floor($number / 256))) * 256;
  290. $number = floor($number / 256);
  291. }
  292. $bytes[] = $number;
  293. $binstring = '';
  294. for ($i = 0; $i < count($bytes); $i++) {
  295. $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring;
  296. }
  297. return $binstring;
  298. }
  299. public static function Bin2Dec($binstring, $signed=false) {
  300. $signmult = 1;
  301. if ($signed) {
  302. if ($binstring{0} == '1') {
  303. $signmult = -1;
  304. }
  305. $binstring = substr($binstring, 1);
  306. }
  307. $decvalue = 0;
  308. for ($i = 0; $i < strlen($binstring); $i++) {
  309. $decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
  310. }
  311. return self::CastAsInt($decvalue * $signmult);
  312. }
  313. public static function Bin2String($binstring) {
  314. // return 'hi' for input of '0110100001101001'
  315. $string = '';
  316. $binstringreversed = strrev($binstring);
  317. for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
  318. $string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
  319. }
  320. return $string;
  321. }
  322. public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
  323. $intstring = '';
  324. while ($number > 0) {
  325. if ($synchsafe) {
  326. $intstring = $intstring.chr($number & 127);
  327. $number >>= 7;
  328. } else {
  329. $intstring = $intstring.chr($number & 255);
  330. $number >>= 8;
  331. }
  332. }
  333. return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
  334. }
  335. public static function array_merge_clobber($array1, $array2) {
  336. // written by kcØhireability*com
  337. // taken from http://www.php.net/manual/en/function.array-merge-recursive.php
  338. if (!is_array($array1) || !is_array($array2)) {
  339. return false;
  340. }
  341. $newarray = $array1;
  342. foreach ($array2 as $key => $val) {
  343. if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
  344. $newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
  345. } else {
  346. $newarray[$key] = $val;
  347. }
  348. }
  349. return $newarray;
  350. }
  351. public static function array_merge_noclobber($array1, $array2) {
  352. if (!is_array($array1) || !is_array($array2)) {
  353. return false;
  354. }
  355. $newarray = $array1;
  356. foreach ($array2 as $key => $val) {
  357. if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
  358. $newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
  359. } elseif (!isset($newarray[$key])) {
  360. $newarray[$key] = $val;
  361. }
  362. }
  363. return $newarray;
  364. }
  365. public static function flipped_array_merge_noclobber($array1, $array2) {
  366. if (!is_array($array1) || !is_array($array2)) {
  367. return false;
  368. }
  369. # naturally, this only works non-recursively
  370. $newarray = array_flip($array1);
  371. foreach (array_flip($array2) as $key => $val) {
  372. if (!isset($newarray[$key])) {
  373. $newarray[$key] = count($newarray);
  374. }
  375. }
  376. return array_flip($newarray);
  377. }
  378. public static function ksort_recursive(&$theArray) {
  379. ksort($theArray);
  380. foreach ($theArray as $key => $value) {
  381. if (is_array($value)) {
  382. self::ksort_recursive($theArray[$key]);
  383. }
  384. }
  385. return true;
  386. }
  387. public static function fileextension($filename, $numextensions=1) {
  388. if (strstr($filename, '.')) {
  389. $reversedfilename = strrev($filename);
  390. $offset = 0;
  391. for ($i = 0; $i < $numextensions; $i++) {
  392. $offset = strpos($reversedfilename, '.', $offset + 1);
  393. if ($offset === false) {
  394. return '';
  395. }
  396. }
  397. return strrev(substr($reversedfilename, 0, $offset));
  398. }
  399. return '';
  400. }
  401. public static function PlaytimeString($seconds) {
  402. $sign = (($seconds < 0) ? '-' : '');
  403. $seconds = round(abs($seconds));
  404. $H = (int) floor( $seconds / 3600);
  405. $M = (int) floor(($seconds - (3600 * $H) ) / 60);
  406. $S = (int) round( $seconds - (3600 * $H) - (60 * $M) );
  407. return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
  408. }
  409. public static function DateMac2Unix($macdate) {
  410. // Macintosh timestamp: seconds since 00:00h January 1, 1904
  411. // UNIX timestamp: seconds since 00:00h January 1, 1970
  412. return self::CastAsInt($macdate - 2082844800);
  413. }
  414. public static function FixedPoint8_8($rawdata) {
  415. return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
  416. }
  417. public static function FixedPoint16_16($rawdata) {
  418. return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
  419. }
  420. public static function FixedPoint2_30($rawdata) {
  421. $binarystring = self::BigEndian2Bin($rawdata);
  422. return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
  423. }
  424. public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
  425. // assigns $Value to a nested array path:
  426. // $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
  427. // is the same as:
  428. // $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
  429. // or
  430. // $foo['path']['to']['my'] = 'file.txt';
  431. $ArrayPath = ltrim($ArrayPath, $Separator);
  432. if (($pos = strpos($ArrayPath, $Separator)) !== false) {
  433. $ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
  434. } else {
  435. $ReturnedArray[$ArrayPath] = $Value;
  436. }
  437. return $ReturnedArray;
  438. }
  439. public static function array_max($arraydata, $returnkey=false) {
  440. $maxvalue = false;
  441. $maxkey = false;
  442. foreach ($arraydata as $key => $value) {
  443. if (!is_array($value)) {
  444. if ($value > $maxvalue) {
  445. $maxvalue = $value;
  446. $maxkey = $key;
  447. }
  448. }
  449. }
  450. return ($returnkey ? $maxkey : $maxvalue);
  451. }
  452. public static function array_min($arraydata, $returnkey=false) {
  453. $minvalue = false;
  454. $minkey = false;
  455. foreach ($arraydata as $key => $value) {
  456. if (!is_array($value)) {
  457. if ($value > $minvalue) {
  458. $minvalue = $value;
  459. $minkey = $key;
  460. }
  461. }
  462. }
  463. return ($returnkey ? $minkey : $minvalue);
  464. }
  465. public static function XML2array($XMLstring) {
  466. if (function_exists('simplexml_load_string') && function_exists('libxml_disable_entity_loader')) {
  467. // http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html
  468. // https://core.trac.wordpress.org/changeset/29378
  469. $loader = libxml_disable_entity_loader(true);
  470. $XMLobject = simplexml_load_string($XMLstring, 'SimpleXMLElement', LIBXML_NOENT);
  471. $return = self::SimpleXMLelement2array($XMLobject);
  472. libxml_disable_entity_loader($loader);
  473. return $return;
  474. }
  475. return false;
  476. }
  477. public static function SimpleXMLelement2array($XMLobject) {
  478. if (!is_object($XMLobject) && !is_array($XMLobject)) {
  479. return $XMLobject;
  480. }
  481. $XMLarray = (is_object($XMLobject) ? get_object_vars($XMLobject) : $XMLobject);
  482. foreach ($XMLarray as $key => $value) {
  483. $XMLarray[$key] = self::SimpleXMLelement2array($value);
  484. }
  485. return $XMLarray;
  486. }
  487. // Allan Hansen <ahØartemis*dk>
  488. // self::md5_data() - returns md5sum for a file from startuing position to absolute end position
  489. public static function hash_data($file, $offset, $end, $algorithm) {
  490. static $tempdir = '';
  491. if (!self::intValueSupported($end)) {
  492. return false;
  493. }
  494. switch ($algorithm) {
  495. case 'md5':
  496. $hash_function = 'md5_file';
  497. $unix_call = 'md5sum';
  498. $windows_call = 'md5sum.exe';
  499. $hash_length = 32;
  500. break;
  501. case 'sha1':
  502. $hash_function = 'sha1_file';
  503. $unix_call = 'sha1sum';
  504. $windows_call = 'sha1sum.exe';
  505. $hash_length = 40;
  506. break;
  507. default:
  508. throw new Exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
  509. break;
  510. }
  511. $size = $end - $offset;
  512. while (true) {
  513. if (GETID3_OS_ISWINDOWS) {
  514. // It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
  515. // Fall back to create-temp-file method:
  516. if ($algorithm == 'sha1') {
  517. break;
  518. }
  519. $RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
  520. foreach ($RequiredFiles as $required_file) {
  521. if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
  522. // helper apps not available - fall back to old method
  523. break 2;
  524. }
  525. }
  526. $commandline = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' '.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).' | ';
  527. $commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
  528. $commandline .= GETID3_HELPERAPPSDIR.$windows_call;
  529. } else {
  530. $commandline = 'head -c'.$end.' '.escapeshellarg($file).' | ';
  531. $commandline .= 'tail -c'.$size.' | ';
  532. $commandline .= $unix_call;
  533. }
  534. if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
  535. //throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
  536. break;
  537. }
  538. return substr(`$commandline`, 0, $hash_length);
  539. }
  540. if (empty($tempdir)) {
  541. // yes this is ugly, feel free to suggest a better way
  542. require_once(dirname(__FILE__).'/getid3.php');
  543. $getid3_temp = new getID3();
  544. $tempdir = $getid3_temp->tempdir;
  545. unset($getid3_temp);
  546. }
  547. // try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
  548. if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
  549. // can't find anywhere to create a temp file, just fail
  550. return false;
  551. }
  552. // Init
  553. $result = false;
  554. // copy parts of file
  555. try {
  556. self::CopyFileParts($file, $data_filename, $offset, $end - $offset);
  557. $result = $hash_function($data_filename);
  558. } catch (Exception $e) {
  559. throw new Exception('self::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
  560. }
  561. unlink($data_filename);
  562. return $result;
  563. }
  564. public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
  565. if (!self::intValueSupported($offset + $length)) {
  566. throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
  567. }
  568. if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
  569. if (($fp_dest = fopen($filename_dest, 'wb'))) {
  570. if (fseek($fp_src, $offset) == 0) {
  571. $byteslefttowrite = $length;
  572. while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
  573. $byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
  574. $byteslefttowrite -= $byteswritten;
  575. }
  576. return true;
  577. } else {
  578. throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
  579. }
  580. fclose($fp_dest);
  581. } else {
  582. throw new Exception('failed to create file for writing '.$filename_dest);
  583. }
  584. fclose($fp_src);
  585. } else {
  586. throw new Exception('failed to open file for reading '.$filename_source);
  587. }
  588. return false;
  589. }
  590. public static function iconv_fallback_int_utf8($charval) {
  591. if ($charval < 128) {
  592. // 0bbbbbbb
  593. $newcharstring = chr($charval);
  594. } elseif ($charval < 2048) {
  595. // 110bbbbb 10bbbbbb
  596. $newcharstring = chr(($charval >> 6) | 0xC0);
  597. $newcharstring .= chr(($charval & 0x3F) | 0x80);
  598. } elseif ($charval < 65536) {
  599. // 1110bbbb 10bbbbbb 10bbbbbb
  600. $newcharstring = chr(($charval >> 12) | 0xE0);
  601. $newcharstring .= chr(($charval >> 6) | 0xC0);
  602. $newcharstring .= chr(($charval & 0x3F) | 0x80);
  603. } else {
  604. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  605. $newcharstring = chr(($charval >> 18) | 0xF0);
  606. $newcharstring .= chr(($charval >> 12) | 0xC0);
  607. $newcharstring .= chr(($charval >> 6) | 0xC0);
  608. $newcharstring .= chr(($charval & 0x3F) | 0x80);
  609. }
  610. return $newcharstring;
  611. }
  612. // ISO-8859-1 => UTF-8
  613. public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
  614. if (function_exists('utf8_encode')) {
  615. return utf8_encode($string);
  616. }
  617. // utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
  618. $newcharstring = '';
  619. if ($bom) {
  620. $newcharstring .= "\xEF\xBB\xBF";
  621. }
  622. for ($i = 0; $i < strlen($string); $i++) {
  623. $charval = ord($string{$i});
  624. $newcharstring .= self::iconv_fallback_int_utf8($charval);
  625. }
  626. return $newcharstring;
  627. }
  628. // ISO-8859-1 => UTF-16BE
  629. public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
  630. $newcharstring = '';
  631. if ($bom) {
  632. $newcharstring .= "\xFE\xFF";
  633. }
  634. for ($i = 0; $i < strlen($string); $i++) {
  635. $newcharstring .= "\x00".$string{$i};
  636. }
  637. return $newcharstring;
  638. }
  639. // ISO-8859-1 => UTF-16LE
  640. public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
  641. $newcharstring = '';
  642. if ($bom) {
  643. $newcharstring .= "\xFF\xFE";
  644. }
  645. for ($i = 0; $i < strlen($string); $i++) {
  646. $newcharstring .= $string{$i}."\x00";
  647. }
  648. return $newcharstring;
  649. }
  650. // ISO-8859-1 => UTF-16LE (BOM)
  651. public static function iconv_fallback_iso88591_utf16($string) {
  652. return self::iconv_fallback_iso88591_utf16le($string, true);
  653. }
  654. // UTF-8 => ISO-8859-1
  655. public static function iconv_fallback_utf8_iso88591($string) {
  656. if (function_exists('utf8_decode')) {
  657. return utf8_decode($string);
  658. }
  659. // utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
  660. $newcharstring = '';
  661. $offset = 0;
  662. $stringlength = strlen($string);
  663. while ($offset < $stringlength) {
  664. if ((ord($string{$offset}) | 0x07) == 0xF7) {
  665. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  666. $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  667. ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  668. ((ord($string{($offset + 2)}) & 0x3F) << 6) &
  669. (ord($string{($offset + 3)}) & 0x3F);
  670. $offset += 4;
  671. } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  672. // 1110bbbb 10bbbbbb 10bbbbbb
  673. $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  674. ((ord($string{($offset + 1)}) & 0x3F) << 6) &
  675. (ord($string{($offset + 2)}) & 0x3F);
  676. $offset += 3;
  677. } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  678. // 110bbbbb 10bbbbbb
  679. $charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
  680. (ord($string{($offset + 1)}) & 0x3F);
  681. $offset += 2;
  682. } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  683. // 0bbbbbbb
  684. $charval = ord($string{$offset});
  685. $offset += 1;
  686. } else {
  687. // error? throw some kind of warning here?
  688. $charval = false;
  689. $offset += 1;
  690. }
  691. if ($charval !== false) {
  692. $newcharstring .= (($charval < 256) ? chr($charval) : '?');
  693. }
  694. }
  695. return $newcharstring;
  696. }
  697. // UTF-8 => UTF-16BE
  698. public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
  699. $newcharstring = '';
  700. if ($bom) {
  701. $newcharstring .= "\xFE\xFF";
  702. }
  703. $offset = 0;
  704. $stringlength = strlen($string);
  705. while ($offset < $stringlength) {
  706. if ((ord($string{$offset}) | 0x07) == 0xF7) {
  707. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  708. $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  709. ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  710. ((ord($string{($offset + 2)}) & 0x3F) << 6) &
  711. (ord($string{($offset + 3)}) & 0x3F);
  712. $offset += 4;
  713. } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  714. // 1110bbbb 10bbbbbb 10bbbbbb
  715. $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  716. ((ord($string{($offset + 1)}) & 0x3F) << 6) &
  717. (ord($string{($offset + 2)}) & 0x3F);
  718. $offset += 3;
  719. } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  720. // 110bbbbb 10bbbbbb
  721. $charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
  722. (ord($string{($offset + 1)}) & 0x3F);
  723. $offset += 2;
  724. } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  725. // 0bbbbbbb
  726. $charval = ord($string{$offset});
  727. $offset += 1;
  728. } else {
  729. // error? throw some kind of warning here?
  730. $charval = false;
  731. $offset += 1;
  732. }
  733. if ($charval !== false) {
  734. $newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
  735. }
  736. }
  737. return $newcharstring;
  738. }
  739. // UTF-8 => UTF-16LE
  740. public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
  741. $newcharstring = '';
  742. if ($bom) {
  743. $newcharstring .= "\xFF\xFE";
  744. }
  745. $offset = 0;
  746. $stringlength = strlen($string);
  747. while ($offset < $stringlength) {
  748. if ((ord($string{$offset}) | 0x07) == 0xF7) {
  749. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  750. $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  751. ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  752. ((ord($string{($offset + 2)}) & 0x3F) << 6) &
  753. (ord($string{($offset + 3)}) & 0x3F);
  754. $offset += 4;
  755. } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  756. // 1110bbbb 10bbbbbb 10bbbbbb
  757. $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  758. ((ord($string{($offset + 1)}) & 0x3F) << 6) &
  759. (ord($string{($offset + 2)}) & 0x3F);
  760. $offset += 3;
  761. } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  762. // 110bbbbb 10bbbbbb
  763. $charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
  764. (ord($string{($offset + 1)}) & 0x3F);
  765. $offset += 2;
  766. } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  767. // 0bbbbbbb
  768. $charval = ord($string{$offset});
  769. $offset += 1;
  770. } else {
  771. // error? maybe throw some warning here?
  772. $charval = false;
  773. $offset += 1;
  774. }
  775. if ($charval !== false) {
  776. $newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
  777. }
  778. }
  779. return $newcharstring;
  780. }
  781. // UTF-8 => UTF-16LE (BOM)
  782. public static function iconv_fallback_utf8_utf16($string) {
  783. return self::iconv_fallback_utf8_utf16le($string, true);
  784. }
  785. // UTF-16BE => UTF-8
  786. public static function iconv_fallback_utf16be_utf8($string) {
  787. if (substr($string, 0, 2) == "\xFE\xFF") {
  788. // strip BOM
  789. $string = substr($string, 2);
  790. }
  791. $newcharstring = '';
  792. for ($i = 0; $i < strlen($string); $i += 2) {
  793. $charval = self::BigEndian2Int(substr($string, $i, 2));
  794. $newcharstring .= self::iconv_fallback_int_utf8($charval);
  795. }
  796. return $newcharstring;
  797. }
  798. // UTF-16LE => UTF-8
  799. public static function iconv_fallback_utf16le_utf8($string) {
  800. if (substr($string, 0, 2) == "\xFF\xFE") {
  801. // strip BOM
  802. $string = substr($string, 2);
  803. }
  804. $newcharstring = '';
  805. for ($i = 0; $i < strlen($string); $i += 2) {
  806. $charval = self::LittleEndian2Int(substr($string, $i, 2));
  807. $newcharstring .= self::iconv_fallback_int_utf8($charval);
  808. }
  809. return $newcharstring;
  810. }
  811. // UTF-16BE => ISO-8859-1
  812. public static function iconv_fallback_utf16be_iso88591($string) {
  813. if (substr($string, 0, 2) == "\xFE\xFF") {
  814. // strip BOM
  815. $string = substr($string, 2);
  816. }
  817. $newcharstring = '';
  818. for ($i = 0; $i < strlen($string); $i += 2) {
  819. $charval = self::BigEndian2Int(substr($string, $i, 2));
  820. $newcharstring .= (($charval < 256) ? chr($charval) : '?');
  821. }
  822. return $newcharstring;
  823. }
  824. // UTF-16LE => ISO-8859-1
  825. public static function iconv_fallback_utf16le_iso88591($string) {
  826. if (substr($string, 0, 2) == "\xFF\xFE") {
  827. // strip BOM
  828. $string = substr($string, 2);
  829. }
  830. $newcharstring = '';
  831. for ($i = 0; $i < strlen($string); $i += 2) {
  832. $charval = self::LittleEndian2Int(substr($string, $i, 2));
  833. $newcharstring .= (($charval < 256) ? chr($charval) : '?');
  834. }
  835. return $newcharstring;
  836. }
  837. // UTF-16 (BOM) => ISO-8859-1
  838. public static function iconv_fallback_utf16_iso88591($string) {
  839. $bom = substr($string, 0, 2);
  840. if ($bom == "\xFE\xFF") {
  841. return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
  842. } elseif ($bom == "\xFF\xFE") {
  843. return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
  844. }
  845. return $string;
  846. }
  847. // UTF-16 (BOM) => UTF-8
  848. public static function iconv_fallback_utf16_utf8($string) {
  849. $bom = substr($string, 0, 2);
  850. if ($bom == "\xFE\xFF") {
  851. return self::iconv_fallback_utf16be_utf8(substr($string, 2));
  852. } elseif ($bom == "\xFF\xFE") {
  853. return self::iconv_fallback_utf16le_utf8(substr($string, 2));
  854. }
  855. return $string;
  856. }
  857. public static function iconv_fallback($in_charset, $out_charset, $string) {
  858. if ($in_charset == $out_charset) {
  859. return $string;
  860. }
  861. // iconv() availble
  862. if (function_exists('iconv')) {
  863. if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
  864. switch ($out_charset) {
  865. case 'ISO-8859-1':
  866. $converted_string = rtrim($converted_string, "\x00");
  867. break;
  868. }
  869. return $converted_string;
  870. }
  871. // iconv() may sometimes fail with "illegal character in input string" error message
  872. // and return an empty string, but returning the unconverted string is more useful
  873. return $string;
  874. }
  875. // iconv() not available
  876. static $ConversionFunctionList = array();
  877. if (empty($ConversionFunctionList)) {
  878. $ConversionFunctionList['ISO-8859-1']['UTF-8'] = 'iconv_fallback_iso88591_utf8';
  879. $ConversionFunctionList['ISO-8859-1']['UTF-16'] = 'iconv_fallback_iso88591_utf16';
  880. $ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
  881. $ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
  882. $ConversionFunctionList['UTF-8']['ISO-8859-1'] = 'iconv_fallback_utf8_iso88591';
  883. $ConversionFunctionList['UTF-8']['UTF-16'] = 'iconv_fallback_utf8_utf16';
  884. $ConversionFunctionList['UTF-8']['UTF-16BE'] = 'iconv_fallback_utf8_utf16be';
  885. $ConversionFunctionList['UTF-8']['UTF-16LE'] = 'iconv_fallback_utf8_utf16le';
  886. $ConversionFunctionList['UTF-16']['ISO-8859-1'] = 'iconv_fallback_utf16_iso88591';
  887. $ConversionFunctionList['UTF-16']['UTF-8'] = 'iconv_fallback_utf16_utf8';
  888. $ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
  889. $ConversionFunctionList['UTF-16LE']['UTF-8'] = 'iconv_fallback_utf16le_utf8';
  890. $ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
  891. $ConversionFunctionList['UTF-16BE']['UTF-8'] = 'iconv_fallback_utf16be_utf8';
  892. }
  893. if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
  894. $ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
  895. return self::$ConversionFunction($string);
  896. }
  897. throw new Exception('PHP does not have iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
  898. }
  899. public static function recursiveMultiByteCharString2HTML($data, $charset='ISO-8859-1') {
  900. if (is_string($data)) {
  901. return self::MultiByteCharString2HTML($data, $charset);
  902. } elseif (is_array($data)) {
  903. $return_data = array();
  904. foreach ($data as $key => $value) {
  905. $return_data[$key] = self::recursiveMultiByteCharString2HTML($value, $charset);
  906. }
  907. return $return_data;
  908. }
  909. // integer, float, objects, resources, etc
  910. return $data;
  911. }
  912. public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
  913. $string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
  914. $HTMLstring = '';
  915. switch ($charset) {
  916. case '1251':
  917. case '1252':
  918. case '866':
  919. case '932':
  920. case '936':
  921. case '950':
  922. case 'BIG5':
  923. case 'BIG5-HKSCS':
  924. case 'cp1251':
  925. case 'cp1252':
  926. case 'cp866':
  927. case 'EUC-JP':
  928. case 'EUCJP':
  929. case 'GB2312':
  930. case 'ibm866':
  931. case 'ISO-8859-1':
  932. case 'ISO-8859-15':
  933. case 'ISO8859-1':
  934. case 'ISO8859-15':
  935. case 'KOI8-R':
  936. case 'koi8-ru':
  937. case 'koi8r':
  938. case 'Shift_JIS':
  939. case 'SJIS':
  940. case 'win-1251':
  941. case 'Windows-1251':
  942. case 'Windows-1252':
  943. $HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
  944. break;
  945. case 'UTF-8':
  946. $strlen = strlen($string);
  947. for ($i = 0; $i < $strlen; $i++) {
  948. $char_ord_val = ord($string{$i});
  949. $charval = 0;
  950. if ($char_ord_val < 0x80) {
  951. $charval = $char_ord_val;
  952. } elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F && $i+3 < $strlen) {
  953. $charval = (($char_ord_val & 0x07) << 18);
  954. $charval += ((ord($string{++$i}) & 0x3F) << 12);
  955. $charval += ((ord($string{++$i}) & 0x3F) << 6);
  956. $charval += (ord($string{++$i}) & 0x3F);
  957. } elseif ((($char_ord_val & 0xE0) >> 5) == 0x07 && $i+2 < $strlen) {
  958. $charval = (($char_ord_val & 0x0F) << 12);
  959. $charval += ((ord($string{++$i}) & 0x3F) << 6);
  960. $charval += (ord($string{++$i}) & 0x3F);
  961. } elseif ((($char_ord_val & 0xC0) >> 6) == 0x03 && $i+1 < $strlen) {
  962. $charval = (($char_ord_val & 0x1F) << 6);
  963. $charval += (ord($string{++$i}) & 0x3F);
  964. }
  965. if (($charval >= 32) && ($charval <= 127)) {
  966. $HTMLstring .= htmlentities(chr($charval));
  967. } else {
  968. $HTMLstring .= '&#'.$charval.';';
  969. }
  970. }
  971. break;
  972. case 'UTF-16LE':
  973. for ($i = 0; $i < strlen($string); $i += 2) {
  974. $charval = self::LittleEndian2Int(substr($string, $i, 2));
  975. if (($charval >= 32) && ($charval <= 127)) {
  976. $HTMLstring .= chr($charval);
  977. } else {
  978. $HTMLstring .= '&#'.$charval.';';
  979. }
  980. }
  981. break;
  982. case 'UTF-16BE':
  983. for ($i = 0; $i < strlen($string); $i += 2) {
  984. $charval = self::BigEndian2Int(substr($string, $i, 2));
  985. if (($charval >= 32) && ($charval <= 127)) {
  986. $HTMLstring .= chr($charval);
  987. } else {
  988. $HTMLstring .= '&#'.$charval.';';
  989. }
  990. }
  991. break;
  992. default:
  993. $HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
  994. break;
  995. }
  996. return $HTMLstring;
  997. }
  998. public static function RGADnameLookup($namecode) {
  999. static $RGADname = array();
  1000. if (empty($RGADname)) {
  1001. $RGADname[0] = 'not set';
  1002. $RGADname[1] = 'Track Gain Adjustment';
  1003. $RGADname[2] = 'Album Gain Adjustment';
  1004. }
  1005. return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
  1006. }
  1007. public static function RGADoriginatorLookup($originatorcode) {
  1008. static $RGADoriginator = array();
  1009. if (empty($RGADoriginator)) {
  1010. $RGADoriginator[0] = 'unspecified';
  1011. $RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
  1012. $RGADoriginator[2] = 'set by user';
  1013. $RGADoriginator[3] = 'determined automatically';
  1014. }
  1015. return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
  1016. }
  1017. public static function RGADadjustmentLookup($rawadjustment, $signbit) {
  1018. $adjustment = $rawadjustment / 10;
  1019. if ($signbit == 1) {
  1020. $adjustment *= -1;
  1021. }
  1022. return (float) $adjustment;
  1023. }
  1024. public static function RGADgainString($namecode, $originatorcode, $replaygain) {
  1025. if ($replaygain < 0) {
  1026. $signbit = '1';
  1027. } else {
  1028. $signbit = '0';
  1029. }
  1030. $storedreplaygain = intval(round($replaygain * 10));
  1031. $gainstring = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
  1032. $gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
  1033. $gainstring .= $signbit;
  1034. $gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
  1035. return $gainstring;
  1036. }
  1037. public static function RGADamplitude2dB($amplitude) {
  1038. return 20 * log10($amplitude);
  1039. }
  1040. public static function GetDataImageSize($imgData, &$imageinfo=array()) {
  1041. static $tempdir = '';
  1042. if (empty($tempdir)) {
  1043. if (function_exists('sys_get_temp_dir')) {
  1044. $tempdir = sys_get_temp_dir(); // https://github.com/JamesHeinrich/getID3/issues/52
  1045. }
  1046. // yes this is ugly, feel free to suggest a better way
  1047. if (include_once(dirname(__FILE__).'/getid3.php')) {
  1048. if ($getid3_temp = new getID3()) {
  1049. if ($getid3_temp_tempdir = $getid3_temp->tempdir) {
  1050. $tempdir = $getid3_temp_tempdir;
  1051. }
  1052. unset($getid3_temp, $getid3_temp_tempdir);
  1053. }
  1054. }
  1055. }
  1056. $GetDataImageSize = false;
  1057. if ($tempfilename = tempnam($tempdir, 'gI3')) {
  1058. if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
  1059. fwrite($tmp, $imgData);
  1060. fclose($tmp);
  1061. $GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
  1062. if (($GetDataImageSize === false) || !isset($GetDataImageSize[0]) || !isset($GetDataImageSize[1])) {
  1063. return false;
  1064. }
  1065. $GetDataImageSize['height'] = $GetDataImageSize[0];
  1066. $GetDataImageSize['width'] = $GetDataImageSize[1];
  1067. }
  1068. unlink($tempfilename);
  1069. }
  1070. return $GetDataImageSize;
  1071. }
  1072. public static function ImageExtFromMime($mime_type) {
  1073. // temporary way, works OK for now, but should be reworked in the future
  1074. return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
  1075. }
  1076. public static function ImageTypesLookup($imagetypeid) {
  1077. static $ImageTypesLookup = array();
  1078. if (empty($ImageTypesLookup)) {
  1079. $ImageTypesLookup[1] = 'gif';
  1080. $ImageTypesLookup[2] = 'jpeg';
  1081. $ImageTypesLookup[3] = 'png';
  1082. $ImageTypesLookup[4] = 'swf';
  1083. $ImageTypesLookup[5] = 'psd';
  1084. $ImageTypesLookup[6] = 'bmp';
  1085. $ImageTypesLookup[7] = 'tiff (little-endian)';
  1086. $ImageTypesLookup[8] = 'tiff (big-endian)';
  1087. $ImageTypesLookup[9] = 'jpc';
  1088. $ImageTypesLookup[10] = 'jp2';
  1089. $ImageTypesLookup[11] = 'jpx';
  1090. $ImageTypesLookup[12] = 'jb2';
  1091. $ImageTypesLookup[13] = 'swc';
  1092. $ImageTypesLookup[14] = 'iff';
  1093. }
  1094. return (isset($ImageTypesLookup[$imagetypeid]) ? $ImageTypesLookup[$imagetypeid] : '');
  1095. }
  1096. public static function CopyTagsToComments(&$ThisFileInfo) {
  1097. // Copy all entries from ['tags'] into common ['comments']
  1098. if (!empty($ThisFileInfo['tags'])) {
  1099. foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
  1100. foreach ($tagarray as $tagname => $tagdata) {
  1101. foreach ($tagdata as $key => $value) {
  1102. if (!empty($value)) {
  1103. if (empty($ThisFileInfo['comments'][$tagname])) {
  1104. // fall through and append value
  1105. } elseif ($tagtype == 'id3v1') {
  1106. $newvaluelength = strlen(trim($value));
  1107. foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  1108. $oldvaluelength = strlen(trim($existingvalue));
  1109. if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
  1110. // new value is identical but shorter-than (or equal-length to) one already in comments - skip
  1111. break 2;
  1112. }
  1113. }
  1114. } elseif (!is_array($value)) {
  1115. $newvaluelength = strlen(trim($value));
  1116. foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  1117. $oldvaluelength = strlen(trim($existingvalue));
  1118. if ((strlen($existingvalue) > 10) && ($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
  1119. $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
  1120. //break 2;
  1121. break;
  1122. }
  1123. }
  1124. }
  1125. if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
  1126. $value = (is_string($value) ? trim($value) : $value);
  1127. if (!is_numeric($key)) {
  1128. $ThisFileInfo['comments'][$tagname][$key] = $value;
  1129. } else {
  1130. $ThisFileInfo['comments'][$tagname][] = $value;
  1131. }
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. // Copy to ['comments_html']
  1138. if (!empty($ThisFileInfo['comments'])) {
  1139. foreach ($ThisFileInfo['comments'] as $field => $values) {
  1140. if ($field == 'picture') {
  1141. // pictures can take up a lot of space, and we don't need multiple copies of them
  1142. // let there be a single copy in [comments][picture], and not elsewhere
  1143. continue;
  1144. }
  1145. foreach ($values as $index => $value) {
  1146. if (is_array($value)) {
  1147. $ThisFileInfo['comments_html'][$field][$index] = $value;
  1148. } else {
  1149. $ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. return true;
  1156. }
  1157. public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
  1158. // Cached
  1159. static $cache;
  1160. if (isset($cache[$file][$name])) {
  1161. return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  1162. }
  1163. // Init
  1164. $keylength = strlen($key);
  1165. $line_count = $end - $begin - 7;
  1166. // Open php file
  1167. $fp = fopen($file, 'r');
  1168. // Discard $begin lines
  1169. for ($i = 0; $i < ($begin + 3); $i++) {
  1170. fgets($fp, 1024);
  1171. }
  1172. // Loop thru line
  1173. while (0 < $line_count--) {
  1174. // Read line
  1175. $line = ltrim(fgets($fp, 1024), "\t ");
  1176. // METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
  1177. //$keycheck = substr($line, 0, $keylength);
  1178. //if ($key == $keycheck) {
  1179. // $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
  1180. // break;
  1181. //}
  1182. // METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
  1183. //$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
  1184. $explodedLine = explode("\t", $line, 2);
  1185. $ThisKey = (isset($explodedLine[0]) ? $explodedLine[0] : '');
  1186. $ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
  1187. $cache[$file][$name][$ThisKey] = trim($ThisValue);
  1188. }
  1189. // Close and return
  1190. fclose($fp);
  1191. return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  1192. }
  1193. public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
  1194. global $GETID3_ERRORARRAY;
  1195. if (file_exists($filename)) {
  1196. if (include_once($filename)) {
  1197. return true;
  1198. } else {
  1199. $diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
  1200. }
  1201. } else {
  1202. $diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
  1203. }
  1204. if ($DieOnFailure) {
  1205. throw new Exception($diemessage);
  1206. } else {
  1207. $GETID3_ERRORARRAY[] = $diemessage;
  1208. }
  1209. return false;
  1210. }
  1211. public static function trimNullByte($string) {
  1212. return trim($string, "\x00");
  1213. }
  1214. public static function getFileSizeSyscall($path) {
  1215. $filesize = false;
  1216. if (GETID3_OS_ISWINDOWS) {
  1217. 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:
  1218. $filesystem = new COM('Scripting.FileSystemObject');
  1219. $file = $filesystem->GetFile($path);
  1220. $filesize = $file->Size();
  1221. unset($filesystem, $file);
  1222. } else {
  1223. $commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
  1224. }
  1225. } else {
  1226. $commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
  1227. }
  1228. if (isset($commandline)) {
  1229. $output = trim(`$commandline`);
  1230. if (ctype_digit($output)) {
  1231. $filesize = (float) $output;
  1232. }
  1233. }
  1234. return $filesize;
  1235. }
  1236. /**
  1237. * Workaround for Bug #37268 (https://bugs.php.net/bug.php?id=37268)
  1238. * @param string $path A path.
  1239. * @param string $suffix If the name component ends in suffix this will also be cut off.
  1240. * @return string
  1241. */
  1242. public static function mb_basename($path, $suffix = null) {
  1243. $splited = preg_split('#/#', rtrim($path, '/ '));
  1244. return substr(basename('X'.$splited[count($splited) - 1], $suffix), 1);
  1245. }
  1246. }