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