MediaWiki  REL1_20
MimeMagic.php
Go to the documentation of this file.
00001 <?php
00042 define('MM_WELL_KNOWN_MIME_TYPES',<<<END_STRING
00043 application/ogg ogx ogg ogm ogv oga spx
00044 application/pdf pdf
00045 application/vnd.oasis.opendocument.chart odc
00046 application/vnd.oasis.opendocument.chart-template otc
00047 application/vnd.oasis.opendocument.database odb
00048 application/vnd.oasis.opendocument.formula odf
00049 application/vnd.oasis.opendocument.formula-template otf
00050 application/vnd.oasis.opendocument.graphics odg
00051 application/vnd.oasis.opendocument.graphics-template otg
00052 application/vnd.oasis.opendocument.image odi
00053 application/vnd.oasis.opendocument.image-template oti
00054 application/vnd.oasis.opendocument.presentation odp
00055 application/vnd.oasis.opendocument.presentation-template otp
00056 application/vnd.oasis.opendocument.spreadsheet ods
00057 application/vnd.oasis.opendocument.spreadsheet-template ots
00058 application/vnd.oasis.opendocument.text odt
00059 application/vnd.oasis.opendocument.text-master otm
00060 application/vnd.oasis.opendocument.text-template ott
00061 application/vnd.oasis.opendocument.text-web oth
00062 application/x-javascript js
00063 application/x-shockwave-flash swf
00064 audio/midi mid midi kar
00065 audio/mpeg mpga mpa mp2 mp3
00066 audio/x-aiff aif aiff aifc
00067 audio/x-wav wav
00068 audio/ogg oga spx ogg
00069 image/x-bmp bmp
00070 image/gif gif
00071 image/jpeg jpeg jpg jpe
00072 image/png png
00073 image/svg+xml svg 
00074 image/svg svg
00075 image/tiff tiff tif
00076 image/vnd.djvu djvu
00077 image/x.djvu djvu
00078 image/x-djvu djvu
00079 image/x-portable-pixmap ppm
00080 image/x-xcf xcf
00081 text/plain txt
00082 text/html html htm
00083 video/ogg ogv ogm ogg
00084 video/mpeg mpg mpeg
00085 END_STRING
00086 );
00087 
00094 define('MM_WELL_KNOWN_MIME_INFO', <<<END_STRING
00095 application/pdf [OFFICE]
00096 application/vnd.oasis.opendocument.chart [OFFICE]
00097 application/vnd.oasis.opendocument.chart-template [OFFICE]
00098 application/vnd.oasis.opendocument.database [OFFICE]
00099 application/vnd.oasis.opendocument.formula [OFFICE]
00100 application/vnd.oasis.opendocument.formula-template [OFFICE]
00101 application/vnd.oasis.opendocument.graphics [OFFICE]
00102 application/vnd.oasis.opendocument.graphics-template [OFFICE]
00103 application/vnd.oasis.opendocument.image [OFFICE]
00104 application/vnd.oasis.opendocument.image-template [OFFICE]
00105 application/vnd.oasis.opendocument.presentation [OFFICE]
00106 application/vnd.oasis.opendocument.presentation-template [OFFICE]
00107 application/vnd.oasis.opendocument.spreadsheet [OFFICE]
00108 application/vnd.oasis.opendocument.spreadsheet-template [OFFICE]
00109 application/vnd.oasis.opendocument.text [OFFICE]
00110 application/vnd.oasis.opendocument.text-template [OFFICE]
00111 application/vnd.oasis.opendocument.text-master [OFFICE]
00112 application/vnd.oasis.opendocument.text-web [OFFICE]
00113 text/javascript application/x-javascript [EXECUTABLE]
00114 application/x-shockwave-flash [MULTIMEDIA]
00115 audio/midi [AUDIO]
00116 audio/x-aiff [AUDIO]
00117 audio/x-wav [AUDIO]
00118 audio/mp3 audio/mpeg [AUDIO]
00119 application/ogg audio/ogg video/ogg [MULTIMEDIA]
00120 image/x-bmp image/x-ms-bmp image/bmp [BITMAP]
00121 image/gif [BITMAP]
00122 image/jpeg [BITMAP]
00123 image/png [BITMAP]
00124 image/svg+xml [DRAWING]
00125 image/tiff [BITMAP]
00126 image/vnd.djvu [BITMAP]
00127 image/x-xcf [BITMAP]
00128 image/x-portable-pixmap [BITMAP]
00129 text/plain [TEXT]
00130 text/html [TEXT]
00131 video/ogg [VIDEO]
00132 video/mpeg [VIDEO]
00133 unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
00134 END_STRING
00135 );
00136 
00144 class MimeMagic {
00145 
00150         var $mMediaTypes = null;
00151 
00154         var $mMimeTypeAliases = null;
00155 
00158         var $mMimeToExt = null;
00159 
00162         var $mExtToMime = null;
00163 
00166         var $mIEAnalyzer;
00167 
00170         private static $instance;
00171 
00174         private static $extensionLoaded = false;
00175 
00180         function __construct() {
00185                 global $wgMimeTypeFile, $IP, $wgLoadFileinfoExtension;
00186 
00187                 $types = MM_WELL_KNOWN_MIME_TYPES;
00188 
00189                 if ( $wgMimeTypeFile == 'includes/mime.types' ) {
00190                         $wgMimeTypeFile = "$IP/$wgMimeTypeFile";
00191                 }
00192 
00193                 if ( $wgLoadFileinfoExtension && !self::$extensionLoaded ) {
00194                         self::$extensionLoaded = true;
00195                         wfDl( 'fileinfo' );
00196                 }
00197 
00198                 if ( $wgMimeTypeFile ) {
00199                         if ( is_file( $wgMimeTypeFile ) and is_readable( $wgMimeTypeFile ) ) {
00200                                 wfDebug( __METHOD__.": loading mime types from $wgMimeTypeFile\n" );
00201                                 $types .= "\n";
00202                                 $types .= file_get_contents( $wgMimeTypeFile );
00203                         } else {
00204                                 wfDebug( __METHOD__.": can't load mime types from $wgMimeTypeFile\n" );
00205                         }
00206                 } else {
00207                         wfDebug( __METHOD__.": no mime types file defined, using build-ins only.\n" );
00208                 }
00209 
00210                 $types = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $types );
00211                 $types = str_replace( "\t", " ", $types );
00212 
00213                 $this->mMimeToExt = array();
00214                 $this->mToMime = array();
00215 
00216                 $lines = explode( "\n",$types );
00217                 foreach ( $lines as $s ) {
00218                         $s = trim( $s );
00219                         if ( empty( $s ) ) {
00220                                 continue;
00221                         }
00222                         if ( strpos( $s, '#' ) === 0 ) {
00223                                 continue;
00224                         }
00225 
00226                         $s = strtolower( $s );
00227                         $i = strpos( $s, ' ' );
00228 
00229                         if ( $i === false ) {
00230                                 continue;
00231                         }
00232 
00233                         $mime = substr( $s, 0, $i );
00234                         $ext = trim( substr($s, $i+1 ) );
00235 
00236                         if ( empty( $ext ) ) {
00237                                 continue;
00238                         }
00239 
00240                         if ( !empty( $this->mMimeToExt[$mime] ) ) {
00241                                 $this->mMimeToExt[$mime] .= ' ' . $ext;
00242                         } else {
00243                                 $this->mMimeToExt[$mime] = $ext;
00244                         }
00245 
00246                         $extensions = explode( ' ', $ext );
00247 
00248                         foreach ( $extensions as $e ) {
00249                                 $e = trim( $e );
00250                                 if ( empty( $e ) ) {
00251                                         continue;
00252                                 }
00253 
00254                                 if ( !empty( $this->mExtToMime[$e] ) ) {
00255                                         $this->mExtToMime[$e] .= ' ' . $mime;
00256                                 } else {
00257                                         $this->mExtToMime[$e] = $mime;
00258                                 }
00259                         }
00260                 }
00261 
00266                 global $wgMimeInfoFile;
00267                 if ( $wgMimeInfoFile == 'includes/mime.info' ) {
00268                         $wgMimeInfoFile = "$IP/$wgMimeInfoFile";
00269                 }
00270 
00271                 $info = MM_WELL_KNOWN_MIME_INFO;
00272 
00273                 if ( $wgMimeInfoFile ) {
00274                         if ( is_file( $wgMimeInfoFile ) and is_readable( $wgMimeInfoFile ) ) {
00275                                 wfDebug( __METHOD__.": loading mime info from $wgMimeInfoFile\n" );
00276                                 $info .= "\n";
00277                                 $info .= file_get_contents( $wgMimeInfoFile );
00278                         } else {
00279                                 wfDebug(__METHOD__.": can't load mime info from $wgMimeInfoFile\n");
00280                         }
00281                 } else {
00282                         wfDebug(__METHOD__.": no mime info file defined, using build-ins only.\n");
00283                 }
00284 
00285                 $info = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $info);
00286                 $info = str_replace( "\t", " ", $info );
00287 
00288                 $this->mMimeTypeAliases = array();
00289                 $this->mMediaTypes = array();
00290 
00291                 $lines = explode( "\n", $info );
00292                 foreach ( $lines as $s ) {
00293                         $s = trim( $s );
00294                         if ( empty( $s ) ) {
00295                                 continue;
00296                         }
00297                         if ( strpos( $s, '#' ) === 0 ) {
00298                                 continue;
00299                         }
00300 
00301                         $s = strtolower( $s );
00302                         $i = strpos( $s, ' ' );
00303 
00304                         if ( $i === false ) {
00305                                 continue;
00306                         }
00307 
00308                         #print "processing MIME INFO line $s<br>";
00309 
00310                         $match = array();
00311                         if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
00312                                 $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
00313                                 $mtype = trim( strtoupper( $match[1] ) );
00314                         } else {
00315                                 $mtype = MEDIATYPE_UNKNOWN;
00316                         }
00317 
00318                         $m = explode( ' ', $s );
00319 
00320                         if ( !isset( $this->mMediaTypes[$mtype] ) ) {
00321                                 $this->mMediaTypes[$mtype] = array();
00322                         }
00323 
00324                         foreach ( $m as $mime ) {
00325                                 $mime = trim( $mime );
00326                                 if ( empty( $mime ) ) {
00327                                         continue;
00328                                 }
00329 
00330                                 $this->mMediaTypes[$mtype][] = $mime;
00331                         }
00332 
00333                         if ( sizeof( $m ) > 1 ) {
00334                                 $main = $m[0];
00335                                 for ( $i=1; $i<sizeof($m); $i += 1 ) {
00336                                         $mime = $m[$i];
00337                                         $this->mMimeTypeAliases[$mime] = $main;
00338                                 }
00339                         }
00340                 }
00341 
00342         }
00343 
00348         public static function &singleton() {
00349                 if ( !isset( self::$instance ) ) {
00350                         self::$instance = new MimeMagic;
00351                 }
00352                 return self::$instance;
00353         }
00354 
00363         public function getExtensionsForType( $mime ) {
00364                 $mime = strtolower( $mime );
00365 
00366                 // Check the mime-to-ext map
00367                 if ( isset( $this->mMimeToExt[$mime] ) ) {
00368                         return $this->mMimeToExt[$mime];
00369                 }
00370 
00371                 // Resolve the mime type to the canonical type
00372                 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
00373                         $mime = $this->mMimeTypeAliases[$mime];
00374                         if ( isset( $this->mMimeToExt[$mime] ) ) {
00375                                 return $this->mMimeToExt[$mime];
00376                         }
00377                 }
00378 
00379                 return null;
00380         }
00381 
00389         public function getTypesForExtension( $ext ) {
00390                 $ext = strtolower( $ext );
00391 
00392                 $r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null;
00393                 return $r;
00394         }
00395 
00403         public function guessTypesForExtension( $ext ) {
00404                 $m = $this->getTypesForExtension( $ext );
00405                 if ( is_null( $m ) ) {
00406                         return null;
00407                 }
00408 
00409                 // TODO: Check if this is needed; strtok( $m, ' ' ) should be sufficient
00410                 $m = trim( $m );
00411                 $m = preg_replace( '/\s.*$/', '', $m );
00412 
00413                 return $m;
00414         }
00415 
00416 
00426         public function isMatchingExtension( $extension, $mime ) {
00427                 $ext = $this->getExtensionsForType( $mime );
00428 
00429                 if ( !$ext ) {
00430                         return null;  // Unknown mime type
00431                 }
00432 
00433                 $ext = explode( ' ', $ext );
00434 
00435                 $extension = strtolower( $extension );
00436                 return  in_array( $extension, $ext );
00437         }
00438 
00447         public function isPHPImageType( $mime ) {
00448                 // As defined by imagegetsize and image_type_to_mime
00449                 static $types = array(
00450                         'image/gif', 'image/jpeg', 'image/png',
00451                         'image/x-bmp', 'image/xbm', 'image/tiff',
00452                         'image/jp2', 'image/jpeg2000', 'image/iff',
00453                         'image/xbm', 'image/x-xbitmap',
00454                         'image/vnd.wap.wbmp', 'image/vnd.xiff',
00455                         'image/x-photoshop',
00456                         'application/x-shockwave-flash',
00457                 );
00458 
00459                 return in_array( $mime, $types );
00460         }
00461 
00473         function isRecognizableExtension( $extension ) {
00474                 static $types = array(
00475                         // Types recognized by getimagesize()
00476                         'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
00477                         'bmp', 'tiff', 'tif', 'jpc', 'jp2',
00478                         'jpx', 'jb2', 'swc', 'iff', 'wbmp',
00479                         'xbm',
00480 
00481                         // Formats we recognize magic numbers for
00482                         'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx',
00483                         'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
00484                         'webp',
00485 
00486                         // XML formats we sure hope we recognize reliably
00487                         'svg',
00488                 );
00489                 return in_array( strtolower( $extension ), $types );
00490         }
00491 
00511         public function improveTypeFromExtension( $mime, $ext ) {
00512                 if ( $mime === 'unknown/unknown' ) {
00513                         if ( $this->isRecognizableExtension( $ext ) ) {
00514                                 wfDebug( __METHOD__. ': refusing to guess mime type for .' . 
00515                                         "$ext file, we should have recognized it\n" );
00516                         } else {
00517                                 // Not something we can detect, so simply 
00518                                 // trust the file extension
00519                                 $mime = $this->guessTypesForExtension( $ext );
00520                         }
00521                 }
00522                 elseif ( $mime === 'application/x-opc+zip' ) {
00523                         if ( $this->isMatchingExtension( $ext, $mime ) ) {
00524                                 // A known file extension for an OPC file,
00525                                 // find the proper mime type for that file extension
00526                                 $mime = $this->guessTypesForExtension( $ext );
00527                         } else {
00528                                 wfDebug( __METHOD__. ": refusing to guess better type for $mime file, " . 
00529                                         ".$ext is not a known OPC extension.\n" );
00530                                 $mime = 'application/zip';
00531                         }
00532                 }
00533 
00534                 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
00535                         $mime = $this->mMimeTypeAliases[$mime];
00536                 }
00537 
00538                 wfDebug(__METHOD__.": improved mime type for .$ext: $mime\n");
00539                 return $mime;
00540         }
00541 
00556         public function guessMimeType( $file, $ext = true ) {
00557                 if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
00558                         wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. " .
00559                                 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
00560                 }
00561 
00562                 $mime = $this->doGuessMimeType( $file, $ext );
00563 
00564                 if( !$mime ) {
00565                         wfDebug( __METHOD__.": internal type detection failed for $file (.$ext)...\n" );
00566                         $mime = $this->detectMimeType( $file, $ext );
00567                 }
00568 
00569                 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
00570                         $mime = $this->mMimeTypeAliases[$mime];
00571                 }
00572 
00573                 wfDebug(__METHOD__.": guessed mime type of $file: $mime\n");
00574                 return $mime;
00575         }
00576 
00584         private function doGuessMimeType( $file, $ext ) { // TODO: remove $ext param
00585                 // Read a chunk of the file
00586                 wfSuppressWarnings();
00587                 // @todo FIXME: Shouldn't this be rb?
00588                 $f = fopen( $file, 'rt' );
00589                 wfRestoreWarnings();
00590                 
00591                 if( !$f ) {
00592                         return 'unknown/unknown';
00593                 }
00594                 $head = fread( $f, 1024 );
00595                 fseek( $f, -65558, SEEK_END );
00596                 $tail = fread( $f, 65558 ); // 65558 = maximum size of a zip EOCDR
00597                 fclose( $f );
00598 
00599                 wfDebug( __METHOD__ . ": analyzing head and tail of $file for magic numbers.\n" );
00600 
00601                 // Hardcode a few magic number checks...
00602                 $headers = array(
00603                         // Multimedia...
00604                         'MThd'             => 'audio/midi',
00605                         'OggS'             => 'application/ogg',
00606 
00607                         // Image formats...
00608                         // Note that WMF may have a bare header, no magic number.
00609                         "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
00610                         "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
00611                         '%PDF'             => 'application/pdf',
00612                         'gimp xcf'         => 'image/x-xcf',
00613 
00614                         // Some forbidden fruit...
00615                         'MZ'               => 'application/octet-stream', // DOS/Windows executable
00616                         "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
00617                         "\x7fELF"          => 'application/octet-stream', // ELF binary
00618                 );
00619 
00620                 foreach ( $headers as $magic => $candidate ) {
00621                         if ( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
00622                                 wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
00623                                 return $candidate;
00624                         }
00625                 }
00626 
00627                 /* Look for WebM and Matroska files */
00628                 if ( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
00629                         $doctype = strpos( $head, "\x42\x82" );
00630                         if ( $doctype ) {
00631                                 // Next byte is datasize, then data (sizes larger than 1 byte are very stupid muxers)
00632                                 $data = substr($head, $doctype+3, 8);
00633                                 if ( strncmp( $data, "matroska", 8 ) == 0 ) {
00634                                         wfDebug( __METHOD__ . ": recognized file as video/x-matroska\n" );
00635                                         return "video/x-matroska";
00636                                 } elseif ( strncmp( $data, "webm", 4 ) == 0 ) {
00637                                         wfDebug( __METHOD__ . ": recognized file as video/webm\n" );
00638                                         return "video/webm";
00639                                 }
00640                         }
00641                         wfDebug( __METHOD__ . ": unknown EBML file\n" );
00642                         return "unknown/unknown";
00643                 }
00644 
00645                 /* Look for WebP */
00646                 if ( strncmp( $head, "RIFF", 4 ) == 0 && strncmp( substr( $head, 8, 8), "WEBPVP8 ", 8 ) == 0 ) {
00647                         wfDebug( __METHOD__ . ": recognized file as image/webp\n" );
00648                         return "image/webp";
00649                 }
00650 
00663                 if ( ( strpos( $head, '<?php' ) !== false ) ||
00664 
00665                     ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
00666                     ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
00667                     ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
00668                     ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
00669                     ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
00670 
00671                         wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
00672                         return 'application/x-php';
00673                 }
00674 
00678                 $xml = new XmlTypeCheck( $file );
00679                 if ( $xml->wellFormed ) {
00680                         global $wgXMLMimeTypes;
00681                         if ( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
00682                                 return $wgXMLMimeTypes[$xml->getRootElement()];
00683                         } else {
00684                                 return 'application/xml';
00685                         }
00686                 }
00687 
00691                 $script_type = null;
00692 
00693                 # detect by shebang
00694                 if ( substr( $head, 0, 2) == "#!" ) {
00695                         $script_type = "ASCII";
00696                 } elseif ( substr( $head, 0, 5) == "\xef\xbb\xbf#!" ) {
00697                         $script_type = "UTF-8";
00698                 } elseif ( substr( $head, 0, 7) == "\xfe\xff\x00#\x00!" ) {
00699                         $script_type = "UTF-16BE";
00700                 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
00701                         $script_type= "UTF-16LE";
00702                 }
00703 
00704                 if ( $script_type ) {
00705                         if ( $script_type !== "UTF-8" && $script_type !== "ASCII") {
00706                                 // Quick and dirty fold down to ASCII!
00707                                 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
00708                                 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
00709                                 $head = '';
00710                                 foreach( $chars as $codepoint ) {
00711                                         if( $codepoint < 128 ) {
00712                                                 $head .= chr( $codepoint );
00713                                         } else {
00714                                                 $head .= '?';
00715                                         }
00716                                 }
00717                         }
00718 
00719                         $match = array();
00720 
00721                         if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
00722                                 $mime = "application/x-{$match[2]}";
00723                                 wfDebug( __METHOD__.": shell script recognized as $mime\n" );
00724                                 return $mime;
00725                         }
00726                 }
00727 
00728                 // Check for ZIP variants (before getimagesize)
00729                 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
00730                         wfDebug( __METHOD__.": ZIP header present in $file\n" );
00731                         return $this->detectZipType( $head, $tail, $ext );
00732                 }
00733 
00734                 wfSuppressWarnings();
00735                 $gis = getimagesize( $file );
00736                 wfRestoreWarnings();
00737 
00738                 if( $gis && isset( $gis['mime'] ) ) {
00739                         $mime = $gis['mime'];
00740                         wfDebug( __METHOD__.": getimagesize detected $file as $mime\n" );
00741                         return $mime;
00742                 }
00743 
00744                 // Also test DjVu
00745                 $deja = new DjVuImage( $file );
00746                 if( $deja->isValid() ) {
00747                         wfDebug( __METHOD__.": detected $file as image/vnd.djvu\n" );
00748                         return 'image/vnd.djvu';
00749                 }
00750 
00751                 return false;
00752         }
00753         
00767         function detectZipType( $header, $tail = null, $ext = false ) {
00768                 if( $ext ) { # TODO: remove $ext param
00769                         wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. " .
00770                                 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
00771                 }
00772 
00773                 $mime = 'application/zip';
00774                 $opendocTypes = array(
00775                         'chart-template',
00776                         'chart',
00777                         'formula-template',
00778                         'formula',
00779                         'graphics-template',
00780                         'graphics',
00781                         'image-template',
00782                         'image',
00783                         'presentation-template',
00784                         'presentation',
00785                         'spreadsheet-template',
00786                         'spreadsheet',
00787                         'text-template',
00788                         'text-master',
00789                         'text-web',
00790                         'text' );
00791 
00792                 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
00793                 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
00794                 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
00795 
00796                 $openxmlRegex = "/^\[Content_Types\].xml/";
00797 
00798                 if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
00799                         $mime = $matches[1];
00800                         wfDebug( __METHOD__.": detected $mime from ZIP archive\n" );
00801                 } elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
00802                         $mime = "application/x-opc+zip";
00803                         # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere 
00804                         if ( $ext !== true && $ext !== false ) { 
00809                                 if ( $this->isMatchingExtension( $ext, $mime) ) {
00810                                         /* A known file extension for an OPC file,
00811                                         * find the proper mime type for that file extension */
00812                                         $mime = $this->guessTypesForExtension( $ext );
00813                                 } else {
00814                                         $mime = "application/zip";
00815                                 }
00816                         }
00817                         wfDebug( __METHOD__.": detected an Open Packaging Conventions archive: $mime\n" );
00818                 } elseif ( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" && 
00819                                 ($headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
00820                                 preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
00821                         if ( substr( $header, 512, 4) == "\xEC\xA5\xC1\x00" ) {
00822                                 $mime = "application/msword";
00823                         } 
00824                         switch( substr( $header, 512, 6) ) {
00825                                 case "\xEC\xA5\xC1\x00\x0E\x00":
00826                                 case "\xEC\xA5\xC1\x00\x1C\x00":
00827                                 case "\xEC\xA5\xC1\x00\x43\x00":
00828                                         $mime = "application/vnd.ms-powerpoint";
00829                                         break;
00830                                 case "\xFD\xFF\xFF\xFF\x10\x00":
00831                                 case "\xFD\xFF\xFF\xFF\x1F\x00":
00832                                 case "\xFD\xFF\xFF\xFF\x22\x00":
00833                                 case "\xFD\xFF\xFF\xFF\x23\x00":
00834                                 case "\xFD\xFF\xFF\xFF\x28\x00":
00835                                 case "\xFD\xFF\xFF\xFF\x29\x00":
00836                                 case "\xFD\xFF\xFF\xFF\x10\x02":
00837                                 case "\xFD\xFF\xFF\xFF\x1F\x02":
00838                                 case "\xFD\xFF\xFF\xFF\x22\x02":
00839                                 case "\xFD\xFF\xFF\xFF\x23\x02":
00840                                 case "\xFD\xFF\xFF\xFF\x28\x02":
00841                                 case "\xFD\xFF\xFF\xFF\x29\x02":
00842                                         $mime = "application/vnd.msexcel";
00843                                         break;
00844                         }
00845 
00846                         wfDebug( __METHOD__.": detected a MS Office document with OPC trailer\n");
00847                 } else {
00848                         wfDebug( __METHOD__.": unable to identify type of ZIP archive\n" );
00849                 }
00850                 return $mime;
00851         }
00852 
00871         private function detectMimeType( $file, $ext = true ) {
00872                 global $wgMimeDetectorCommand;
00873 
00874                 if ( $ext ) { # TODO:  make $ext default to false. Or better, remove it.
00875                         wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
00876                 }
00877 
00878                 $m = null;
00879                 if ( $wgMimeDetectorCommand ) {
00880                         // @todo FIXME: Use wfShellExec
00881                         $fn = wfEscapeShellArg( $file );
00882                         $m = `$wgMimeDetectorCommand $fn`;
00883                 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
00884 
00885                         # This required the fileinfo extension by PECL,
00886                         # see http://pecl.php.net/package/fileinfo
00887                         # This must be compiled into PHP
00888                         #
00889                         # finfo is the official replacement for the deprecated
00890                         # mime_content_type function, see below.
00891                         #
00892                         # If you may need to load the fileinfo extension at runtime, set
00893                         # $wgLoadFileinfoExtension in LocalSettings.php
00894 
00895                         $mime_magic_resource = finfo_open( FILEINFO_MIME ); /* return mime type ala mimetype extension */
00896 
00897                         if ( $mime_magic_resource ) {
00898                                 $m = finfo_file( $mime_magic_resource, $file );
00899                                 finfo_close( $mime_magic_resource );
00900                         } else {
00901                                 wfDebug( __METHOD__.": finfo_open failed on ".FILEINFO_MIME."!\n" );
00902                         }
00903                 } elseif ( function_exists( "mime_content_type" ) ) {
00904 
00905                         # NOTE: this function is available since PHP 4.3.0, but only if
00906                         # PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
00907                         #
00908                         # On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundeled with PHP;
00909                         # sometimes, this may even be needed under linus/unix.
00910                         #
00911                         # Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
00912                         # see http://www.php.net/manual/en/ref.mime-magic.php for details.
00913 
00914                         $m = mime_content_type($file);
00915                 } else {
00916                         wfDebug( __METHOD__.": no magic mime detector found!\n" );
00917                 }
00918 
00919                 if ( $m ) {
00920                         # normalize
00921                         $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
00922                         $m = trim( $m );
00923                         $m = strtolower( $m );
00924 
00925                         if ( strpos( $m, 'unknown' ) !== false ) {
00926                                 $m = null;
00927                         } else {
00928                                 wfDebug( __METHOD__.": magic mime type of $file: $m\n" );
00929                                 return $m;
00930                         }
00931                 }
00932 
00933                 // If desired, look at extension as a fallback.
00934                 if ( $ext === true ) {
00935                         $i = strrpos( $file, '.' );
00936                         $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
00937                 }
00938                 if ( $ext ) {
00939                         if( $this->isRecognizableExtension( $ext ) ) {
00940                                 wfDebug( __METHOD__. ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
00941                         } else {
00942                                 $m = $this->guessTypesForExtension( $ext );
00943                                 if ( $m ) {
00944                                         wfDebug( __METHOD__.": extension mime type of $file: $m\n" );
00945                                         return $m;
00946                                 }
00947                         }
00948                 }
00949 
00950                 // Unknown type
00951                 wfDebug( __METHOD__ . ": failed to guess mime type for $file!\n" );
00952                 return 'unknown/unknown';
00953         }
00954 
00971         function getMediaType( $path = null, $mime = null ) {
00972                 if( !$mime && !$path ) {
00973                         return MEDIATYPE_UNKNOWN;
00974                 }
00975 
00976                 // If mime type is unknown, guess it
00977                 if( !$mime ) {
00978                         $mime = $this->guessMimeType( $path, false );
00979                 }
00980 
00981                 // Special code for ogg - detect if it's video (theora),
00982                 // else label it as sound.
00983                 if ( $mime == 'application/ogg' && file_exists( $path ) ) {
00984 
00985                         // Read a chunk of the file
00986                         $f = fopen( $path, "rt" );
00987                         if ( !$f ) return MEDIATYPE_UNKNOWN;
00988                         $head = fread( $f, 256 );
00989                         fclose( $f );
00990 
00991                         $head = strtolower( $head );
00992 
00993                         // This is an UGLY HACK, file should be parsed correctly
00994                         if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
00995                         elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
00996                         elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
00997                         elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
00998                         else return MEDIATYPE_MULTIMEDIA;
00999                 }
01000 
01001                 // Check for entry for full mime type
01002                 if( $mime ) {
01003                         $type = $this->findMediaType( $mime );
01004                         if ( $type !== MEDIATYPE_UNKNOWN ) {
01005                                 return $type;
01006                         }
01007                 }
01008 
01009                 // Check for entry for file extension
01010                 if ( $path ) {
01011                         $i = strrpos( $path, '.' );
01012                         $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
01013 
01014                         // TODO: look at multi-extension if this fails, parse from full path
01015                         $type = $this->findMediaType( '.' . $e );
01016                         if ( $type !== MEDIATYPE_UNKNOWN ) {
01017                                 return $type;
01018                         }
01019                 }
01020 
01021                 // Check major mime type
01022                 if ( $mime ) {
01023                         $i = strpos( $mime, '/' );
01024                         if ( $i !== false ) {
01025                                 $major = substr( $mime, 0, $i );
01026                                 $type = $this->findMediaType( $major );
01027                                 if ( $type !== MEDIATYPE_UNKNOWN ) {
01028                                         return $type;
01029                                 }
01030                         }
01031                 }
01032 
01033                 if( !$type ) {
01034                         $type = MEDIATYPE_UNKNOWN;
01035                 }
01036 
01037                 return $type;
01038         }
01039 
01049         function findMediaType( $extMime ) {
01050                 if ( strpos( $extMime, '.' ) === 0 ) { 
01051                         // If it's an extension, look up the mime types
01052                         $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
01053                         if ( !$m ) {
01054                                 return MEDIATYPE_UNKNOWN;
01055                         }
01056 
01057                         $m = explode( ' ', $m );
01058                 } else {
01059                         // Normalize mime type
01060                         if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
01061                                 $extMime = $this->mMimeTypeAliases[$extMime];
01062                         }
01063 
01064                         $m = array( $extMime );
01065                 }
01066 
01067                 foreach ( $m as $mime ) {
01068                         foreach ( $this->mMediaTypes as $type => $codes ) {
01069                                 if ( in_array($mime, $codes, true ) ) {
01070                                         return $type;
01071                                 }
01072                         }
01073                 }
01074 
01075                 return MEDIATYPE_UNKNOWN;
01076         }
01077 
01087         public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
01088                 $ca = $this->getIEContentAnalyzer();
01089                 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
01090         }
01091 
01097         protected function getIEContentAnalyzer() {
01098                 if ( is_null( $this->mIEAnalyzer ) ) {
01099                         $this->mIEAnalyzer = new IEContentAnalyzer;
01100                 }
01101                 return $this->mIEAnalyzer;
01102         }
01103 }