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