getid3.lib.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  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 LittleEndian2Bin($byteword) {
  261. return self::BigEndian2Bin(strrev($byteword));
  262. }
  263. public static function BigEndian2Bin($byteword) {
  264. $binvalue = '';
  265. $bytewordlen = strlen($byteword);
  266. for ($i = 0; $i < $bytewordlen; $i++) {
  267. $binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
  268. }
  269. return $binvalue;
  270. }
  271. public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
  272. if ($number < 0) {
  273. throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
  274. }
  275. $maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
  276. $intstring = '';
  277. if ($signed) {
  278. if ($minbytes > PHP_INT_SIZE) {
  279. throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
  280. }
  281. $number = $number & (0x80 << (8 * ($minbytes - 1)));
  282. }
  283. while ($number != 0) {
  284. $quotient = ($number / ($maskbyte + 1));
  285. $intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
  286. $number = floor($quotient);
  287. }
  288. return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
  289. }
  290. public static function Dec2Bin($number) {
  291. while ($number >= 256) {
  292. $bytes[] = (($number / 256) - (floor($number / 256))) * 256;
  293. $number = floor($number / 256);
  294. }
  295. $bytes[] = $number;
  296. $binstring = '';
  297. for ($i = 0; $i < count($bytes); $i++) {
  298. $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring;
  299. }
  300. return $binstring;
  301. }
  302. public static function Bin2Dec($binstring, $signed=false) {
  303. $signmult = 1;
  304. if ($signed) {
  305. if ($binstring{0} == '1') {
  306. $signmult = -1;
  307. }
  308. $binstring = substr($binstring, 1);
  309. }
  310. $decvalue = 0;
  311. for ($i = 0; $i < strlen($binstring); $i++) {
  312. $decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
  313. }
  314. return self::CastAsInt($decvalue * $signmult);
  315. }
  316. public static function Bin2String($binstring) {
  317. // return 'hi' for input of '0110100001101001'
  318. $string = '';
  319. $binstringreversed = strrev($binstring);
  320. for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
  321. $string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
  322. }
  323. return $string;
  324. }
  325. public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
  326. $intstring = '';
  327. while ($number > 0) {
  328. if ($synchsafe) {
  329. $intstring = $intstring.chr($number & 127);
  330. $number >>= 7;
  331. } else {
  332. $intstring = $intstring.chr($number & 255);
  333. $number >>= 8;
  334. }
  335. }
  336. return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
  337. }
  338. public static function array_merge_clobber($array1, $array2) {
  339. // written by kcØhireability*com
  340. // taken from http://www.php.net/manual/en/function.array-merge-recursive.php
  341. if (!is_array($array1) || !is_array($array2)) {
  342. return false;
  343. }
  344. $newarray = $array1;
  345. foreach ($array2 as $key => $val) {
  346. if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
  347. $newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
  348. } else {
  349. $newarray[$key] = $val;
  350. }
  351. }
  352. return $newarray;
  353. }
  354. public static function array_merge_noclobber($array1, $array2) {
  355. if (!is_array($array1) || !is_array($array2)) {
  356. return false;
  357. }
  358. $newarray = $array1;
  359. foreach ($array2 as $key => $val) {
  360. if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
  361. $newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
  362. } elseif (!isset($newarray[$key])) {
  363. $newarray[$key] = $val;
  364. }
  365. }
  366. return $newarray;
  367. }
  368. public static function flipped_array_merge_noclobber($array1, $array2) {
  369. if (!is_array($array1) || !is_array($array2)) {
  370. return false;
  371. }
  372. # naturally, this only works non-recursively
  373. $newarray = array_flip($array1);
  374. foreach (array_flip($array2) as $key => $val) {
  375. if (!isset($newarray[$key])) {
  376. $newarray[$key] = count($newarray);
  377. }
  378. }
  379. return array_flip($newarray);
  380. }
  381. public static function ksort_recursive(&$theArray) {
  382. ksort($theArray);
  383. foreach ($theArray as $key => $value) {
  384. if (is_array($value)) {
  385. self::ksort_recursive($theArray[$key]);
  386. }
  387. }
  388. return true;
  389. }
  390. public static function fileextension($filename, $numextensions=1) {
  391. if (strstr($filename, '.')) {
  392. $reversedfilename = strrev($filename);
  393. $offset = 0;
  394. for ($i = 0; $i < $numextensions; $i++) {
  395. $offset = strpos($reversedfilename, '.', $offset + 1);
  396. if ($offset === false) {
  397. return '';
  398. }
  399. }
  400. return strrev(substr($reversedfilename, 0, $offset));
  401. }
  402. return '';
  403. }
  404. public static function PlaytimeString($seconds) {
  405. $sign = (($seconds < 0) ? '-' : '');
  406. $seconds = round(abs($seconds));
  407. $H = (int) floor( $seconds / 3600);
  408. $M = (int) floor(($seconds - (3600 * $H) ) / 60);
  409. $S = (int) round( $seconds - (3600 * $H) - (60 * $M) );
  410. return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
  411. }
  412. public static function DateMac2Unix($macdate) {
  413. // Macintosh timestamp: seconds since 00:00h January 1, 1904
  414. // UNIX timestamp: seconds since 00:00h January 1, 1970
  415. return self::CastAsInt($macdate - 2082844800);
  416. }
  417. public static function FixedPoint8_8($rawdata) {
  418. return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
  419. }
  420. public static function FixedPoint16_16($rawdata) {
  421. return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
  422. }
  423. public static function FixedPoint2_30($rawdata) {
  424. $binarystring = self::BigEndian2Bin($rawdata);
  425. return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
  426. }
  427. public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
  428. // assigns $Value to a nested array path:
  429. // $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
  430. // is the same as:
  431. // $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
  432. // or
  433. // $foo['path']['to']['my'] = 'file.txt';
  434. $ArrayPath = ltrim($ArrayPath, $Separator);
  435. if (($pos = strpos($ArrayPath, $Separator)) !== false) {
  436. $ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
  437. } else {
  438. $ReturnedArray[$ArrayPath] = $Value;
  439. }
  440. return $ReturnedArray;
  441. }
  442. public static function array_max($arraydata, $returnkey=false) {
  443. $maxvalue = false;
  444. $maxkey = false;
  445. foreach ($arraydata as $key => $value) {
  446. if (!is_array($value)) {
  447. if ($value > $maxvalue) {
  448. $maxvalue = $value;
  449. $maxkey = $key;
  450. }
  451. }
  452. }
  453. return ($returnkey ? $maxkey : $maxvalue);
  454. }
  455. public static function array_min($arraydata, $returnkey=false) {
  456. $minvalue = false;
  457. $minkey = false;
  458. foreach ($arraydata as $key => $value) {
  459. if (!is_array($value)) {
  460. if ($value > $minvalue) {
  461. $minvalue = $value;
  462. $minkey = $key;
  463. }
  464. }
  465. }
  466. return ($returnkey ? $minkey : $minvalue);
  467. }
  468. public static function XML2array($XMLstring) {
  469. if (function_exists('simplexml_load_string') && function_exists('libxml_disable_entity_loader')) {
  470. // http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html
  471. // https://core.trac.wordpress.org/changeset/29378
  472. $loader = libxml_disable_entity_loader(true);
  473. $XMLobject = simplexml_load_string($XMLstring, 'SimpleXMLElement', LIBXML_NOENT);
  474. $return = self::SimpleXMLelement2array($XMLobject);
  475. libxml_disable_entity_loader($loader);
  476. return $return;
  477. }
  478. return false;
  479. }
  480. public static function SimpleXMLelement2array($XMLobject) {
  481. if (!is_object($XMLobject) && !is_array($XMLobject)) {
  482. return $XMLobject;
  483. }
  484. $XMLarray = (is_object($XMLobject) ? get_object_vars($XMLobject) : $XMLobject);
  485. foreach ($XMLarray as $key => $value) {
  486. $XMLarray[$key] = self::SimpleXMLelement2array($value);
  487. }
  488. return $XMLarray;
  489. }
  490. // Allan Hansen <ahØartemis*dk>
  491. // self::md5_data() - returns md5sum for a file from startuing position to absolute end position
  492. public static function hash_data($file, $offset, $end, $algorithm) {
  493. static $tempdir = '';
  494. if (!self::intValueSupported($end)) {
  495. return false;
  496. }
  497. switch ($algorithm) {
  498. case 'md5':
  499. $hash_function = 'md5_file';
  500. $unix_call = 'md5sum';
  501. $windows_call = 'md5sum.exe';
  502. $hash_length = 32;
  503. break;
  504. case 'sha1':
  505. $hash_function = 'sha1_file';
  506. $unix_call = 'sha1sum';
  507. $windows_call = 'sha1sum.exe';
  508. $hash_length = 40;
  509. break;
  510. default:
  511. throw new Exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
  512. break;
  513. }
  514. $size = $end - $offset;
  515. while (true) {
  516. if (GETID3_OS_ISWINDOWS) {
  517. // It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
  518. // Fall back to create-temp-file method:
  519. if ($algorithm == 'sha1') {
  520. break;
  521. }
  522. $RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
  523. foreach ($RequiredFiles as $required_file) {
  524. if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
  525. // helper apps not available - fall back to old method
  526. break 2;
  527. }
  528. }
  529. $commandline = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' '.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).' | ';
  530. $commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
  531. $commandline .= GETID3_HELPERAPPSDIR.$windows_call;
  532. } else {
  533. $commandline = 'head -c'.$end.' '.escapeshellarg($file).' | ';
  534. $commandline .= 'tail -c'.$size.' | ';
  535. $commandline .= $unix_call;
  536. }
  537. if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
  538. //throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
  539. break;
  540. }
  541. return substr(`$commandline`, 0, $hash_length);
  542. }
  543. if (empty($tempdir)) {
  544. // yes this is ugly, feel free to suggest a better way
  545. require_once(dirname(__FILE__).'/getid3.php');
  546. $getid3_temp = new getID3();
  547. $tempdir = $getid3_temp->tempdir;
  548. unset($getid3_temp);
  549. }
  550. // try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
  551. if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
  552. // can't find anywhere to create a temp file, just fail
  553. return false;
  554. }
  555. // Init
  556. $result = false;
  557. // copy parts of file
  558. try {
  559. self::CopyFileParts($file, $data_filename, $offset, $end - $offset);
  560. $result = $hash_function($data_filename);
  561. } catch (Exception $e) {
  562. throw new Exception('self::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
  563. }
  564. unlink($data_filename);
  565. return $result;
  566. }
  567. public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
  568. if (!self::intValueSupported($offset + $length)) {
  569. throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
  570. }
  571. if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
  572. if (($fp_dest = fopen($filename_dest, 'wb'))) {
  573. if (fseek($fp_src, $offset) == 0) {
  574. $byteslefttowrite = $length;
  575. while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
  576. $byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
  577. $byteslefttowrite -= $byteswritten;
  578. }
  579. return true;
  580. } else {
  581. throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
  582. }
  583. fclose($fp_dest);
  584. } else {
  585. throw new Exception('failed to create file for writing '.$filename_dest);
  586. }
  587. fclose($fp_src);
  588. } else {
  589. throw new Exception('failed to open file for reading '.$filename_source);
  590. }
  591. return false;
  592. }
  593. public static function iconv_fallback_int_utf8($charval) {
  594. if ($charval < 128) {
  595. // 0bbbbbbb
  596. $newcharstring = chr($charval);
  597. } elseif ($charval < 2048) {
  598. // 110bbbbb 10bbbbbb
  599. $newcharstring = chr(($charval >> 6) | 0xC0);
  600. $newcharstring .= chr(($charval & 0x3F) | 0x80);
  601. } elseif ($charval < 65536) {
  602. // 1110bbbb 10bbbbbb 10bbbbbb
  603. $newcharstring = chr(($charval >> 12) | 0xE0);
  604. $newcharstring .= chr(($charval >> 6) | 0xC0);
  605. $newcharstring .= chr(($charval & 0x3F) | 0x80);
  606. } else {
  607. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  608. $newcharstring = chr(($charval >> 18) | 0xF0);
  609. $newcharstring .= chr(($charval >> 12) | 0xC0);
  610. $newcharstring .= chr(($charval >> 6) | 0xC0);
  611. $newcharstring .= chr(($charval & 0x3F) | 0x80);
  612. }
  613. return $newcharstring;
  614. }
  615. // ISO-8859-1 => UTF-8
  616. public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
  617. if (function_exists('utf8_encode')) {
  618. return utf8_encode($string);
  619. }
  620. // utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
  621. $newcharstring = '';
  622. if ($bom) {
  623. $newcharstring .= "\xEF\xBB\xBF";
  624. }
  625. for ($i = 0; $i < strlen($string); $i++) {
  626. $charval = ord($string{$i});
  627. $newcharstring .= self::iconv_fallback_int_utf8($charval);
  628. }
  629. return $newcharstring;
  630. }
  631. // ISO-8859-1 => UTF-16BE
  632. public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
  633. $newcharstring = '';
  634. if ($bom) {
  635. $newcharstring .= "\xFE\xFF";
  636. }
  637. for ($i = 0; $i < strlen($string); $i++) {
  638. $newcharstring .= "\x00".$string{$i};
  639. }
  640. return $newcharstring;
  641. }
  642. // ISO-8859-1 => UTF-16LE
  643. public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
  644. $newcharstring = '';
  645. if ($bom) {
  646. $newcharstring .= "\xFF\xFE";
  647. }
  648. for ($i = 0; $i < strlen($string); $i++) {
  649. $newcharstring .= $string{$i}."\x00";
  650. }
  651. return $newcharstring;
  652. }
  653. // ISO-8859-1 => UTF-16LE (BOM)
  654. public static function iconv_fallback_iso88591_utf16($string) {
  655. return self::iconv_fallback_iso88591_utf16le($string, true);
  656. }
  657. // UTF-8 => ISO-8859-1
  658. public static function iconv_fallback_utf8_iso88591($string) {
  659. if (function_exists('utf8_decode')) {
  660. return utf8_decode($string);
  661. }
  662. // utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
  663. $newcharstring = '';
  664. $offset = 0;
  665. $stringlength = strlen($string);
  666. while ($offset < $stringlength) {
  667. if ((ord($string{$offset}) | 0x07) == 0xF7) {
  668. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  669. $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  670. ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  671. ((ord($string{($offset + 2)}) & 0x3F) << 6) &
  672. (ord($string{($offset + 3)}) & 0x3F);
  673. $offset += 4;
  674. } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  675. // 1110bbbb 10bbbbbb 10bbbbbb
  676. $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  677. ((ord($string{($offset + 1)}) & 0x3F) << 6) &
  678. (ord($string{($offset + 2)}) & 0x3F);
  679. $offset += 3;
  680. } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  681. // 110bbbbb 10bbbbbb
  682. $charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
  683. (ord($string{($offset + 1)}) & 0x3F);
  684. $offset += 2;
  685. } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  686. // 0bbbbbbb
  687. $charval = ord($string{$offset});
  688. $offset += 1;
  689. } else {
  690. // error? throw some kind of warning here?
  691. $charval = false;
  692. $offset += 1;
  693. }
  694. if ($charval !== false) {
  695. $newcharstring .= (($charval < 256) ? chr($charval) : '?');
  696. }
  697. }
  698. return $newcharstring;
  699. }
  700. // UTF-8 => UTF-16BE
  701. public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
  702. $newcharstring = '';
  703. if ($bom) {
  704. $newcharstring .= "\xFE\xFF";
  705. }
  706. $offset = 0;
  707. $stringlength = strlen($string);
  708. while ($offset < $stringlength) {
  709. if ((ord($string{$offset}) | 0x07) == 0xF7) {
  710. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  711. $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  712. ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  713. ((ord($string{($offset + 2)}) & 0x3F) << 6) &
  714. (ord($string{($offset + 3)}) & 0x3F);
  715. $offset += 4;
  716. } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  717. // 1110bbbb 10bbbbbb 10bbbbbb
  718. $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  719. ((ord($string{($offset + 1)}) & 0x3F) << 6) &
  720. (ord($string{($offset + 2)}) & 0x3F);
  721. $offset += 3;
  722. } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  723. // 110bbbbb 10bbbbbb
  724. $charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
  725. (ord($string{($offset + 1)}) & 0x3F);
  726. $offset += 2;
  727. } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  728. // 0bbbbbbb
  729. $charval = ord($string{$offset});
  730. $offset += 1;
  731. } else {
  732. // error? throw some kind of warning here?
  733. $charval = false;
  734. $offset += 1;
  735. }
  736. if ($charval !== false) {
  737. $newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
  738. }
  739. }
  740. return $newcharstring;
  741. }
  742. // UTF-8 => UTF-16LE
  743. public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
  744. $newcharstring = '';
  745. if ($bom) {
  746. $newcharstring .= "\xFF\xFE";
  747. }
  748. $offset = 0;
  749. $stringlength = strlen($string);
  750. while ($offset < $stringlength) {
  751. if ((ord($string{$offset}) | 0x07) == 0xF7) {
  752. // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  753. $charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
  754. ((ord($string{($offset + 1)}) & 0x3F) << 12) &
  755. ((ord($string{($offset + 2)}) & 0x3F) << 6) &
  756. (ord($string{($offset + 3)}) & 0x3F);
  757. $offset += 4;
  758. } elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
  759. // 1110bbbb 10bbbbbb 10bbbbbb
  760. $charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
  761. ((ord($string{($offset + 1)}) & 0x3F) << 6) &
  762. (ord($string{($offset + 2)}) & 0x3F);
  763. $offset += 3;
  764. } elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
  765. // 110bbbbb 10bbbbbb
  766. $charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
  767. (ord($string{($offset + 1)}) & 0x3F);
  768. $offset += 2;
  769. } elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
  770. // 0bbbbbbb
  771. $charval = ord($string{$offset});
  772. $offset += 1;
  773. } else {
  774. // error? maybe throw some warning here?
  775. $charval = false;
  776. $offset += 1;
  777. }
  778. if ($charval !== false) {
  779. $newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
  780. }
  781. }
  782. return $newcharstring;
  783. }
  784. // UTF-8 => UTF-16LE (BOM)
  785. public static function iconv_fallback_utf8_utf16($string) {
  786. return self::iconv_fallback_utf8_utf16le($string, true);
  787. }
  788. // UTF-16BE => UTF-8
  789. public static function iconv_fallback_utf16be_utf8($string) {
  790. if (substr($string, 0, 2) == "\xFE\xFF") {
  791. // strip BOM
  792. $string = substr($string, 2);
  793. }
  794. $newcharstring = '';
  795. for ($i = 0; $i < strlen($string); $i += 2) {
  796. $charval = self::BigEndian2Int(substr($string, $i, 2));
  797. $newcharstring .= self::iconv_fallback_int_utf8($charval);
  798. }
  799. return $newcharstring;
  800. }
  801. // UTF-16LE => UTF-8
  802. public static function iconv_fallback_utf16le_utf8($string) {
  803. if (substr($string, 0, 2) == "\xFF\xFE") {
  804. // strip BOM
  805. $string = substr($string, 2);
  806. }
  807. $newcharstring = '';
  808. for ($i = 0; $i < strlen($string); $i += 2) {
  809. $charval = self::LittleEndian2Int(substr($string, $i, 2));
  810. $newcharstring .= self::iconv_fallback_int_utf8($charval);
  811. }
  812. return $newcharstring;
  813. }
  814. // UTF-16BE => ISO-8859-1
  815. public static function iconv_fallback_utf16be_iso88591($string) {
  816. if (substr($string, 0, 2) == "\xFE\xFF") {
  817. // strip BOM
  818. $string = substr($string, 2);
  819. }
  820. $newcharstring = '';
  821. for ($i = 0; $i < strlen($string); $i += 2) {
  822. $charval = self::BigEndian2Int(substr($string, $i, 2));
  823. $newcharstring .= (($charval < 256) ? chr($charval) : '?');
  824. }
  825. return $newcharstring;
  826. }
  827. // UTF-16LE => ISO-8859-1
  828. public static function iconv_fallback_utf16le_iso88591($string) {
  829. if (substr($string, 0, 2) == "\xFF\xFE") {
  830. // strip BOM
  831. $string = substr($string, 2);
  832. }
  833. $newcharstring = '';
  834. for ($i = 0; $i < strlen($string); $i += 2) {
  835. $charval = self::LittleEndian2Int(substr($string, $i, 2));
  836. $newcharstring .= (($charval < 256) ? chr($charval) : '?');
  837. }
  838. return $newcharstring;
  839. }
  840. // UTF-16 (BOM) => ISO-8859-1
  841. public static function iconv_fallback_utf16_iso88591($string) {
  842. $bom = substr($string, 0, 2);
  843. if ($bom == "\xFE\xFF") {
  844. return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
  845. } elseif ($bom == "\xFF\xFE") {
  846. return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
  847. }
  848. return $string;
  849. }
  850. // UTF-16 (BOM) => UTF-8
  851. public static function iconv_fallback_utf16_utf8($string) {
  852. $bom = substr($string, 0, 2);
  853. if ($bom == "\xFE\xFF") {
  854. return self::iconv_fallback_utf16be_utf8(substr($string, 2));
  855. } elseif ($bom == "\xFF\xFE") {
  856. return self::iconv_fallback_utf16le_utf8(substr($string, 2));
  857. }
  858. return $string;
  859. }
  860. public static function iconv_fallback($in_charset, $out_charset, $string) {
  861. if ($in_charset == $out_charset) {
  862. return $string;
  863. }
  864. // mb_convert_encoding() availble
  865. if (function_exists('mb_convert_encoding')) {
  866. if ($converted_string = @mb_convert_encoding($string, $out_charset, $in_charset)) {
  867. switch ($out_charset) {
  868. case 'ISO-8859-1':
  869. $converted_string = rtrim($converted_string, "\x00");
  870. break;
  871. }
  872. return $converted_string;
  873. }
  874. return $string;
  875. }
  876. // iconv() availble
  877. else if (function_exists('iconv')) {
  878. if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
  879. switch ($out_charset) {
  880. case 'ISO-8859-1':
  881. $converted_string = rtrim($converted_string, "\x00");
  882. break;
  883. }
  884. return $converted_string;
  885. }
  886. // iconv() may sometimes fail with "illegal character in input string" error message
  887. // and return an empty string, but returning the unconverted string is more useful
  888. return $string;
  889. }
  890. // neither mb_convert_encoding or iconv() is available
  891. static $ConversionFunctionList = array();
  892. if (empty($ConversionFunctionList)) {
  893. $ConversionFunctionList['ISO-8859-1']['UTF-8'] = 'iconv_fallback_iso88591_utf8';
  894. $ConversionFunctionList['ISO-8859-1']['UTF-16'] = 'iconv_fallback_iso88591_utf16';
  895. $ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
  896. $ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
  897. $ConversionFunctionList['UTF-8']['ISO-8859-1'] = 'iconv_fallback_utf8_iso88591';
  898. $ConversionFunctionList['UTF-8']['UTF-16'] = 'iconv_fallback_utf8_utf16';
  899. $ConversionFunctionList['UTF-8']['UTF-16BE'] = 'iconv_fallback_utf8_utf16be';
  900. $ConversionFunctionList['UTF-8']['UTF-16LE'] = 'iconv_fallback_utf8_utf16le';
  901. $ConversionFunctionList['UTF-16']['ISO-8859-1'] = 'iconv_fallback_utf16_iso88591';
  902. $ConversionFunctionList['UTF-16']['UTF-8'] = 'iconv_fallback_utf16_utf8';
  903. $ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
  904. $ConversionFunctionList['UTF-16LE']['UTF-8'] = 'iconv_fallback_utf16le_utf8';
  905. $ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
  906. $ConversionFunctionList['UTF-16BE']['UTF-8'] = 'iconv_fallback_utf16be_utf8';
  907. }
  908. if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
  909. $ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
  910. return self::$ConversionFunction($string);
  911. }
  912. throw new Exception('PHP does not has mb_convert_encoding() or iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
  913. }
  914. public static function recursiveMultiByteCharString2HTML($data, $charset='ISO-8859-1') {
  915. if (is_string($data)) {
  916. return self::MultiByteCharString2HTML($data, $charset);
  917. } elseif (is_array($data)) {
  918. $return_data = array();
  919. foreach ($data as $key => $value) {
  920. $return_data[$key] = self::recursiveMultiByteCharString2HTML($value, $charset);
  921. }
  922. return $return_data;
  923. }
  924. // integer, float, objects, resources, etc
  925. return $data;
  926. }
  927. public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
  928. $string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
  929. $HTMLstring = '';
  930. switch (strtolower($charset)) {
  931. case '1251':
  932. case '1252':
  933. case '866':
  934. case '932':
  935. case '936':
  936. case '950':
  937. case 'big5':
  938. case 'big5-hkscs':
  939. case 'cp1251':
  940. case 'cp1252':
  941. case 'cp866':
  942. case 'euc-jp':
  943. case 'eucjp':
  944. case 'gb2312':
  945. case 'ibm866':
  946. case 'iso-8859-1':
  947. case 'iso-8859-15':
  948. case 'iso8859-1':
  949. case 'iso8859-15':
  950. case 'koi8-r':
  951. case 'koi8-ru':
  952. case 'koi8r':
  953. case 'shift_jis':
  954. case 'sjis':
  955. case 'win-1251':
  956. case 'windows-1251':
  957. case 'windows-1252':
  958. $HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
  959. break;
  960. case 'utf-8':
  961. $strlen = strlen($string);
  962. for ($i = 0; $i < $strlen; $i++) {
  963. $char_ord_val = ord($string{$i});
  964. $charval = 0;
  965. if ($char_ord_val < 0x80) {
  966. $charval = $char_ord_val;
  967. } elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F && $i+3 < $strlen) {
  968. $charval = (($char_ord_val & 0x07) << 18);
  969. $charval += ((ord($string{++$i}) & 0x3F) << 12);
  970. $charval += ((ord($string{++$i}) & 0x3F) << 6);
  971. $charval += (ord($string{++$i}) & 0x3F);
  972. } elseif ((($char_ord_val & 0xE0) >> 5) == 0x07 && $i+2 < $strlen) {
  973. $charval = (($char_ord_val & 0x0F) << 12);
  974. $charval += ((ord($string{++$i}) & 0x3F) << 6);
  975. $charval += (ord($string{++$i}) & 0x3F);
  976. } elseif ((($char_ord_val & 0xC0) >> 6) == 0x03 && $i+1 < $strlen) {
  977. $charval = (($char_ord_val & 0x1F) << 6);
  978. $charval += (ord($string{++$i}) & 0x3F);
  979. }
  980. if (($charval >= 32) && ($charval <= 127)) {
  981. $HTMLstring .= htmlentities(chr($charval));
  982. } else {
  983. $HTMLstring .= '&#'.$charval.';';
  984. }
  985. }
  986. break;
  987. case 'utf-16le':
  988. for ($i = 0; $i < strlen($string); $i += 2) {
  989. $charval = self::LittleEndian2Int(substr($string, $i, 2));
  990. if (($charval >= 32) && ($charval <= 127)) {
  991. $HTMLstring .= chr($charval);
  992. } else {
  993. $HTMLstring .= '&#'.$charval.';';
  994. }
  995. }
  996. break;
  997. case 'utf-16be':
  998. for ($i = 0; $i < strlen($string); $i += 2) {
  999. $charval = self::BigEndian2Int(substr($string, $i, 2));
  1000. if (($charval >= 32) && ($charval <= 127)) {
  1001. $HTMLstring .= chr($charval);
  1002. } else {
  1003. $HTMLstring .= '&#'.$charval.';';
  1004. }
  1005. }
  1006. break;
  1007. default:
  1008. $HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
  1009. break;
  1010. }
  1011. return $HTMLstring;
  1012. }
  1013. public static function RGADnameLookup($namecode) {
  1014. static $RGADname = array();
  1015. if (empty($RGADname)) {
  1016. $RGADname[0] = 'not set';
  1017. $RGADname[1] = 'Track Gain Adjustment';
  1018. $RGADname[2] = 'Album Gain Adjustment';
  1019. }
  1020. return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
  1021. }
  1022. public static function RGADoriginatorLookup($originatorcode) {
  1023. static $RGADoriginator = array();
  1024. if (empty($RGADoriginator)) {
  1025. $RGADoriginator[0] = 'unspecified';
  1026. $RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
  1027. $RGADoriginator[2] = 'set by user';
  1028. $RGADoriginator[3] = 'determined automatically';
  1029. }
  1030. return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
  1031. }
  1032. public static function RGADadjustmentLookup($rawadjustment, $signbit) {
  1033. $adjustment = $rawadjustment / 10;
  1034. if ($signbit == 1) {
  1035. $adjustment *= -1;
  1036. }
  1037. return (float) $adjustment;
  1038. }
  1039. public static function RGADgainString($namecode, $originatorcode, $replaygain) {
  1040. if ($replaygain < 0) {
  1041. $signbit = '1';
  1042. } else {
  1043. $signbit = '0';
  1044. }
  1045. $storedreplaygain = intval(round($replaygain * 10));
  1046. $gainstring = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
  1047. $gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
  1048. $gainstring .= $signbit;
  1049. $gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
  1050. return $gainstring;
  1051. }
  1052. public static function RGADamplitude2dB($amplitude) {
  1053. return 20 * log10($amplitude);
  1054. }
  1055. public static function GetDataImageSize($imgData, &$imageinfo=array()) {
  1056. static $tempdir = '';
  1057. if (empty($tempdir)) {
  1058. if (function_exists('sys_get_temp_dir')) {
  1059. $tempdir = sys_get_temp_dir(); // https://github.com/JamesHeinrich/getID3/issues/52
  1060. }
  1061. // yes this is ugly, feel free to suggest a better way
  1062. if (include_once(dirname(__FILE__).'/getid3.php')) {
  1063. if ($getid3_temp = new getID3()) {
  1064. if ($getid3_temp_tempdir = $getid3_temp->tempdir) {
  1065. $tempdir = $getid3_temp_tempdir;
  1066. }
  1067. unset($getid3_temp, $getid3_temp_tempdir);
  1068. }
  1069. }
  1070. }
  1071. $GetDataImageSize = false;
  1072. if ($tempfilename = tempnam($tempdir, 'gI3')) {
  1073. if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
  1074. fwrite($tmp, $imgData);
  1075. fclose($tmp);
  1076. $GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
  1077. if (($GetDataImageSize === false) || !isset($GetDataImageSize[0]) || !isset($GetDataImageSize[1])) {
  1078. return false;
  1079. }
  1080. $GetDataImageSize['height'] = $GetDataImageSize[0];
  1081. $GetDataImageSize['width'] = $GetDataImageSize[1];
  1082. }
  1083. unlink($tempfilename);
  1084. }
  1085. return $GetDataImageSize;
  1086. }
  1087. public static function ImageExtFromMime($mime_type) {
  1088. // temporary way, works OK for now, but should be reworked in the future
  1089. return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
  1090. }
  1091. public static function ImageTypesLookup($imagetypeid) {
  1092. static $ImageTypesLookup = array();
  1093. if (empty($ImageTypesLookup)) {
  1094. $ImageTypesLookup[1] = 'gif';
  1095. $ImageTypesLookup[2] = 'jpeg';
  1096. $ImageTypesLookup[3] = 'png';
  1097. $ImageTypesLookup[4] = 'swf';
  1098. $ImageTypesLookup[5] = 'psd';
  1099. $ImageTypesLookup[6] = 'bmp';
  1100. $ImageTypesLookup[7] = 'tiff (little-endian)';
  1101. $ImageTypesLookup[8] = 'tiff (big-endian)';
  1102. $ImageTypesLookup[9] = 'jpc';
  1103. $ImageTypesLookup[10] = 'jp2';
  1104. $ImageTypesLookup[11] = 'jpx';
  1105. $ImageTypesLookup[12] = 'jb2';
  1106. $ImageTypesLookup[13] = 'swc';
  1107. $ImageTypesLookup[14] = 'iff';
  1108. }
  1109. return (isset($ImageTypesLookup[$imagetypeid]) ? $ImageTypesLookup[$imagetypeid] : '');
  1110. }
  1111. public static function CopyTagsToComments(&$ThisFileInfo) {
  1112. // Copy all entries from ['tags'] into common ['comments']
  1113. if (!empty($ThisFileInfo['tags'])) {
  1114. foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
  1115. foreach ($tagarray as $tagname => $tagdata) {
  1116. foreach ($tagdata as $key => $value) {
  1117. if (!empty($value)) {
  1118. if (empty($ThisFileInfo['comments'][$tagname])) {
  1119. // fall through and append value
  1120. } elseif ($tagtype == 'id3v1') {
  1121. $newvaluelength = strlen(trim($value));
  1122. foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  1123. $oldvaluelength = strlen(trim($existingvalue));
  1124. if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
  1125. // new value is identical but shorter-than (or equal-length to) one already in comments - skip
  1126. break 2;
  1127. }
  1128. }
  1129. } elseif (!is_array($value)) {
  1130. $newvaluelength = strlen(trim($value));
  1131. foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  1132. $oldvaluelength = strlen(trim($existingvalue));
  1133. if ((strlen($existingvalue) > 10) && ($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
  1134. $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
  1135. //break 2;
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
  1141. $value = (is_string($value) ? trim($value) : $value);
  1142. if (!is_int($key) && !ctype_digit($key)) {
  1143. $ThisFileInfo['comments'][$tagname][$key] = $value;
  1144. } else {
  1145. if (isset($ThisFileInfo['comments'][$tagname])) {
  1146. $ThisFileInfo['comments'][$tagname] = array($value);
  1147. } else {
  1148. $ThisFileInfo['comments'][$tagname][] = $value;
  1149. }
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. }
  1156. // attempt to standardize spelling of returned keys
  1157. $StandardizeFieldNames = array(
  1158. 'tracknumber' => 'track_number',
  1159. 'track' => 'track_number',
  1160. );
  1161. foreach ($StandardizeFieldNames as $badkey => $goodkey) {
  1162. if (array_key_exists($badkey, $ThisFileInfo['comments']) && !array_key_exists($goodkey, $ThisFileInfo['comments'])) {
  1163. $ThisFileInfo['comments'][$goodkey] = $ThisFileInfo['comments'][$badkey];
  1164. unset($ThisFileInfo['comments'][$badkey]);
  1165. }
  1166. }
  1167. // Copy to ['comments_html']
  1168. if (!empty($ThisFileInfo['comments'])) {
  1169. foreach ($ThisFileInfo['comments'] as $field => $values) {
  1170. if ($field == 'picture') {
  1171. // pictures can take up a lot of space, and we don't need multiple copies of them
  1172. // let there be a single copy in [comments][picture], and not elsewhere
  1173. continue;
  1174. }
  1175. foreach ($values as $index => $value) {
  1176. if (is_array($value)) {
  1177. $ThisFileInfo['comments_html'][$field][$index] = $value;
  1178. } else {
  1179. $ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. return true;
  1186. }
  1187. public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
  1188. // Cached
  1189. static $cache;
  1190. if (isset($cache[$file][$name])) {
  1191. return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  1192. }
  1193. // Init
  1194. $keylength = strlen($key);
  1195. $line_count = $end - $begin - 7;
  1196. // Open php file
  1197. $fp = fopen($file, 'r');
  1198. // Discard $begin lines
  1199. for ($i = 0; $i < ($begin + 3); $i++) {
  1200. fgets($fp, 1024);
  1201. }
  1202. // Loop thru line
  1203. while (0 < $line_count--) {
  1204. // Read line
  1205. $line = ltrim(fgets($fp, 1024), "\t ");
  1206. // METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
  1207. //$keycheck = substr($line, 0, $keylength);
  1208. //if ($key == $keycheck) {
  1209. // $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
  1210. // break;
  1211. //}
  1212. // METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
  1213. //$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
  1214. $explodedLine = explode("\t", $line, 2);
  1215. $ThisKey = (isset($explodedLine[0]) ? $explodedLine[0] : '');
  1216. $ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
  1217. $cache[$file][$name][$ThisKey] = trim($ThisValue);
  1218. }
  1219. // Close and return
  1220. fclose($fp);
  1221. return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  1222. }
  1223. public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
  1224. global $GETID3_ERRORARRAY;
  1225. if (file_exists($filename)) {
  1226. if (include_once($filename)) {
  1227. return true;
  1228. } else {
  1229. $diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
  1230. }
  1231. } else {
  1232. $diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
  1233. }
  1234. if ($DieOnFailure) {
  1235. throw new Exception($diemessage);
  1236. } else {
  1237. $GETID3_ERRORARRAY[] = $diemessage;
  1238. }
  1239. return false;
  1240. }
  1241. public static function trimNullByte($string) {
  1242. return trim($string, "\x00");
  1243. }
  1244. public static function getFileSizeSyscall($path) {
  1245. $filesize = false;
  1246. if (GETID3_OS_ISWINDOWS) {
  1247. 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:
  1248. $filesystem = new COM('Scripting.FileSystemObject');
  1249. $file = $filesystem->GetFile($path);
  1250. $filesize = $file->Size();
  1251. unset($filesystem, $file);
  1252. } else {
  1253. $commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
  1254. }
  1255. } else {
  1256. $commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
  1257. }
  1258. if (isset($commandline)) {
  1259. $output = trim(`$commandline`);
  1260. if (ctype_digit($output)) {
  1261. $filesize = (float) $output;
  1262. }
  1263. }
  1264. return $filesize;
  1265. }
  1266. /**
  1267. * Workaround for Bug #37268 (https://bugs.php.net/bug.php?id=37268)
  1268. * @param string $path A path.
  1269. * @param string $suffix If the name component ends in suffix this will also be cut off.
  1270. * @return string
  1271. */
  1272. public static function mb_basename($path, $suffix = null) {
  1273. $splited = preg_split('#/#', rtrim($path, '/ '));
  1274. return substr(basename('X'.$splited[count($splited) - 1], $suffix), 1);
  1275. }
  1276. }