PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/ID3/getid3.php

http://github.com/wordpress/wordpress
PHP | 2190 lines | 1335 code | 286 blank | 569 comment | 262 complexity | c389120396078fc768fe90f10be04d9d MD5 | raw file
Possible License(s): 0BSD
  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. // Please see readme.txt for more information //
  9. // ///
  10. /////////////////////////////////////////////////////////////////
  11. // define a constant rather than looking up every time it is needed
  12. if (!defined('GETID3_OS_ISWINDOWS')) {
  13. define('GETID3_OS_ISWINDOWS', (stripos(PHP_OS, 'WIN') === 0));
  14. }
  15. // Get base path of getID3() - ONCE
  16. if (!defined('GETID3_INCLUDEPATH')) {
  17. define('GETID3_INCLUDEPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
  18. }
  19. // Workaround Bug #39923 (https://bugs.php.net/bug.php?id=39923)
  20. if (!defined('IMG_JPG') && defined('IMAGETYPE_JPEG')) {
  21. define('IMG_JPG', IMAGETYPE_JPEG);
  22. }
  23. if (!defined('ENT_SUBSTITUTE')) { // PHP5.3 adds ENT_IGNORE, PHP5.4 adds ENT_SUBSTITUTE
  24. define('ENT_SUBSTITUTE', (defined('ENT_IGNORE') ? ENT_IGNORE : 8));
  25. }
  26. /*
  27. https://www.getid3.org/phpBB3/viewtopic.php?t=2114
  28. If you are running into a the problem where filenames with special characters are being handled
  29. incorrectly by external helper programs (e.g. metaflac), notably with the special characters removed,
  30. and you are passing in the filename in UTF8 (typically via a HTML form), try uncommenting this line:
  31. */
  32. //setlocale(LC_CTYPE, 'en_US.UTF-8');
  33. // attempt to define temp dir as something flexible but reliable
  34. $temp_dir = ini_get('upload_tmp_dir');
  35. if ($temp_dir && (!is_dir($temp_dir) || !is_readable($temp_dir))) {
  36. $temp_dir = '';
  37. }
  38. if (!$temp_dir && function_exists('sys_get_temp_dir')) { // sys_get_temp_dir added in PHP v5.2.1
  39. // sys_get_temp_dir() may give inaccessible temp dir, e.g. with open_basedir on virtual hosts
  40. $temp_dir = sys_get_temp_dir();
  41. }
  42. $temp_dir = @realpath($temp_dir); // see https://github.com/JamesHeinrich/getID3/pull/10
  43. $open_basedir = ini_get('open_basedir');
  44. if ($open_basedir) {
  45. // e.g. "/var/www/vhosts/getid3.org/httpdocs/:/tmp/"
  46. $temp_dir = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $temp_dir);
  47. $open_basedir = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $open_basedir);
  48. if (substr($temp_dir, -1, 1) != DIRECTORY_SEPARATOR) {
  49. $temp_dir .= DIRECTORY_SEPARATOR;
  50. }
  51. $found_valid_tempdir = false;
  52. $open_basedirs = explode(PATH_SEPARATOR, $open_basedir);
  53. foreach ($open_basedirs as $basedir) {
  54. if (substr($basedir, -1, 1) != DIRECTORY_SEPARATOR) {
  55. $basedir .= DIRECTORY_SEPARATOR;
  56. }
  57. if (preg_match('#^'.preg_quote($basedir).'#', $temp_dir)) {
  58. $found_valid_tempdir = true;
  59. break;
  60. }
  61. }
  62. if (!$found_valid_tempdir) {
  63. $temp_dir = '';
  64. }
  65. unset($open_basedirs, $found_valid_tempdir, $basedir);
  66. }
  67. if (!$temp_dir) {
  68. $temp_dir = '*'; // invalid directory name should force tempnam() to use system default temp dir
  69. }
  70. // $temp_dir = '/something/else/'; // feel free to override temp dir here if it works better for your system
  71. if (!defined('GETID3_TEMP_DIR')) {
  72. define('GETID3_TEMP_DIR', $temp_dir);
  73. }
  74. unset($open_basedir, $temp_dir);
  75. // End: Defines
  76. class getID3
  77. {
  78. /*
  79. * Settings
  80. */
  81. /**
  82. * CASE SENSITIVE! - i.e. (must be supported by iconv()). Examples: ISO-8859-1 UTF-8 UTF-16 UTF-16BE
  83. *
  84. * @var string
  85. */
  86. public $encoding = 'UTF-8';
  87. /**
  88. * Should always be 'ISO-8859-1', but some tags may be written in other encodings such as 'EUC-CN' or 'CP1252'
  89. *
  90. * @var string
  91. */
  92. public $encoding_id3v1 = 'ISO-8859-1';
  93. /*
  94. * Optional tag checks - disable for speed.
  95. */
  96. /**
  97. * Read and process ID3v1 tags
  98. *
  99. * @var bool
  100. */
  101. public $option_tag_id3v1 = true;
  102. /**
  103. * Read and process ID3v2 tags
  104. *
  105. * @var bool
  106. */
  107. public $option_tag_id3v2 = true;
  108. /**
  109. * Read and process Lyrics3 tags
  110. *
  111. * @var bool
  112. */
  113. public $option_tag_lyrics3 = true;
  114. /**
  115. * Read and process APE tags
  116. *
  117. * @var bool
  118. */
  119. public $option_tag_apetag = true;
  120. /**
  121. * Copy tags to root key 'tags' and encode to $this->encoding
  122. *
  123. * @var bool
  124. */
  125. public $option_tags_process = true;
  126. /**
  127. * Copy tags to root key 'tags_html' properly translated from various encodings to HTML entities
  128. *
  129. * @var bool
  130. */
  131. public $option_tags_html = true;
  132. /*
  133. * Optional tag/comment calculations
  134. */
  135. /**
  136. * Calculate additional info such as bitrate, channelmode etc
  137. *
  138. * @var bool
  139. */
  140. public $option_extra_info = true;
  141. /*
  142. * Optional handling of embedded attachments (e.g. images)
  143. */
  144. /**
  145. * Defaults to true (ATTACHMENTS_INLINE) for backward compatibility
  146. *
  147. * @var bool|string
  148. */
  149. public $option_save_attachments = true;
  150. /*
  151. * Optional calculations
  152. */
  153. /**
  154. * Get MD5 sum of data part - slow
  155. *
  156. * @var bool
  157. */
  158. public $option_md5_data = false;
  159. /**
  160. * Use MD5 of source file if availble - only FLAC and OptimFROG
  161. *
  162. * @var bool
  163. */
  164. public $option_md5_data_source = false;
  165. /**
  166. * Get SHA1 sum of data part - slow
  167. *
  168. * @var bool
  169. */
  170. public $option_sha1_data = false;
  171. /**
  172. * Check whether file is larger than 2GB and thus not supported by 32-bit PHP (null: auto-detect based on
  173. * PHP_INT_MAX)
  174. *
  175. * @var bool|null
  176. */
  177. public $option_max_2gb_check;
  178. /**
  179. * Read buffer size in bytes
  180. *
  181. * @var int
  182. */
  183. public $option_fread_buffer_size = 32768;
  184. // Public variables
  185. /**
  186. * Filename of file being analysed.
  187. *
  188. * @var string
  189. */
  190. public $filename;
  191. /**
  192. * Filepointer to file being analysed.
  193. *
  194. * @var resource
  195. */
  196. public $fp;
  197. /**
  198. * Result array.
  199. *
  200. * @var array
  201. */
  202. public $info;
  203. /**
  204. * @var string
  205. */
  206. public $tempdir = GETID3_TEMP_DIR;
  207. /**
  208. * @var int
  209. */
  210. public $memory_limit = 0;
  211. /**
  212. * @var string
  213. */
  214. protected $startup_error = '';
  215. /**
  216. * @var string
  217. */
  218. protected $startup_warning = '';
  219. const VERSION = '1.9.19-201912211559';
  220. const FREAD_BUFFER_SIZE = 32768;
  221. const ATTACHMENTS_NONE = false;
  222. const ATTACHMENTS_INLINE = true;
  223. public function __construct() {
  224. // Check for PHP version
  225. $required_php_version = '5.3.0';
  226. if (version_compare(PHP_VERSION, $required_php_version, '<')) {
  227. $this->startup_error .= 'getID3() requires PHP v'.$required_php_version.' or higher - you are running v'.PHP_VERSION."\n";
  228. return;
  229. }
  230. // Check memory
  231. $memoryLimit = ini_get('memory_limit');
  232. if (preg_match('#([0-9]+) ?M#i', $memoryLimit, $matches)) {
  233. // could be stored as "16M" rather than 16777216 for example
  234. $memoryLimit = $matches[1] * 1048576;
  235. } elseif (preg_match('#([0-9]+) ?G#i', $memoryLimit, $matches)) { // The 'G' modifier is available since PHP 5.1.0
  236. // could be stored as "2G" rather than 2147483648 for example
  237. $memoryLimit = $matches[1] * 1073741824;
  238. }
  239. $this->memory_limit = $memoryLimit;
  240. if ($this->memory_limit <= 0) {
  241. // memory limits probably disabled
  242. } elseif ($this->memory_limit <= 4194304) {
  243. $this->startup_error .= 'PHP has less than 4MB available memory and will very likely run out. Increase memory_limit in php.ini'."\n";
  244. } elseif ($this->memory_limit <= 12582912) {
  245. $this->startup_warning .= 'PHP has less than 12MB available memory and might run out if all modules are loaded. Increase memory_limit in php.ini'."\n";
  246. }
  247. // Check safe_mode off
  248. if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved
  249. $this->warning('WARNING: Safe mode is on, shorten support disabled, md5data/sha1data for ogg vorbis disabled, ogg vorbos/flac tag writing disabled.');
  250. }
  251. if (($mbstring_func_overload = (int) ini_get('mbstring.func_overload')) && ($mbstring_func_overload & 0x02)) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated
  252. // http://php.net/manual/en/mbstring.overload.php
  253. // "mbstring.func_overload in php.ini is a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions"
  254. // getID3 cannot run when string functions are overloaded. It doesn't matter if mail() or ereg* functions are overloaded since getID3 does not use those.
  255. $this->startup_error .= 'WARNING: php.ini contains "mbstring.func_overload = '.ini_get('mbstring.func_overload').'", getID3 cannot run with this setting (bitmask 2 (string functions) cannot be set). Recommended to disable entirely.'."\n"; // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated
  256. }
  257. // check for magic quotes in PHP < 7.4.0 (when these functions became deprecated)
  258. if (version_compare(PHP_VERSION, '7.4.0', '<')) {
  259. // Check for magic_quotes_runtime
  260. if (function_exists('get_magic_quotes_runtime')) {
  261. if (get_magic_quotes_runtime()) { // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.get_magic_quotes_runtimeDeprecated
  262. $this->startup_error .= 'magic_quotes_runtime must be disabled before running getID3(). Surround getid3 block by set_magic_quotes_runtime(0) and set_magic_quotes_runtime(1).'."\n";
  263. }
  264. }
  265. // Check for magic_quotes_gpc
  266. if (function_exists('get_magic_quotes_gpc')) {
  267. if (get_magic_quotes_gpc()) { // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.get_magic_quotes_gpcDeprecated
  268. $this->startup_error .= 'magic_quotes_gpc must be disabled before running getID3(). Surround getid3 block by set_magic_quotes_gpc(0) and set_magic_quotes_gpc(1).'."\n";
  269. }
  270. }
  271. }
  272. // Load support library
  273. if (!include_once(GETID3_INCLUDEPATH.'getid3.lib.php')) {
  274. $this->startup_error .= 'getid3.lib.php is missing or corrupt'."\n";
  275. }
  276. if ($this->option_max_2gb_check === null) {
  277. $this->option_max_2gb_check = (PHP_INT_MAX <= 2147483647);
  278. }
  279. // Needed for Windows only:
  280. // Define locations of helper applications for Shorten, VorbisComment, MetaFLAC
  281. // as well as other helper functions such as head, etc
  282. // This path cannot contain spaces, but the below code will attempt to get the
  283. // 8.3-equivalent path automatically
  284. // IMPORTANT: This path must include the trailing slash
  285. if (GETID3_OS_ISWINDOWS && !defined('GETID3_HELPERAPPSDIR')) {
  286. $helperappsdir = GETID3_INCLUDEPATH.'..'.DIRECTORY_SEPARATOR.'helperapps'; // must not have any space in this path
  287. if (!is_dir($helperappsdir)) {
  288. $this->startup_warning .= '"'.$helperappsdir.'" cannot be defined as GETID3_HELPERAPPSDIR because it does not exist'."\n";
  289. } elseif (strpos(realpath($helperappsdir), ' ') !== false) {
  290. $DirPieces = explode(DIRECTORY_SEPARATOR, realpath($helperappsdir));
  291. $path_so_far = array();
  292. foreach ($DirPieces as $key => $value) {
  293. if (strpos($value, ' ') !== false) {
  294. if (!empty($path_so_far)) {
  295. $commandline = 'dir /x '.escapeshellarg(implode(DIRECTORY_SEPARATOR, $path_so_far));
  296. $dir_listing = `$commandline`;
  297. $lines = explode("\n", $dir_listing);
  298. foreach ($lines as $line) {
  299. $line = trim($line);
  300. if (preg_match('#^([0-9/]{10}) +([0-9:]{4,5}( [AP]M)?) +(<DIR>|[0-9,]+) +([^ ]{0,11}) +(.+)$#', $line, $matches)) {
  301. list($dummy, $date, $time, $ampm, $filesize, $shortname, $filename) = $matches;
  302. if ((strtoupper($filesize) == '<DIR>') && (strtolower($filename) == strtolower($value))) {
  303. $value = $shortname;
  304. }
  305. }
  306. }
  307. } else {
  308. $this->startup_warning .= 'GETID3_HELPERAPPSDIR must not have any spaces in it - use 8dot3 naming convention if neccesary. You can run "dir /x" from the commandline to see the correct 8.3-style names.'."\n";
  309. }
  310. }
  311. $path_so_far[] = $value;
  312. }
  313. $helperappsdir = implode(DIRECTORY_SEPARATOR, $path_so_far);
  314. }
  315. define('GETID3_HELPERAPPSDIR', $helperappsdir.DIRECTORY_SEPARATOR);
  316. }
  317. if (!empty($this->startup_error)) {
  318. echo $this->startup_error;
  319. throw new getid3_exception($this->startup_error);
  320. }
  321. }
  322. /**
  323. * @return string
  324. */
  325. public function version() {
  326. return self::VERSION;
  327. }
  328. /**
  329. * @return int
  330. */
  331. public function fread_buffer_size() {
  332. return $this->option_fread_buffer_size;
  333. }
  334. /**
  335. * @param array $optArray
  336. *
  337. * @return bool
  338. */
  339. public function setOption($optArray) {
  340. if (!is_array($optArray) || empty($optArray)) {
  341. return false;
  342. }
  343. foreach ($optArray as $opt => $val) {
  344. if (isset($this->$opt) === false) {
  345. continue;
  346. }
  347. $this->$opt = $val;
  348. }
  349. return true;
  350. }
  351. /**
  352. * @param string $filename
  353. * @param int $filesize
  354. * @param resource $fp
  355. *
  356. * @return bool
  357. *
  358. * @throws getid3_exception
  359. */
  360. public function openfile($filename, $filesize=null, $fp=null) {
  361. try {
  362. if (!empty($this->startup_error)) {
  363. throw new getid3_exception($this->startup_error);
  364. }
  365. if (!empty($this->startup_warning)) {
  366. foreach (explode("\n", $this->startup_warning) as $startup_warning) {
  367. $this->warning($startup_warning);
  368. }
  369. }
  370. // init result array and set parameters
  371. $this->filename = $filename;
  372. $this->info = array();
  373. $this->info['GETID3_VERSION'] = $this->version();
  374. $this->info['php_memory_limit'] = (($this->memory_limit > 0) ? $this->memory_limit : false);
  375. // remote files not supported
  376. if (preg_match('#^(ht|f)tp://#', $filename)) {
  377. throw new getid3_exception('Remote files are not supported - please copy the file locally first');
  378. }
  379. $filename = str_replace('/', DIRECTORY_SEPARATOR, $filename);
  380. //$filename = preg_replace('#(?<!gs:)('.preg_quote(DIRECTORY_SEPARATOR).'{2,})#', DIRECTORY_SEPARATOR, $filename);
  381. // open local file
  382. //if (is_readable($filename) && is_file($filename) && ($this->fp = fopen($filename, 'rb'))) { // see https://www.getid3.org/phpBB3/viewtopic.php?t=1720
  383. if (($fp != null) && ((get_resource_type($fp) == 'file') || (get_resource_type($fp) == 'stream'))) {
  384. $this->fp = $fp;
  385. } elseif ((is_readable($filename) || file_exists($filename)) && is_file($filename) && ($this->fp = fopen($filename, 'rb'))) {
  386. // great
  387. } else {
  388. $errormessagelist = array();
  389. if (!is_readable($filename)) {
  390. $errormessagelist[] = '!is_readable';
  391. }
  392. if (!is_file($filename)) {
  393. $errormessagelist[] = '!is_file';
  394. }
  395. if (!file_exists($filename)) {
  396. $errormessagelist[] = '!file_exists';
  397. }
  398. if (empty($errormessagelist)) {
  399. $errormessagelist[] = 'fopen failed';
  400. }
  401. throw new getid3_exception('Could not open "'.$filename.'" ('.implode('; ', $errormessagelist).')');
  402. }
  403. $this->info['filesize'] = (!is_null($filesize) ? $filesize : filesize($filename));
  404. // set redundant parameters - might be needed in some include file
  405. // filenames / filepaths in getID3 are always expressed with forward slashes (unix-style) for both Windows and other to try and minimize confusion
  406. $filename = str_replace('\\', '/', $filename);
  407. $this->info['filepath'] = str_replace('\\', '/', realpath(dirname($filename)));
  408. $this->info['filename'] = getid3_lib::mb_basename($filename);
  409. $this->info['filenamepath'] = $this->info['filepath'].'/'.$this->info['filename'];
  410. // set more parameters
  411. $this->info['avdataoffset'] = 0;
  412. $this->info['avdataend'] = $this->info['filesize'];
  413. $this->info['fileformat'] = ''; // filled in later
  414. $this->info['audio']['dataformat'] = ''; // filled in later, unset if not used
  415. $this->info['video']['dataformat'] = ''; // filled in later, unset if not used
  416. $this->info['tags'] = array(); // filled in later, unset if not used
  417. $this->info['error'] = array(); // filled in later, unset if not used
  418. $this->info['warning'] = array(); // filled in later, unset if not used
  419. $this->info['comments'] = array(); // filled in later, unset if not used
  420. $this->info['encoding'] = $this->encoding; // required by id3v2 and iso modules - can be unset at the end if desired
  421. // option_max_2gb_check
  422. if ($this->option_max_2gb_check) {
  423. // PHP (32-bit all, and 64-bit Windows) doesn't support integers larger than 2^31 (~2GB)
  424. // filesize() simply returns (filesize % (pow(2, 32)), no matter the actual filesize
  425. // ftell() returns 0 if seeking to the end is beyond the range of unsigned integer
  426. $fseek = fseek($this->fp, 0, SEEK_END);
  427. if (($fseek < 0) || (($this->info['filesize'] != 0) && (ftell($this->fp) == 0)) ||
  428. ($this->info['filesize'] < 0) ||
  429. (ftell($this->fp) < 0)) {
  430. $real_filesize = getid3_lib::getFileSizeSyscall($this->info['filenamepath']);
  431. if ($real_filesize === false) {
  432. unset($this->info['filesize']);
  433. fclose($this->fp);
  434. throw new getid3_exception('Unable to determine actual filesize. File is most likely larger than '.round(PHP_INT_MAX / 1073741824).'GB and is not supported by PHP.');
  435. } elseif (getid3_lib::intValueSupported($real_filesize)) {
  436. unset($this->info['filesize']);
  437. fclose($this->fp);
  438. throw new getid3_exception('PHP seems to think the file is larger than '.round(PHP_INT_MAX / 1073741824).'GB, but filesystem reports it as '.number_format($real_filesize / 1073741824, 3).'GB, please report to info@getid3.org');
  439. }
  440. $this->info['filesize'] = $real_filesize;
  441. $this->warning('File is larger than '.round(PHP_INT_MAX / 1073741824).'GB (filesystem reports it as '.number_format($real_filesize / 1073741824, 3).'GB) and is not properly supported by PHP.');
  442. }
  443. }
  444. return true;
  445. } catch (Exception $e) {
  446. $this->error($e->getMessage());
  447. }
  448. return false;
  449. }
  450. /**
  451. * analyze file
  452. *
  453. * @param string $filename
  454. * @param int $filesize
  455. * @param string $original_filename
  456. * @param resource $fp
  457. *
  458. * @return array
  459. */
  460. public function analyze($filename, $filesize=null, $original_filename='', $fp=null) {
  461. try {
  462. if (!$this->openfile($filename, $filesize, $fp)) {
  463. return $this->info;
  464. }
  465. // Handle tags
  466. foreach (array('id3v2'=>'id3v2', 'id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
  467. $option_tag = 'option_tag_'.$tag_name;
  468. if ($this->$option_tag) {
  469. $this->include_module('tag.'.$tag_name);
  470. try {
  471. $tag_class = 'getid3_'.$tag_name;
  472. $tag = new $tag_class($this);
  473. $tag->Analyze();
  474. }
  475. catch (getid3_exception $e) {
  476. throw $e;
  477. }
  478. }
  479. }
  480. if (isset($this->info['id3v2']['tag_offset_start'])) {
  481. $this->info['avdataoffset'] = max($this->info['avdataoffset'], $this->info['id3v2']['tag_offset_end']);
  482. }
  483. foreach (array('id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
  484. if (isset($this->info[$tag_key]['tag_offset_start'])) {
  485. $this->info['avdataend'] = min($this->info['avdataend'], $this->info[$tag_key]['tag_offset_start']);
  486. }
  487. }
  488. // ID3v2 detection (NOT parsing), even if ($this->option_tag_id3v2 == false) done to make fileformat easier
  489. if (!$this->option_tag_id3v2) {
  490. fseek($this->fp, 0);
  491. $header = fread($this->fp, 10);
  492. if ((substr($header, 0, 3) == 'ID3') && (strlen($header) == 10)) {
  493. $this->info['id3v2']['header'] = true;
  494. $this->info['id3v2']['majorversion'] = ord($header[3]);
  495. $this->info['id3v2']['minorversion'] = ord($header[4]);
  496. $this->info['avdataoffset'] += getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length
  497. }
  498. }
  499. // read 32 kb file data
  500. fseek($this->fp, $this->info['avdataoffset']);
  501. $formattest = fread($this->fp, 32774);
  502. // determine format
  503. $determined_format = $this->GetFileFormat($formattest, ($original_filename ? $original_filename : $filename));
  504. // unable to determine file format
  505. if (!$determined_format) {
  506. fclose($this->fp);
  507. return $this->error('unable to determine file format');
  508. }
  509. // check for illegal ID3 tags
  510. if (isset($determined_format['fail_id3']) && (in_array('id3v1', $this->info['tags']) || in_array('id3v2', $this->info['tags']))) {
  511. if ($determined_format['fail_id3'] === 'ERROR') {
  512. fclose($this->fp);
  513. return $this->error('ID3 tags not allowed on this file type.');
  514. } elseif ($determined_format['fail_id3'] === 'WARNING') {
  515. $this->warning('ID3 tags not allowed on this file type.');
  516. }
  517. }
  518. // check for illegal APE tags
  519. if (isset($determined_format['fail_ape']) && in_array('ape', $this->info['tags'])) {
  520. if ($determined_format['fail_ape'] === 'ERROR') {
  521. fclose($this->fp);
  522. return $this->error('APE tags not allowed on this file type.');
  523. } elseif ($determined_format['fail_ape'] === 'WARNING') {
  524. $this->warning('APE tags not allowed on this file type.');
  525. }
  526. }
  527. // set mime type
  528. $this->info['mime_type'] = $determined_format['mime_type'];
  529. // supported format signature pattern detected, but module deleted
  530. if (!file_exists(GETID3_INCLUDEPATH.$determined_format['include'])) {
  531. fclose($this->fp);
  532. return $this->error('Format not supported, module "'.$determined_format['include'].'" was removed.');
  533. }
  534. // module requires mb_convert_encoding/iconv support
  535. // Check encoding/iconv support
  536. if (!empty($determined_format['iconv_req']) && !function_exists('mb_convert_encoding') && !function_exists('iconv') && !in_array($this->encoding, array('ISO-8859-1', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'UTF-16'))) {
  537. $errormessage = 'mb_convert_encoding() or iconv() support is required for this module ('.$determined_format['include'].') for encodings other than ISO-8859-1, UTF-8, UTF-16LE, UTF16-BE, UTF-16. ';
  538. if (GETID3_OS_ISWINDOWS) {
  539. $errormessage .= 'PHP does not have mb_convert_encoding() or iconv() support. Please enable php_mbstring.dll / php_iconv.dll in php.ini, and copy php_mbstring.dll / iconv.dll from c:/php/dlls to c:/windows/system32';
  540. } else {
  541. $errormessage .= 'PHP is not compiled with mb_convert_encoding() or iconv() support. Please recompile with the --enable-mbstring / --with-iconv switch';
  542. }
  543. return $this->error($errormessage);
  544. }
  545. // include module
  546. include_once(GETID3_INCLUDEPATH.$determined_format['include']);
  547. // instantiate module class
  548. $class_name = 'getid3_'.$determined_format['module'];
  549. if (!class_exists($class_name)) {
  550. return $this->error('Format not supported, module "'.$determined_format['include'].'" is corrupt.');
  551. }
  552. $class = new $class_name($this);
  553. $class->Analyze();
  554. unset($class);
  555. // close file
  556. fclose($this->fp);
  557. // process all tags - copy to 'tags' and convert charsets
  558. if ($this->option_tags_process) {
  559. $this->HandleAllTags();
  560. }
  561. // perform more calculations
  562. if ($this->option_extra_info) {
  563. $this->ChannelsBitratePlaytimeCalculations();
  564. $this->CalculateCompressionRatioVideo();
  565. $this->CalculateCompressionRatioAudio();
  566. $this->CalculateReplayGain();
  567. $this->ProcessAudioStreams();
  568. }
  569. // get the MD5 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
  570. if ($this->option_md5_data) {
  571. // do not calc md5_data if md5_data_source is present - set by flac only - future MPC/SV8 too
  572. if (!$this->option_md5_data_source || empty($this->info['md5_data_source'])) {
  573. $this->getHashdata('md5');
  574. }
  575. }
  576. // get the SHA1 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
  577. if ($this->option_sha1_data) {
  578. $this->getHashdata('sha1');
  579. }
  580. // remove undesired keys
  581. $this->CleanUp();
  582. } catch (Exception $e) {
  583. $this->error('Caught exception: '.$e->getMessage());
  584. }
  585. // return info array
  586. return $this->info;
  587. }
  588. /**
  589. * Error handling.
  590. *
  591. * @param string $message
  592. *
  593. * @return array
  594. */
  595. public function error($message) {
  596. $this->CleanUp();
  597. if (!isset($this->info['error'])) {
  598. $this->info['error'] = array();
  599. }
  600. $this->info['error'][] = $message;
  601. return $this->info;
  602. }
  603. /**
  604. * Warning handling.
  605. *
  606. * @param string $message
  607. *
  608. * @return bool
  609. */
  610. public function warning($message) {
  611. $this->info['warning'][] = $message;
  612. return true;
  613. }
  614. /**
  615. * @return bool
  616. */
  617. private function CleanUp() {
  618. // remove possible empty keys
  619. $AVpossibleEmptyKeys = array('dataformat', 'bits_per_sample', 'encoder_options', 'streams', 'bitrate');
  620. foreach ($AVpossibleEmptyKeys as $dummy => $key) {
  621. if (empty($this->info['audio'][$key]) && isset($this->info['audio'][$key])) {
  622. unset($this->info['audio'][$key]);
  623. }
  624. if (empty($this->info['video'][$key]) && isset($this->info['video'][$key])) {
  625. unset($this->info['video'][$key]);
  626. }
  627. }
  628. // remove empty root keys
  629. if (!empty($this->info)) {
  630. foreach ($this->info as $key => $value) {
  631. if (empty($this->info[$key]) && ($this->info[$key] !== 0) && ($this->info[$key] !== '0')) {
  632. unset($this->info[$key]);
  633. }
  634. }
  635. }
  636. // remove meaningless entries from unknown-format files
  637. if (empty($this->info['fileformat'])) {
  638. if (isset($this->info['avdataoffset'])) {
  639. unset($this->info['avdataoffset']);
  640. }
  641. if (isset($this->info['avdataend'])) {
  642. unset($this->info['avdataend']);
  643. }
  644. }
  645. // remove possible duplicated identical entries
  646. if (!empty($this->info['error'])) {
  647. $this->info['error'] = array_values(array_unique($this->info['error']));
  648. }
  649. if (!empty($this->info['warning'])) {
  650. $this->info['warning'] = array_values(array_unique($this->info['warning']));
  651. }
  652. // remove "global variable" type keys
  653. unset($this->info['php_memory_limit']);
  654. return true;
  655. }
  656. /**
  657. * Return array containing information about all supported formats.
  658. *
  659. * @return array
  660. */
  661. public function GetFileFormatArray() {
  662. static $format_info = array();
  663. if (empty($format_info)) {
  664. $format_info = array(
  665. // Audio formats
  666. // AC-3 - audio - Dolby AC-3 / Dolby Digital
  667. 'ac3' => array(
  668. 'pattern' => '^\\x0B\\x77',
  669. 'group' => 'audio',
  670. 'module' => 'ac3',
  671. 'mime_type' => 'audio/ac3',
  672. ),
  673. // AAC - audio - Advanced Audio Coding (AAC) - ADIF format
  674. 'adif' => array(
  675. 'pattern' => '^ADIF',
  676. 'group' => 'audio',
  677. 'module' => 'aac',
  678. 'mime_type' => 'audio/aac',
  679. 'fail_ape' => 'WARNING',
  680. ),
  681. /*
  682. // AA - audio - Audible Audiobook
  683. 'aa' => array(
  684. 'pattern' => '^.{4}\\x57\\x90\\x75\\x36',
  685. 'group' => 'audio',
  686. 'module' => 'aa',
  687. 'mime_type' => 'audio/audible',
  688. ),
  689. */
  690. // AAC - audio - Advanced Audio Coding (AAC) - ADTS format (very similar to MP3)
  691. 'adts' => array(
  692. 'pattern' => '^\\xFF[\\xF0-\\xF1\\xF8-\\xF9]',
  693. 'group' => 'audio',
  694. 'module' => 'aac',
  695. 'mime_type' => 'audio/aac',
  696. 'fail_ape' => 'WARNING',
  697. ),
  698. // AU - audio - NeXT/Sun AUdio (AU)
  699. 'au' => array(
  700. 'pattern' => '^\\.snd',
  701. 'group' => 'audio',
  702. 'module' => 'au',
  703. 'mime_type' => 'audio/basic',
  704. ),
  705. // AMR - audio - Adaptive Multi Rate
  706. 'amr' => array(
  707. 'pattern' => '^\\x23\\x21AMR\\x0A', // #!AMR[0A]
  708. 'group' => 'audio',
  709. 'module' => 'amr',
  710. 'mime_type' => 'audio/amr',
  711. ),
  712. // AVR - audio - Audio Visual Research
  713. 'avr' => array(
  714. 'pattern' => '^2BIT',
  715. 'group' => 'audio',
  716. 'module' => 'avr',
  717. 'mime_type' => 'application/octet-stream',
  718. ),
  719. // BONK - audio - Bonk v0.9+
  720. 'bonk' => array(
  721. 'pattern' => '^\\x00(BONK|INFO|META| ID3)',
  722. 'group' => 'audio',
  723. 'module' => 'bonk',
  724. 'mime_type' => 'audio/xmms-bonk',
  725. ),
  726. // DSF - audio - Direct Stream Digital (DSD) Storage Facility files (DSF) - https://en.wikipedia.org/wiki/Direct_Stream_Digital
  727. 'dsf' => array(
  728. 'pattern' => '^DSD ', // including trailing space: 44 53 44 20
  729. 'group' => 'audio',
  730. 'module' => 'dsf',
  731. 'mime_type' => 'audio/dsd',
  732. ),
  733. // DSS - audio - Digital Speech Standard
  734. 'dss' => array(
  735. 'pattern' => '^[\\x02-\\x08]ds[s2]',
  736. 'group' => 'audio',
  737. 'module' => 'dss',
  738. 'mime_type' => 'application/octet-stream',
  739. ),
  740. // DTS - audio - Dolby Theatre System
  741. 'dts' => array(
  742. 'pattern' => '^\\x7F\\xFE\\x80\\x01',
  743. 'group' => 'audio',
  744. 'module' => 'dts',
  745. 'mime_type' => 'audio/dts',
  746. ),
  747. // FLAC - audio - Free Lossless Audio Codec
  748. 'flac' => array(
  749. 'pattern' => '^fLaC',
  750. 'group' => 'audio',
  751. 'module' => 'flac',
  752. 'mime_type' => 'audio/flac',
  753. ),
  754. // LA - audio - Lossless Audio (LA)
  755. 'la' => array(
  756. 'pattern' => '^LA0[2-4]',
  757. 'group' => 'audio',
  758. 'module' => 'la',
  759. 'mime_type' => 'application/octet-stream',
  760. ),
  761. // LPAC - audio - Lossless Predictive Audio Compression (LPAC)
  762. 'lpac' => array(
  763. 'pattern' => '^LPAC',
  764. 'group' => 'audio',
  765. 'module' => 'lpac',
  766. 'mime_type' => 'application/octet-stream',
  767. ),
  768. // MIDI - audio - MIDI (Musical Instrument Digital Interface)
  769. 'midi' => array(
  770. 'pattern' => '^MThd',
  771. 'group' => 'audio',
  772. 'module' => 'midi',
  773. 'mime_type' => 'audio/midi',
  774. ),
  775. // MAC - audio - Monkey's Audio Compressor
  776. 'mac' => array(
  777. 'pattern' => '^MAC ',
  778. 'group' => 'audio',
  779. 'module' => 'monkey',
  780. 'mime_type' => 'audio/x-monkeys-audio',
  781. ),
  782. // has been known to produce false matches in random files (e.g. JPEGs), leave out until more precise matching available
  783. // // MOD - audio - MODule (assorted sub-formats)
  784. // 'mod' => array(
  785. // 'pattern' => '^.{1080}(M\\.K\\.|M!K!|FLT4|FLT8|[5-9]CHN|[1-3][0-9]CH)',
  786. // 'group' => 'audio',
  787. // 'module' => 'mod',
  788. // 'option' => 'mod',
  789. // 'mime_type' => 'audio/mod',
  790. // ),
  791. // MOD - audio - MODule (Impulse Tracker)
  792. 'it' => array(
  793. 'pattern' => '^IMPM',
  794. 'group' => 'audio',
  795. 'module' => 'mod',
  796. //'option' => 'it',
  797. 'mime_type' => 'audio/it',
  798. ),
  799. // MOD - audio - MODule (eXtended Module, various sub-formats)
  800. 'xm' => array(
  801. 'pattern' => '^Extended Module',
  802. 'group' => 'audio',
  803. 'module' => 'mod',
  804. //'option' => 'xm',
  805. 'mime_type' => 'audio/xm',
  806. ),
  807. // MOD - audio - MODule (ScreamTracker)
  808. 's3m' => array(
  809. 'pattern' => '^.{44}SCRM',
  810. 'group' => 'audio',
  811. 'module' => 'mod',
  812. //'option' => 's3m',
  813. 'mime_type' => 'audio/s3m',
  814. ),
  815. // MPC - audio - Musepack / MPEGplus
  816. 'mpc' => array(
  817. 'pattern' => '^(MPCK|MP\\+|[\\x00\\x01\\x10\\x11\\x40\\x41\\x50\\x51\\x80\\x81\\x90\\x91\\xC0\\xC1\\xD0\\xD1][\\x20-\\x37][\\x00\\x20\\x40\\x60\\x80\\xA0\\xC0\\xE0])',
  818. 'group' => 'audio',
  819. 'module' => 'mpc',
  820. 'mime_type' => 'audio/x-musepack',
  821. ),
  822. // MP3 - audio - MPEG-audio Layer 3 (very similar to AAC-ADTS)
  823. 'mp3' => array(
  824. 'pattern' => '^\\xFF[\\xE2-\\xE7\\xF2-\\xF7\\xFA-\\xFF][\\x00-\\x0B\\x10-\\x1B\\x20-\\x2B\\x30-\\x3B\\x40-\\x4B\\x50-\\x5B\\x60-\\x6B\\x70-\\x7B\\x80-\\x8B\\x90-\\x9B\\xA0-\\xAB\\xB0-\\xBB\\xC0-\\xCB\\xD0-\\xDB\\xE0-\\xEB\\xF0-\\xFB]',
  825. 'group' => 'audio',
  826. 'module' => 'mp3',
  827. 'mime_type' => 'audio/mpeg',
  828. ),
  829. // OFR - audio - OptimFROG
  830. 'ofr' => array(
  831. 'pattern' => '^(\\*RIFF|OFR)',
  832. 'group' => 'audio',
  833. 'module' => 'optimfrog',
  834. 'mime_type' => 'application/octet-stream',
  835. ),
  836. // RKAU - audio - RKive AUdio compressor
  837. 'rkau' => array(
  838. 'pattern' => '^RKA',
  839. 'group' => 'audio',
  840. 'module' => 'rkau',
  841. 'mime_type' => 'application/octet-stream',
  842. ),
  843. // SHN - audio - Shorten
  844. 'shn' => array(
  845. 'pattern' => '^ajkg',
  846. 'group' => 'audio',
  847. 'module' => 'shorten',
  848. 'mime_type' => 'audio/xmms-shn',
  849. 'fail_id3' => 'ERROR',
  850. 'fail_ape' => 'ERROR',
  851. ),
  852. // TTA - audio - TTA Lossless Audio Compressor (http://tta.corecodec.org)
  853. 'tta' => array(
  854. 'pattern' => '^TTA', // could also be '^TTA(\\x01|\\x02|\\x03|2|1)'
  855. 'group' => 'audio',
  856. 'module' => 'tta',
  857. 'mime_type' => 'application/octet-stream',
  858. ),
  859. // VOC - audio - Creative Voice (VOC)
  860. 'voc' => array(
  861. 'pattern' => '^Creative Voice File',
  862. 'group' => 'audio',
  863. 'module' => 'voc',
  864. 'mime_type' => 'audio/voc',
  865. ),
  866. // VQF - audio - transform-domain weighted interleave Vector Quantization Format (VQF)
  867. 'vqf' => array(
  868. 'pattern' => '^TWIN',
  869. 'group' => 'audio',
  870. 'module' => 'vqf',
  871. 'mime_type' => 'application/octet-stream',
  872. ),
  873. // WV - audio - WavPack (v4.0+)
  874. 'wv' => array(
  875. 'pattern' => '^wvpk',
  876. 'group' => 'audio',
  877. 'module' => 'wavpack',
  878. 'mime_type' => 'application/octet-stream',
  879. ),
  880. // Audio-Video formats
  881. // ASF - audio/video - Advanced Streaming Format, Windows Media Video, Windows Media Audio
  882. 'asf' => array(
  883. 'pattern' => '^\\x30\\x26\\xB2\\x75\\x8E\\x66\\xCF\\x11\\xA6\\xD9\\x00\\xAA\\x00\\x62\\xCE\\x6C',
  884. 'group' => 'audio-video',
  885. 'module' => 'asf',
  886. 'mime_type' => 'video/x-ms-asf',
  887. 'iconv_req' => false,
  888. ),
  889. // BINK - audio/video - Bink / Smacker
  890. 'bink' => array(
  891. 'pattern' => '^(BIK|SMK)',
  892. 'group' => 'audio-video',
  893. 'module' => 'bink',
  894. 'mime_type' => 'application/octet-stream',
  895. ),
  896. // FLV - audio/video - FLash Video
  897. 'flv' => array(
  898. 'pattern' => '^FLV[\\x01]',
  899. 'group' => 'audio-video',
  900. 'module' => 'flv',
  901. 'mime_type' => 'video/x-flv',
  902. ),
  903. // MKAV - audio/video - Mastroka
  904. 'matroska' => array(
  905. 'pattern' => '^\\x1A\\x45\\xDF\\xA3',
  906. 'group' => 'audio-video',
  907. 'module' => 'matroska',
  908. 'mime_type' => 'video/x-matroska', // may also be audio/x-matroska
  909. ),
  910. // MPEG - audio/video - MPEG (Moving Pictures Experts Group)
  911. 'mpeg' => array(
  912. 'pattern' => '^\\x00\\x00\\x01[\\xB3\\xBA]',
  913. 'group' => 'audio-video',
  914. 'module' => 'mpeg',
  915. 'mime_type' => 'video/mpeg',
  916. ),
  917. // NSV - audio/video - Nullsoft Streaming Video (NSV)
  918. 'nsv' => array(
  919. 'pattern' => '^NSV[sf]',
  920. 'group' => 'audio-video',
  921. 'module' => 'nsv',
  922. 'mime_type' => 'application/octet-stream',
  923. ),
  924. // Ogg - audio/video - Ogg (Ogg-Vorbis, Ogg-FLAC, Speex, Ogg-Theora(*), Ogg-Tarkin(*))
  925. 'ogg' => array(
  926. 'pattern' => '^OggS',
  927. 'group' => 'audio',
  928. 'module' => 'ogg',
  929. 'mime_type' => 'application/ogg',
  930. 'fail_id3' => 'WARNING',
  931. 'fail_ape' => 'WARNING',
  932. ),
  933. // QT - audio/video - Quicktime
  934. 'quicktime' => array(
  935. 'pattern' => '^.{4}(cmov|free|ftyp|mdat|moov|pnot|skip|wide)',
  936. 'group' => 'audio-video',
  937. 'module' => 'quicktime',
  938. 'mime_type' => 'video/quicktime',
  939. ),
  940. // RIFF - audio/video - Resource Interchange File Format (RIFF) / WAV / AVI / CD-audio / SDSS = renamed variant used by SmartSound QuickTracks (www.smartsound.com) / FORM = Audio Interchange File Format (AIFF)
  941. 'riff' => array(
  942. 'pattern' => '^(RIFF|SDSS|FORM)',
  943. 'group' => 'audio-video',
  944. 'module' => 'riff',
  945. 'mime_type' => 'audio/wav',
  946. 'fail_ape' => 'WARNING',
  947. ),
  948. // Real - audio/video - RealAudio, RealVideo
  949. 'real' => array(
  950. 'pattern' => '^\\.(RMF|ra)',
  951. 'group' => 'audio-video',
  952. 'module' => 'real',
  953. 'mime_type' => 'audio/x-realaudio',
  954. ),
  955. // SWF - audio/video - ShockWave Flash
  956. 'swf' => array(
  957. 'pattern' => '^(F|C)WS',
  958. 'group' => 'audio-video',
  959. 'module' => 'swf',
  960. 'mime_type' => 'application/x-shockwave-flash',
  961. ),
  962. // TS - audio/video - MPEG-2 Transport Stream
  963. 'ts' => array(
  964. 'pattern' => '^(\\x47.{187}){10,}', // packets are 188 bytes long and start with 0x47 "G". Check for at least 10 packets matching this pattern
  965. 'group' => 'audio-video',
  966. 'module' => 'ts',
  967. 'mime_type' => 'video/MP2T',
  968. ),
  969. // WTV - audio/video - Windows Recorded TV Show
  970. 'wtv' => array(
  971. 'pattern' => '^\\xB7\\xD8\\x00\\x20\\x37\\x49\\xDA\\x11\\xA6\\x4E\\x00\\x07\\xE9\\x5E\\xAD\\x8D',
  972. 'group' => 'audio-video',
  973. 'module' => 'wtv',
  974. 'mime_type' => 'video/x-ms-wtv',
  975. ),
  976. // Still-Image formats
  977. // BMP - still image - Bitmap (Windows, OS/2; uncompressed, RLE8, RLE4)
  978. 'bmp' => array(
  979. 'pattern' => '^BM',
  980. 'group' => 'graphic',
  981. 'module' => 'bmp',
  982. 'mime_type' => 'image/bmp',
  983. 'fail_id3' => 'ERROR',
  984. 'fail_ape' => 'ERROR',
  985. ),
  986. // GIF - still image - Graphics Interchange Format
  987. 'gif' => array(
  988. 'pattern' => '^GIF',
  989. 'group' => 'graphic',
  990. 'module' => 'gif',
  991. 'mime_type' => 'image/gif',
  992. 'fail_id3' => 'ERROR',
  993. 'fail_ape' => 'ERROR',
  994. ),
  995. // JPEG - still image - Joint Photographic Experts Group (JPEG)
  996. 'jpg' => array(
  997. 'pattern' => '^\\xFF\\xD8\\xFF',
  998. 'group' => 'graphic',
  999. 'module' => 'jpg',
  1000. 'mime_type' => 'image/jpeg',
  1001. 'fail_id3' => 'ERROR',
  1002. 'fail_ape' => 'ERROR',
  1003. ),
  1004. // PCD - still image - Kodak Photo CD
  1005. 'pcd' => array(
  1006. 'pattern' => '^.{2048}PCD_IPI\\x00',
  1007. 'group' => 'graphic',
  1008. 'module' => 'pcd',
  1009. 'mime_type' => 'image/x-photo-cd',
  1010. 'fail_id3' => 'ERROR',
  1011. 'fail_ape' => 'ERROR',
  1012. ),
  1013. // PNG - still image - Portable Network Graphics (PNG)
  1014. 'png' => array(
  1015. 'pattern' => '^\\x89\\x50\\x4E\\x47\\x0D\\x0A\\x1A\\x0A',
  1016. 'group' => 'graphic',
  1017. 'module' => 'png',
  1018. 'mime_type' => 'image/png',
  1019. 'fail_id3' => 'ERROR',
  1020. 'fail_ape' => 'ERROR',
  1021. ),
  1022. // SVG - still image - Scalable Vector Graphics (SVG)
  1023. 'svg' => array(
  1024. 'pattern' => '(<!DOCTYPE svg PUBLIC |xmlns="http://www\\.w3\\.org/2000/svg")',
  1025. 'group' => 'graphic',
  1026. 'module' => 'svg',
  1027. 'mime_type' => 'image/svg+xml',
  1028. 'fail_id3' => 'ERROR',
  1029. 'fail_ape' => 'ERROR',
  1030. ),
  1031. // TIFF - still image - Tagged Information File Format (TIFF)
  1032. 'tiff' => array(
  1033. 'pattern' => '^(II\\x2A\\x00|MM\\x00\\x2A)',
  1034. 'group' => 'graphic',
  1035. 'module' => 'tiff',
  1036. 'mime_type' => 'image/tiff',
  1037. 'fail_id3' => 'ERROR',
  1038. 'fail_ape' => 'ERROR',
  1039. ),
  1040. // EFAX - still image - eFax (TIFF derivative)
  1041. 'efax' => array(
  1042. 'pattern' => '^\\xDC\\xFE',
  1043. 'group' => 'graphic',
  1044. 'module' => 'efax',
  1045. 'mime_type' => 'image/efax',
  1046. 'fail_id3' => 'ERROR',
  1047. 'fail_ape' => 'ERROR',
  1048. ),
  1049. // Data formats
  1050. // ISO - data - International Standards Organization (ISO) CD-ROM Image
  1051. 'iso' => array(
  1052. 'pattern' => '^.{32769}CD001',
  1053. 'group' => 'misc',
  1054. 'module' => 'iso',
  1055. 'mime_type' => 'application/octet-stream',
  1056. 'fail_id3' => 'ERROR',
  1057. 'fail_ape' => 'ERROR',
  1058. 'iconv_req' => false,
  1059. ),
  1060. // RAR - data - RAR compressed data
  1061. 'rar' => array(
  1062. 'pattern' => '^Rar\\!',
  1063. 'group' => 'archive',
  1064. 'module' => 'rar',
  1065. 'mime_type' => 'application/octet-stream',
  1066. 'fail_id3' => 'ERROR',
  1067. 'fail_ape' => 'ERROR',
  1068. ),
  1069. // SZIP - audio/data - SZIP compressed data
  1070. 'szip' => array(
  1071. 'pattern' => '^SZ\\x0A\\x04',
  1072. 'group' => 'archive',
  1073. 'module' => 'szip',
  1074. 'mime_type' => 'application/octet-stream',
  1075. 'fail_id3' => 'ERROR',
  1076. 'fail_ape' => 'ERROR',
  1077. ),
  1078. // TAR - data - TAR compressed data
  1079. 'tar' => array(
  1080. 'pattern' => '^.{100}[0-9\\x20]{7}\\x00[0-9\\x20]{7}\\x00[0-9\\x20]{7}\\x00[0-9\\x20\\x00]{12}[0-9\\x20\\x00]{12}',
  1081. 'group' => 'archive',
  1082. 'module' => 'tar',
  1083. 'mime_type' => 'application/x-tar',
  1084. 'fail_id3' => 'ERROR',
  1085. 'fail_ape' => 'ERROR',
  1086. ),
  1087. // GZIP - data - GZIP compressed data
  1088. 'gz' => array(
  1089. 'pattern' => '^\\x1F\\x8B\\x08',
  1090. 'group' => 'archive',
  1091. 'module' => 'gzip',
  1092. 'mime_type' => 'application/gzip',
  1093. 'fail_id3' => 'ERROR',
  1094. 'fail_ape' => 'ERROR',
  1095. ),
  1096. // ZIP - data - ZIP compressed data
  1097. 'zip' => array(
  1098. 'pattern' => '^PK\\x03\\x04',
  1099. 'group' => 'archive',
  1100. 'module' => 'zip',
  1101. 'mime_type' => 'application/zip',
  1102. 'fail_id3' => 'ERROR',
  1103. 'fail_ape' => 'ERROR',
  1104. ),
  1105. // XZ - data - XZ compressed data
  1106. 'xz' => array(
  1107. 'pattern' => '^\\xFD7zXZ\\x00',
  1108. 'group' => 'archive',
  1109. 'module' => 'xz',
  1110. 'mime_type' => 'application/x-xz',
  1111. 'fail_id3' => 'ERROR',
  1112. 'fail_ape' => 'ERROR',
  1113. ),
  1114. // Misc other formats
  1115. // PAR2 - data - Parity Volume Set Specification 2.0
  1116. 'par2' => array (
  1117. 'pattern' => '^PAR2\\x00PKT',
  1118. 'group' => 'misc',
  1119. 'module' => 'par2',
  1120. 'mime_type' => 'application/octet-stream',
  1121. 'fail_id3' => 'ERROR',
  1122. 'fail_ape' => 'ERROR',
  1123. ),
  1124. // PDF - data - Portable Document Format
  1125. 'pdf' => array(
  1126. 'pattern' => '^\\x25PDF',
  1127. 'group' => 'misc',
  1128. 'module' => 'pdf',
  1129. 'mime_type' => 'application/pdf',
  1130. 'fail_id3' => 'ERROR',
  1131. 'fail_ape' => 'ERROR',
  1132. ),
  1133. // MSOFFICE - data - ZIP compressed data
  1134. 'msoffice' => array(
  1135. 'pattern' => '^\\xD0\\xCF\\x11\\xE0\\xA1\\xB1\\x1A\\xE1', // D0CF11E == DOCFILE == Microsoft Office Document
  1136. 'group' => 'misc',
  1137. 'module' => 'msoffice',
  1138. 'mime_type' => 'application/octet-stream',
  1139. 'fail_id3' => 'ERROR',
  1140. 'fail_ape' => 'ERROR',
  1141. ),
  1142. // CUE - data - CUEsheet (index to single-file disc images)
  1143. 'cue' => array(
  1144. 'pattern' => '', // empty pattern means cannot be automatically detected, will fall through all other formats and match based on filename and very basic file contents
  1145. 'group' => 'misc',
  1146. 'module' => 'cue',
  1147. 'mime_type' => 'application/octet-stream',
  1148. ),
  1149. );
  1150. }
  1151. return $format_info;
  1152. }
  1153. /**
  1154. * @param string $filedata
  1155. * @param string $filename
  1156. *
  1157. * @return mixed|false
  1158. */
  1159. public function GetFileFormat(&$filedata, $filename='') {
  1160. // this function will determine the format of a file based on usually
  1161. // the first 2-4 bytes of the file (8 bytes for PNG, 16 bytes for JPG,
  1162. // and in the case of ISO CD image, 6 bytes offset 32kb from the start
  1163. // of the file).
  1164. // Identify file format - loop through $format_info and detect with reg expr
  1165. foreach ($this->GetFileFormatArray() as $format_name => $info) {
  1166. // The /s switch on preg_match() forces preg_match() NOT to treat
  1167. // newline (0x0A) characters as special chars but do a binary match
  1168. if (!empty($info['pattern']) && preg_match('#'.$info['pattern'].'#s', $filedata)) {
  1169. $info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
  1170. return $info;
  1171. }
  1172. }
  1173. if (preg_match('#\\.mp[123a]$#i', $filename)) {
  1174. // Too many mp3 encoders on the market put garbage in front of mpeg files
  1175. // use assume format on these if format detection failed
  1176. $GetFileFormatArray = $this->GetFileFormatArray();
  1177. $info = $GetFileFormatArray['mp3'];
  1178. $info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
  1179. return $info;
  1180. } elseif (preg_match('#\\.cue$#i', $filename) && preg_match('#FILE "[^"]+" (BINARY|MOTOROLA|AIFF|WAVE|MP3)#', $filedata)) {
  1181. // there's not really a useful consistent "magic" at the beginning of .cue files to identify them
  1182. // so until I think of something better, just go by filename if all other format checks fail
  1183. // and verify there's at least one instance of "TRACK xx AUDIO" in the file
  1184. $GetFileFormatArray = $this->GetFileFormatArray();
  1185. $info = $GetFileFormatArray['cue'];
  1186. $info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
  1187. return $info;
  1188. }
  1189. return false;
  1190. }
  1191. /**
  1192. * Converts array to $encoding charset from $this->encoding.
  1193. *
  1194. * @param array $array
  1195. * @param string $encoding
  1196. */
  1197. public function CharConvert(&$array, $encoding) {
  1198. // identical encoding - end here
  1199. if ($encoding == $this->encoding) {
  1200. return;
  1201. }
  1202. // loop thru array
  1203. foreach ($array as $key => $value) {
  1204. // go recursive
  1205. if (is_array($value)) {
  1206. $this->CharConvert($array[$key], $encoding);
  1207. }
  1208. // convert string
  1209. elseif (is_string($value)) {
  1210. $array[$key] = trim(getid3_lib::iconv_fallback($encoding, $this->encoding, $value));
  1211. }
  1212. }
  1213. }
  1214. /**
  1215. * @return bool
  1216. */
  1217. public function HandleAllTags() {
  1218. // key name => array (tag name, character encoding)
  1219. static $tags;
  1220. if (empty($tags)) {
  1221. $tags = array(
  1222. 'asf' => array('asf' , 'UTF-16LE'),
  1223. 'midi' => array('midi' , 'ISO-8859-1'),
  1224. 'nsv' => array('nsv' , 'ISO-8859-1'),
  1225. 'ogg' => array('vorbiscomment' , 'UTF-8'),
  1226. 'png' => array('png' , 'UTF-8'),
  1227. 'tiff' => array('tiff' , 'ISO-8859-1'),
  1228. 'quicktime' => array('quicktime' , 'UTF-8'),
  1229. 'real' => array('real' , 'ISO-8859-1'),
  1230. 'vqf' => array('vqf' , 'ISO-8859-1'),
  1231. 'zip' => array('zip' , 'ISO-8859-1'),
  1232. 'riff' => array('riff' , 'ISO-8859-1'),
  1233. 'lyrics3' => array('lyrics3' , 'ISO-8859-1'),
  1234. 'id3v1' => array('id3v1' , $this->encoding_id3v1),
  1235. 'id3v2' => array('id3v2' , 'UTF-8'), // not according to the specs (every frame can have a different encoding), but getID3() force-converts all encodings to UTF-8
  1236. 'ape' => array('ape' , 'UTF-8'),
  1237. 'cue' => array('cue' , 'ISO-8859-1'),
  1238. 'matroska' => array('matroska' , 'UTF-8'),
  1239. 'flac' => array('vorbiscomment' , 'UTF-8'),
  1240. 'divxtag' => array('divx' , 'ISO-8859-1'),
  1241. 'iptc' => array('iptc' , 'ISO-8859-1'),
  1242. );
  1243. }
  1244. // loop through comments array
  1245. foreach ($tags as $comment_name => $tagname_encoding_array) {
  1246. list($tag_name, $encoding) = $tagname_encoding_array;
  1247. // fill in default encoding type if not already present
  1248. if (isset($this->info[$comment_name]) && !isset($this->info[$comment_name]['encoding'])) {
  1249. $this->info[$comment_name]['encoding'] = $encoding;
  1250. }
  1251. // copy comments if key name set
  1252. if (!empty($this->info[$comment_name]['comments'])) {
  1253. foreach ($this->info[$comment_name]['comments'] as $tag_key => $valuearray) {
  1254. foreach ($valuearray as $key => $value) {
  1255. if (is_string($value)) {
  1256. $value = trim($value, " \r\n\t"); // do not trim nulls from $value!! Unicode characters will get mangled if trailing nulls are removed!
  1257. }
  1258. if ($value) {
  1259. if (!is_numeric($key)) {
  1260. $this->info['tags'][trim($tag_name)][trim($tag_key)][$key] = $value;
  1261. } else {
  1262. $this->info['tags'][trim($tag_name)][trim($tag_key)][] = $value;
  1263. }
  1264. }
  1265. }
  1266. if ($tag_key == 'picture') {
  1267. // pictures can take up a lot of space, and we don't need multiple copies of them; let there be a single copy in [comments][picture], and not elsewhere
  1268. unset($this->info[$comment_name]['comments'][$tag_key]);
  1269. }
  1270. }
  1271. if (!isset($this->info['tags'][$tag_name])) {
  1272. // comments are set but contain nothing but empty strings, so skip
  1273. continue;
  1274. }
  1275. $this->CharConvert($this->info['tags'][$tag_name], $this->info[$comment_name]['encoding']); // only copy gets converted!
  1276. if ($this->option_tags_html) {
  1277. foreach ($this->info['tags'][$tag_name] as $tag_key => $valuearray) {
  1278. if ($tag_key == 'picture') {
  1279. // Do not to try to convert binary picture data to HTML
  1280. // https://github.com/JamesHeinrich/getID3/issues/178
  1281. continue;
  1282. }
  1283. $this->info['tags_html'][$tag_name][$tag_key] = getid3_lib::recursiveMultiByteCharString2HTML($valuearray, $this->info[$comment_name]['encoding']);
  1284. }
  1285. }
  1286. }
  1287. }
  1288. // pictures can take up a lot of space, and we don't need multiple copies of them; let there be a single copy in [comments][picture], and not elsewhere
  1289. if (!empty($this->info['tags'])) {
  1290. $unset_keys = array('tags', 'tags_html');
  1291. foreach ($this->info['tags'] as $tagtype => $tagarray) {
  1292. foreach ($tagarray as $tagname => $tagdata) {
  1293. if ($tagname == 'picture') {
  1294. foreach ($tagdata as $key => $tagarray) {
  1295. $this->info['comments']['picture'][] = $tagarray;
  1296. if (isset($tagarray['data']) && isset($tagarray['image_mime'])) {
  1297. if (isset($this->info['tags'][$tagtype][$tagname][$key])) {
  1298. unset($this->info['tags'][$tagtype][$tagname][$key]);
  1299. }
  1300. if (isset($this->info['tags_html'][$tagtype][$tagname][$key])) {
  1301. unset($this->info['tags_html'][$tagtype][$tagname][$key]);
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. foreach ($unset_keys as $unset_key) {
  1308. // remove possible empty keys from (e.g. [tags][id3v2][picture])
  1309. if (empty($this->info[$unset_key][$tagtype]['picture'])) {
  1310. unset($this->info[$unset_key][$tagtype]['picture']);
  1311. }
  1312. if (empty($this->info[$unset_key][$tagtype])) {
  1313. unset($this->info[$unset_key][$tagtype]);
  1314. }
  1315. if (empty($this->info[$unset_key])) {
  1316. unset($this->info[$unset_key]);
  1317. }
  1318. }
  1319. // remove duplicate copy of picture data from (e.g. [id3v2][comments][picture])
  1320. if (isset($this->info[$tagtype]['comments']['picture'])) {
  1321. unset($this->info[$tagtype]['comments']['picture']);
  1322. }
  1323. if (empty($this->info[$tagtype]['comments'])) {
  1324. unset($this->info[$tagtype]['comments']);
  1325. }
  1326. if (empty($this->info[$tagtype])) {
  1327. unset($this->info[$tagtype]);
  1328. }
  1329. }
  1330. }
  1331. return true;
  1332. }
  1333. /**
  1334. * @param string $algorithm
  1335. *
  1336. * @return array|bool
  1337. */
  1338. public function getHashdata($algorithm) {
  1339. switch ($algorithm) {
  1340. case 'md5':
  1341. case 'sha1':
  1342. break;
  1343. default:
  1344. return $this->error('bad algorithm "'.$algorithm.'" in getHashdata()');
  1345. }
  1346. if (!empty($this->info['fileformat']) && !empty($this->info['dataformat']) && ($this->info['fileformat'] == 'ogg') && ($this->info['audio']['dataformat'] == 'vorbis')) {
  1347. // We cannot get an identical md5_data value for Ogg files where the comments
  1348. // span more than 1 Ogg page (compared to the same audio data with smaller
  1349. // comments) using the normal getID3() method of MD5'ing the data between the
  1350. // end of the comments and the end of the file (minus any trailing tags),
  1351. // because the page sequence numbers of the pages that the audio data is on
  1352. // do not match. Under normal circumstances, where comments are smaller than
  1353. // the nominal 4-8kB page size, then this is not a problem, but if there are
  1354. // very large comments, the only way around it is to strip off the comment
  1355. // tags with vorbiscomment and MD5 that file.
  1356. // This procedure must be applied to ALL Ogg files, not just the ones with
  1357. // comments larger than 1 page, because the below method simply MD5's the
  1358. // whole file with the comments stripped, not just the portion after the
  1359. // comments block (which is the standard getID3() method.
  1360. // The above-mentioned problem of comments spanning multiple pages and changing
  1361. // page sequence numbers likely happens for OggSpeex and OggFLAC as well, but
  1362. // currently vorbiscomment only works on OggVorbis files.
  1363. if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved
  1364. $this->warning('Failed making system call to vorbiscomment.exe - '.$algorithm.'_data is incorrect - error returned: PHP running in Safe Mode (backtick operator not available)');
  1365. $this->info[$algorithm.'_data'] = false;
  1366. } else {
  1367. // Prevent user from aborting script
  1368. $old_abort = ignore_user_abort(true);
  1369. // Create empty file
  1370. $empty = tempnam(GETID3_TEMP_DIR, 'getID3');
  1371. touch($empty);
  1372. // Use vorbiscomment to make temp file without comments
  1373. $temp = tempnam(GETID3_TEMP_DIR, 'getID3');
  1374. $file = $this->info['filenamepath'];
  1375. if (GETID3_OS_ISWINDOWS) {
  1376. if (file_exists(GETID3_HELPERAPPSDIR.'vorbiscomment.exe')) {
  1377. $commandline = '"'.GETID3_HELPERAPPSDIR.'vorbiscomment.exe" -w -c "'.$empty.'" "'.$file.'" "'.$temp.'"';
  1378. $VorbisCommentError = `$commandline`;
  1379. } else {
  1380. $VorbisCommentError = 'vorbiscomment.exe not found in '.GETID3_HELPERAPPSDIR;
  1381. }
  1382. } else {
  1383. $commandline = 'vorbiscomment -w -c '.escapeshellarg($empty).' '.escapeshellarg($file).' '.escapeshellarg($temp).' 2>&1';
  1384. $VorbisCommentError = `$commandline`;
  1385. }
  1386. if (!empty($VorbisCommentError)) {
  1387. $this->warning('Failed making system call to vorbiscomment(.exe) - '.$algorithm.'_data will be incorrect. If vorbiscomment is unavailable, please download from http://www.vorbis.com/download.psp and put in the getID3() directory. Error returned: '.$VorbisCommentError);
  1388. $this->info[$algorithm.'_data'] = false;
  1389. } else {
  1390. // Get hash of newly created file
  1391. switch ($algorithm) {
  1392. case 'md5':
  1393. $this->info[$algorithm.'_data'] = md5_file($temp);
  1394. break;
  1395. case 'sha1':
  1396. $this->info[$algorithm.'_data'] = sha1_file($temp);
  1397. break;
  1398. }
  1399. }
  1400. // Clean up
  1401. unlink($empty);
  1402. unlink($temp);
  1403. // Reset abort setting
  1404. ignore_user_abort($old_abort);
  1405. }
  1406. } else {
  1407. if (!empty($this->info['avdataoffset']) || (isset($this->info['avdataend']) && ($this->info['avdataend'] < $this->info['filesize']))) {
  1408. // get hash from part of file
  1409. $this->info[$algorithm.'_data'] = getid3_lib::hash_data($this->info['filenamepath'], $this->info['avdataoffset'], $this->info['avdataend'], $algorithm);
  1410. } else {
  1411. // get hash from whole file
  1412. switch ($algorithm) {
  1413. case 'md5':
  1414. $this->info[$algorithm.'_data'] = md5_file($this->info['filenamepath']);
  1415. break;
  1416. case 'sha1':
  1417. $this->info[$algorithm.'_data'] = sha1_file($this->info['filenamepath']);
  1418. break;
  1419. }
  1420. }
  1421. }
  1422. return true;
  1423. }
  1424. public function ChannelsBitratePlaytimeCalculations() {
  1425. // set channelmode on audio
  1426. if (!empty($this->info['audio']['channelmode']) || !isset($this->info['audio']['channels'])) {
  1427. // ignore
  1428. } elseif ($this->info['audio']['channels'] == 1) {
  1429. $this->info['audio']['channelmode'] = 'mono';
  1430. } elseif ($this->info['audio']['channels'] == 2) {
  1431. $this->info['audio']['channelmode'] = 'stereo';
  1432. }
  1433. // Calculate combined bitrate - audio + video
  1434. $CombinedBitrate = 0;
  1435. $CombinedBitrate += (isset($this->info['audio']['bitrate']) ? $this->info['audio']['bitrate'] : 0);
  1436. $CombinedBitrate += (isset($this->info['video']['bitrate']) ? $this->info['video']['bitrate'] : 0);
  1437. if (($CombinedBitrate > 0) && empty($this->info['bitrate'])) {
  1438. $this->info['bitrate'] = $CombinedBitrate;
  1439. }
  1440. //if ((isset($this->info['video']) && !isset($this->info['video']['bitrate'])) || (isset($this->info['audio']) && !isset($this->info['audio']['bitrate']))) {
  1441. // // for example, VBR MPEG video files cannot determine video bitrate:
  1442. // // should not set overall bitrate and playtime from audio bitrate only
  1443. // unset($this->info['bitrate']);
  1444. //}
  1445. // video bitrate undetermined, but calculable
  1446. if (isset($this->info['video']['dataformat']) && $this->info['video']['dataformat'] && (!isset($this->info['video']['bitrate']) || ($this->info['video']['bitrate'] == 0))) {
  1447. // if video bitrate not set
  1448. if (isset($this->info['audio']['bitrate']) && ($this->info['audio']['bitrate'] > 0) && ($this->info['audio']['bitrate'] == $this->info['bitrate'])) {
  1449. // AND if audio bitrate is set to same as overall bitrate
  1450. if (isset($this->info['playtime_seconds']) && ($this->info['playtime_seconds'] > 0)) {
  1451. // AND if playtime is set
  1452. if (isset($this->info['avdataend']) && isset($this->info['avdataoffset'])) {
  1453. // AND if AV data offset start/end is known
  1454. // THEN we can calculate the video bitrate
  1455. $this->info['bitrate'] = round((($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['playtime_seconds']);
  1456. $this->info['video']['bitrate'] = $this->info['bitrate'] - $this->info['audio']['bitrate'];
  1457. }
  1458. }
  1459. }
  1460. }
  1461. if ((!isset($this->info['playtime_seconds']) || ($this->info['playtime_seconds'] <= 0)) && !empty($this->info['bitrate'])) {
  1462. $this->info['playtime_seconds'] = (($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['bitrate'];
  1463. }
  1464. if (!isset($this->info['bitrate']) && !empty($this->info['playtime_seconds'])) {
  1465. $this->info['bitrate'] = (($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['playtime_seconds'];
  1466. }
  1467. if (isset($this->info['bitrate']) && empty($this->info['audio']['bitrate']) && empty($this->info['video']['bitrate'])) {
  1468. if (isset($this->info['audio']['dataformat']) && empty($this->info['video']['resolution_x'])) {
  1469. // audio only
  1470. $this->info['audio']['bitrate'] = $this->info['bitrate'];
  1471. } elseif (isset($this->info['video']['resolution_x']) && empty($this->info['audio']['dataformat'])) {
  1472. // video only
  1473. $this->info['video']['bitrate'] = $this->info['bitrate'];
  1474. }
  1475. }
  1476. // Set playtime string
  1477. if (!empty($this->info['playtime_seconds']) && empty($this->info['playtime_string'])) {
  1478. $this->info['playtime_string'] = getid3_lib::PlaytimeString($this->info['playtime_seconds']);
  1479. }
  1480. }
  1481. /**
  1482. * @return bool
  1483. */
  1484. public function CalculateCompressionRatioVideo() {
  1485. if (empty($this->info['video'])) {
  1486. return false;
  1487. }
  1488. if (empty($this->info['video']['resolution_x']) || empty($this->info['video']['resolution_y'])) {
  1489. return false;
  1490. }
  1491. if (empty($this->info['video']['bits_per_sample'])) {
  1492. return false;
  1493. }
  1494. switch ($this->info['video']['dataformat']) {
  1495. case 'bmp':
  1496. case 'gif':
  1497. case 'jpeg':
  1498. case 'jpg':
  1499. case 'png':
  1500. case 'tiff':
  1501. $FrameRate = 1;
  1502. $PlaytimeSeconds = 1;
  1503. $BitrateCompressed = $this->info['filesize'] * 8;
  1504. break;
  1505. default:
  1506. if (!empty($this->info['video']['frame_rate'])) {
  1507. $FrameRate = $this->info['video']['frame_rate'];
  1508. } else {
  1509. return false;
  1510. }
  1511. if (!empty($this->info['playtime_seconds'])) {
  1512. $PlaytimeSeconds = $this->info['playtime_seconds'];
  1513. } else {
  1514. return false;
  1515. }
  1516. if (!empty($this->info['video']['bitrate'])) {
  1517. $BitrateCompressed = $this->info['video']['bitrate'];
  1518. } else {
  1519. return false;
  1520. }
  1521. break;
  1522. }
  1523. $BitrateUncompressed = $this->info['video']['resolution_x'] * $this->info['video']['resolution_y'] * $this->info['video']['bits_per_sample'] * $FrameRate;
  1524. $this->info['video']['compression_ratio'] = $BitrateCompressed / $BitrateUncompressed;
  1525. return true;
  1526. }
  1527. /**
  1528. * @return bool
  1529. */
  1530. public function CalculateCompressionRatioAudio() {
  1531. if (empty($this->info['audio']['bitrate']) || empty($this->info['audio']['channels']) || empty($this->info['audio']['sample_rate']) || !is_numeric($this->info['audio']['sample_rate'])) {
  1532. return false;
  1533. }
  1534. $this->info['audio']['compression_ratio'] = $this->info['audio']['bitrate'] / ($this->info['audio']['channels'] * $this->info['audio']['sample_rate'] * (!empty($this->info['audio']['bits_per_sample']) ? $this->info['audio']['bits_per_sample'] : 16));
  1535. if (!empty($this->info['audio']['streams'])) {
  1536. foreach ($this->info['audio']['streams'] as $streamnumber => $streamdata) {
  1537. if (!empty($streamdata['bitrate']) && !empty($streamdata['channels']) && !empty($streamdata['sample_rate'])) {
  1538. $this->info['audio']['streams'][$streamnumber]['compression_ratio'] = $streamdata['bitrate'] / ($streamdata['channels'] * $streamdata['sample_rate'] * (!empty($streamdata['bits_per_sample']) ? $streamdata['bits_per_sample'] : 16));
  1539. }
  1540. }
  1541. }
  1542. return true;
  1543. }
  1544. /**
  1545. * @return bool
  1546. */
  1547. public function CalculateReplayGain() {
  1548. if (isset($this->info['replay_gain'])) {
  1549. if (!isset($this->info['replay_gain']['reference_volume'])) {
  1550. $this->info['replay_gain']['reference_volume'] = 89.0;
  1551. }
  1552. if (isset($this->info['replay_gain']['track']['adjustment'])) {
  1553. $this->info['replay_gain']['track']['volume'] = $this->info['replay_gain']['reference_volume'] - $this->info['replay_gain']['track']['adjustment'];
  1554. }
  1555. if (isset($this->info['replay_gain']['album']['adjustment'])) {
  1556. $this->info['replay_gain']['album']['volume'] = $this->info['replay_gain']['reference_volume'] - $this->info['replay_gain']['album']['adjustment'];
  1557. }
  1558. if (isset($this->info['replay_gain']['track']['peak'])) {
  1559. $this->info['replay_gain']['track']['max_noclip_gain'] = 0 - getid3_lib::RGADamplitude2dB($this->info['replay_gain']['track']['peak']);
  1560. }
  1561. if (isset($this->info['replay_gain']['album']['peak'])) {
  1562. $this->info['replay_gain']['album']['max_noclip_gain'] = 0 - getid3_lib::RGADamplitude2dB($this->info['replay_gain']['album']['peak']);
  1563. }
  1564. }
  1565. return true;
  1566. }
  1567. /**
  1568. * @return bool
  1569. */
  1570. public function ProcessAudioStreams() {
  1571. if (!empty($this->info['audio']['bitrate']) || !empty($this->info['audio']['channels']) || !empty($this->info['audio']['sample_rate'])) {
  1572. if (!isset($this->info['audio']['streams'])) {
  1573. foreach ($this->info['audio'] as $key => $value) {
  1574. if ($key != 'streams') {
  1575. $this->info['audio']['streams'][0][$key] = $value;
  1576. }
  1577. }
  1578. }
  1579. }
  1580. return true;
  1581. }
  1582. /**
  1583. * @return string|bool
  1584. */
  1585. public function getid3_tempnam() {
  1586. return tempnam($this->tempdir, 'gI3');
  1587. }
  1588. /**
  1589. * @param string $name
  1590. *
  1591. * @return bool
  1592. *
  1593. * @throws getid3_exception
  1594. */
  1595. public function include_module($name) {
  1596. //if (!file_exists($this->include_path.'module.'.$name.'.php')) {
  1597. if (!file_exists(GETID3_INCLUDEPATH.'module.'.$name.'.php')) {
  1598. throw new getid3_exception('Required module.'.$name.'.php is missing.');
  1599. }
  1600. include_once(GETID3_INCLUDEPATH.'module.'.$name.'.php');
  1601. return true;
  1602. }
  1603. /**
  1604. * @param string $filename
  1605. *
  1606. * @return bool
  1607. */
  1608. public static function is_writable ($filename) {
  1609. $ret = is_writable($filename);
  1610. if (!$ret) {
  1611. $perms = fileperms($filename);
  1612. $ret = ($perms & 0x0080) || ($perms & 0x0010) || ($perms & 0x0002);
  1613. }
  1614. return $ret;
  1615. }
  1616. }
  1617. abstract class getid3_handler
  1618. {
  1619. /**
  1620. * @var getID3
  1621. */
  1622. protected $getid3; // pointer
  1623. /**
  1624. * Analyzing filepointer or string.
  1625. *
  1626. * @var bool
  1627. */
  1628. protected $data_string_flag = false;
  1629. /**
  1630. * String to analyze.
  1631. *
  1632. * @var string
  1633. */
  1634. protected $data_string = '';
  1635. /**
  1636. * Seek position in string.
  1637. *
  1638. * @var int
  1639. */
  1640. protected $data_string_position = 0;
  1641. /**
  1642. * String length.
  1643. *
  1644. * @var int
  1645. */
  1646. protected $data_string_length = 0;
  1647. /**
  1648. * @var string
  1649. */
  1650. private $dependency_to;
  1651. /**
  1652. * getid3_handler constructor.
  1653. *
  1654. * @param getID3 $getid3
  1655. * @param string $call_module
  1656. */
  1657. public function __construct(getID3 $getid3, $call_module=null) {
  1658. $this->getid3 = $getid3;
  1659. if ($call_module) {
  1660. $this->dependency_to = str_replace('getid3_', '', $call_module);
  1661. }
  1662. }
  1663. /**
  1664. * Analyze from file pointer.
  1665. *
  1666. * @return bool
  1667. */
  1668. abstract public function Analyze();
  1669. /**
  1670. * Analyze from string instead.
  1671. *
  1672. * @param string $string
  1673. */
  1674. public function AnalyzeString($string) {
  1675. // Enter string mode
  1676. $this->setStringMode($string);
  1677. // Save info
  1678. $saved_avdataoffset = $this->getid3->info['avdataoffset'];
  1679. $saved_avdataend = $this->getid3->info['avdataend'];
  1680. $saved_filesize = (isset($this->getid3->info['filesize']) ? $this->getid3->info['filesize'] : null); // may be not set if called as dependency without openfile() call
  1681. // Reset some info
  1682. $this->getid3->info['avdataoffset'] = 0;
  1683. $this->getid3->info['avdataend'] = $this->getid3->info['filesize'] = $this->data_string_length;
  1684. // Analyze
  1685. $this->Analyze();
  1686. // Restore some info
  1687. $this->getid3->info['avdataoffset'] = $saved_avdataoffset;
  1688. $this->getid3->info['avdataend'] = $saved_avdataend;
  1689. $this->getid3->info['filesize'] = $saved_filesize;
  1690. // Exit string mode
  1691. $this->data_string_flag = false;
  1692. }
  1693. /**
  1694. * @param string $string
  1695. */
  1696. public function setStringMode($string) {
  1697. $this->data_string_flag = true;
  1698. $this->data_string = $string;
  1699. $this->data_string_length = strlen($string);
  1700. }
  1701. /**
  1702. * @return int|bool
  1703. */
  1704. protected function ftell() {
  1705. if ($this->data_string_flag) {
  1706. return $this->data_string_position;
  1707. }
  1708. return ftell($this->getid3->fp);
  1709. }
  1710. /**
  1711. * @param int $bytes
  1712. *
  1713. * @return string|false
  1714. *
  1715. * @throws getid3_exception
  1716. */
  1717. protected function fread($bytes) {
  1718. if ($this->data_string_flag) {
  1719. $this->data_string_position += $bytes;
  1720. return substr($this->data_string, $this->data_string_position - $bytes, $bytes);
  1721. }
  1722. $pos = $this->ftell() + $bytes;
  1723. if (!getid3_lib::intValueSupported($pos)) {
  1724. throw new getid3_exception('cannot fread('.$bytes.' from '.$this->ftell().') because beyond PHP filesystem limit', 10);
  1725. }
  1726. //return fread($this->getid3->fp, $bytes);
  1727. /*
  1728. * https://www.getid3.org/phpBB3/viewtopic.php?t=1930
  1729. * "I found out that the root cause for the problem was how getID3 uses the PHP system function fread().
  1730. * It seems to assume that fread() would always return as many bytes as were requested.
  1731. * However, according the PHP manual (http://php.net/manual/en/function.fread.php), this is the case only with regular local files, but not e.g. with Linux pipes.
  1732. * The call may return only part of the requested data and a new call is needed to get more."
  1733. */
  1734. $contents = '';
  1735. do {
  1736. //if (($this->getid3->memory_limit > 0) && ($bytes > $this->getid3->memory_limit)) {
  1737. if (($this->getid3->memory_limit > 0) && (($bytes / $this->getid3->memory_limit) > 0.99)) { // enable a more-fuzzy match to prevent close misses generating errors like "PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 33554464 bytes)"
  1738. throw new getid3_exception('cannot fread('.$bytes.' from '.$this->ftell().') that is more than available PHP memory ('.$this->getid3->memory_limit.')', 10);
  1739. }
  1740. $part = fread($this->getid3->fp, $bytes);
  1741. $partLength = strlen($part);
  1742. $bytes -= $partLength;
  1743. $contents .= $part;
  1744. } while (($bytes > 0) && ($partLength > 0));
  1745. return $contents;
  1746. }
  1747. /**
  1748. * @param int $bytes
  1749. * @param int $whence
  1750. *
  1751. * @return int
  1752. *
  1753. * @throws getid3_exception
  1754. */
  1755. protected function fseek($bytes, $whence=SEEK_SET) {
  1756. if ($this->data_string_flag) {
  1757. switch ($whence) {
  1758. case SEEK_SET:
  1759. $this->data_string_position = $bytes;
  1760. break;
  1761. case SEEK_CUR:
  1762. $this->data_string_position += $bytes;
  1763. break;
  1764. case SEEK_END:
  1765. $this->data_string_position = $this->data_string_length + $bytes;
  1766. break;
  1767. }
  1768. return 0;
  1769. } else {
  1770. $pos = $bytes;
  1771. if ($whence == SEEK_CUR) {
  1772. $pos = $this->ftell() + $bytes;
  1773. } elseif ($whence == SEEK_END) {
  1774. $pos = $this->getid3->info['filesize'] + $bytes;
  1775. }
  1776. if (!getid3_lib::intValueSupported($pos)) {
  1777. throw new getid3_exception('cannot fseek('.$pos.') because beyond PHP filesystem limit', 10);
  1778. }
  1779. }
  1780. return fseek($this->getid3->fp, $bytes, $whence);
  1781. }
  1782. /**
  1783. * @return bool
  1784. */
  1785. protected function feof() {
  1786. if ($this->data_string_flag) {
  1787. return $this->data_string_position >= $this->data_string_length;
  1788. }
  1789. return feof($this->getid3->fp);
  1790. }
  1791. /**
  1792. * @param string $module
  1793. *
  1794. * @return bool
  1795. */
  1796. final protected function isDependencyFor($module) {
  1797. return $this->dependency_to == $module;
  1798. }
  1799. /**
  1800. * @param string $text
  1801. *
  1802. * @return bool
  1803. */
  1804. protected function error($text) {
  1805. $this->getid3->info['error'][] = $text;
  1806. return false;
  1807. }
  1808. /**
  1809. * @param string $text
  1810. *
  1811. * @return bool
  1812. */
  1813. protected function warning($text) {
  1814. return $this->getid3->warning($text);
  1815. }
  1816. /**
  1817. * @param string $text
  1818. */
  1819. protected function notice($text) {
  1820. // does nothing for now
  1821. }
  1822. /**
  1823. * @param string $name
  1824. * @param int $offset
  1825. * @param int $length
  1826. * @param string $image_mime
  1827. *
  1828. * @return string|null
  1829. *
  1830. * @throws Exception
  1831. * @throws getid3_exception
  1832. */
  1833. public function saveAttachment($name, $offset, $length, $image_mime=null) {
  1834. try {
  1835. // do not extract at all
  1836. if ($this->getid3->option_save_attachments === getID3::ATTACHMENTS_NONE) {
  1837. $attachment = null; // do not set any
  1838. // extract to return array
  1839. } elseif ($this->getid3->option_save_attachments === getID3::ATTACHMENTS_INLINE) {
  1840. $this->fseek($offset);
  1841. $attachment = $this->fread($length); // get whole data in one pass, till it is anyway stored in memory
  1842. if ($attachment === false || strlen($attachment) != $length) {
  1843. throw new Exception('failed to read attachment data');
  1844. }
  1845. // assume directory path is given
  1846. } else {
  1847. // set up destination path
  1848. $dir = rtrim(str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->getid3->option_save_attachments), DIRECTORY_SEPARATOR);
  1849. if (!is_dir($dir) || !getID3::is_writable($dir)) { // check supplied directory
  1850. throw new Exception('supplied path ('.$dir.') does not exist, or is not writable');
  1851. }
  1852. $dest = $dir.DIRECTORY_SEPARATOR.$name.($image_mime ? '.'.getid3_lib::ImageExtFromMime($image_mime) : '');
  1853. // create dest file
  1854. if (($fp_dest = fopen($dest, 'wb')) == false) {
  1855. throw new Exception('failed to create file '.$dest);
  1856. }
  1857. // copy data
  1858. $this->fseek($offset);
  1859. $buffersize = ($this->data_string_flag ? $length : $this->getid3->fread_buffer_size());
  1860. $bytesleft = $length;
  1861. while ($bytesleft > 0) {
  1862. if (($buffer = $this->fread(min($buffersize, $bytesleft))) === false || ($byteswritten = fwrite($fp_dest, $buffer)) === false || ($byteswritten === 0)) {
  1863. throw new Exception($buffer === false ? 'not enough data to read' : 'failed to write to destination file, may be not enough disk space');
  1864. }
  1865. $bytesleft -= $byteswritten;
  1866. }
  1867. fclose($fp_dest);
  1868. $attachment = $dest;
  1869. }
  1870. } catch (Exception $e) {
  1871. // close and remove dest file if created
  1872. if (isset($fp_dest) && is_resource($fp_dest)) {
  1873. fclose($fp_dest);
  1874. }
  1875. if (isset($dest) && file_exists($dest)) {
  1876. unlink($dest);
  1877. }
  1878. // do not set any is case of error
  1879. $attachment = null;
  1880. $this->warning('Failed to extract attachment '.$name.': '.$e->getMessage());
  1881. }
  1882. // seek to the end of attachment
  1883. $this->fseek($offset + $length);
  1884. return $attachment;
  1885. }
  1886. }
  1887. class getid3_exception extends Exception
  1888. {
  1889. public $message;
  1890. }