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