No Description

getid3.php 78KB

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