getid3.lib.php 53 KB

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