<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org>               //
//  available at http://getid3.sourceforge.net                 //
//            or http://www.getid3.org                         //
/////////////////////////////////////////////////////////////////
//                                                             //
// Please see readme.txt for more information                  //
//                                                            ///
/////////////////////////////////////////////////////////////////

// Defines
define('GETID3_VERSION', '1.7.8b2');
define('GETID3_FREAD_BUFFER_SIZE', 16384); // read buffer size in bytes



class getID3
{
    
// public: Settings
    
var $encoding        = 'ISO-8859-1';   // CASE SENSITIVE! - i.e. (must be supported by iconv())
                                           // Examples:  ISO-8859-1  UTF-8  UTF-16  UTF-16BE

    
var $encoding_id3v1  = 'ISO-8859-1';   // Should always be 'ISO-8859-1', but some tags may be written in other encodings such as 'EUC-CN'

    
var $tempdir         = '*';            // default '*' should use system temp dir

    // public: Optional tag checks - disable for speed.
    
var $option_tag_id3v1         = true;  // Read and process ID3v1 tags
    
var $option_tag_id3v2         = true;  // Read and process ID3v2 tags
    
var $option_tag_lyrics3       = true;  // Read and process Lyrics3 tags
    
var $option_tag_apetag        = true;  // Read and process APE tags
    
var $option_tags_process      = true;  // Copy tags to root key 'tags' and encode to $this->encoding
    
var $option_tags_html         = true;  // Copy tags to root key 'tags_html' properly translated from various encodings to HTML entities

    // public: Optional tag/comment calucations
    
var $option_extra_info        = true;  // Calculate additional info such as bitrate, channelmode etc

    // public: Optional calculations
    
var $option_md5_data          = false; // Get MD5 sum of data part - slow
    
var $option_md5_data_source   = false; // Use MD5 of source file if availble - only FLAC and OptimFROG
    
var $option_sha1_data         = false; // Get SHA1 sum of data part - slow
    
var $option_max_2gb_check     = true;  // Check whether file is larger than 2 Gb and thus not supported by PHP

