getid3.lib.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  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. // mb_convert_encoding() availble
  862. if (function_exists('mb_convert_encoding')) {
  863. if ($converted_string = @mb_convert_encoding($string, $out_charset, $in_charset)) {
  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. return $string;
  872. }
  873. // iconv() availble
  874. else if (function_exists('iconv')) {
  875. if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
  876. switch ($out_charset) {
  877. case 'ISO-8859-1':
  878. $converted_string = rtrim($converted_string, "\x00");
  879. break;
  880. }
  881. return $converted_string;
  882. }
  883. // iconv() may sometimes fail with "illegal character in input string" error message
  884. // and return an empty string, but returning the unconverted string is more useful
  885. return $string;
  886. }
  887. // neither mb_convert_encoding or iconv() is available
  888. static $ConversionFunctionList = array();
  889. if (empty($ConversionFunctionList)) {
  890. $ConversionFunctionList['ISO-8859-1']['UTF-8'] = 'iconv_fallback_iso88591_utf8';
  891. $ConversionFunctionList['ISO-8859-1']['UTF-16'] = 'iconv_fallback_iso88591_utf16';
  892. $ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
  893. $ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
  894. $ConversionFunctionList['UTF-8']['ISO-8859-1'] = 'iconv_fallback_utf8_iso88591';
  895. $ConversionFunctionList['UTF-8']['UTF-16'] = 'iconv_fallback_utf8_utf16';
  896. $ConversionFunctionList['UTF-8']['UTF-16BE'] = 'iconv_fallback_utf8_utf16be';
  897. $ConversionFunctionList['UTF-8']['UTF-16LE'] = 'iconv_fallback_utf8_utf16le';
  898. $ConversionFunctionList['UTF-16']['ISO-8859-1'] = 'iconv_fallback_utf16_iso88591';
  899. $ConversionFunctionList['UTF-16']['UTF-8'] = 'iconv_fallback_utf16_utf8';
  900. $ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
  901. $ConversionFunctionList['UTF-16LE']['UTF-8'] = 'iconv_fallback_utf16le_utf8';
  902. $ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
  903. $ConversionFunctionList['UTF-16BE']['UTF-8'] = 'iconv_fallback_utf16be_utf8';
  904. }
  905. if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
  906. $ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
  907. return self::$ConversionFunction($string);
  908. }
  909. throw new Exception('PHP does not has mb_convert_encoding() or iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
  910. }
  911. public static function recursiveMultiByteCharString2HTML($data, $charset='ISO-8859-1') {
  912. if (is_string($data)) {
  913. return self::MultiByteCharString2HTML($data, $charset);
  914. } elseif (is_array($data)) {
  915. $return_data = array();
  916. foreach ($data as $key => $value) {
  917. $return_data[$key] = self::recursiveMultiByteCharString2HTML($value, $charset);
  918. }
  919. return $return_data;
  920. }
  921. // integer, float, objects, resources, etc
  922. return $data;
  923. }
  924. public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
  925. $string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
  926. $HTMLstring = '';
  927. switch (strtolower($charset)) {
  928. case '1251':
  929. case '1252':
  930. case '866':
  931. case '932':
  932. case '936':
  933. case '950':
  934. case 'big5':
  935. case 'big5-hkscs':
  936. case 'cp1251':
  937. case 'cp1252':
  938. case 'cp866':
  939. case 'euc-jp':
  940. case 'eucjp':
  941. case 'gb2312':
  942. case 'ibm866':
  943. case 'iso-8859-1':
  944. case 'iso-8859-15':
  945. case 'iso8859-1':
  946. case 'iso8859-15':
  947. case 'koi8-r':
  948. case 'koi8-ru':
  949. case 'koi8r':
  950. case 'shift_jis':
  951. case 'sjis':
  952. case 'win-1251':
  953. case 'windows-1251':
  954. case 'windows-1252':
  955. $HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
  956. break;
  957. case 'utf-8':
  958. $strlen = strlen($string);
  959. for ($i = 0; $i < $strlen; $i++) {
  960. $char_ord_val = ord($string{$i});
  961. $charval = 0;
  962. if ($char_ord_val < 0x80) {
  963. $charval = $char_ord_val;
  964. } elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F && $i+3 < $strlen) {
  965. $charval = (($char_ord_val & 0x07) << 18);
  966. $charval += ((ord($string{++$i}) & 0x3F) << 12);
  967. $charval += ((ord($string{++$i}) & 0x3F) << 6);
  968. $charval += (ord($string{++$i}) & 0x3F);
  969. } elseif ((($char_ord_val & 0xE0) >> 5) == 0x07 && $i+2 < $strlen) {
  970. $charval = (($char_ord_val & 0x0F) << 12);
  971. $charval += ((ord($string{++$i}) & 0x3F) << 6);
  972. $charval += (ord($string{++$i}) & 0x3F);
  973. } elseif ((($char_ord_val & 0xC0) >> 6) == 0x03 && $i+1 < $strlen) {
  974. $charval = (($char_ord_val & 0x1F) << 6);
  975. $charval += (ord($string{++$i}) & 0x3F);
  976. }
  977. if (($charval >= 32) && ($charval <= 127)) {
  978. $HTMLstring .= htmlentities(chr($charval));
  979. } else {
  980. $HTMLstring .= '&#'.$charval.';';
  981. }
  982. }
  983. break;
  984. case 'utf-16le':
  985. for ($i = 0; $i < strlen($string); $i += 2) {
  986. $charval = self::LittleEndian2Int(substr($string, $i, 2));
  987. if (($charval >= 32) && ($charval <= 127)) {
  988. $HTMLstring .= chr($charval);
  989. } else {
  990. $HTMLstring .= '&#'.$charval.';';
  991. }
  992. }
  993. break;
  994. case 'utf-16be':
  995. for ($i = 0; $i < strlen($string); $i += 2) {
  996. $charval = self::BigEndian2Int(substr($string, $i, 2));
  997. if (($charval >= 32) && ($charval <= 127)) {
  998. $HTMLstring .= chr($charval);
  999. } else {
  1000. $HTMLstring .= '&#'.$charval.';';
  1001. }
  1002. }
  1003. break;
  1004. default:
  1005. $HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
  1006. break;
  1007. }
  1008. return $HTMLstring;
  1009. }
  1010. public static function RGADnameLookup($namecode) {
  1011. static $RGADname = array();
  1012. if (empty($RGADname)) {
  1013. $RGADname[0] = 'not set';
  1014. $RGADname[1] = 'Track Gain Adjustment';
  1015. $RGADname[2] = 'Album Gain Adjustment';
  1016. }
  1017. return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
  1018. }
  1019. public static function RGADoriginatorLookup($originatorcode) {
  1020. static $RGADoriginator = array();
  1021. if (empty($RGADoriginator)) {
  1022. $RGADoriginator[0] = 'unspecified';
  1023. $RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
  1024. $RGADoriginator[2] = 'set by user';
  1025. $RGADoriginator[3] = 'determined automatically';
  1026. }
  1027. return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
  1028. }
  1029. public static function RGADadjustmentLookup($rawadjustment, $signbit) {
  1030. $adjustment = $rawadjustment / 10;
  1031. if ($signbit == 1) {
  1032. $adjustment *= -1;
  1033. }
  1034. return (float) $adjustment;
  1035. }
  1036. public static function RGADgainString($namecode, $originatorcode, $replaygain) {
  1037. if ($replaygain < 0) {
  1038. $signbit = '1';
  1039. } else {
  1040. $signbit = '0';
  1041. }
  1042. $storedreplaygain = intval(round($replaygain * 10));
  1043. $gainstring = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
  1044. $gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
  1045. $gainstring .= $signbit;
  1046. $gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
  1047. return $gainstring;
  1048. }
  1049. public static function RGADamplitude2dB($amplitude) {
  1050. return 20 * log10($amplitude);
  1051. }
  1052. public static function GetDataImageSize($imgData, &$imageinfo=array()) {
  1053. static $tempdir = '';
  1054. if (empty($tempdir)) {
  1055. if (function_exists('sys_get_temp_dir')) {
  1056. $tempdir = sys_get_temp_dir(); // https://github.com/JamesHeinrich/getID3/issues/52
  1057. }
  1058. // yes this is ugly, feel free to suggest a better way
  1059. if (include_once(dirname(__FILE__).'/getid3.php')) {
  1060. if ($getid3_temp = new getID3()) {
  1061. if ($getid3_temp_tempdir = $getid3_temp->tempdir) {
  1062. $tempdir = $getid3_temp_tempdir;
  1063. }
  1064. unset($getid3_temp, $getid3_temp_tempdir);
  1065. }
  1066. }
  1067. }
  1068. $GetDataImageSize = false;
  1069. if ($tempfilename = tempnam($tempdir, 'gI3')) {
  1070. if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
  1071. fwrite($tmp, $imgData);
  1072. fclose($tmp);
  1073. $GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
  1074. if (($GetDataImageSize === false) || !isset($GetDataImageSize[0]) || !isset($GetDataImageSize[1])) {
  1075. return false;
  1076. }
  1077. $GetDataImageSize['height'] = $GetDataImageSize[0];
  1078. $GetDataImageSize['width'] = $GetDataImageSize[1];
  1079. }
  1080. unlink($tempfilename);
  1081. }
  1082. return $GetDataImageSize;
  1083. }
  1084. public static function ImageExtFromMime($mime_type) {
  1085. // temporary way, works OK for now, but should be reworked in the future
  1086. return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
  1087. }
  1088. public static function ImageTypesLookup($imagetypeid) {
  1089. static $ImageTypesLookup = array();
  1090. if (empty($ImageTypesLookup)) {
  1091. $ImageTypesLookup[1] = 'gif';
  1092. $ImageTypesLookup[2] = 'jpeg';
  1093. $ImageTypesLookup[3] = 'png';
  1094. $ImageTypesLookup[4] = 'swf';
  1095. $ImageTypesLookup[5] = 'psd';
  1096. $ImageTypesLookup[6] = 'bmp';
  1097. $ImageTypesLookup[7] = 'tiff (little-endian)';
  1098. $ImageTypesLookup[8] = 'tiff (big-endian)';
  1099. $ImageTypesLookup[9] = 'jpc';
  1100. $ImageTypesLookup[10] = 'jp2';
  1101. $ImageTypesLookup[11] = 'jpx';
  1102. $ImageTypesLookup[12] = 'jb2';
  1103. $ImageTypesLookup[13] = 'swc';
  1104. $ImageTypesLookup[14] = 'iff';
  1105. }
  1106. return (isset($ImageTypesLookup[$imagetypeid]) ? $ImageTypesLookup[$imagetypeid] : '');
  1107. }
  1108. public static function CopyTagsToComments(&$ThisFileInfo) {
  1109. // Copy all entries from ['tags'] into common ['comments']
  1110. if (!empty($ThisFileInfo['tags'])) {
  1111. foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
  1112. foreach ($tagarray as $tagname => $tagdata) {
  1113. foreach ($tagdata as $key => $value) {
  1114. if (!empty($value)) {
  1115. if (empty($ThisFileInfo['comments'][$tagname])) {
  1116. // fall through and append value
  1117. } elseif ($tagtype == 'id3v1') {
  1118. $newvaluelength = strlen(trim($value));
  1119. foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  1120. $oldvaluelength = strlen(trim($existingvalue));
  1121. if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
  1122. // new value is identical but shorter-than (or equal-length to) one already in comments - skip
  1123. break 2;
  1124. }
  1125. }
  1126. } elseif (!is_array($value)) {
  1127. $newvaluelength = strlen(trim($value));
  1128. foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
  1129. $oldvaluelength = strlen(trim($existingvalue));
  1130. if ((strlen($existingvalue) > 10) && ($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
  1131. $ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
  1132. //break 2;
  1133. break;
  1134. }
  1135. }
  1136. }
  1137. if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
  1138. $value = (is_string($value) ? trim($value) : $value);
  1139. if (!is_int($key) && !ctype_digit($key)) {
  1140. $ThisFileInfo['comments'][$tagname][$key] = $value;
  1141. } else {
  1142. if (isset($ThisFileInfo['comments'][$tagname])) {
  1143. $ThisFileInfo['comments'][$tagname] = array($value);
  1144. } else {
  1145. $ThisFileInfo['comments'][$tagname][] = $value;
  1146. }
  1147. }
  1148. }
  1149. }
  1150. }
  1151. }
  1152. }
  1153. // attempt to standardize spelling of returned keys
  1154. $StandardizeFieldNames = array(
  1155. 'tracknumber' => 'track_number',
  1156. 'track' => 'track_number',
  1157. );
  1158. foreach ($StandardizeFieldNames as $badkey => $goodkey) {
  1159. if (array_key_exists($badkey, $ThisFileInfo['comments']) && !array_key_exists($goodkey, $ThisFileInfo['comments'])) {
  1160. $ThisFileInfo['comments'][$goodkey] = $ThisFileInfo['comments'][$badkey];
  1161. unset($ThisFileInfo['comments'][$badkey]);
  1162. }
  1163. }
  1164. // Copy to ['comments_html']
  1165. if (!empty($ThisFileInfo['comments'])) {
  1166. foreach ($ThisFileInfo['comments'] as $field => $values) {
  1167. if ($field == 'picture') {
  1168. // pictures can take up a lot of space, and we don't need multiple copies of them
  1169. // let there be a single copy in [comments][picture], and not elsewhere
  1170. continue;
  1171. }
  1172. foreach ($values as $index => $value) {
  1173. if (is_array($value)) {
  1174. $ThisFileInfo['comments_html'][$field][$index] = $value;
  1175. } else {
  1176. $ThisFileInfo['comments_html'][$field][$index] = str_replace('&#0;', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. return true;
  1183. }
  1184. public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
  1185. // Cached
  1186. static $cache;
  1187. if (isset($cache[$file][$name])) {
  1188. return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  1189. }
  1190. // Init
  1191. $keylength = strlen($key);
  1192. $line_count = $end - $begin - 7;
  1193. // Open php file
  1194. $fp = fopen($file, 'r');
  1195. // Discard $begin lines
  1196. for ($i = 0; $i < ($begin + 3); $i++) {
  1197. fgets($fp, 1024);
  1198. }
  1199. // Loop thru line
  1200. while (0 < $line_count--) {
  1201. // Read line
  1202. $line = ltrim(fgets($fp, 1024), "\t ");
  1203. // METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
  1204. //$keycheck = substr($line, 0, $keylength);
  1205. //if ($key == $keycheck) {
  1206. // $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
  1207. // break;
  1208. //}
  1209. // METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
  1210. //$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
  1211. $explodedLine = explode("\t", $line, 2);
  1212. $ThisKey = (isset($explodedLine[0]) ? $explodedLine[0] : '');
  1213. $ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
  1214. $cache[$file][$name][$ThisKey] = trim($ThisValue);
  1215. }
  1216. // Close and return
  1217. fclose($fp);
  1218. return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
  1219. }
  1220. public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
  1221. global $GETID3_ERRORARRAY;
  1222. if (file_exists($filename)) {
  1223. if (include_once($filename)) {
  1224. return true;
  1225. } else {
  1226. $diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
  1227. }
  1228. } else {
  1229. $diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
  1230. }
  1231. if ($DieOnFailure) {
  1232. throw new Exception($diemessage);
  1233. } else {
  1234. $GETID3_ERRORARRAY[] = $diemessage;
  1235. }
  1236. return false;
  1237. }
  1238. public static function trimNullByte($string) {
  1239. return trim($string, "\x00");
  1240. }
  1241. public static function getFileSizeSyscall($path) {
  1242. $filesize = false;
  1243. if (GETID3_OS_ISWINDOWS) {
  1244. 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:
  1245. $filesystem = new COM('Scripting.FileSystemObject');
  1246. $file = $filesystem->GetFile($path);
  1247. $filesize = $file->Size();
  1248. unset($filesystem, $file);
  1249. } else {
  1250. $commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
  1251. }
  1252. } else {
  1253. $commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
  1254. }
  1255. if (isset($commandline)) {
  1256. $output = trim(`$commandline`);
  1257. if (ctype_digit($output)) {
  1258. $filesize = (float) $output;
  1259. }
  1260. }
  1261. return $filesize;
  1262. }
  1263. /**
  1264. * Workaround for Bug #37268 (https://bugs.php.net/bug.php?id=37268)
  1265. * @param string $path A path.
  1266. * @param string $suffix If the name component ends in suffix this will also be cut off.
  1267. * @return string
  1268. */
  1269. public static function mb_basename($path, $suffix = null) {
  1270. $splited = preg_split('#/#', rtrim($path, '/ '));
  1271. return substr(basename('X'.$splited[count($splited) - 1], $suffix), 1);
  1272. }
  1273. }