getid3.php 65 KB

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