home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / ID3 / getid3.php < prev    next >
Encoding:
PHP Script  |  2017-07-31  |  65.0 KB  |  1,845 lines

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