3 * Module defining helper functions for detecting and dealing with mime types.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Defines a set of well known mime types
25 * This is used as a fallback to mime.types files.
26 * An extensive list of well known mime types is provided by
27 * the file mime.types in the includes directory.
29 * This list concatenated with mime.types is used to create a mime <-> ext
30 * map. Each line contains a mime type followed by a space separated list of
31 * extensions. If multiple extensions for a single mime type exist or if
32 * multiple mime types exist for a single extension then in most cases
33 * MediaWiki assumes that the first extension following the mime type is the
34 * canonical extension, and the first time a mime type appears for a certain
35 * extension is considered the canonical mime type.
37 * (Note that appending $wgMimeTypeFile to the end of MM_WELL_KNOWN_MIME_TYPES
38 * sucks because you can't redefine canonical types. This could be fixed by
39 * appending MM_WELL_KNOWN_MIME_TYPES behind $wgMimeTypeFile, but who knows
40 * what will break? In practice this probably isn't a problem anyway -- Bryan)
42 define( 'MM_WELL_KNOWN_MIME_TYPES', <<<END_STRING
43 application/ogg ogx ogg ogm ogv oga spx
45 application/vnd.oasis.opendocument.chart odc
46 application/vnd.oasis.opendocument.chart-template otc
47 application/vnd.oasis.opendocument.database odb
48 application/vnd.oasis.opendocument.formula odf
49 application/vnd.oasis.opendocument.formula-template otf
50 application/vnd.oasis.opendocument.graphics odg
51 application/vnd.oasis.opendocument.graphics-template otg
52 application/vnd.oasis.opendocument.image odi
53 application/vnd.oasis.opendocument.image-template oti
54 application/vnd.oasis.opendocument.presentation odp
55 application/vnd.oasis.opendocument.presentation-template otp
56 application/vnd.oasis.opendocument.spreadsheet ods
57 application/vnd.oasis.opendocument.spreadsheet-template ots
58 application/vnd.oasis.opendocument.text odt
59 application/vnd.oasis.opendocument.text-master otm
60 application/vnd.oasis.opendocument.text-template ott
61 application/vnd.oasis.opendocument.text-web oth
62 application/x-javascript js
63 application/x-shockwave-flash swf
64 audio/midi mid midi kar
65 audio/mpeg mpga mpa mp2 mp3
66 audio/x-aiff aif aiff aifc
71 image/jpeg jpeg jpg jpe
79 image/x-portable-pixmap ppm
89 * Defines a set of well known mime info entries
90 * This is used as a fallback to mime.info files.
91 * An extensive list of well known mime types is provided by
92 * the file mime.info in the includes directory.
94 define( 'MM_WELL_KNOWN_MIME_INFO', <<<END_STRING
95 application/pdf [OFFICE]
96 application/vnd.oasis.opendocument.chart [OFFICE]
97 application/vnd.oasis.opendocument.chart-template [OFFICE]
98 application/vnd.oasis.opendocument.database [OFFICE]
99 application/vnd.oasis.opendocument.formula [OFFICE]
100 application/vnd.oasis.opendocument.formula-template [OFFICE]
101 application/vnd.oasis.opendocument.graphics [OFFICE]
102 application/vnd.oasis.opendocument.graphics-template [OFFICE]
103 application/vnd.oasis.opendocument.image [OFFICE]
104 application/vnd.oasis.opendocument.image-template [OFFICE]
105 application/vnd.oasis.opendocument.presentation [OFFICE]
106 application/vnd.oasis.opendocument.presentation-template [OFFICE]
107 application/vnd.oasis.opendocument.spreadsheet [OFFICE]
108 application/vnd.oasis.opendocument.spreadsheet-template [OFFICE]
109 application/vnd.oasis.opendocument.text [OFFICE]
110 application/vnd.oasis.opendocument.text-template [OFFICE]
111 application/vnd.oasis.opendocument.text-master [OFFICE]
112 application/vnd.oasis.opendocument.text-web [OFFICE]
113 text/javascript application/x-javascript [EXECUTABLE]
114 application/x-shockwave-flash [MULTIMEDIA]
118 audio/mp3 audio/mpeg [AUDIO]
119 application/ogg audio/ogg video/ogg [MULTIMEDIA]
120 image/x-bmp image/x-ms-bmp image/bmp [BITMAP]
124 image/svg+xml [DRAWING]
126 image/vnd.djvu [BITMAP]
128 image/x-portable-pixmap [BITMAP]
133 unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
138 * Implements functions related to mime types such as detection and mapping to
141 * Instances of this class are stateless, there only needs to be one global instance
142 * of MimeMagic. Please use MimeMagic::singleton() to get that instance.
146 * @var array Mapping of media types to arrays of mime types.
147 * This is used by findMediaType and getMediaType, respectively
149 protected $mMediaTypes = null;
151 /** @var array Map of mime type aliases
153 protected $mMimeTypeAliases = null;
155 /** @var array Map of mime types to file extensions (as a space separated list)
157 protected $mMimeToExt = null;
159 /** @var array Map of file extensions types to mime types (as a space separated list)
161 public $mExtToMime = null;
163 /** @var IEContentAnalyzer
165 protected $mIEAnalyzer;
167 /** @var MimeMagic The singleton instance
169 private static $instance = null;
171 /** Initializes the MimeMagic object. This is called by MimeMagic::singleton().
173 * This constructor parses the mime.types and mime.info files and build internal mappings.
175 function __construct() {
177 * --- load mime.types ---
180 global $wgMimeTypeFile, $IP;
182 $types = MM_WELL_KNOWN_MIME_TYPES;
184 if ( $wgMimeTypeFile == 'includes/mime.types' ) {
185 $wgMimeTypeFile = "$IP/$wgMimeTypeFile";
188 if ( $wgMimeTypeFile ) {
189 if ( is_file( $wgMimeTypeFile ) and is_readable( $wgMimeTypeFile ) ) {
190 wfDebug( __METHOD__ . ": loading mime types from $wgMimeTypeFile\n" );
192 $types .= file_get_contents( $wgMimeTypeFile );
194 wfDebug( __METHOD__ . ": can't load mime types from $wgMimeTypeFile\n" );
197 wfDebug( __METHOD__ . ": no mime types file defined, using build-ins only.\n" );
200 $types = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $types );
201 $types = str_replace( "\t", " ", $types );
203 $this->mMimeToExt = array();
204 $this->mToMime = array();
206 $lines = explode( "\n", $types );
207 foreach ( $lines as $s ) {
212 if ( strpos( $s, '#' ) === 0 ) {
216 $s = strtolower( $s );
217 $i = strpos( $s, ' ' );
219 if ( $i === false ) {
223 $mime = substr( $s, 0, $i );
224 $ext = trim( substr( $s, $i + 1 ) );
226 if ( empty( $ext ) ) {
230 if ( !empty( $this->mMimeToExt[$mime] ) ) {
231 $this->mMimeToExt[$mime] .= ' ' . $ext;
233 $this->mMimeToExt[$mime] = $ext;
236 $extensions = explode( ' ', $ext );
238 foreach ( $extensions as $e ) {
244 if ( !empty( $this->mExtToMime[$e] ) ) {
245 $this->mExtToMime[$e] .= ' ' . $mime;
247 $this->mExtToMime[$e] = $mime;
253 * --- load mime.info ---
256 global $wgMimeInfoFile;
257 if ( $wgMimeInfoFile == 'includes/mime.info' ) {
258 $wgMimeInfoFile = "$IP/$wgMimeInfoFile";
261 $info = MM_WELL_KNOWN_MIME_INFO;
263 if ( $wgMimeInfoFile ) {
264 if ( is_file( $wgMimeInfoFile ) and is_readable( $wgMimeInfoFile ) ) {
265 wfDebug( __METHOD__ . ": loading mime info from $wgMimeInfoFile\n" );
267 $info .= file_get_contents( $wgMimeInfoFile );
269 wfDebug( __METHOD__ . ": can't load mime info from $wgMimeInfoFile\n" );
272 wfDebug( __METHOD__ . ": no mime info file defined, using build-ins only.\n" );
275 $info = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $info );
276 $info = str_replace( "\t", " ", $info );
278 $this->mMimeTypeAliases = array();
279 $this->mMediaTypes = array();
281 $lines = explode( "\n", $info );
282 foreach ( $lines as $s ) {
287 if ( strpos( $s, '#' ) === 0 ) {
291 $s = strtolower( $s );
292 $i = strpos( $s, ' ' );
294 if ( $i === false ) {
298 #print "processing MIME INFO line $s<br>";
301 if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
302 $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
303 $mtype = trim( strtoupper( $match[1] ) );
305 $mtype = MEDIATYPE_UNKNOWN;
308 $m = explode( ' ', $s );
310 if ( !isset( $this->mMediaTypes[$mtype] ) ) {
311 $this->mMediaTypes[$mtype] = array();
314 foreach ( $m as $mime ) {
315 $mime = trim( $mime );
316 if ( empty( $mime ) ) {
320 $this->mMediaTypes[$mtype][] = $mime;
323 if ( count( $m ) > 1 ) {
325 $mCount = count( $m );
326 for ( $i = 1; $i < $mCount; $i += 1 ) {
328 $this->mMimeTypeAliases[$mime] = $main;
335 * Get an instance of this class
338 public static function singleton() {
339 if ( self::$instance === null ) {
340 self::$instance = new MimeMagic;
342 return self::$instance;
346 * Returns a list of file extensions for a given mime type as a space
347 * separated string or null if the mime type was unrecognized. Resolves
350 * @param string $mime
351 * @return string|null
353 public function getExtensionsForType( $mime ) {
354 $mime = strtolower( $mime );
356 // Check the mime-to-ext map
357 if ( isset( $this->mMimeToExt[$mime] ) ) {
358 return $this->mMimeToExt[$mime];
361 // Resolve the mime type to the canonical type
362 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
363 $mime = $this->mMimeTypeAliases[$mime];
364 if ( isset( $this->mMimeToExt[$mime] ) ) {
365 return $this->mMimeToExt[$mime];
373 * Returns a list of mime types for a given file extension as a space
374 * separated string or null if the extension was unrecognized.
377 * @return string|null
379 public function getTypesForExtension( $ext ) {
380 $ext = strtolower( $ext );
382 $r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null;
387 * Returns a single mime type for a given file extension or null if unknown.
388 * This is always the first type from the list returned by getTypesForExtension($ext).
391 * @return string|null
393 public function guessTypesForExtension( $ext ) {
394 $m = $this->getTypesForExtension( $ext );
395 if ( is_null( $m ) ) {
399 // TODO: Check if this is needed; strtok( $m, ' ' ) should be sufficient
401 $m = preg_replace( '/\s.*$/', '', $m );
407 * Tests if the extension matches the given mime type. Returns true if a
408 * match was found, null if the mime type is unknown, and false if the
409 * mime type is known but no matches where found.
411 * @param string $extension
412 * @param string $mime
415 public function isMatchingExtension( $extension, $mime ) {
416 $ext = $this->getExtensionsForType( $mime );
419 return null; // Unknown mime type
422 $ext = explode( ' ', $ext );
424 $extension = strtolower( $extension );
425 return in_array( $extension, $ext );
429 * Returns true if the mime type is known to represent an image format
430 * supported by the PHP GD library.
432 * @param string $mime
436 public function isPHPImageType( $mime ) {
437 // As defined by imagegetsize and image_type_to_mime
438 static $types = array(
439 'image/gif', 'image/jpeg', 'image/png',
440 'image/x-bmp', 'image/xbm', 'image/tiff',
441 'image/jp2', 'image/jpeg2000', 'image/iff',
442 'image/xbm', 'image/x-xbitmap',
443 'image/vnd.wap.wbmp', 'image/vnd.xiff',
445 'application/x-shockwave-flash',
448 return in_array( $mime, $types );
452 * Returns true if the extension represents a type which can
453 * be reliably detected from its content. Use this to determine
454 * whether strict content checks should be applied to reject
455 * invalid uploads; if we can't identify the type we won't
456 * be able to say if it's invalid.
458 * @todo Be more accurate when using fancy mime detector plugins;
459 * right now this is the bare minimum getimagesize() list.
460 * @param string $extension
463 function isRecognizableExtension( $extension ) {
464 static $types = array(
465 // Types recognized by getimagesize()
466 'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
467 'bmp', 'tiff', 'tif', 'jpc', 'jp2',
468 'jpx', 'jb2', 'swc', 'iff', 'wbmp',
471 // Formats we recognize magic numbers for
472 'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx',
473 'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
476 // XML formats we sure hope we recognize reliably
479 return in_array( strtolower( $extension ), $types );
483 * Improves a mime type using the file extension. Some file formats are very generic,
484 * so their mime type is not very meaningful. A more useful mime type can be derived
485 * by looking at the file extension. Typically, this method would be called on the
486 * result of guessMimeType().
488 * @param string $mime The mime type, typically guessed from a file's content.
489 * @param string $ext The file extension, as taken from the file name
491 * @return string The mime type
493 public function improveTypeFromExtension( $mime, $ext ) {
494 if ( $mime === 'unknown/unknown' ) {
495 if ( $this->isRecognizableExtension( $ext ) ) {
496 wfDebug( __METHOD__ . ': refusing to guess mime type for .' .
497 "$ext file, we should have recognized it\n" );
499 // Not something we can detect, so simply
500 // trust the file extension
501 $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';
513 } elseif ( $mime === 'text/plain' && $this->findMediaType( ".$ext" ) === MEDIATYPE_TEXT ) {
514 // Textual types are sometimes not recognized properly.
515 // If detected as text/plain, and has an extension which is textual
516 // improve to the extension's type. For example, csv and json are often
517 // misdetected as text/plain.
518 $mime = $this->guessTypesForExtension( $ext );
521 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
522 $mime = $this->mMimeTypeAliases[$mime];
525 wfDebug( __METHOD__ . ": improved mime type for .$ext: $mime\n" );
530 * Mime type detection. This uses detectMimeType to detect the mime type
531 * of the file, but applies additional checks to determine some well known
532 * file formats that may be missed or misinterpreted by the default mime
533 * detection (namely XML based formats like XHTML or SVG, as well as ZIP
534 * based formats like OPC/ODF files).
536 * @param string $file The file to check
537 * @param string|bool $ext The file extension, or true (default) to extract it from the filename.
538 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
539 * improveTypeFromExtension($mime, $ext) later to improve mime type.
541 * @return string The mime type of $file
543 public function guessMimeType( $file, $ext = true ) {
544 if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
545 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. " .
546 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
549 $mime = $this->doGuessMimeType( $file, $ext );
552 wfDebug( __METHOD__ . ": internal type detection failed for $file (.$ext)...\n" );
553 $mime = $this->detectMimeType( $file, $ext );
556 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
557 $mime = $this->mMimeTypeAliases[$mime];
560 wfDebug( __METHOD__ . ": guessed mime type of $file: $mime\n" );
565 * Guess the mime type from the file contents.
567 * @param string $file
569 * @return bool|string
570 * @throws MWException
572 private function doGuessMimeType( $file, $ext ) { // TODO: remove $ext param
573 // Read a chunk of the file
574 wfSuppressWarnings();
575 $f = fopen( $file, 'rb' );
579 return 'unknown/unknown';
582 $fsize = filesize( $file );
583 if ( $fsize === false ) {
584 return 'unknown/unknown';
587 $head = fread( $f, 1024 );
588 $tailLength = min( 65558, $fsize ); // 65558 = maximum size of a zip EOCDR
589 if ( fseek( $f, -1 * $tailLength, SEEK_END ) === -1 ) {
590 throw new MWException(
591 "Seeking $tailLength bytes from EOF failed in " . __METHOD__ );
593 $tail = fread( $f, $tailLength );
596 wfDebug( __METHOD__ . ": analyzing head and tail of $file for magic numbers.\n" );
598 // Hardcode a few magic number checks...
601 'MThd' => 'audio/midi',
602 'OggS' => 'application/ogg',
605 // Note that WMF may have a bare header, no magic number.
606 "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
607 "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
608 '%PDF' => 'application/pdf',
609 'gimp xcf' => 'image/x-xcf',
611 // Some forbidden fruit...
612 'MZ' => 'application/octet-stream', // DOS/Windows executable
613 "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
614 "\x7fELF" => 'application/octet-stream', // ELF binary
617 foreach ( $headers as $magic => $candidate ) {
618 if ( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
619 wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
624 /* Look for WebM and Matroska files */
625 if ( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
626 $doctype = strpos( $head, "\x42\x82" );
628 // Next byte is datasize, then data (sizes larger than 1 byte are very stupid muxers)
629 $data = substr( $head, $doctype + 3, 8 );
630 if ( strncmp( $data, "matroska", 8 ) == 0 ) {
631 wfDebug( __METHOD__ . ": recognized file as video/x-matroska\n" );
632 return "video/x-matroska";
633 } elseif ( strncmp( $data, "webm", 4 ) == 0 ) {
634 wfDebug( __METHOD__ . ": recognized file as video/webm\n" );
638 wfDebug( __METHOD__ . ": unknown EBML file\n" );
639 return "unknown/unknown";
643 if ( strncmp( $head, "RIFF", 4 ) == 0 && strncmp( substr( $head, 8, 8 ), "WEBPVP8 ", 8 ) == 0 ) {
644 wfDebug( __METHOD__ . ": recognized file as image/webp\n" );
649 * Look for PHP. Check for this before HTML/XML... Warning: this is a
650 * heuristic, and won't match a file with a lot of non-PHP before. It
651 * will also match text files which could be PHP. :)
653 * @todo FIXME: For this reason, the check is probably useless -- an attacker
654 * could almost certainly just pad the file with a lot of nonsense to
655 * circumvent the check in any case where it would be a security
656 * problem. On the other hand, it causes harmful false positives (bug
657 * 16583). The heuristic has been cut down to exclude three-character
658 * strings like "<? ", but should it be axed completely?
660 if ( ( strpos( $head, '<?php' ) !== false ) ||
661 ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
662 ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
663 ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
664 ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
665 ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
667 wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
668 return 'application/x-php';
672 * look for XML formats (XHTML and SVG)
674 $xml = new XmlTypeCheck( $file );
675 if ( $xml->wellFormed ) {
676 global $wgXMLMimeTypes;
677 if ( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
678 return $wgXMLMimeTypes[$xml->getRootElement()];
680 return 'application/xml';
685 * look for shell scripts
690 if ( substr( $head, 0, 2 ) == "#!" ) {
691 $script_type = "ASCII";
692 } elseif ( substr( $head, 0, 5 ) == "\xef\xbb\xbf#!" ) {
693 $script_type = "UTF-8";
694 } elseif ( substr( $head, 0, 7 ) == "\xfe\xff\x00#\x00!" ) {
695 $script_type = "UTF-16BE";
696 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
697 $script_type = "UTF-16LE";
700 if ( $script_type ) {
701 if ( $script_type !== "UTF-8" && $script_type !== "ASCII" ) {
702 // Quick and dirty fold down to ASCII!
703 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
704 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
706 foreach ( $chars as $codepoint ) {
707 if ( $codepoint < 128 ) {
708 $head .= chr( $codepoint );
717 if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
718 $mime = "application/x-{$match[2]}";
719 wfDebug( __METHOD__ . ": shell script recognized as $mime\n" );
724 // Check for ZIP variants (before getimagesize)
725 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
726 wfDebug( __METHOD__ . ": ZIP header present in $file\n" );
727 return $this->detectZipType( $head, $tail, $ext );
730 wfSuppressWarnings();
731 $gis = getimagesize( $file );
734 if ( $gis && isset( $gis['mime'] ) ) {
735 $mime = $gis['mime'];
736 wfDebug( __METHOD__ . ": getimagesize detected $file as $mime\n" );
741 $deja = new DjVuImage( $file );
742 if ( $deja->isValid() ) {
743 wfDebug( __METHOD__ . ": detected $file as image/vnd.djvu\n" );
744 return 'image/vnd.djvu';
751 * Detect application-specific file type of a given ZIP file from its
752 * header data. Currently works for OpenDocument and OpenXML types...
753 * If can't tell, returns 'application/zip'.
755 * @param string $header Some reasonably-sized chunk of file header
756 * @param string|null $tail The tail of the file
757 * @param string|bool $ext The file extension, or true to extract it from the filename.
758 * Set it to false (default) to ignore the extension. DEPRECATED! Set to false,
759 * use improveTypeFromExtension($mime, $ext) later to improve mime type.
763 function detectZipType( $header, $tail = null, $ext = false ) {
764 if ( $ext ) { # TODO: remove $ext param
765 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. " .
766 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
769 $mime = 'application/zip';
770 $opendocTypes = array(
779 'presentation-template',
781 'spreadsheet-template',
788 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
789 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
790 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
792 $openxmlRegex = "/^\[Content_Types\].xml/";
794 if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
796 wfDebug( __METHOD__ . ": detected $mime from ZIP archive\n" );
797 } elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
798 $mime = "application/x-opc+zip";
799 # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
800 if ( $ext !== true && $ext !== false ) {
801 /** This is the mode used by getPropsFromPath
802 * These mime's are stored in the database, where we don't really want
803 * x-opc+zip, because we use it only for internal purposes
805 if ( $this->isMatchingExtension( $ext, $mime ) ) {
806 /* A known file extension for an OPC file,
807 * find the proper mime type for that file extension
809 $mime = $this->guessTypesForExtension( $ext );
811 $mime = "application/zip";
814 wfDebug( __METHOD__ . ": detected an Open Packaging Conventions archive: $mime\n" );
815 } elseif ( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" &&
816 ( $headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
817 preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
818 if ( substr( $header, 512, 4 ) == "\xEC\xA5\xC1\x00" ) {
819 $mime = "application/msword";
821 switch ( substr( $header, 512, 6 ) ) {
822 case "\xEC\xA5\xC1\x00\x0E\x00":
823 case "\xEC\xA5\xC1\x00\x1C\x00":
824 case "\xEC\xA5\xC1\x00\x43\x00":
825 $mime = "application/vnd.ms-powerpoint";
827 case "\xFD\xFF\xFF\xFF\x10\x00":
828 case "\xFD\xFF\xFF\xFF\x1F\x00":
829 case "\xFD\xFF\xFF\xFF\x22\x00":
830 case "\xFD\xFF\xFF\xFF\x23\x00":
831 case "\xFD\xFF\xFF\xFF\x28\x00":
832 case "\xFD\xFF\xFF\xFF\x29\x00":
833 case "\xFD\xFF\xFF\xFF\x10\x02":
834 case "\xFD\xFF\xFF\xFF\x1F\x02":
835 case "\xFD\xFF\xFF\xFF\x22\x02":
836 case "\xFD\xFF\xFF\xFF\x23\x02":
837 case "\xFD\xFF\xFF\xFF\x28\x02":
838 case "\xFD\xFF\xFF\xFF\x29\x02":
839 $mime = "application/vnd.msexcel";
843 wfDebug( __METHOD__ . ": detected a MS Office document with OPC trailer\n" );
845 wfDebug( __METHOD__ . ": unable to identify type of ZIP archive\n" );
851 * Internal mime type detection. Detection is done using an external
852 * program, if $wgMimeDetectorCommand is set. Otherwise, the fileinfo
853 * extension and mime_content_type are tried (in this order), if they
854 * are available. If the detections fails and $ext is not false, the mime
855 * type is guessed from the file extension, using guessTypesForExtension.
857 * If the mime type is still unknown, getimagesize is used to detect the
858 * mime type if the file is an image. If no mime type can be determined,
859 * this function returns 'unknown/unknown'.
861 * @param string $file The file to check
862 * @param string|bool $ext The file extension, or true (default) to extract it from the filename.
863 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
864 * improveTypeFromExtension($mime, $ext) later to improve mime type.
866 * @return string The mime type of $file
868 private function detectMimeType( $file, $ext = true ) {
869 global $wgMimeDetectorCommand;
871 /** @todo Make $ext default to false. Or better, remove it. */
873 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. "
874 . "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
878 if ( $wgMimeDetectorCommand ) {
879 $args = wfEscapeShellArg( $file );
880 $m = wfShellExec( "$wgMimeDetectorCommand $args" );
881 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
883 # This required the fileinfo extension by PECL,
884 # see http://pecl.php.net/package/fileinfo
885 # This must be compiled into PHP
887 # finfo is the official replacement for the deprecated
888 # mime_content_type function, see below.
890 # If you may need to load the fileinfo extension at runtime, set
891 # $wgLoadFileinfoExtension in LocalSettings.php
893 $mime_magic_resource = finfo_open( FILEINFO_MIME ); /* return mime type ala mimetype extension */
895 if ( $mime_magic_resource ) {
896 $m = finfo_file( $mime_magic_resource, $file );
897 finfo_close( $mime_magic_resource );
899 wfDebug( __METHOD__ . ": finfo_open failed on " . FILEINFO_MIME . "!\n" );
901 } elseif ( function_exists( "mime_content_type" ) ) {
903 # NOTE: this function is available since PHP 4.3.0, but only if
904 # PHP was compiled with --with-mime-magic or, before 4.3.2, with
905 # --enable-mime-magic.
907 # On Windows, you must set mime_magic.magicfile in php.ini to point
908 # to the mime.magic file bundled with PHP; sometimes, this may even
909 # be needed under *nix.
911 # Also note that this has been DEPRECATED in favor of the fileinfo
912 # extension by PECL, see above.
913 # See http://www.php.net/manual/en/ref.mime-magic.php for details.
915 $m = mime_content_type( $file );
917 wfDebug( __METHOD__ . ": no magic mime detector found!\n" );
922 $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
924 $m = strtolower( $m );
926 if ( strpos( $m, 'unknown' ) !== false ) {
929 wfDebug( __METHOD__ . ": magic mime type of $file: $m\n" );
934 // If desired, look at extension as a fallback.
935 if ( $ext === true ) {
936 $i = strrpos( $file, '.' );
937 $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
940 if ( $this->isRecognizableExtension( $ext ) ) {
941 wfDebug( __METHOD__ . ": refusing to guess mime type for .$ext file, "
942 . "we should have recognized it\n" );
944 $m = $this->guessTypesForExtension( $ext );
946 wfDebug( __METHOD__ . ": extension mime type of $file: $m\n" );
953 wfDebug( __METHOD__ . ": failed to guess mime type for $file!\n" );
954 return 'unknown/unknown';
958 * Determine the media type code for a file, using its mime type, name and
959 * possibly its contents.
961 * This function relies on the findMediaType(), mapping extensions and mime
962 * types to media types.
964 * @todo analyse file if need be
965 * @todo look at multiple extension, separately and together.
967 * @param string $path Full path to the image file, in case we have to look at the contents
968 * (if null, only the mime type is used to determine the media type code).
969 * @param string $mime Mime type. If null it will be guessed using guessMimeType.
971 * @return string A value to be used with the MEDIATYPE_xxx constants.
973 function getMediaType( $path = null, $mime = null ) {
974 if ( !$mime && !$path ) {
975 return MEDIATYPE_UNKNOWN;
978 // If mime type is unknown, guess it
980 $mime = $this->guessMimeType( $path, false );
983 // Special code for ogg - detect if it's video (theora),
984 // else label it as sound.
985 if ( $mime == 'application/ogg' && file_exists( $path ) ) {
987 // Read a chunk of the file
988 $f = fopen( $path, "rt" );
990 return MEDIATYPE_UNKNOWN;
992 $head = fread( $f, 256 );
995 $head = str_replace( 'ffmpeg2theora', '', strtolower( $head ) );
997 // This is an UGLY HACK, file should be parsed correctly
998 if ( strpos( $head, 'theora' ) !== false ) {
999 return MEDIATYPE_VIDEO;
1000 } elseif ( strpos( $head, 'vorbis' ) !== false ) {
1001 return MEDIATYPE_AUDIO;
1002 } elseif ( strpos( $head, 'flac' ) !== false ) {
1003 return MEDIATYPE_AUDIO;
1004 } elseif ( strpos( $head, 'speex' ) !== false ) {
1005 return MEDIATYPE_AUDIO;
1007 return MEDIATYPE_MULTIMEDIA;
1011 // Check for entry for full mime type
1013 $type = $this->findMediaType( $mime );
1014 if ( $type !== MEDIATYPE_UNKNOWN ) {
1019 // Check for entry for file extension
1021 $i = strrpos( $path, '.' );
1022 $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1024 // TODO: look at multi-extension if this fails, parse from full path
1025 $type = $this->findMediaType( '.' . $e );
1026 if ( $type !== MEDIATYPE_UNKNOWN ) {
1031 // Check major mime type
1033 $i = strpos( $mime, '/' );
1034 if ( $i !== false ) {
1035 $major = substr( $mime, 0, $i );
1036 $type = $this->findMediaType( $major );
1037 if ( $type !== MEDIATYPE_UNKNOWN ) {
1044 $type = MEDIATYPE_UNKNOWN;
1051 * Returns a media code matching the given mime type or file extension.
1052 * File extensions are represented by a string starting with a dot (.) to
1053 * distinguish them from mime types.
1055 * This function relies on the mapping defined by $this->mMediaTypes
1057 * @param string $extMime
1058 * @return int|string
1060 function findMediaType( $extMime ) {
1061 if ( strpos( $extMime, '.' ) === 0 ) {
1062 // If it's an extension, look up the mime types
1063 $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
1065 return MEDIATYPE_UNKNOWN;
1068 $m = explode( ' ', $m );
1070 // Normalize mime type
1071 if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
1072 $extMime = $this->mMimeTypeAliases[$extMime];
1075 $m = array( $extMime );
1078 foreach ( $m as $mime ) {
1079 foreach ( $this->mMediaTypes as $type => $codes ) {
1080 if ( in_array( $mime, $codes, true ) ) {
1086 return MEDIATYPE_UNKNOWN;
1090 * Get the MIME types that various versions of Internet Explorer would
1091 * detect from a chunk of the content.
1093 * @param string $fileName The file name (unused at present)
1094 * @param string $chunk The first 256 bytes of the file
1095 * @param string $proposed The MIME type proposed by the server
1098 public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
1099 $ca = $this->getIEContentAnalyzer();
1100 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
1104 * Get a cached instance of IEContentAnalyzer
1106 * @return IEContentAnalyzer
1108 protected function getIEContentAnalyzer() {
1109 if ( is_null( $this->mIEAnalyzer ) ) {
1110 $this->mIEAnalyzer = new IEContentAnalyzer;
1112 return $this->mIEAnalyzer;