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