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