]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/MimeMagic.php
MediaWiki 1.17.1
[autoinstallsdev/mediawiki.git] / includes / MimeMagic.php
1 <?php
2 /**
3  * Module defining helper functions for detecting and dealing with mime types.
4  *
5  * @file
6  */
7
8 /**
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.
13  * 
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.
21  * 
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)
26  */
27 define('MM_WELL_KNOWN_MIME_TYPES',<<<END_STRING
28 application/ogg ogx ogg ogm ogv oga spx
29 application/pdf pdf
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
51 audio/x-wav wav
52 audio/ogg oga spx ogg
53 image/x-bmp bmp
54 image/gif gif
55 image/jpeg jpeg jpg jpe
56 image/png png
57 image/svg+xml svg 
58 image/svg svg
59 image/tiff tiff tif
60 image/vnd.djvu djvu
61 image/x.djvu djvu
62 image/x-djvu djvu
63 image/x-portable-pixmap ppm
64 image/x-xcf xcf
65 text/plain txt
66 text/html html htm
67 video/ogg ogv ogm ogg
68 video/mpeg mpg mpeg
69 END_STRING
70 );
71
72 /**
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.
77  */
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]
98 audio/midi [AUDIO]
99 audio/x-aiff [AUDIO]
100 audio/x-wav [AUDIO]
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]
104 image/gif [BITMAP]
105 image/jpeg [BITMAP]
106 image/png [BITMAP]
107 image/svg+xml [DRAWING]
108 image/tiff [BITMAP]
109 image/vnd.djvu [BITMAP]
110 image/x-xcf [BITMAP]
111 image/x-portable-pixmap [BITMAP]
112 text/plain [TEXT]
113 text/html [TEXT]
114 video/ogg [VIDEO]
115 video/mpeg [VIDEO]
116 unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
117 END_STRING
118 );
119
120 #note: because this file is possibly included by a function,
121 #we need to access the global scope explicitely!
122 global $wgLoadFileinfoExtension;
123
124 if ($wgLoadFileinfoExtension) {
125         wfDl( 'fileinfo' );
126 }
127
128 /**
129  * Implements functions related to mime types such as detection and mapping to
130  * file extension.
131  *
132  * Instances of this class are stateles, there only needs to be one global instance
133  * of MimeMagic. Please use MimeMagic::singleton() to get that instance.
134  */
135 class MimeMagic {
136
137         /**
138         * Mapping of media types to arrays of mime types.
139         * This is used by findMediaType and getMediaType, respectively
140         */
141         var $mMediaTypes= null;
142
143         /** Map of mime type aliases
144         */
145         var $mMimeTypeAliases= null;
146
147         /** map of mime types to file extensions (as a space seprarated list)
148         */
149         var $mMimeToExt= null;
150
151         /** map of file extensions types to mime types (as a space seprarated list)
152         */
153         var $mExtToMime= null;
154
155         /** IEContentAnalyzer instance
156          */
157         var $mIEAnalyzer;
158
159         /** The singleton instance
160          */
161         private static $instance;
162
163         /** Initializes the MimeMagic object. This is called by MimeMagic::singleton().
164         *
165         * This constructor parses the mime.types and mime.info files and build internal mappings.
166         */
167         function __construct() {
168                 /*
169                 *   --- load mime.types ---
170                 */
171
172                 global $wgMimeTypeFile, $IP;
173
174                 $types = MM_WELL_KNOWN_MIME_TYPES;
175
176                 if ( $wgMimeTypeFile == 'includes/mime.types' ) {
177                         $wgMimeTypeFile = "$IP/$wgMimeTypeFile";
178                 }
179
180                 if ( $wgMimeTypeFile ) {
181                         if ( is_file( $wgMimeTypeFile ) and is_readable( $wgMimeTypeFile ) ) {
182                                 wfDebug( __METHOD__.": loading mime types from $wgMimeTypeFile\n" );
183                                 $types .= "\n";
184                                 $types .= file_get_contents( $wgMimeTypeFile );
185                         } else {
186                                 wfDebug( __METHOD__.": can't load mime types from $wgMimeTypeFile\n" );
187                         }
188                 } else {
189                         wfDebug( __METHOD__.": no mime types file defined, using build-ins only.\n" );
190                 }
191
192                 $types = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $types );
193                 $types = str_replace( "\t", " ", $types );
194
195                 $this->mMimeToExt = array();
196                 $this->mToMime = array();
197
198                 $lines = explode( "\n",$types );
199                 foreach ( $lines as $s ) {
200                         $s = trim( $s );
201                         if ( empty( $s ) ) continue;
202                         if ( strpos( $s, '#' ) === 0 ) continue;
203
204                         $s = strtolower( $s );
205                         $i = strpos( $s, ' ' );
206
207                         if ( $i === false ) continue;
208
209                         #print "processing MIME line $s<br>";
210
211                         $mime = substr( $s, 0, $i );
212                         $ext = trim( substr($s, $i+1 ) );
213
214                         if ( empty( $ext ) ) continue;
215
216                         if ( !empty( $this->mMimeToExt[$mime] ) ) {
217                                 $this->mMimeToExt[$mime] .= ' ' . $ext;
218                         } else {
219                                 $this->mMimeToExt[$mime] = $ext;
220                         }
221
222                         $extensions = explode( ' ', $ext );
223
224                         foreach ( $extensions as $e ) {
225                                 $e = trim( $e );
226                                 if ( empty( $e ) ) continue;
227
228                                 if ( !empty( $this->mExtToMime[$e] ) ) {
229                                         $this->mExtToMime[$e] .= ' ' . $mime;
230                                 } else {
231                                         $this->mExtToMime[$e] = $mime;
232                                 }
233                         }
234                 }
235
236                 /*
237                 *   --- load mime.info ---
238                 */
239
240                 global $wgMimeInfoFile;
241                 if ( $wgMimeInfoFile == 'includes/mime.info' ) {
242                         $wgMimeInfoFile = "$IP/$wgMimeInfoFile";
243                 }
244
245                 $info = MM_WELL_KNOWN_MIME_INFO;
246
247                 if ( $wgMimeInfoFile ) {
248                         if ( is_file( $wgMimeInfoFile ) and is_readable( $wgMimeInfoFile ) ) {
249                                 wfDebug( __METHOD__.": loading mime info from $wgMimeInfoFile\n" );
250                                 $info .= "\n";
251                                 $info .= file_get_contents( $wgMimeInfoFile );
252                         } else {
253                                 wfDebug(__METHOD__.": can't load mime info from $wgMimeInfoFile\n");
254                         }
255                 } else {
256                         wfDebug(__METHOD__.": no mime info file defined, using build-ins only.\n");
257                 }
258
259                 $info = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $info);
260                 $info = str_replace( "\t", " ", $info );
261
262                 $this->mMimeTypeAliases = array();
263                 $this->mMediaTypes = array();
264
265                 $lines = explode( "\n", $info );
266                 foreach ( $lines as $s ) {
267                         $s = trim( $s );
268                         if ( empty( $s ) ) continue;
269                         if ( strpos( $s, '#' ) === 0 ) continue;
270
271                         $s = strtolower( $s );
272                         $i = strpos( $s, ' ' );
273
274                         if ( $i === false ) continue;
275
276                         #print "processing MIME INFO line $s<br>";
277
278                         $match = array();
279                         if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
280                                 $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
281                                 $mtype = trim( strtoupper( $match[1] ) );
282                         } else {
283                                 $mtype = MEDIATYPE_UNKNOWN;
284                         }
285
286                         $m = explode( ' ', $s );
287
288                         if ( !isset( $this->mMediaTypes[$mtype] ) ) {
289                                 $this->mMediaTypes[$mtype] = array();
290                         }
291
292                         foreach ( $m as $mime ) {
293                                 $mime = trim( $mime );
294                                 if ( empty( $mime ) ) continue;
295
296                                 $this->mMediaTypes[$mtype][] = $mime;
297                         }
298
299                         if ( sizeof( $m ) > 1 ) {
300                                 $main = $m[0];
301                                 for ( $i=1; $i<sizeof($m); $i += 1 ) {
302                                         $mime = $m[$i];
303                                         $this->mMimeTypeAliases[$mime] = $main;
304                                 }
305                         }
306                 }
307
308         }
309
310         /**
311          * Get an instance of this class
312          */
313         static function &singleton() {
314                 if ( !isset( self::$instance ) ) {
315                         self::$instance = new MimeMagic;
316                 }
317                 return self::$instance;
318         }
319
320         /** returns a list of file extensions for a given mime type
321         * as a space separated string.
322         */
323         function getExtensionsForType( $mime ) {
324                 $mime = strtolower( $mime );
325
326                 $r = @$this->mMimeToExt[$mime];
327
328                 if ( @!$r and isset( $this->mMimeTypeAliases[$mime] ) ) {
329                         $mime = $this->mMimeTypeAliases[$mime];
330                         $r = @$this->mMimeToExt[$mime];
331                 }
332
333                 return $r;
334         }
335
336         /** returns a list of mime types for a given file extension
337         * as a space separated string.
338         */
339         function getTypesForExtension( $ext ) {
340                 $ext = strtolower( $ext );
341
342                 $r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null;
343                 return $r;
344         }
345
346         /** returns a single mime type for a given file extension.
347         * This is always the first type from the list returned by getTypesForExtension($ext).
348         */
349         function guessTypesForExtension( $ext ) {
350                 $m = $this->getTypesForExtension( $ext );
351                 if ( is_null( $m ) ) return null;
352
353                 $m = trim( $m );
354                 $m = preg_replace( '/\s.*$/', '', $m );
355
356                 return $m;
357         }
358
359
360         /** tests if the extension matches the given mime type.
361         * returns true if a match was found, NULL if the mime type is unknown,
362         * and false if the mime type is known but no matches where found.
363         */
364         function isMatchingExtension( $extension, $mime ) {
365                 $ext = $this->getExtensionsForType( $mime );
366
367                 if ( !$ext ) {
368                         return null;  //unknown
369                 }
370
371                 $ext = explode( ' ', $ext );
372
373                 $extension = strtolower( $extension );
374                 if ( in_array( $extension, $ext ) ) {
375                         return true;
376                 }
377
378                 return false;
379         }
380
381         /** returns true if the mime type is known to represent
382         * an image format supported by the PHP GD library.
383         */
384         function isPHPImageType( $mime ) {
385                 #as defined by imagegetsize and image_type_to_mime
386                 static $types = array(
387                         'image/gif', 'image/jpeg', 'image/png',
388                         'image/x-bmp', 'image/xbm', 'image/tiff',
389                         'image/jp2', 'image/jpeg2000', 'image/iff',
390                         'image/xbm', 'image/x-xbitmap',
391                         'image/vnd.wap.wbmp', 'image/vnd.xiff',
392                         'image/x-photoshop',
393                         'application/x-shockwave-flash',
394                 );
395
396                 return in_array( $mime, $types );
397         }
398
399         /**
400          * Returns true if the extension represents a type which can
401          * be reliably detected from its content. Use this to determine
402          * whether strict content checks should be applied to reject
403          * invalid uploads; if we can't identify the type we won't
404          * be able to say if it's invalid.
405          *
406          * @todo Be more accurate when using fancy mime detector plugins;
407          *       right now this is the bare minimum getimagesize() list.
408          * @return bool
409          */
410         function isRecognizableExtension( $extension ) {
411                 static $types = array(
412                         // Types recognized by getimagesize()
413                         'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
414                         'bmp', 'tiff', 'tif', 'jpc', 'jp2',
415                         'jpx', 'jb2', 'swc', 'iff', 'wbmp',
416                         'xbm',
417
418                         // Formats we recognize magic numbers for
419                         'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx',
420                         'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
421                         'webp',
422
423                         // XML formats we sure hope we recognize reliably
424                         'svg',
425                 );
426                 return in_array( strtolower( $extension ), $types );
427         }
428
429         /** improves a mime type using the file extension. Some file formats are very generic,
430         * so their mime type is not very meaningful. A more useful mime type can be derived 
431         * by looking at the file extension. Typically, this method would be called on the 
432         * result of guessMimeType().
433         * 
434         * Currently, this method does the following:
435         *
436         * If $mime is "unknown/unknown" and isRecognizableExtension( $ext ) returns false,
437         * return the result of guessTypesForExtension($ext). 
438         *
439         * If $mime is "application/x-opc+zip" and isMatchingExtension( $ext, $mime )
440         * gives true, return the result of guessTypesForExtension($ext). 
441         *
442         * @param $mime String: the mime type, typically guessed from a file's content.
443         * @param $ext String: the file extension, as taken from the file name
444         *
445         * @return string the mime type
446         */
447         function improveTypeFromExtension( $mime, $ext ) {
448                 if ( $mime === "unknown/unknown" ) {
449                         if( $this->isRecognizableExtension( $ext ) ) {
450                                 wfDebug( __METHOD__. ": refusing to guess mime type for .$ext file, " .
451                                         "we should have recognized it\n" );
452                         } else {
453                                 /* Not something we can detect, so simply 
454                                 * trust the file extension */
455                                 $mime = $this->guessTypesForExtension( $ext );
456                         }
457                 }
458                 else if ( $mime === "application/x-opc+zip" ) {
459                         if ( $this->isMatchingExtension( $ext, $mime ) ) {
460                                 /* A known file extension for an OPC file,
461                                 * find the proper mime type for that file extension */
462                                 $mime = $this->guessTypesForExtension( $ext );
463                         } else {
464                                 wfDebug( __METHOD__. ": refusing to guess better type for $mime file, " . 
465                                         ".$ext is not a known OPC extension.\n" );
466                                 $mime = "application/zip";
467                         }
468                 }
469
470                 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
471                         $mime = $this->mMimeTypeAliases[$mime];
472                 }
473
474                 wfDebug(__METHOD__.": improved mime type for .$ext: $mime\n");
475                 return $mime;
476         }
477
478         /** mime type detection. This uses detectMimeType to detect the mime type of the file,
479         * but applies additional checks to determine some well known file formats that may be missed
480         * or misinterpreter by the default mime detection (namely XML based formats like XHTML or SVG,
481         * as well as ZIP based formats like OPC/ODF files).
482         *
483         * @param $file String: the file to check
484         * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
485         *             Set it to false to ignore the extension. DEPRECATED! Set to false, use 
486         *             improveTypeFromExtension($mime, $ext) later to improve mime type.
487         *
488         * @return string the mime type of $file
489         */
490         function guessMimeType( $file, $ext = true ) {
491                 if( $ext ) { # TODO: make $ext default to false. Or better, remove it.
492                         wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. " .
493                                 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
494                 }
495
496                 $mime = $this->doGuessMimeType( $file, $ext );
497
498                 if( !$mime ) {
499                         wfDebug( __METHOD__.": internal type detection failed for $file (.$ext)...\n" );
500                         $mime = $this->detectMimeType( $file, $ext );
501                 }
502
503                 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
504                         $mime = $this->mMimeTypeAliases[$mime];
505                 }
506
507                 wfDebug(__METHOD__.": guessed mime type of $file: $mime\n");
508                 return $mime;
509         }
510
511         private function doGuessMimeType( $file, $ext ) { # TODO: remove $ext param
512                 // Read a chunk of the file
513                 wfSuppressWarnings();
514                 $f = fopen( $file, "rt" );
515                 wfRestoreWarnings();
516                 if( !$f ) return "unknown/unknown";
517                 $head = fread( $f, 1024 );
518                 fseek( $f, -65558, SEEK_END );
519                 $tail = fread( $f, 65558 ); // 65558 = maximum size of a zip EOCDR
520                 fclose( $f );
521
522                 wfDebug( __METHOD__ . ": analyzing head and tail of $file for magic numbers.\n" );
523
524                 // Hardcode a few magic number checks...
525                 $headers = array(
526                         // Multimedia...
527                         'MThd'             => 'audio/midi',
528                         'OggS'             => 'application/ogg',
529
530                         // Image formats...
531                         // Note that WMF may have a bare header, no magic number.
532                         "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
533                         "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
534                         '%PDF'             => 'application/pdf',
535                         'gimp xcf'         => 'image/x-xcf',
536
537                         // Some forbidden fruit...
538                         'MZ'               => 'application/octet-stream', // DOS/Windows executable
539                         "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
540                         "\x7fELF"          => 'application/octet-stream', // ELF binary
541                 );
542
543                 foreach( $headers as $magic => $candidate ) {
544                         if( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
545                                 wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
546                                 return $candidate;
547                         }
548                 }
549
550                 /* Look for WebM and Matroska files */
551                 if( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
552                         $doctype = strpos( $head, "\x42\x82" );
553                         if( $doctype ) {
554                                 // Next byte is datasize, then data (sizes larger than 1 byte are very stupid muxers)
555                                 $data = substr($head, $doctype+3, 8);
556                                 if( strncmp( $data, "matroska", 8 ) == 0 ) {
557                                         wfDebug( __METHOD__ . ": recognized file as video/x-matroska\n" );
558                                         return "video/x-matroska";
559                                 } else if ( strncmp( $data, "webm", 4 ) == 0 ) {
560                                         wfDebug( __METHOD__ . ": recognized file as video/webm\n" );
561                                         return "video/webm";
562                                 }
563                         }
564                         wfDebug( __METHOD__ . ": unknown EBML file\n" );
565                         return "unknown/unknown";
566                 }
567
568                 /* Look for WebP */
569                 if( strncmp( $head, "RIFF", 4 ) == 0 && strncmp( substr( $head, 8, 8), "WEBPVP8 ", 8 ) == 0 ) {
570                         wfDebug( __METHOD__ . ": recognized file as image/webp\n" );
571                         return "image/webp";
572                 }
573
574                 /*
575                  * Look for PHP.  Check for this before HTML/XML...  Warning: this is a
576                  * heuristic, and won't match a file with a lot of non-PHP before.  It
577                  * will also match text files which could be PHP. :)
578                  *
579                  * FIXME: For this reason, the check is probably useless -- an attacker
580                  * could almost certainly just pad the file with a lot of nonsense to
581                  * circumvent the check in any case where it would be a security
582                  * problem.  On the other hand, it causes harmful false positives (bug
583                  * 16583).  The heuristic has been cut down to exclude three-character
584                  * strings like "<? ", but should it be axed completely?
585                  */
586                 if( ( strpos( $head, '<?php' ) !== false ) ||
587
588                     ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
589                     ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
590                     ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
591                     ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
592                     ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
593
594                         wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
595                         return "application/x-php";
596                 }
597
598                 /*
599                  * look for XML formats (XHTML and SVG)
600                  */
601                 $xml = new XmlTypeCheck( $file );
602                 if( $xml->wellFormed ) {
603                         global $wgXMLMimeTypes;
604                         if( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
605                                 return $wgXMLMimeTypes[$xml->getRootElement()];
606                         } else {
607                                 return 'application/xml';
608                         }
609                 }
610
611                 /*
612                  * look for shell scripts
613                  */
614                 $script_type = null;
615
616                 # detect by shebang
617                 if ( substr( $head, 0, 2) == "#!" ) {
618                         $script_type = "ASCII";
619                 } elseif ( substr( $head, 0, 5) == "\xef\xbb\xbf#!" ) {
620                         $script_type = "UTF-8";
621                 } elseif ( substr( $head, 0, 7) == "\xfe\xff\x00#\x00!" ) {
622                         $script_type = "UTF-16BE";
623                 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
624                         $script_type= "UTF-16LE";
625                 }
626
627                 if ( $script_type ) {
628                         if ( $script_type !== "UTF-8" && $script_type !== "ASCII") {
629                                 // Quick and dirty fold down to ASCII!
630                                 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
631                                 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
632                                 $head = '';
633                                 foreach( $chars as $codepoint ) {
634                                         if( $codepoint < 128 ) {
635                                                 $head .= chr( $codepoint );
636                                         } else {
637                                                 $head .= '?';
638                                         }
639                                 }
640                         }
641
642                         $match = array();
643
644                         if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
645                                 $mime = "application/x-{$match[2]}";
646                                 wfDebug( __METHOD__.": shell script recognized as $mime\n" );
647                                 return $mime;
648                         }
649                 }
650
651                 // Check for ZIP variants (before getimagesize)
652                 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
653                         wfDebug( __METHOD__.": ZIP header present in $file\n" );
654                         return $this->detectZipType( $head, $tail, $ext );
655                 }
656
657                 wfSuppressWarnings();
658                 $gis = getimagesize( $file );
659                 wfRestoreWarnings();
660
661                 if( $gis && isset( $gis['mime'] ) ) {
662                         $mime = $gis['mime'];
663                         wfDebug( __METHOD__.": getimagesize detected $file as $mime\n" );
664                         return $mime;
665                 }
666
667                 // Also test DjVu
668                 $deja = new DjVuImage( $file );
669                 if( $deja->isValid() ) {
670                         wfDebug( __METHOD__.": detected $file as image/vnd.djvu\n" );
671                         return 'image/vnd.djvu';
672                 }
673
674                 return false;
675         }
676         
677         /**
678          * Detect application-specific file type of a given ZIP file from its
679          * header data.  Currently works for OpenDocument and OpenXML types...
680          * If can't tell, returns 'application/zip'.
681          *
682          * @param $header String: some reasonably-sized chunk of file header
683          * @param $tail   String: the tail of the file
684          * @param $ext Mixed: the file extension, or true to extract it from the filename.
685          *             Set it to false (default) to ignore the extension. DEPRECATED! Set to false, 
686          *             use improveTypeFromExtension($mime, $ext) later to improve mime type.
687          *
688          * @return string
689          */
690         function detectZipType( $header, $tail = null, $ext = false ) {
691                 if( $ext ) { # TODO: remove $ext param
692                         wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. " .
693                                 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
694                 }
695
696                 $mime = 'application/zip';
697                 $opendocTypes = array(
698                         'chart-template',
699                         'chart',
700                         'formula-template',
701                         'formula',
702                         'graphics-template',
703                         'graphics',
704                         'image-template',
705                         'image',
706                         'presentation-template',
707                         'presentation',
708                         'spreadsheet-template',
709                         'spreadsheet',
710                         'text-template',
711                         'text-master',
712                         'text-web',
713                         'text' );
714
715                 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
716                 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
717                 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
718
719                 $openxmlRegex = "/^\[Content_Types\].xml/";
720
721                 if( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
722                         $mime = $matches[1];
723                         wfDebug( __METHOD__.": detected $mime from ZIP archive\n" );
724                 } elseif( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
725                         $mime = "application/x-opc+zip";
726                         # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere 
727                         if( $ext !== true && $ext !== false ) { 
728                                 /** This is the mode used by getPropsFromPath
729                                 * These mime's are stored in the database, where we don't really want
730                                 * x-opc+zip, because we use it only for internal purposes
731                                 */
732                                 if( $this->isMatchingExtension( $ext, $mime) ) {
733                                         /* A known file extension for an OPC file,
734                                         * find the proper mime type for that file extension */
735                                         $mime = $this->guessTypesForExtension( $ext );
736                                 } else {
737                                         $mime = "application/zip";
738                                 }
739                         }
740                         wfDebug( __METHOD__.": detected an Open Packaging Conventions archive: $mime\n" );
741                 } else if( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" && 
742                                 ($headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
743                                 preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
744                         if( substr( $header, 512, 4) == "\xEC\xA5\xC1\x00" ) {
745                                 $mime = "application/msword";
746                         } 
747                         switch( substr( $header, 512, 6) ) {
748                                 case "\xEC\xA5\xC1\x00\x0E\x00":
749                                 case "\xEC\xA5\xC1\x00\x1C\x00":
750                                 case "\xEC\xA5\xC1\x00\x43\x00":
751                                         $mime = "application/vnd.ms-powerpoint";
752                                         break;
753                                 case "\xFD\xFF\xFF\xFF\x10\x00":
754                                 case "\xFD\xFF\xFF\xFF\x1F\x00":
755                                 case "\xFD\xFF\xFF\xFF\x22\x00":
756                                 case "\xFD\xFF\xFF\xFF\x23\x00":
757                                 case "\xFD\xFF\xFF\xFF\x28\x00":
758                                 case "\xFD\xFF\xFF\xFF\x29\x00":
759                                 case "\xFD\xFF\xFF\xFF\x10\x02":
760                                 case "\xFD\xFF\xFF\xFF\x1F\x02":
761                                 case "\xFD\xFF\xFF\xFF\x22\x02":
762                                 case "\xFD\xFF\xFF\xFF\x23\x02":
763                                 case "\xFD\xFF\xFF\xFF\x28\x02":
764                                 case "\xFD\xFF\xFF\xFF\x29\x02":
765                                         $mime = "application/vnd.msexcel";
766                                         break;
767                         }
768
769                         wfDebug( __METHOD__.": detected a MS Office document with OPC trailer\n");
770                 } else {
771                         wfDebug( __METHOD__.": unable to identify type of ZIP archive\n" );
772                 }
773                 return $mime;
774         }
775
776         /** Internal mime type detection, please use guessMimeType() for application code instead.
777         * Detection is done using an external program, if $wgMimeDetectorCommand is set.
778         * Otherwise, the fileinfo extension and mime_content_type are tried (in this order), if they are available.
779         * If the dections fails and $ext is not false, the mime type is guessed from the file extension, using
780         * guessTypesForExtension.
781         * If the mime type is still unknown, getimagesize is used to detect the mime type if the file is an image.
782         * If no mime type can be determined, this function returns "unknown/unknown".
783         *
784         * @param $file String: the file to check
785         * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
786         *             Set it to false to ignore the extension. DEPRECATED! Set to false, use 
787         *             improveTypeFromExtension($mime, $ext) later to improve mime type.
788         *
789         * @return string the mime type of $file
790         * @access private
791         */
792         private function detectMimeType( $file, $ext = true ) {
793                 global $wgMimeDetectorCommand;
794
795                 if( $ext ) { # TODO:  make $ext default to false. Or better, remove it.
796                         wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
797                 }
798
799                 $m = null;
800                 if ( $wgMimeDetectorCommand ) {
801                         $fn = wfEscapeShellArg( $file );
802                         $m = `$wgMimeDetectorCommand $fn`;
803                 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
804
805                         # This required the fileinfo extension by PECL,
806                         # see http://pecl.php.net/package/fileinfo
807                         # This must be compiled into PHP
808                         #
809                         # finfo is the official replacement for the deprecated
810                         # mime_content_type function, see below.
811                         #
812                         # If you may need to load the fileinfo extension at runtime, set
813                         # $wgLoadFileinfoExtension in LocalSettings.php
814
815                         $mime_magic_resource = finfo_open(FILEINFO_MIME); /* return mime type ala mimetype extension */
816
817                         if ($mime_magic_resource) {
818                                 $m = finfo_file( $mime_magic_resource, $file );
819                                 finfo_close( $mime_magic_resource );
820                         } else {
821                                 wfDebug( __METHOD__.": finfo_open failed on ".FILEINFO_MIME."!\n" );
822                         }
823                 } elseif ( function_exists( "mime_content_type" ) ) {
824
825                         # NOTE: this function is available since PHP 4.3.0, but only if
826                         # PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
827                         #
828                         # On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundeled with PHP;
829                         # sometimes, this may even be needed under linus/unix.
830                         #
831                         # Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
832                         # see http://www.php.net/manual/en/ref.mime-magic.php for details.
833
834                         $m = mime_content_type($file);
835                 } else {
836                         wfDebug( __METHOD__.": no magic mime detector found!\n" );
837                 }
838
839                 if ( $m ) {
840                         # normalize
841                         $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
842                         $m = trim( $m );
843                         $m = strtolower( $m );
844
845                         if ( strpos( $m, 'unknown' ) !== false ) {
846                                 $m = null;
847                         } else {
848                                 wfDebug( __METHOD__.": magic mime type of $file: $m\n" );
849                                 return $m;
850                         }
851                 }
852
853                 # if desired, look at extension as a fallback.
854                 if ( $ext === true ) {
855                         $i = strrpos( $file, '.' );
856                         $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
857                 }
858                 if ( $ext ) {
859                         if( $this->isRecognizableExtension( $ext ) ) {
860                                 wfDebug( __METHOD__. ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
861                         } else {
862                                 $m = $this->guessTypesForExtension( $ext );
863                                 if ( $m ) {
864                                         wfDebug( __METHOD__.": extension mime type of $file: $m\n" );
865                                         return $m;
866                                 }
867                         }
868                 }
869
870                 #unknown type
871                 wfDebug( __METHOD__.": failed to guess mime type for $file!\n" );
872                 return "unknown/unknown";
873         }
874
875         /**
876         * Determine the media type code for a file, using its mime type, name and possibly
877         * its contents.
878         *
879         * This function relies on the findMediaType(), mapping extensions and mime
880         * types to media types.
881         *
882         * @todo analyse file if need be
883         * @todo look at multiple extension, separately and together.
884         *
885         * @param $path String: full path to the image file, in case we have to look at the contents
886         *        (if null, only the mime type is used to determine the media type code).
887         * @param $mime String: mime type. If null it will be guessed using guessMimeType.
888         *
889         * @return (int?string?) a value to be used with the MEDIATYPE_xxx constants.
890         */
891         function getMediaType( $path = null, $mime = null ) {
892                 if( !$mime && !$path ) return MEDIATYPE_UNKNOWN;
893
894                 # If mime type is unknown, guess it
895                 if( !$mime ) $mime = $this->guessMimeType( $path, false );
896
897                 # Special code for ogg - detect if it's video (theora),
898                 # else label it as sound.
899                 if( $mime == "application/ogg" && file_exists( $path ) ) {
900
901                         // Read a chunk of the file
902                         $f = fopen( $path, "rt" );
903                         if ( !$f ) return MEDIATYPE_UNKNOWN;
904                         $head = fread( $f, 256 );
905                         fclose( $f );
906
907                         $head = strtolower( $head );
908
909                         # This is an UGLY HACK, file should be parsed correctly
910                         if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
911                         elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
912                         elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
913                         elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
914                         else return MEDIATYPE_MULTIMEDIA;
915                 }
916
917                 # check for entry for full mime type
918                 if( $mime ) {
919                         $type = $this->findMediaType( $mime );
920                         if( $type !== MEDIATYPE_UNKNOWN ) return $type;
921                 }
922
923                 # Check for entry for file extension
924                 if ( $path ) {
925                         $i = strrpos( $path, '.' );
926                         $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
927
928                         # TODO: look at multi-extension if this fails, parse from full path
929
930                         $type = $this->findMediaType( '.' . $e );
931                         if ( $type !== MEDIATYPE_UNKNOWN ) return $type;
932                 }
933
934                 # Check major mime type
935                 if( $mime ) {
936                         $i = strpos( $mime, '/' );
937                         if( $i !== false ) {
938                                 $major = substr( $mime, 0, $i );
939                                 $type = $this->findMediaType( $major );
940                                 if( $type !== MEDIATYPE_UNKNOWN ) return $type;
941                         }
942                 }
943
944                 if( !$type ) $type = MEDIATYPE_UNKNOWN;
945
946                 return $type;
947         }
948
949         /** returns a media code matching the given mime type or file extension.
950         * File extensions are represented by a string starting with a dot (.) to
951         * distinguish them from mime types.
952         *
953         * This funktion relies on the mapping defined by $this->mMediaTypes
954         * @access private
955         */
956         function findMediaType( $extMime ) {
957                 if ( strpos( $extMime, '.' ) === 0 ) { #if it's an extension, look up the mime types
958                         $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
959                         if ( !$m ) return MEDIATYPE_UNKNOWN;
960
961                         $m = explode( ' ', $m );
962                 } else {
963                         # Normalize mime type
964                         if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
965                                 $extMime = $this->mMimeTypeAliases[$extMime];
966                         }
967
968                         $m = array($extMime);
969                 }
970
971                 foreach ( $m as $mime ) {
972                         foreach ( $this->mMediaTypes as $type => $codes ) {
973                                 if ( in_array($mime, $codes, true ) ) {
974                                         return $type;
975                                 }
976                         }
977                 }
978
979                 return MEDIATYPE_UNKNOWN;
980         }
981
982         /**
983          * Get the MIME types that various versions of Internet Explorer would 
984          * detect from a chunk of the content.
985          *
986          * @param $fileName String: the file name (unused at present)
987          * @param $chunk String: the first 256 bytes of the file
988          * @param $proposed String: the MIME type proposed by the server
989          */
990         public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
991                 $ca = $this->getIEContentAnalyzer();
992                 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
993         }
994
995         /**
996          * Get a cached instance of IEContentAnalyzer
997          */
998         protected function getIEContentAnalyzer() {
999                 if ( is_null( $this->mIEAnalyzer ) ) {
1000                         $this->mIEAnalyzer = new IEContentAnalyzer;
1001                 }
1002                 return $this->mIEAnalyzer;
1003         }
1004 }