Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / includes / MimeMagic.php
blob11fc5741476394c292fc46d7c170b4ac6b766488
1 <?php
2 /**
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
20 * @file
23 /**
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
44 application/pdf pdf
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
67 audio/x-wav wav
68 audio/ogg oga spx ogg
69 image/x-bmp bmp
70 image/gif gif
71 image/jpeg jpeg jpg jpe
72 image/png png
73 image/svg+xml svg
74 image/svg svg
75 image/tiff tiff tif
76 image/vnd.djvu djvu
77 image/x.djvu djvu
78 image/x-djvu djvu
79 image/x-portable-pixmap ppm
80 image/x-xcf xcf
81 text/plain txt
82 text/html html htm
83 video/ogg ogv ogm ogg
84 video/mpeg mpg mpeg
85 END_STRING
88 /**
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]
115 audio/midi [AUDIO]
116 audio/x-aiff [AUDIO]
117 audio/x-wav [AUDIO]
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]
121 image/gif [BITMAP]
122 image/jpeg [BITMAP]
123 image/png [BITMAP]
124 image/svg+xml [DRAWING]
125 image/tiff [BITMAP]
126 image/vnd.djvu [BITMAP]
127 image/x-xcf [BITMAP]
128 image/x-portable-pixmap [BITMAP]
129 text/plain [TEXT]
130 text/html [TEXT]
131 video/ogg [VIDEO]
132 video/mpeg [VIDEO]
133 unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
134 END_STRING
138 * Implements functions related to mime types such as detection and mapping to
139 * file extension.
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.
144 class MimeMagic {
147 * Mapping of media types to arrays of mime types.
148 * This is used by findMediaType and getMediaType, respectively
150 var $mMediaTypes = null;
152 /** Map of mime type aliases
154 var $mMimeTypeAliases = null;
156 /** map of mime types to file extensions (as a space separated list)
158 var $mMimeToExt = null;
160 /** map of file extensions types to mime types (as a space separated list)
162 var $mExtToMime = null;
164 /** IEContentAnalyzer instance
166 var $mIEAnalyzer;
168 /** The singleton instance
170 private static $instance;
172 /** True if the fileinfo extension has been loaded
174 private static $extensionLoaded = false;
176 /** Initializes the MimeMagic object. This is called by MimeMagic::singleton().
178 * This constructor parses the mime.types and mime.info files and build internal mappings.
180 function __construct() {
182 * --- load mime.types ---
185 global $wgMimeTypeFile, $IP, $wgLoadFileinfoExtension;
187 $types = MM_WELL_KNOWN_MIME_TYPES;
189 if ( $wgMimeTypeFile == 'includes/mime.types' ) {
190 $wgMimeTypeFile = "$IP/$wgMimeTypeFile";
193 if ( $wgLoadFileinfoExtension && !self::$extensionLoaded ) {
194 self::$extensionLoaded = true;
195 wfDl( 'fileinfo' );
198 if ( $wgMimeTypeFile ) {
199 if ( is_file( $wgMimeTypeFile ) and is_readable( $wgMimeTypeFile ) ) {
200 wfDebug( __METHOD__ . ": loading mime types from $wgMimeTypeFile\n" );
201 $types .= "\n";
202 $types .= file_get_contents( $wgMimeTypeFile );
203 } else {
204 wfDebug( __METHOD__ . ": can't load mime types from $wgMimeTypeFile\n" );
206 } else {
207 wfDebug( __METHOD__ . ": no mime types file defined, using build-ins only.\n" );
210 $types = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $types );
211 $types = str_replace( "\t", " ", $types );
213 $this->mMimeToExt = array();
214 $this->mToMime = array();
216 $lines = explode( "\n", $types );
217 foreach ( $lines as $s ) {
218 $s = trim( $s );
219 if ( empty( $s ) ) {
220 continue;
222 if ( strpos( $s, '#' ) === 0 ) {
223 continue;
226 $s = strtolower( $s );
227 $i = strpos( $s, ' ' );
229 if ( $i === false ) {
230 continue;
233 $mime = substr( $s, 0, $i );
234 $ext = trim( substr( $s, $i + 1 ) );
236 if ( empty( $ext ) ) {
237 continue;
240 if ( !empty( $this->mMimeToExt[$mime] ) ) {
241 $this->mMimeToExt[$mime] .= ' ' . $ext;
242 } else {
243 $this->mMimeToExt[$mime] = $ext;
246 $extensions = explode( ' ', $ext );
248 foreach ( $extensions as $e ) {
249 $e = trim( $e );
250 if ( empty( $e ) ) {
251 continue;
254 if ( !empty( $this->mExtToMime[$e] ) ) {
255 $this->mExtToMime[$e] .= ' ' . $mime;
256 } else {
257 $this->mExtToMime[$e] = $mime;
263 * --- load mime.info ---
266 global $wgMimeInfoFile;
267 if ( $wgMimeInfoFile == 'includes/mime.info' ) {
268 $wgMimeInfoFile = "$IP/$wgMimeInfoFile";
271 $info = MM_WELL_KNOWN_MIME_INFO;
273 if ( $wgMimeInfoFile ) {
274 if ( is_file( $wgMimeInfoFile ) and is_readable( $wgMimeInfoFile ) ) {
275 wfDebug( __METHOD__ . ": loading mime info from $wgMimeInfoFile\n" );
276 $info .= "\n";
277 $info .= file_get_contents( $wgMimeInfoFile );
278 } else {
279 wfDebug( __METHOD__ . ": can't load mime info from $wgMimeInfoFile\n" );
281 } else {
282 wfDebug( __METHOD__ . ": no mime info file defined, using build-ins only.\n" );
285 $info = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $info );
286 $info = str_replace( "\t", " ", $info );
288 $this->mMimeTypeAliases = array();
289 $this->mMediaTypes = array();
291 $lines = explode( "\n", $info );
292 foreach ( $lines as $s ) {
293 $s = trim( $s );
294 if ( empty( $s ) ) {
295 continue;
297 if ( strpos( $s, '#' ) === 0 ) {
298 continue;
301 $s = strtolower( $s );
302 $i = strpos( $s, ' ' );
304 if ( $i === false ) {
305 continue;
308 #print "processing MIME INFO line $s<br>";
310 $match = array();
311 if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
312 $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
313 $mtype = trim( strtoupper( $match[1] ) );
314 } else {
315 $mtype = MEDIATYPE_UNKNOWN;
318 $m = explode( ' ', $s );
320 if ( !isset( $this->mMediaTypes[$mtype] ) ) {
321 $this->mMediaTypes[$mtype] = array();
324 foreach ( $m as $mime ) {
325 $mime = trim( $mime );
326 if ( empty( $mime ) ) {
327 continue;
330 $this->mMediaTypes[$mtype][] = $mime;
333 if ( count( $m ) > 1 ) {
334 $main = $m[0];
335 for ( $i = 1; $i < count( $m ); $i += 1 ) {
336 $mime = $m[$i];
337 $this->mMimeTypeAliases[$mime] = $main;
345 * Get an instance of this class
346 * @return MimeMagic
348 public static function &singleton() {
349 if ( self::$instance === null ) {
350 self::$instance = new MimeMagic;
352 return self::$instance;
356 * Returns a list of file extensions for a given mime type as a space
357 * separated string or null if the mime type was unrecognized. Resolves
358 * mime type aliases.
360 * @param $mime string
361 * @return string|null
363 public function getExtensionsForType( $mime ) {
364 $mime = strtolower( $mime );
366 // Check the mime-to-ext map
367 if ( isset( $this->mMimeToExt[$mime] ) ) {
368 return $this->mMimeToExt[$mime];
371 // Resolve the mime type to the canonical type
372 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
373 $mime = $this->mMimeTypeAliases[$mime];
374 if ( isset( $this->mMimeToExt[$mime] ) ) {
375 return $this->mMimeToExt[$mime];
379 return null;
383 * Returns a list of mime types for a given file extension as a space
384 * separated string or null if the extension was unrecognized.
386 * @param $ext string
387 * @return string|null
389 public function getTypesForExtension( $ext ) {
390 $ext = strtolower( $ext );
392 $r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null;
393 return $r;
397 * Returns a single mime type for a given file extension or null if unknown.
398 * This is always the first type from the list returned by getTypesForExtension($ext).
400 * @param $ext string
401 * @return string|null
403 public function guessTypesForExtension( $ext ) {
404 $m = $this->getTypesForExtension( $ext );
405 if ( is_null( $m ) ) {
406 return null;
409 // TODO: Check if this is needed; strtok( $m, ' ' ) should be sufficient
410 $m = trim( $m );
411 $m = preg_replace( '/\s.*$/', '', $m );
413 return $m;
417 * Tests if the extension matches the given mime type. Returns true if a
418 * match was found, null if the mime type is unknown, and false if the
419 * mime type is known but no matches where found.
421 * @param $extension string
422 * @param $mime string
423 * @return bool|null
425 public function isMatchingExtension( $extension, $mime ) {
426 $ext = $this->getExtensionsForType( $mime );
428 if ( !$ext ) {
429 return null; // Unknown mime type
432 $ext = explode( ' ', $ext );
434 $extension = strtolower( $extension );
435 return in_array( $extension, $ext );
439 * Returns true if the mime type is known to represent an image format
440 * supported by the PHP GD library.
442 * @param $mime string
444 * @return bool
446 public function isPHPImageType( $mime ) {
447 // As defined by imagegetsize and image_type_to_mime
448 static $types = array(
449 'image/gif', 'image/jpeg', 'image/png',
450 'image/x-bmp', 'image/xbm', 'image/tiff',
451 'image/jp2', 'image/jpeg2000', 'image/iff',
452 'image/xbm', 'image/x-xbitmap',
453 'image/vnd.wap.wbmp', 'image/vnd.xiff',
454 'image/x-photoshop',
455 'application/x-shockwave-flash',
458 return in_array( $mime, $types );
462 * Returns true if the extension represents a type which can
463 * be reliably detected from its content. Use this to determine
464 * whether strict content checks should be applied to reject
465 * invalid uploads; if we can't identify the type we won't
466 * be able to say if it's invalid.
468 * @todo Be more accurate when using fancy mime detector plugins;
469 * right now this is the bare minimum getimagesize() list.
470 * @return bool
472 function isRecognizableExtension( $extension ) {
473 static $types = array(
474 // Types recognized by getimagesize()
475 'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
476 'bmp', 'tiff', 'tif', 'jpc', 'jp2',
477 'jpx', 'jb2', 'swc', 'iff', 'wbmp',
478 'xbm',
480 // Formats we recognize magic numbers for
481 'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx',
482 'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
483 'webp',
485 // XML formats we sure hope we recognize reliably
486 'svg',
488 return in_array( strtolower( $extension ), $types );
492 * Improves a mime type using the file extension. Some file formats are very generic,
493 * so their mime type is not very meaningful. A more useful mime type can be derived
494 * by looking at the file extension. Typically, this method would be called on the
495 * result of guessMimeType().
497 * Currently, this method does the following:
499 * If $mime is "unknown/unknown" and isRecognizableExtension( $ext ) returns false,
500 * return the result of guessTypesForExtension($ext).
502 * If $mime is "application/x-opc+zip" and isMatchingExtension( $ext, $mime )
503 * gives true, return the result of guessTypesForExtension($ext).
505 * @param string $mime the mime type, typically guessed from a file's content.
506 * @param string $ext the file extension, as taken from the file name
508 * @return string the mime type
510 public function improveTypeFromExtension( $mime, $ext ) {
511 if ( $mime === 'unknown/unknown' ) {
512 if ( $this->isRecognizableExtension( $ext ) ) {
513 wfDebug( __METHOD__ . ': refusing to guess mime type for .' .
514 "$ext file, we should have recognized it\n" );
515 } else {
516 // Not something we can detect, so simply
517 // trust the file extension
518 $mime = $this->guessTypesForExtension( $ext );
521 elseif ( $mime === 'application/x-opc+zip' ) {
522 if ( $this->isMatchingExtension( $ext, $mime ) ) {
523 // A known file extension for an OPC file,
524 // find the proper mime type for that file extension
525 $mime = $this->guessTypesForExtension( $ext );
526 } else {
527 wfDebug( __METHOD__ . ": refusing to guess better type for $mime file, " .
528 ".$ext is not a known OPC extension.\n" );
529 $mime = 'application/zip';
533 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
534 $mime = $this->mMimeTypeAliases[$mime];
537 wfDebug( __METHOD__ . ": improved mime type for .$ext: $mime\n" );
538 return $mime;
542 * Mime type detection. This uses detectMimeType to detect the mime type
543 * of the file, but applies additional checks to determine some well known
544 * file formats that may be missed or misinterpreted by the default mime
545 * detection (namely XML based formats like XHTML or SVG, as well as ZIP
546 * based formats like OPC/ODF files).
548 * @param string $file the file to check
549 * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
550 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
551 * improveTypeFromExtension($mime, $ext) later to improve mime type.
553 * @return string the mime type of $file
555 public function guessMimeType( $file, $ext = true ) {
556 if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
557 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. " .
558 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
561 $mime = $this->doGuessMimeType( $file, $ext );
563 if( !$mime ) {
564 wfDebug( __METHOD__ . ": internal type detection failed for $file (.$ext)...\n" );
565 $mime = $this->detectMimeType( $file, $ext );
568 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
569 $mime = $this->mMimeTypeAliases[$mime];
572 wfDebug( __METHOD__ . ": guessed mime type of $file: $mime\n" );
573 return $mime;
577 * Guess the mime type from the file contents.
579 * @param string $file
580 * @param mixed $ext
581 * @return bool|string
583 private function doGuessMimeType( $file, $ext ) { // TODO: remove $ext param
584 // Read a chunk of the file
585 wfSuppressWarnings();
586 // @todo FIXME: Shouldn't this be rb?
587 $f = fopen( $file, 'rt' );
588 wfRestoreWarnings();
590 if( !$f ) {
591 return 'unknown/unknown';
593 $head = fread( $f, 1024 );
594 fseek( $f, -65558, SEEK_END );
595 $tail = fread( $f, 65558 ); // 65558 = maximum size of a zip EOCDR
596 fclose( $f );
598 wfDebug( __METHOD__ . ": analyzing head and tail of $file for magic numbers.\n" );
600 // Hardcode a few magic number checks...
601 $headers = array(
602 // Multimedia...
603 'MThd' => 'audio/midi',
604 'OggS' => 'application/ogg',
606 // Image formats...
607 // Note that WMF may have a bare header, no magic number.
608 "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
609 "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
610 '%PDF' => 'application/pdf',
611 'gimp xcf' => 'image/x-xcf',
613 // Some forbidden fruit...
614 'MZ' => 'application/octet-stream', // DOS/Windows executable
615 "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
616 "\x7fELF" => 'application/octet-stream', // ELF binary
619 foreach ( $headers as $magic => $candidate ) {
620 if ( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
621 wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
622 return $candidate;
626 /* Look for WebM and Matroska files */
627 if ( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
628 $doctype = strpos( $head, "\x42\x82" );
629 if ( $doctype ) {
630 // Next byte is datasize, then data (sizes larger than 1 byte are very stupid muxers)
631 $data = substr( $head, $doctype + 3, 8 );
632 if ( strncmp( $data, "matroska", 8 ) == 0 ) {
633 wfDebug( __METHOD__ . ": recognized file as video/x-matroska\n" );
634 return "video/x-matroska";
635 } elseif ( strncmp( $data, "webm", 4 ) == 0 ) {
636 wfDebug( __METHOD__ . ": recognized file as video/webm\n" );
637 return "video/webm";
640 wfDebug( __METHOD__ . ": unknown EBML file\n" );
641 return "unknown/unknown";
644 /* Look for WebP */
645 if ( strncmp( $head, "RIFF", 4 ) == 0 && strncmp( substr( $head, 8, 8), "WEBPVP8 ", 8 ) == 0 ) {
646 wfDebug( __METHOD__ . ": recognized file as image/webp\n" );
647 return "image/webp";
651 * Look for PHP. Check for this before HTML/XML... Warning: this is a
652 * heuristic, and won't match a file with a lot of non-PHP before. It
653 * will also match text files which could be PHP. :)
655 * @todo FIXME: For this reason, the check is probably useless -- an attacker
656 * could almost certainly just pad the file with a lot of nonsense to
657 * circumvent the check in any case where it would be a security
658 * problem. On the other hand, it causes harmful false positives (bug
659 * 16583). The heuristic has been cut down to exclude three-character
660 * strings like "<? ", but should it be axed completely?
662 if ( ( strpos( $head, '<?php' ) !== false ) ||
663 ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
664 ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
665 ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
666 ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
667 ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
669 wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
670 return 'application/x-php';
674 * look for XML formats (XHTML and SVG)
676 $xml = new XmlTypeCheck( $file );
677 if ( $xml->wellFormed ) {
678 global $wgXMLMimeTypes;
679 if ( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
680 return $wgXMLMimeTypes[$xml->getRootElement()];
681 } else {
682 return 'application/xml';
687 * look for shell scripts
689 $script_type = null;
691 # detect by shebang
692 if ( substr( $head, 0, 2 ) == "#!" ) {
693 $script_type = "ASCII";
694 } elseif ( substr( $head, 0, 5 ) == "\xef\xbb\xbf#!" ) {
695 $script_type = "UTF-8";
696 } elseif ( substr( $head, 0, 7 ) == "\xfe\xff\x00#\x00!" ) {
697 $script_type = "UTF-16BE";
698 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
699 $script_type = "UTF-16LE";
702 if ( $script_type ) {
703 if ( $script_type !== "UTF-8" && $script_type !== "ASCII" ) {
704 // Quick and dirty fold down to ASCII!
705 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
706 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
707 $head = '';
708 foreach( $chars as $codepoint ) {
709 if( $codepoint < 128 ) {
710 $head .= chr( $codepoint );
711 } else {
712 $head .= '?';
717 $match = array();
719 if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
720 $mime = "application/x-{$match[2]}";
721 wfDebug( __METHOD__ . ": shell script recognized as $mime\n" );
722 return $mime;
726 // Check for ZIP variants (before getimagesize)
727 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
728 wfDebug( __METHOD__ . ": ZIP header present in $file\n" );
729 return $this->detectZipType( $head, $tail, $ext );
732 wfSuppressWarnings();
733 $gis = getimagesize( $file );
734 wfRestoreWarnings();
736 if( $gis && isset( $gis['mime'] ) ) {
737 $mime = $gis['mime'];
738 wfDebug( __METHOD__ . ": getimagesize detected $file as $mime\n" );
739 return $mime;
742 // Also test DjVu
743 $deja = new DjVuImage( $file );
744 if( $deja->isValid() ) {
745 wfDebug( __METHOD__ . ": detected $file as image/vnd.djvu\n" );
746 return 'image/vnd.djvu';
749 return false;
753 * Detect application-specific file type of a given ZIP file from its
754 * header data. Currently works for OpenDocument and OpenXML types...
755 * If can't tell, returns 'application/zip'.
757 * @param string $header some reasonably-sized chunk of file header
758 * @param $tail String: the tail of the file
759 * @param $ext Mixed: the file extension, or true to extract it from the filename.
760 * Set it to false (default) to ignore the extension. DEPRECATED! Set to false,
761 * use improveTypeFromExtension($mime, $ext) later to improve mime type.
763 * @return string
765 function detectZipType( $header, $tail = null, $ext = false ) {
766 if( $ext ) { # TODO: remove $ext param
767 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. " .
768 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
771 $mime = 'application/zip';
772 $opendocTypes = array(
773 'chart-template',
774 'chart',
775 'formula-template',
776 'formula',
777 'graphics-template',
778 'graphics',
779 'image-template',
780 'image',
781 'presentation-template',
782 'presentation',
783 'spreadsheet-template',
784 'spreadsheet',
785 'text-template',
786 'text-master',
787 'text-web',
788 'text' );
790 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
791 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
792 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
794 $openxmlRegex = "/^\[Content_Types\].xml/";
796 if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
797 $mime = $matches[1];
798 wfDebug( __METHOD__ . ": detected $mime from ZIP archive\n" );
799 } elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
800 $mime = "application/x-opc+zip";
801 # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
802 if ( $ext !== true && $ext !== false ) {
803 /** This is the mode used by getPropsFromPath
804 * These mime's are stored in the database, where we don't really want
805 * x-opc+zip, because we use it only for internal purposes
807 if ( $this->isMatchingExtension( $ext, $mime ) ) {
808 /* A known file extension for an OPC file,
809 * find the proper mime type for that file extension
811 $mime = $this->guessTypesForExtension( $ext );
812 } else {
813 $mime = "application/zip";
816 wfDebug( __METHOD__ . ": detected an Open Packaging Conventions archive: $mime\n" );
817 } elseif ( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" &&
818 ($headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
819 preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
820 if ( substr( $header, 512, 4 ) == "\xEC\xA5\xC1\x00" ) {
821 $mime = "application/msword";
823 switch( substr( $header, 512, 6 ) ) {
824 case "\xEC\xA5\xC1\x00\x0E\x00":
825 case "\xEC\xA5\xC1\x00\x1C\x00":
826 case "\xEC\xA5\xC1\x00\x43\x00":
827 $mime = "application/vnd.ms-powerpoint";
828 break;
829 case "\xFD\xFF\xFF\xFF\x10\x00":
830 case "\xFD\xFF\xFF\xFF\x1F\x00":
831 case "\xFD\xFF\xFF\xFF\x22\x00":
832 case "\xFD\xFF\xFF\xFF\x23\x00":
833 case "\xFD\xFF\xFF\xFF\x28\x00":
834 case "\xFD\xFF\xFF\xFF\x29\x00":
835 case "\xFD\xFF\xFF\xFF\x10\x02":
836 case "\xFD\xFF\xFF\xFF\x1F\x02":
837 case "\xFD\xFF\xFF\xFF\x22\x02":
838 case "\xFD\xFF\xFF\xFF\x23\x02":
839 case "\xFD\xFF\xFF\xFF\x28\x02":
840 case "\xFD\xFF\xFF\xFF\x29\x02":
841 $mime = "application/vnd.msexcel";
842 break;
845 wfDebug( __METHOD__ . ": detected a MS Office document with OPC trailer\n" );
846 } else {
847 wfDebug( __METHOD__ . ": unable to identify type of ZIP archive\n" );
849 return $mime;
853 * Internal mime type detection. Detection is done using an external
854 * program, if $wgMimeDetectorCommand is set. Otherwise, the fileinfo
855 * extension and mime_content_type are tried (in this order), if they
856 * are available. If the detections fails and $ext is not false, the mime
857 * type is guessed from the file extension, using guessTypesForExtension.
859 * If the mime type is still unknown, getimagesize is used to detect the
860 * mime type if the file is an image. If no mime type can be determined,
861 * this function returns 'unknown/unknown'.
863 * @param string $file the file to check
864 * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
865 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
866 * improveTypeFromExtension($mime, $ext) later to improve mime type.
868 * @return string the mime type of $file
870 private function detectMimeType( $file, $ext = true ) {
871 global $wgMimeDetectorCommand;
873 if ( $ext ) { # TODO: make $ext default to false. Or better, remove it.
874 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
877 $m = null;
878 if ( $wgMimeDetectorCommand ) {
879 // @todo FIXME: Use wfShellExec
880 $fn = wfEscapeShellArg( $file );
881 $m = `$wgMimeDetectorCommand $fn`;
882 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
884 # This required the fileinfo extension by PECL,
885 # see http://pecl.php.net/package/fileinfo
886 # This must be compiled into PHP
888 # finfo is the official replacement for the deprecated
889 # mime_content_type function, see below.
891 # If you may need to load the fileinfo extension at runtime, set
892 # $wgLoadFileinfoExtension in LocalSettings.php
894 $mime_magic_resource = finfo_open( FILEINFO_MIME ); /* return mime type ala mimetype extension */
896 if ( $mime_magic_resource ) {
897 $m = finfo_file( $mime_magic_resource, $file );
898 finfo_close( $mime_magic_resource );
899 } else {
900 wfDebug( __METHOD__ . ": finfo_open failed on " . FILEINFO_MIME . "!\n" );
902 } elseif ( function_exists( "mime_content_type" ) ) {
904 # NOTE: this function is available since PHP 4.3.0, but only if
905 # PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
907 # On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundled with PHP;
908 # sometimes, this may even be needed under linus/unix.
910 # Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
911 # see http://www.php.net/manual/en/ref.mime-magic.php for details.
913 $m = mime_content_type( $file );
914 } else {
915 wfDebug( __METHOD__ . ": no magic mime detector found!\n" );
918 if ( $m ) {
919 # normalize
920 $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
921 $m = trim( $m );
922 $m = strtolower( $m );
924 if ( strpos( $m, 'unknown' ) !== false ) {
925 $m = null;
926 } else {
927 wfDebug( __METHOD__ . ": magic mime type of $file: $m\n" );
928 return $m;
932 // If desired, look at extension as a fallback.
933 if ( $ext === true ) {
934 $i = strrpos( $file, '.' );
935 $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
937 if ( $ext ) {
938 if( $this->isRecognizableExtension( $ext ) ) {
939 wfDebug( __METHOD__ . ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
940 } else {
941 $m = $this->guessTypesForExtension( $ext );
942 if ( $m ) {
943 wfDebug( __METHOD__ . ": extension mime type of $file: $m\n" );
944 return $m;
949 // Unknown type
950 wfDebug( __METHOD__ . ": failed to guess mime type for $file!\n" );
951 return 'unknown/unknown';
955 * Determine the media type code for a file, using its mime type, name and
956 * possibly its contents.
958 * This function relies on the findMediaType(), mapping extensions and mime
959 * types to media types.
961 * @todo analyse file if need be
962 * @todo look at multiple extension, separately and together.
964 * @param string $path full path to the image file, in case we have to look at the contents
965 * (if null, only the mime type is used to determine the media type code).
966 * @param string $mime mime type. If null it will be guessed using guessMimeType.
968 * @return (int?string?) a value to be used with the MEDIATYPE_xxx constants.
970 function getMediaType( $path = null, $mime = null ) {
971 if( !$mime && !$path ) {
972 return MEDIATYPE_UNKNOWN;
975 // If mime type is unknown, guess it
976 if( !$mime ) {
977 $mime = $this->guessMimeType( $path, false );
980 // Special code for ogg - detect if it's video (theora),
981 // else label it as sound.
982 if ( $mime == 'application/ogg' && file_exists( $path ) ) {
984 // Read a chunk of the file
985 $f = fopen( $path, "rt" );
986 if ( !$f ) return MEDIATYPE_UNKNOWN;
987 $head = fread( $f, 256 );
988 fclose( $f );
990 $head = strtolower( $head );
992 // This is an UGLY HACK, file should be parsed correctly
993 if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
994 elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
995 elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
996 elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
997 else return MEDIATYPE_MULTIMEDIA;
1000 // Check for entry for full mime type
1001 if( $mime ) {
1002 $type = $this->findMediaType( $mime );
1003 if ( $type !== MEDIATYPE_UNKNOWN ) {
1004 return $type;
1008 // Check for entry for file extension
1009 if ( $path ) {
1010 $i = strrpos( $path, '.' );
1011 $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1013 // TODO: look at multi-extension if this fails, parse from full path
1014 $type = $this->findMediaType( '.' . $e );
1015 if ( $type !== MEDIATYPE_UNKNOWN ) {
1016 return $type;
1020 // Check major mime type
1021 if ( $mime ) {
1022 $i = strpos( $mime, '/' );
1023 if ( $i !== false ) {
1024 $major = substr( $mime, 0, $i );
1025 $type = $this->findMediaType( $major );
1026 if ( $type !== MEDIATYPE_UNKNOWN ) {
1027 return $type;
1032 if( !$type ) {
1033 $type = MEDIATYPE_UNKNOWN;
1036 return $type;
1040 * Returns a media code matching the given mime type or file extension.
1041 * File extensions are represented by a string starting with a dot (.) to
1042 * distinguish them from mime types.
1044 * This function relies on the mapping defined by $this->mMediaTypes
1045 * @access private
1046 * @return int|string
1048 function findMediaType( $extMime ) {
1049 if ( strpos( $extMime, '.' ) === 0 ) {
1050 // If it's an extension, look up the mime types
1051 $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
1052 if ( !$m ) {
1053 return MEDIATYPE_UNKNOWN;
1056 $m = explode( ' ', $m );
1057 } else {
1058 // Normalize mime type
1059 if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
1060 $extMime = $this->mMimeTypeAliases[$extMime];
1063 $m = array( $extMime );
1066 foreach ( $m as $mime ) {
1067 foreach ( $this->mMediaTypes as $type => $codes ) {
1068 if ( in_array( $mime, $codes, true ) ) {
1069 return $type;
1074 return MEDIATYPE_UNKNOWN;
1078 * Get the MIME types that various versions of Internet Explorer would
1079 * detect from a chunk of the content.
1081 * @param string $fileName the file name (unused at present)
1082 * @param string $chunk the first 256 bytes of the file
1083 * @param string $proposed the MIME type proposed by the server
1084 * @return Array
1086 public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
1087 $ca = $this->getIEContentAnalyzer();
1088 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
1092 * Get a cached instance of IEContentAnalyzer
1094 * @return IEContentAnalyzer
1096 protected function getIEContentAnalyzer() {
1097 if ( is_null( $this->mIEAnalyzer ) ) {
1098 $this->mIEAnalyzer = new IEContentAnalyzer;
1100 return $this->mIEAnalyzer;