    // private
    
var $filename;


    
// public: constructor
    
function getID3()
    {

        
$this->startup_error   = '';
        
$this->startup_warning = '';

        
// Check for PHP version >= 4.2.0
        
if (phpversion() < '4.2.0') {
            
$this->startup_error .= 'getID3() requires PHP v4.2.0 or higher - you are running v'.phpversion();
        }

        
// Check memory
        
$memory_limit = ini_get('memory_limit');
        if (
eregi('([0-9]+)M', $memory_limit, $matches)) {
            
// could be stored as "16M" rather than 16777216 for example
            
$memory_limit = $matches[1] * 1048576;
        }
        if (
$memory_limit <= 0) {
            
// memory limits probably disabled
        
} elseif ($memory_limit <= 3145728) {
            
$this->startup_error .= 'PHP has less than 3MB available memory and will very likely run out. Increase memory_limit in php.ini';
        } elseif (
$memory_limit <= 12582912) {
            
$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';
        }

        
// Check safe_mode off
        
if ((bool) ini_get('safe_mode')) {
            
$this->warning('WARNING: Safe mode is on, shorten support disabled, md5data/sha1data for ogg vorbis disabled, ogg vorbos/flac tag writing disabled.');
        }


        
// define a constant rather than looking up every time it is needed
        
if (!defined('GETID3_OS_ISWINDOWS')) {
            if (
strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
                
define('GETID3_OS_ISWINDOWS', true);
            } else {
                
define('GETID3_OS_ISWINDOWS', false);
            }
        }

        
// Get base path of getID3() - ONCE
        
if (!defined('GETID3_INCLUDEPATH')) {
            foreach (
get_included_files() as $key => $val) {
                if (
basename($val) == 'getid3.php') {
                    
define('GETID3_INCLUDEPATH', dirname($val).DIRECTORY_SEPARATOR);
                    break;
                }
            }
        }

        
// Load support library
        
if (!include_once(GETID3_INCLUDEPATH.'getid3.lib.php')) {
            
$this->startup_error .= 'getid3.lib.php is missing or corrupt';
        }


        
// Needed for Windows only:
        // Define locations of helper applications for Shorten, VorbisComment, MetaFLAC
        //   as well as other helper functions such as head, tail, md5sum, etc
        // IMPORTANT: This path cannot have spaces in it. If neccesary, use the 8dot3 equivalent
        //   ie for "C:/Program Files/Apache/" put "C:/PROGRA~1/APACHE/"
        // IMPORTANT: This path must include the trailing slash
        
if (GETID3_OS_ISWINDOWS && !defined('GETID3_HELPERAPPSDIR')) {

            
$helperappsdir = GETID3_INCLUDEPATH.'..'.DIRECTORY_SEPARATOR.'helperapps'; // must not have any space in this path

            
if (!is_dir($helperappsdir)) {
                
$this->startup_error .= '"'.$helperappsdir.'" cannot be defined as GETID3_HELPERAPPSDIR because it does not exist';
            } elseif (
strpos(realpath($helperappsdir), ' ') !== false) {
                
$DirPieces = explode(DIRECTORY_SEPARATOR, realpath($helperappsdir));
                foreach (
$DirPieces as $key => $value) {
                    if ((
strpos($value, '.') !== false) && (strpos($value, ' ') === false)) {
                        if (
strpos($value, '.') > 8) {
                            
$value = substr($value, 0, 6).'~1';
                        }
                    } elseif ((
strpos($value, ' ') !== false) || strlen($value) > 8) {
                        
$value = substr($value, 0, 6).'~1';
                    }
                    
$DirPieces[$key] = strtoupper($value);
                }
                
$this->startup_error .= 'GETID3_HELPERAPPSDIR must not have any spaces in it - use 8dot3 naming convention if neccesary (on this server that would be something like "'.implode(DIRECTORY_SEPARATOR, $DirPieces).'" - NOTE: this may or may not be the actual 8.3 equivalent of "'.$helperappsdir.'", please double-check). You can run "dir /x" from the commandline to see the correct 8.3-style names.';
            }
            
define('GETID3_HELPERAPPSDIR', realpath($helperappsdir).DIRECTORY_SEPARATOR);
        }

    }


    
// public: setOption
    
function setOption($optArray) {
        if (!
is_array($optArray) || empty($optArray)) {
            return
false;
        }
        foreach (
$optArray as $opt => $val) {
            if (isset(
$this, $opt) === false) {
                continue;
            }
            
$this->$opt = $val;
        }
        return
true;
    }


    
// public: analyze file - replaces GetAllFileInfo() and GetTagOnly()
    
function analyze($filename) {

        if (!empty(
$this->startup_error)) {
            return
$this->error($this->startup_error);
        }
        if (!empty(
$this->startup_warning)) {
            
$this->warning($this->startup_warning);
        }

        
// init result array and set parameters
        
$this->info = array();
        
$this->info['GETID3_VERSION'] = GETID3_VERSION;

        
// Check encoding/iconv support
        
if (!function_exists('iconv') && !in_array($this->encoding, array('ISO-8859-1', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'UTF-16'))) {
            
$errormessage = 'iconv() support is needed for encodings other than ISO-8859-1, UTF-8, UTF-16LE, UTF16-BE, UTF-16. ';
            if (
GETID3_OS_ISWINDOWS) {
                
$errormessage .= 'PHP does not have iconv() support. Please enable php_iconv.dll in php.ini, and copy iconv.dll from c:/php/dlls to c:/windows/system32';
            } else {
                
$errormessage .= 'PHP is not compiled with iconv() support. Please recompile with the --with-iconv switch';
            }
            return
$this->error($errormessage);
        }

        
// Disable magic_quotes_runtime, if neccesary
        
$old_magic_quotes_runtime = get_magic_quotes_runtime(); // store current setting of magic_quotes_runtime
        
if ($old_magic_quotes_runtime) {
            
set_magic_quotes_runtime(0);                        // turn off magic_quotes_runtime
            
if (get_magic_quotes_runtime()) {
                return
$this->error('Could not disable magic_quotes_runtime - getID3() cannot work properly with this setting enabled');
            }
        }

        
// remote files not supported
        
if (preg_match('/^(ht|f)tp:\/\//', $filename)) {
            return
$this->error('Remote files are not supported in this version of getID3() - please copy the file locally first');
        }

        
// open local file
        
if (!$fp = @fopen($filename, 'rb')) {
            return
$this->error('Could not open file "'.$filename.'"');
        }

        
// set parameters
        
$this->info['filesize'] = filesize($filename);

        
// option_max_2gb_check
        
if ($this->option_max_2gb_check) {
            
// PHP doesn't support integers larger than 31-bit (~2GB)
            // filesize() simply returns (filesize % (pow(2, 32)), no matter the actual filesize
            // ftell() returns 0 if seeking to the end is beyond the range of unsigned integer
            
fseek($fp, 0, SEEK_END);
            if (((
$this->info['filesize'] != 0) && (ftell($fp) == 0)) ||
                (
$this->info['filesize'] < 0) ||
                (
ftell($fp) < 0)) {
                    unset(
$this->info['filesize']);
                    
fclose($fp);
                    return
$this->error('File is most likely larger than 2GB and is not supported by PHP');
            }
        }

        
// set more parameters
        
$this->info['avdataoffset']        = 0;
        
$this->info['avdataend']           = $this->info['filesize'];
        
$this->info['fileformat']          = '';                // filled in later
        
$this->info['audio']['dataformat'] = '';                // filled in later, unset if not used
        
$this->info['video']['dataformat'] = '';                // filled in later, unset if not used
        
$this->info['tags']                = array();           // filled in later, unset if not used
        
$this->info['error']               = array();           // filled in later, unset if not used
        
$this->info['warning']             = array();           // filled in later, unset if not used
        
$this->info['comments']            = array();           // filled in later, unset if not used
        
$this->info['encoding']            = $this->encoding;   // required by id3v2 and iso modules - can be unset at the end if desired

        // set redundant parameters - might be needed in some include file
        
$this->info['filename']            = basename($filename);
        
$this->info['filepath']            = str_replace('\\', '/', realpath(dirname($filename)));
        
$this->info['filenamepath']        = $this->info['filepath'].'/'.$this->info['filename'];


        
// handle ID3v2 tag - done first - already at beginning of file
        // ID3v2 detection (even if not parsing) is always done otherwise fileformat is much harder to detect
        
if ($this->option_tag_id3v2) {

            
$GETID3_ERRORARRAY = &$this->info['warning'];
            if (
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, false)) {
                
$tag = new getid3_id3v2($fp, $this->info);
                unset(
$tag);
            }

        } else {

            
fseek($fp, 0, SEEK_SET);
            
$header = fread($fp, 10);
            if (
substr($header, 0, 3) == 'ID3'  &&  strlen($header) == 10) {
                
$this->info['id3v2']['header']           = true;
                
$this->info['id3v2']['majorversion']     = ord($header{3});
                
$this->info['id3v2']['minorversion']     = ord($header{4});
                
$this->info['id3v2']['headerlength']     = getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length

                
$this->info['id3v2']['tag_offset_start'] = 0;
                
$this->info['id3v2']['tag_offset_end']   = $this->info['id3v2']['tag_offset_start'] + $this->info['id3v2']['headerlength'];
                
$this->info['avdataoffset']              = $this->info['id3v2']['tag_offset_end'];
            }

        }


        
// handle ID3v1 tag
        
if ($this->option_tag_id3v1) {
            if (!@include_once(
GETID3_INCLUDEPATH.'module.tag.id3v1.php')) {
                return
$this->error('module.tag.id3v1.php is missing - you may disable option_tag_id3v1.');
            }
            
$tag = new getid3_id3v1($fp, $this->info);
            unset(
$tag);
        }

        
// handle APE tag
        
if ($this->option_tag_apetag) {
            if (!@include_once(
GETID3_INCLUDEPATH.'module.tag.apetag.php')) {
                return
$this->error('module.tag.apetag.php is missing - you may disable option_tag_apetag.');
            }
            
$tag = new getid3_apetag($fp, $this->info);
            unset(
$tag);
        }

        
// handle lyrics3 tag
        
if ($this->option_tag_lyrics3) {
            if (!@include_once(
GETID3_INCLUDEPATH.'module.tag.lyrics3.php')) {
                return
$this->error('module.tag.lyrics3.php is missing - you may disable option_tag_lyrics3.');
            }
            
$tag = new getid3_lyrics3($fp, $this->info);
            unset(
$tag);
        }

        
// read 32 kb file data
        
fseek($fp, $this->info['avdataoffset'], SEEK_SET);
        
$formattest = fread($fp, 32774);

        
// determine format
        
$determined_format = $this->GetFileFormat($formattest, $filename);

        
// unable to determine file format
        
if (!$determined_format) {
            
fclose($fp);
            return
$this->error('unable to determine file format');
        }

        
// check for illegal ID3 tags
        
if (isset($determined_format['fail_id3']) && (in_array('id3v1', $this->info['tags']) || in_array('id3v2', $this->info['tags']))) {
            if (
$determined_format['fail_id3'] === 'ERROR') {
                
fclose($fp);
                return
$this->error('ID3 tags not allowed on this file type.');
            } elseif (
$determined_format['fail_id3'] === 'WARNING') {
                
$this->info['warning'][] = 'ID3 tags not allowed on this file type.';
            }
        }

        
// check for illegal APE tags
        
if (isset($determined_format['fail_ape']) && in_array('ape', $this->info['tags'])) {
            if (
$determined_format['fail_ape'] === 'ERROR') {
                
fclose($fp);
                return
$this->error('APE tags not allowed on this file type.');
            } elseif (
$determined_format['fail_ape'] === 'WARNING') {
                
$this->info['warning'][] = 'APE tags not allowed on this file type.';
            }
        }

        
// set mime type
        
$this->info['mime_type'] = $determined_format['mime_type'];

        
// supported format signature pattern detected, but module deleted
        
if (!file_exists(GETID3_INCLUDEPATH.$determined_format['include'])) {
            
fclose($fp);
            return
$this->error('Format not supported, module, '.$determined_format['include'].', was removed.');
        }

        
// module requires iconv support
        
if (!function_exists('iconv') && @$determined_format['iconv_req']) {
            return
$this->error('iconv support is required for this module ('.$determined_format['include'].').');
        }

        
// include module
        
include_once(GETID3_INCLUDEPATH.$determined_format['include']);

        
// instantiate module class
        
$class_name = 'getid3_'.$determined_format['module'];
        if (!
class_exists($class_name)) {
            return
$this->error('Format not supported, module, '.$determined_format['include'].', is corrupt.');
        }
        if (isset(
$determined_format['option'])) {
            
$class = new $class_name($fp, $this->info, $determined_format['option']);
        } else {
            
$class = new $class_name($fp, $this->info);
        }
        unset(
$class);

        
// close file
        
fclose($fp);

        
// process all tags - copy to 'tags' and convert charsets
        
if ($this->option_tags_process) {
            
$this->HandleAllTags();
        }

        
// perform more calculations
        
if ($this->option_extra_info) {
            
$this->ChannelsBitratePlaytimeCalculations();
            
$this->CalculateCompressionRatioVideo();
            
$this->CalculateCompressionRatioAudio();
            
$this->CalculateReplayGain();
            
$this->ProcessAudioStreams();
        }

        
// get the MD5 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
        
if ($this->option_md5_data) {
            
// do not cald md5_data if md5_data_source is present - set by flac only - future MPC/SV8 too
            
if (!$this->option_md5_data_source || empty($this->info['md5_data_source'])) {
                
$this->getHashdata('md5');
            }
        }

        
// get the SHA1 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
        
if ($this->option_sha1_data) {
            
$this->getHashdata('sha1');
        }

        
// remove undesired keys
        
$this->CleanUp();

        
// restore magic_quotes_runtime setting
        
set_magic_quotes_runtime($old_magic_quotes_runtime);

        
// return info array
        
return $this->info;
    }


    
