getid3.php 65 KB

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