暂无描述

getid3.lib.php 53KB

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