// private: error handling
    
function error($message) {

        
$this->CleanUp();

        
$this->info['error'][] = $message;
        return
$this->info;
    }


    
// private: warning handling
    
function warning($message) {
        
$this->info['warning'][] = $message;
        return
true;
    }


    
// private: CleanUp
    
function CleanUp() {

        
// remove possible empty keys
        
$AVpossibleEmptyKeys = array('dataformat', 'bits_per_sample', 'encoder_options', 'streams', 'bitrate');
        foreach (
$AVpossibleEmptyKeys as $dummy => $key) {
            if (empty(
$this->info['audio'][$key]) && isset($this->info['audio'][$key])) {
                unset(
$this->info['audio'][$key]);
            }
            if (empty(
$this->info['video'][$key]) && isset($this->info['video'][$key])) {
                unset(
$this->info['video'][$key]);
            }
        }

        
// remove empty root keys
        
if (!empty($this->info)) {
            foreach (
$this->info as $key => $value) {
                if (empty(
$this->info[$key]) && ($this->info[$key] !== 0) && ($this->info[$key] !== '0')) {
                    unset(
$this->info[$key]);
                }
            }
        }

        
// remove meaningless entries from unknown-format files
        
if (empty($this->info['fileformat'])) {
            if (isset(
$this->info['avdataoffset'])) {
                unset(
$this->info['avdataoffset']);
            }
            if (isset(
$this->info['avdataend'])) {
                unset(
$this->info['avdataend']);
            }
        }
    }


    
