getid3.php 78 KB

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