de32dccdd4734868db5f73968300f974df048918
3 * Module defining helper functions for detecting and dealing with mime types.
9 * Defines a set of well known mime types
10 * This is used as a fallback to mime.types files.
11 * An extensive list of well known mime types is provided by
12 * the file mime.types in the includes directory.
14 * This list concatenated with mime.types is used to create a mime <-> ext
15 * map. Each line contains a mime type followed by a space separated list of
16 * extensions. If multiple extensions for a single mime type exist or if
17 * multiple mime types exist for a single extension then in most cases
18 * MediaWiki assumes that the first extension following the mime type is the
19 * canonical extension, and the first time a mime type appears for a certain
20 * extension is considered the canonical mime type.
22 * (Note that appending $wgMimeTypeFile to the end of MM_WELL_KNOWN_MIME_TYPES
23 * sucks because you can't redefine canonical types. This could be fixed by
24 * appending MM_WELL_KNOWN_MIME_TYPES behind $wgMimeTypeFile, but who knows
25 * what will break? In practice this probably isn't a problem anyway -- Bryan)
27 define('MM_WELL_KNOWN_MIME_TYPES',<<<END_STRING
28 application/ogg ogx ogg ogm ogv oga spx
30 application/vnd.oasis.opendocument.chart odc
31 application/vnd.oasis.opendocument.chart-template otc
32 application/vnd.oasis.opendocument.formula odf
33 application/vnd.oasis.opendocument.formula-template otf
34 application/vnd.oasis.opendocument.graphics odg
35 application/vnd.oasis.opendocument.graphics-template otg
36 application/vnd.oasis.opendocument.image odi
37 application/vnd.oasis.opendocument.image-template oti
38 application/vnd.oasis.opendocument.presentation odp
39 application/vnd.oasis.opendocument.presentation-template otp
40 application/vnd.oasis.opendocument.spreadsheet ods
41 application/vnd.oasis.opendocument.spreadsheet-template ots
42 application/vnd.oasis.opendocument.text odt
43 application/vnd.oasis.opendocument.text-template ott
44 application/vnd.oasis.opendocument.text-master otm
45 application/vnd.oasis.opendocument.text-web oth
46 application/x-javascript js
47 application/x-shockwave-flash swf
48 audio/midi mid midi kar
49 audio/mpeg mpga mpa mp2 mp3
50 audio/x-aiff aif aiff aifc
55 image/jpeg jpeg jpg jpe
63 image/x-portable-pixmap ppm
73 * Defines a set of well known mime info entries
74 * This is used as a fallback to mime.info files.
75 * An extensive list of well known mime types is provided by
76 * the file mime.info in the includes directory.
78 define('MM_WELL_KNOWN_MIME_INFO', <<<END_STRING
79 application/pdf [OFFICE]
80 application/vnd.oasis.opendocument.chart [OFFICE]
81 application/vnd.oasis.opendocument.chart-template [OFFICE]
82 application/vnd.oasis.opendocument.formula [OFFICE]
83 application/vnd.oasis.opendocument.formula-template [OFFICE]
84 application/vnd.oasis.opendocument.graphics [OFFICE]
85 application/vnd.oasis.opendocument.graphics-template [OFFICE]
86 application/vnd.oasis.opendocument.image [OFFICE]
87 application/vnd.oasis.opendocument.image-template [OFFICE]
88 application/vnd.oasis.opendocument.presentation [OFFICE]
89 application/vnd.oasis.opendocument.presentation-template [OFFICE]
90 application/vnd.oasis.opendocument.spreadsheet [OFFICE]
91 application/vnd.oasis.opendocument.spreadsheet-template [OFFICE]
92 application/vnd.oasis.opendocument.text [OFFICE]
93 application/vnd.oasis.opendocument.text-template [OFFICE]
94 application/vnd.oasis.opendocument.text-master [OFFICE]
95 application/vnd.oasis.opendocument.text-web [OFFICE]
96 text/javascript application/x-javascript [EXECUTABLE]
97 application/x-shockwave-flash [MULTIMEDIA]
101 audio/mp3 audio/mpeg [AUDIO]
102 application/ogg audio/ogg video/ogg [MULTIMEDIA]
103 image/x-bmp image/x-ms-bmp image/bmp [BITMAP]
107 image/svg+xml [DRAWING]
109 image/vnd.djvu [BITMAP]
111 image/x-portable-pixmap [BITMAP]
116 unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
121 * Implements functions related to mime types such as detection and mapping to
124 * Instances of this class are stateles, there only needs to be one global instance
125 * of MimeMagic. Please use MimeMagic::singleton() to get that instance.
130 * Mapping of media types to arrays of mime types.
131 * This is used by findMediaType and getMediaType, respectively
133 var $mMediaTypes = null;
135 /** Map of mime type aliases
137 var $mMimeTypeAliases = null;
139 /** map of mime types to file extensions (as a space seprarated list)
141 var $mMimeToExt = null;
143 /** map of file extensions types to mime types (as a space seprarated list)
145 var $mExtToMime = null;
147 /** IEContentAnalyzer instance
151 /** The singleton instance
153 private static $instance;
155 /** True if the fileinfo extension has been loaded
157 private static $extensionLoaded = false;
159 /** Initializes the MimeMagic object. This is called by MimeMagic::singleton().
161 * This constructor parses the mime.types and mime.info files and build internal mappings.
163 function __construct() {
165 * --- load mime.types ---
168 global $wgMimeTypeFile, $IP, $wgLoadFileinfoExtension;
170 $types = MM_WELL_KNOWN_MIME_TYPES;
172 if ( $wgMimeTypeFile == 'includes/mime.types' ) {
173 $wgMimeTypeFile = "$IP/$wgMimeTypeFile";
176 if ( $wgLoadFileinfoExtension && !self::$extensionLoaded ) {
177 self::$extensionLoaded = true;
181 if ( $wgMimeTypeFile ) {
182 if ( is_file( $wgMimeTypeFile ) and is_readable( $wgMimeTypeFile ) ) {
183 wfDebug( __METHOD__.": loading mime types from $wgMimeTypeFile\n" );
185 $types .= file_get_contents( $wgMimeTypeFile );
187 wfDebug( __METHOD__.": can't load mime types from $wgMimeTypeFile\n" );
190 wfDebug( __METHOD__.": no mime types file defined, using build-ins only.\n" );
193 $types = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $types );
194 $types = str_replace( "\t", " ", $types );
196 $this->mMimeToExt = array();
197 $this->mToMime = array();
199 $lines = explode( "\n",$types );
200 foreach ( $lines as $s ) {
205 if ( strpos( $s, '#' ) === 0 ) {
209 $s = strtolower( $s );
210 $i = strpos( $s, ' ' );
212 if ( $i === false ) {
216 #print "processing MIME line $s<br>";
218 $mime = substr( $s, 0, $i );
219 $ext = trim( substr($s, $i+1 ) );
221 if ( empty( $ext ) ) {
225 if ( !empty( $this->mMimeToExt[$mime] ) ) {
226 $this->mMimeToExt[$mime] .= ' ' . $ext;
228 $this->mMimeToExt[$mime] = $ext;
231 $extensions = explode( ' ', $ext );
233 foreach ( $extensions as $e ) {
239 if ( !empty( $this->mExtToMime[$e] ) ) {
240 $this->mExtToMime[$e] .= ' ' . $mime;
242 $this->mExtToMime[$e] = $mime;
248 * --- load mime.info ---
251 global $wgMimeInfoFile;
252 if ( $wgMimeInfoFile == 'includes/mime.info' ) {
253 $wgMimeInfoFile = "$IP/$wgMimeInfoFile";
256 $info = MM_WELL_KNOWN_MIME_INFO;
258 if ( $wgMimeInfoFile ) {
259 if ( is_file( $wgMimeInfoFile ) and is_readable( $wgMimeInfoFile ) ) {
260 wfDebug( __METHOD__.": loading mime info from $wgMimeInfoFile\n" );
262 $info .= file_get_contents( $wgMimeInfoFile );
264 wfDebug(__METHOD__.": can't load mime info from $wgMimeInfoFile\n");
267 wfDebug(__METHOD__.": no mime info file defined, using build-ins only.\n");
270 $info = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $info);
271 $info = str_replace( "\t", " ", $info );
273 $this->mMimeTypeAliases = array();
274 $this->mMediaTypes = array();
276 $lines = explode( "\n", $info );
277 foreach ( $lines as $s ) {
282 if ( strpos( $s, '#' ) === 0 ) {
286 $s = strtolower( $s );
287 $i = strpos( $s, ' ' );
289 if ( $i === false ) {
293 #print "processing MIME INFO line $s<br>";
296 if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
297 $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
298 $mtype = trim( strtoupper( $match[1] ) );
300 $mtype = MEDIATYPE_UNKNOWN;
303 $m = explode( ' ', $s );
305 if ( !isset( $this->mMediaTypes[$mtype] ) ) {
306 $this->mMediaTypes[$mtype] = array();
309 foreach ( $m as $mime ) {
310 $mime = trim( $mime );
311 if ( empty( $mime ) ) {
315 $this->mMediaTypes[$mtype][] = $mime;
318 if ( sizeof( $m ) > 1 ) {
320 for ( $i=1; $i<sizeof($m); $i += 1 ) {
322 $this->mMimeTypeAliases[$mime] = $main;
330 * Get an instance of this class
333 public static function &singleton() {
334 if ( !isset( self::$instance ) ) {
335 self::$instance = new MimeMagic;
337 return self::$instance;
341 * Returns a list of file extensions for a given mime type as a space
342 * separated string or null if the mime type was unrecognized. Resolves
345 * @param $mime string
346 * @return string|null
348 public function getExtensionsForType( $mime ) {
349 $mime = strtolower( $mime );
351 // Check the mime-to-ext map
352 if ( isset( $this->mMimeToExt[$mime] ) ) {
353 return $this->mMimeToExt[$mime];
356 // Resolve the mime type to the canonical type
357 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
358 $mime = $this->mMimeTypeAliases[$mime];
359 if ( isset( $this->mMimeToExt[$mime] ) ) {
360 return $this->mMimeToExt[$mime];
368 * Returns a list of mime types for a given file extension as a space
369 * separated string or null if the extension was unrecognized.
372 * @return string|null
374 public function getTypesForExtension( $ext ) {
375 $ext = strtolower( $ext );
377 $r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null;
382 * Returns a single mime type for a given file extension or null if unknown.
383 * This is always the first type from the list returned by getTypesForExtension($ext).
386 * @return string|null
388 public function guessTypesForExtension( $ext ) {
389 $m = $this->getTypesForExtension( $ext );
390 if ( is_null( $m ) ) {
394 // TODO: Check if this is needed; strtok( $m, ' ' ) should be sufficient
396 $m = preg_replace( '/\s.*$/', '', $m );
403 * Tests if the extension matches the given mime type. Returns true if a
404 * match was found, null if the mime type is unknown, and false if the
405 * mime type is known but no matches where found.
407 * @param $extension string
408 * @param $mime string
411 public function isMatchingExtension( $extension, $mime ) {
412 $ext = $this->getExtensionsForType( $mime );
415 return null; // Unknown mime type
418 $ext = explode( ' ', $ext );
420 $extension = strtolower( $extension );
421 return in_array( $extension, $ext );
425 * Returns true if the mime type is known to represent an image format
426 * supported by the PHP GD library.
428 public function isPHPImageType( $mime ) {
429 // As defined by imagegetsize and image_type_to_mime
430 static $types = array(
431 'image/gif', 'image/jpeg', 'image/png',
432 'image/x-bmp', 'image/xbm', 'image/tiff',
433 'image/jp2', 'image/jpeg2000', 'image/iff',
434 'image/xbm', 'image/x-xbitmap',
435 'image/vnd.wap.wbmp', 'image/vnd.xiff',
437 'application/x-shockwave-flash',
440 return in_array( $mime, $types );
444 * Returns true if the extension represents a type which can
445 * be reliably detected from its content. Use this to determine
446 * whether strict content checks should be applied to reject
447 * invalid uploads; if we can't identify the type we won't
448 * be able to say if it's invalid.
450 * @todo Be more accurate when using fancy mime detector plugins;
451 * right now this is the bare minimum getimagesize() list.
454 function isRecognizableExtension( $extension ) {
455 static $types = array(
456 // Types recognized by getimagesize()
457 'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
458 'bmp', 'tiff', 'tif', 'jpc', 'jp2',
459 'jpx', 'jb2', 'swc', 'iff', 'wbmp',
462 // Formats we recognize magic numbers for
463 'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx',
464 'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
467 // XML formats we sure hope we recognize reliably
470 return in_array( strtolower( $extension ), $types );
474 * Improves a mime type using the file extension. Some file formats are very generic,
475 * so their mime type is not very meaningful. A more useful mime type can be derived
476 * by looking at the file extension. Typically, this method would be called on the
477 * result of guessMimeType().
479 * Currently, this method does the following:
481 * If $mime is "unknown/unknown" and isRecognizableExtension( $ext ) returns false,
482 * return the result of guessTypesForExtension($ext).
484 * If $mime is "application/x-opc+zip" and isMatchingExtension( $ext, $mime )
485 * gives true, return the result of guessTypesForExtension($ext).
487 * @param $mime String: the mime type, typically guessed from a file's content.
488 * @param $ext String: the file extension, as taken from the file name
490 * @return string the mime type
492 public function improveTypeFromExtension( $mime, $ext ) {
493 if ( $mime === 'unknown/unknown' ) {
494 if ( $this->isRecognizableExtension( $ext ) ) {
495 wfDebug( __METHOD__. ': refusing to guess mime type for .' .
496 "$ext file, we should have recognized it\n" );
498 // Not something we can detect, so simply
499 // trust the file extension
500 $mime = $this->guessTypesForExtension( $ext );
503 elseif ( $mime === 'application/x-opc+zip' ) {
504 if ( $this->isMatchingExtension( $ext, $mime ) ) {
505 // A known file extension for an OPC file,
506 // find the proper mime type for that file extension
507 $mime = $this->guessTypesForExtension( $ext );
509 wfDebug( __METHOD__. ": refusing to guess better type for $mime file, " .
510 ".$ext is not a known OPC extension.\n" );
511 $mime = 'application/zip';
515 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
516 $mime = $this->mMimeTypeAliases[$mime];
519 wfDebug(__METHOD__.": improved mime type for .$ext: $mime\n");
524 * Mime type detection. This uses detectMimeType to detect the mime type
525 * of the file, but applies additional checks to determine some well known
526 * file formats that may be missed or misinterpreter by the default mime
527 * detection (namely XML based formats like XHTML or SVG, as well as ZIP
528 * based formats like OPC/ODF files).
530 * @param $file String: the file to check
531 * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
532 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
533 * improveTypeFromExtension($mime, $ext) later to improve mime type.
535 * @return string the mime type of $file
537 public function guessMimeType( $file, $ext = true ) {
538 if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
539 wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. " .
540 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
543 $mime = $this->doGuessMimeType( $file, $ext );
546 wfDebug( __METHOD__.": internal type detection failed for $file (.$ext)...\n" );
547 $mime = $this->detectMimeType( $file, $ext );
550 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
551 $mime = $this->mMimeTypeAliases[$mime];
554 wfDebug(__METHOD__.": guessed mime type of $file: $mime\n");
559 * Guess the mime type from the file contents.
561 * @param string $file
564 private function doGuessMimeType( $file, $ext ) { // TODO: remove $ext param
565 // Read a chunk of the file
566 wfSuppressWarnings();
567 // @todo FIXME: Shouldn't this be rb?
568 $f = fopen( $file, 'rt' );
572 return 'unknown/unknown';
574 $head = fread( $f, 1024 );
575 fseek( $f, -65558, SEEK_END );
576 $tail = fread( $f, 65558 ); // 65558 = maximum size of a zip EOCDR
579 wfDebug( __METHOD__ . ": analyzing head and tail of $file for magic numbers.\n" );
581 // Hardcode a few magic number checks...
584 'MThd' => 'audio/midi',
585 'OggS' => 'application/ogg',
588 // Note that WMF may have a bare header, no magic number.
589 "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
590 "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
591 '%PDF' => 'application/pdf',
592 'gimp xcf' => 'image/x-xcf',
594 // Some forbidden fruit...
595 'MZ' => 'application/octet-stream', // DOS/Windows executable
596 "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
597 "\x7fELF" => 'application/octet-stream', // ELF binary
600 foreach ( $headers as $magic => $candidate ) {
601 if ( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
602 wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
607 /* Look for WebM and Matroska files */
608 if ( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
609 $doctype = strpos( $head, "\x42\x82" );
611 // Next byte is datasize, then data (sizes larger than 1 byte are very stupid muxers)
612 $data = substr($head, $doctype+3, 8);
613 if ( strncmp( $data, "matroska", 8 ) == 0 ) {
614 wfDebug( __METHOD__ . ": recognized file as video/x-matroska\n" );
615 return "video/x-matroska";
616 } elseif ( strncmp( $data, "webm", 4 ) == 0 ) {
617 wfDebug( __METHOD__ . ": recognized file as video/webm\n" );
621 wfDebug( __METHOD__ . ": unknown EBML file\n" );
622 return "unknown/unknown";
626 if ( strncmp( $head, "RIFF", 4 ) == 0 && strncmp( substr( $head, 8, 8), "WEBPVP8 ", 8 ) == 0 ) {
627 wfDebug( __METHOD__ . ": recognized file as image/webp\n" );
632 * Look for PHP. Check for this before HTML/XML... Warning: this is a
633 * heuristic, and won't match a file with a lot of non-PHP before. It
634 * will also match text files which could be PHP. :)
636 * @todo FIXME: For this reason, the check is probably useless -- an attacker
637 * could almost certainly just pad the file with a lot of nonsense to
638 * circumvent the check in any case where it would be a security
639 * problem. On the other hand, it causes harmful false positives (bug
640 * 16583). The heuristic has been cut down to exclude three-character
641 * strings like "<? ", but should it be axed completely?
643 if ( ( strpos( $head, '<?php' ) !== false ) ||
645 ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
646 ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
647 ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
648 ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
649 ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
651 wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
652 return 'application/x-php';
656 * look for XML formats (XHTML and SVG)
658 $xml = new XmlTypeCheck( $file );
659 if ( $xml->wellFormed ) {
660 global $wgXMLMimeTypes;
661 if ( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
662 return $wgXMLMimeTypes[$xml->getRootElement()];
664 return 'application/xml';
669 * look for shell scripts
674 if ( substr( $head, 0, 2) == "#!" ) {
675 $script_type = "ASCII";
676 } elseif ( substr( $head, 0, 5) == "\xef\xbb\xbf#!" ) {
677 $script_type = "UTF-8";
678 } elseif ( substr( $head, 0, 7) == "\xfe\xff\x00#\x00!" ) {
679 $script_type = "UTF-16BE";
680 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
681 $script_type= "UTF-16LE";
684 if ( $script_type ) {
685 if ( $script_type !== "UTF-8" && $script_type !== "ASCII") {
686 // Quick and dirty fold down to ASCII!
687 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
688 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
690 foreach( $chars as $codepoint ) {
691 if( $codepoint < 128 ) {
692 $head .= chr( $codepoint );
701 if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
702 $mime = "application/x-{$match[2]}";
703 wfDebug( __METHOD__.": shell script recognized as $mime\n" );
708 // Check for ZIP variants (before getimagesize)
709 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
710 wfDebug( __METHOD__.": ZIP header present in $file\n" );
711 return $this->detectZipType( $head, $tail, $ext );
714 wfSuppressWarnings();
715 $gis = getimagesize( $file );
718 if( $gis && isset( $gis['mime'] ) ) {
719 $mime = $gis['mime'];
720 wfDebug( __METHOD__.": getimagesize detected $file as $mime\n" );
725 $deja = new DjVuImage( $file );
726 if( $deja->isValid() ) {
727 wfDebug( __METHOD__.": detected $file as image/vnd.djvu\n" );
728 return 'image/vnd.djvu';
735 * Detect application-specific file type of a given ZIP file from its
736 * header data. Currently works for OpenDocument and OpenXML types...
737 * If can't tell, returns 'application/zip'.
739 * @param $header String: some reasonably-sized chunk of file header
740 * @param $tail String: the tail of the file
741 * @param $ext Mixed: the file extension, or true to extract it from the filename.
742 * Set it to false (default) to ignore the extension. DEPRECATED! Set to false,
743 * use improveTypeFromExtension($mime, $ext) later to improve mime type.
747 function detectZipType( $header, $tail = null, $ext = false ) {
748 if( $ext ) { # TODO: remove $ext param
749 wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. " .
750 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
753 $mime = 'application/zip';
754 $opendocTypes = array(
763 'presentation-template',
765 'spreadsheet-template',
772 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
773 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
774 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
776 $openxmlRegex = "/^\[Content_Types\].xml/";
778 if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
780 wfDebug( __METHOD__.": detected $mime from ZIP archive\n" );
781 } elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
782 $mime = "application/x-opc+zip";
783 # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
784 if ( $ext !== true && $ext !== false ) {
785 /** This is the mode used by getPropsFromPath
786 * These mime's are stored in the database, where we don't really want
787 * x-opc+zip, because we use it only for internal purposes
789 if ( $this->isMatchingExtension( $ext, $mime) ) {
790 /* A known file extension for an OPC file,
791 * find the proper mime type for that file extension */
792 $mime = $this->guessTypesForExtension( $ext );
794 $mime = "application/zip";
797 wfDebug( __METHOD__.": detected an Open Packaging Conventions archive: $mime\n" );
798 } elseif ( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" &&
799 ($headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
800 preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
801 if ( substr( $header, 512, 4) == "\xEC\xA5\xC1\x00" ) {
802 $mime = "application/msword";
804 switch( substr( $header, 512, 6) ) {
805 case "\xEC\xA5\xC1\x00\x0E\x00":
806 case "\xEC\xA5\xC1\x00\x1C\x00":
807 case "\xEC\xA5\xC1\x00\x43\x00":
808 $mime = "application/vnd.ms-powerpoint";
810 case "\xFD\xFF\xFF\xFF\x10\x00":
811 case "\xFD\xFF\xFF\xFF\x1F\x00":
812 case "\xFD\xFF\xFF\xFF\x22\x00":
813 case "\xFD\xFF\xFF\xFF\x23\x00":
814 case "\xFD\xFF\xFF\xFF\x28\x00":
815 case "\xFD\xFF\xFF\xFF\x29\x00":
816 case "\xFD\xFF\xFF\xFF\x10\x02":
817 case "\xFD\xFF\xFF\xFF\x1F\x02":
818 case "\xFD\xFF\xFF\xFF\x22\x02":
819 case "\xFD\xFF\xFF\xFF\x23\x02":
820 case "\xFD\xFF\xFF\xFF\x28\x02":
821 case "\xFD\xFF\xFF\xFF\x29\x02":
822 $mime = "application/vnd.msexcel";
826 wfDebug( __METHOD__.": detected a MS Office document with OPC trailer\n");
828 wfDebug( __METHOD__.": unable to identify type of ZIP archive\n" );
834 * Internal mime type detection. Detection is done using an external
835 * program, if $wgMimeDetectorCommand is set. Otherwise, the fileinfo
836 * extension and mime_content_type are tried (in this order), if they
837 * are available. If the dections fails and $ext is not false, the mime
838 * type is guessed from the file extension, using guessTypesForExtension.
840 * If the mime type is still unknown, getimagesize is used to detect the
841 * mime type if the file is an image. If no mime type can be determined,
842 * this function returns 'unknown/unknown'.
844 * @param $file String: the file to check
845 * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
846 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
847 * improveTypeFromExtension($mime, $ext) later to improve mime type.
849 * @return string the mime type of $file
851 private function detectMimeType( $file, $ext = true ) {
852 global $wgMimeDetectorCommand;
854 if ( $ext ) { # TODO: make $ext default to false. Or better, remove it.
855 wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
859 if ( $wgMimeDetectorCommand ) {
860 // @todo FIXME: Use wfShellExec
861 $fn = wfEscapeShellArg( $file );
862 $m = `$wgMimeDetectorCommand $fn`;
863 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
865 # This required the fileinfo extension by PECL,
866 # see http://pecl.php.net/package/fileinfo
867 # This must be compiled into PHP
869 # finfo is the official replacement for the deprecated
870 # mime_content_type function, see below.
872 # If you may need to load the fileinfo extension at runtime, set
873 # $wgLoadFileinfoExtension in LocalSettings.php
875 $mime_magic_resource = finfo_open( FILEINFO_MIME ); /* return mime type ala mimetype extension */
877 if ( $mime_magic_resource ) {
878 $m = finfo_file( $mime_magic_resource, $file );
879 finfo_close( $mime_magic_resource );
881 wfDebug( __METHOD__.": finfo_open failed on ".FILEINFO_MIME."!\n" );
883 } elseif ( function_exists( "mime_content_type" ) ) {
885 # NOTE: this function is available since PHP 4.3.0, but only if
886 # PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
888 # On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundeled with PHP;
889 # sometimes, this may even be needed under linus/unix.
891 # Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
892 # see http://www.php.net/manual/en/ref.mime-magic.php for details.
894 $m = mime_content_type($file);
896 wfDebug( __METHOD__.": no magic mime detector found!\n" );
901 $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
903 $m = strtolower( $m );
905 if ( strpos( $m, 'unknown' ) !== false ) {
908 wfDebug( __METHOD__.": magic mime type of $file: $m\n" );
913 // If desired, look at extension as a fallback.
914 if ( $ext === true ) {
915 $i = strrpos( $file, '.' );
916 $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
919 if( $this->isRecognizableExtension( $ext ) ) {
920 wfDebug( __METHOD__. ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
922 $m = $this->guessTypesForExtension( $ext );
924 wfDebug( __METHOD__.": extension mime type of $file: $m\n" );
931 wfDebug( __METHOD__ . ": failed to guess mime type for $file!\n" );
932 return 'unknown/unknown';
936 * Determine the media type code for a file, using its mime type, name and
937 * possibly its contents.
939 * This function relies on the findMediaType(), mapping extensions and mime
940 * types to media types.
942 * @todo analyse file if need be
943 * @todo look at multiple extension, separately and together.
945 * @param $path String: full path to the image file, in case we have to look at the contents
946 * (if null, only the mime type is used to determine the media type code).
947 * @param $mime String: mime type. If null it will be guessed using guessMimeType.
949 * @return (int?string?) a value to be used with the MEDIATYPE_xxx constants.
951 function getMediaType( $path = null, $mime = null ) {
952 if( !$mime && !$path ) {
953 return MEDIATYPE_UNKNOWN;
956 // If mime type is unknown, guess it
958 $mime = $this->guessMimeType( $path, false );
961 // Special code for ogg - detect if it's video (theora),
962 // else label it as sound.
963 if ( $mime == 'application/ogg' && file_exists( $path ) ) {
965 // Read a chunk of the file
966 $f = fopen( $path, "rt" );
967 if ( !$f ) return MEDIATYPE_UNKNOWN;
968 $head = fread( $f, 256 );
971 $head = strtolower( $head );
973 // This is an UGLY HACK, file should be parsed correctly
974 if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
975 elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
976 elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
977 elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
978 else return MEDIATYPE_MULTIMEDIA;
981 // Check for entry for full mime type
983 $type = $this->findMediaType( $mime );
984 if ( $type !== MEDIATYPE_UNKNOWN ) {
989 // Check for entry for file extension
991 $i = strrpos( $path, '.' );
992 $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
994 // TODO: look at multi-extension if this fails, parse from full path
995 $type = $this->findMediaType( '.' . $e );
996 if ( $type !== MEDIATYPE_UNKNOWN ) {
1001 // Check major mime type
1003 $i = strpos( $mime, '/' );
1004 if ( $i !== false ) {
1005 $major = substr( $mime, 0, $i );
1006 $type = $this->findMediaType( $major );
1007 if ( $type !== MEDIATYPE_UNKNOWN ) {
1014 $type = MEDIATYPE_UNKNOWN;
1021 * Returns a media code matching the given mime type or file extension.
1022 * File extensions are represented by a string starting with a dot (.) to
1023 * distinguish them from mime types.
1025 * This funktion relies on the mapping defined by $this->mMediaTypes
1028 function findMediaType( $extMime ) {
1029 if ( strpos( $extMime, '.' ) === 0 ) {
1030 // If it's an extension, look up the mime types
1031 $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
1033 return MEDIATYPE_UNKNOWN;
1036 $m = explode( ' ', $m );
1038 // Normalize mime type
1039 if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
1040 $extMime = $this->mMimeTypeAliases[$extMime];
1043 $m = array( $extMime );
1046 foreach ( $m as $mime ) {
1047 foreach ( $this->mMediaTypes as $type => $codes ) {
1048 if ( in_array($mime, $codes, true ) ) {
1054 return MEDIATYPE_UNKNOWN;
1058 * Get the MIME types that various versions of Internet Explorer would
1059 * detect from a chunk of the content.
1061 * @param $fileName String: the file name (unused at present)
1062 * @param $chunk String: the first 256 bytes of the file
1063 * @param $proposed String: the MIME type proposed by the server
1065 public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
1066 $ca = $this->getIEContentAnalyzer();
1067 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
1071 * Get a cached instance of IEContentAnalyzer
1073 * @return IEContentAnalyzer
1075 protected function getIEContentAnalyzer() {
1076 if ( is_null( $this->mIEAnalyzer ) ) {
1077 $this->mIEAnalyzer = new IEContentAnalyzer;
1079 return $this->mIEAnalyzer;