// return array containing information about all supported formats
    
function GetFileFormatArray() {
        static
$format_info = array();
        if (empty(
$format_info)) {
            
$format_info = array(

                
// Audio formats

                // AC-3   - audio      - Dolby AC-3 / Dolby Digital
                
'ac3'  => array(
                            
'pattern'   => '^\x0B\x77',
                            
'group'     => 'audio',
                            
'module'    => 'ac3',
                            
'mime_type' => 'audio/ac3',
                        ),

                
// AAC  - audio       - Advanced Audio Coding (AAC) - ADIF format
                
'adif' => array(
                            
'pattern'   => '^ADIF',
                            
'group'     => 'audio',
                            
'module'    => 'aac',
                            
'option'    => 'adif',
                            
'mime_type' => 'application/octet-stream',
                            
'fail_ape'  => 'WARNING',
                        ),


                
// AAC  - audio       - Advanced Audio Coding (AAC) - ADTS format (very similar to MP3)
                
'adts' => array(
                            
'pattern'   => '^\xFF[\xF0-\xF1\xF8-\xF9]',
                            
'group'     => 'audio',
                            
'module'    => 'aac',
                            
'option'    => 'adts',
                            
'mime_type' => 'application/octet-stream',
                            
'fail_ape'  => 'WARNING',
                        ),


                
// AU   - audio       - NeXT/Sun AUdio (AU)
                
'au'   => array(
                            
'pattern'   => '^\.snd',
                            
'group'     => 'audio',
                            
'module'    => 'au',
                            
'mime_type' => 'audio/basic',
                        ),

                
// AVR  - audio       - Audio Visual Research
                
'avr'  => array(
                            
'pattern'   => '^2BIT',
                            
'group'     => 'audio',
                            
'module'    => 'avr',
                            
'mime_type' => 'application/octet-stream',
                        ),

                
// BONK - audio       - Bonk v0.9+
                
'bonk' => array(
                            
'pattern'   => '^\x00(BONK|INFO|META| ID3)',
                            
'group'     => 'audio',
                            
'module'    => 'bonk',
                            
'mime_type' => 'audio/xmms-bonk',
                        ),

                
// DTS  - audio       - Dolby Theatre System
                
'dts'  => array(
                            
'pattern'   => '^\x7F\xFE\x80\x01',
                            
'group'     => 'audio',
                            
'module'    => 'dts',
                            
'mime_type' => 'audio/dts',
                        ),

                
// FLAC - audio       - Free Lossless Audio Codec
                
'flac' => array(
                            
'pattern'   => '^fLaC',
                            
'group'     => 'audio',
                            
'module'    => 'flac',
                            
'mime_type' => 'audio/x-flac',
                        ),

                
// LA   - audio       - Lossless Audio (LA)
                
'la'   => array(
                            
'pattern'   => '^LA0[2-4]',
                            
'group'     => 'audio',
                            
'module'    => 'la',
                            
'mime_type' => 'application/octet-stream',
                        ),

                
// LPAC - audio       - Lossless Predictive Audio Compression (LPAC)
                
'lpac' => array(
                            
'pattern'   => '^LPAC',
                            
'group'     => 'audio',
                            
'module'    => 'lpac',
                            
'mime_type' => 'application/octet-stream',
                        ),

                
// MIDI - audio       - MIDI (Musical Instrument Digital Interface)
                
'midi' => array(
                            
'pattern'   => '^MThd',
                            
'group'     => 'audio',
                            
'module'    => 'midi',
                            
'mime_type' => 'audio/midi',
                        ),

                
// MAC  - audio       - Monkey's Audio Compressor
                
'mac'  => array(
                            
'pattern'   => '^MAC ',
                            
'group'     => 'audio',
                            
'module'    => 'monkey',
                            
'mime_type' => 'application/octet-stream',
                        ),

                
// MOD  - audio       - MODule (assorted sub-formats)
                
'mod'  => array(
                            
'pattern'   => '^.{1080}(M.K.|[5-9]CHN|[1-3][0-9]CH)',
                            
'group'     => 'audio',
                            
'module'    => 'mod',
                            
'option'    => 'mod',
                            
'mime_type' => 'audio/mod',
                        ),

                
// MOD  - audio       - MODule (Impulse Tracker)
                
'it'   => array(
                            
'pattern'   => '^IMPM',
                            
'group'     => 'audio',
                            
'module'    => 'mod',
                            
'option'    => 'it',
                            
'mime_type' => 'audio/it',
                        ),

                
// MOD  - audio       - MODule (eXtended Module, various sub-formats)
                
'xm'   => array(
                            
'pattern'   => '^Extended Module',
                            
'group'     => 'audio',
                            
'module'    => 'mod',
                            
'option'    => 'xm',
                            
'mime_type' => 'audio/xm',
                        ),

                
// MOD  - audio       - MODule (ScreamTracker)
                
's3m'  => array(
                            
'pattern'   => '^.{44}SCRM',
                            
'group'     => 'audio',
                            
'module'    => 'mod',
                            
'option'    => 's3m',
                            
'mime_type' => 'audio/s3m',
                        ),

                
// MPC  - audio       - Musepack / MPEGplus
                
'mpc'  => array(
                            
'pattern'   => '^(MP\+|[\x00\x01\x10\x11\x40\x41\x50\x51\x80\x81\x90\x91\xC0\xC1\xD0\xD1][\x20-37][\x00\x20\x40\x60\x80\xA0\xC0\xE0])',
                            
'group'     => 'audio',
                            
'module'    => 'mpc',
                            
'mime_type' => 'audio/x-musepack',
                        ),

                
// MP3  - audio       - MPEG-audio Layer 3 (very similar to AAC-ADTS)
                
'mp3'  => array(
                            
'pattern'   => '^\xFF[\xE2-\xE7\xF2-\xF7\xFA-\xFF][\x00-\xEB]',
                            
'group'     => 'audio',
                            
'module'    => 'mp3',
                            
'mime_type' => 'audio/mpeg',
                        ),

                
// OFR  - audio       - OptimFROG
                
'ofr'  => array(
                            
'pattern'   => '^(\*RIFF|OFR)',
                            
'group'     => 'audio',
                            
'module'    => 'optimfrog',
                            
'mime_type' => 'application/octet-stream',
                        ),

                
// RKAU - audio       - RKive AUdio compressor
                
'rkau' => array(
                            
'pattern'   =>