Fix grammar in 'mimesearch-summary'
[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
406 // XML formats we sure hope we recognize reliably
407 'svg',
408 );
409 return in_array( strtolower( $extension ), $types );
410 }
411
412 /** improves a mime type using the file extension. Some file formats are very generic,
413 * so their mime type is not very meaningful. A more useful mime type can be derived
414 * by looking at the file extension. Typically, this method would be called on the
415 * result of guessMimeType().
416 *
417 * Currently, this method does the following:
418 *
419 * If $mime is "unknown/unknown" and isRecognizableExtension( $ext ) returns false,
420 * return the result of guessTypesForExtension($ext).
421 *
422 * If $mime is "application/x-opc+zip" and isMatchingExtension( $ext, $mime )
423 * gives true, return the result of guessTypesForExtension($ext).
424 *
425 * @param $mime String: the mime type, typically guessed from a file's content.
426 * @param $ext String: the file extension, as taken from the file name
427 *
428 * @return string the mime type
429 */
430 function improveTypeFromExtension( $mime, $ext ) {
431 if ( $mime === "unknown/unknown" ) {
432 if( $this->isRecognizableExtension( $ext ) ) {
433 wfDebug( __METHOD__. ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
434 } else {
435 /* Not something we can detect, so simply
436 * trust the file extension */
437 $mime = $this->guessTypesForExtension( $ext );
438 }
439 }
440 else if ( $mime === "application/x-opc+zip" ) {
441 if ( $this->isMatchingExtension( $ext, $mime ) ) {
442 /* A known file extension for an OPC file,
443 * find the proper mime type for that file extension */
444 $mime = $this->guessTypesForExtension( $ext );
445 } else {
446 wfDebug( __METHOD__. ": refusing to guess better type for $mime file, .$ext is not a known OPC extension.\n" );
447 $mime = "application/zip";
448 }
449 }
450
451 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
452 $mime = $this->mMimeTypeAliases[$mime];
453 }
454
455 wfDebug(__METHOD__.": improved mime type for .$ext: $mime\n");
456 return $mime;
457 }
458
459 /** mime type detection. This uses detectMimeType to detect the mime type of the file,
460 * but applies additional checks to determine some well known file formats that may be missed
461 * or misinterpreter by the default mime detection (namely XML based formats like XHTML or SVG,
462 * as well as ZIP based formats like OPC/ODF files).
463 *
464 * @param $file String: the file to check
465 * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
466 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
467 * improveTypeFromExtension($mime, $ext) later to improve mime type.
468 *
469 * @return string the mime type of $file
470 */
471 function guessMimeType( $file, $ext = true ) {
472 if( $ext ) { # TODO: make $ext default to false. Or better, remove it.
473 wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
474 }
475
476 $mime = $this->doGuessMimeType( $file, $ext );
477
478 if( !$mime ) {
479 wfDebug( __METHOD__.": internal type detection failed for $file (.$ext)...\n" );
480 $mime = $this->detectMimeType( $file, $ext );
481 }
482
483 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
484 $mime = $this->mMimeTypeAliases[$mime];
485 }
486
487 wfDebug(__METHOD__.": guessed mime type of $file: $mime\n");
488 return $mime;
489 }
490
491 private function doGuessMimeType( $file, $ext ) { # TODO: remove $ext param
492 // Read a chunk of the file
493 wfSuppressWarnings();
494 $f = fopen( $file, "rt" );
495 wfRestoreWarnings();
496 if( !$f ) return "unknown/unknown";
497 $head = fread( $f, 1024 );
498 fseek( $f, -65558, SEEK_END );
499 $tail = fread( $f, 65558 ); // 65558 = maximum size of a zip EOCDR
500 fclose( $f );
501
502 wfDebug( __METHOD__ . ": analyzing head and tail of $file for magic numbers.\n" );
503
504 // Hardcode a few magic number checks...
505 $headers = array(
506 // Multimedia...
507 'MThd' => 'audio/midi',
508 'OggS' => 'application/ogg',
509
510 // Image formats...
511 // Note that WMF may have a bare header, no magic number.
512 "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
513 "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
514 '%PDF' => 'application/pdf',
515 'gimp xcf' => 'image/x-xcf',
516
517 // Some forbidden fruit...
518 'MZ' => 'application/octet-stream', // DOS/Windows executable
519 "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
520 "\x7fELF" => 'application/octet-stream', // ELF binary
521 );
522
523 foreach( $headers as $magic => $candidate ) {
524 if( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
525 wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
526 return $candidate;
527 }
528 }
529
530 /* Look for WebM and Matroska files */
531 if( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
532 $doctype = strpos( $head, "\x42\x82" );
533 if( $doctype ) {
534 // Next byte is datasize, then data (sizes larger than 1 byte are very stupid muxers)
535 $data = substr($head, $doctype+3, 8);
536 if( strncmp( $data, "matroska", 8 ) == 0 ) {
537 wfDebug( __METHOD__ . ": recognized file as video/x-matroska\n" );
538 return "video/x-matroska";
539 } else if ( strncmp( $data, "webm", 4 ) == 0 ) {
540 wfDebug( __METHOD__ . ": recognized file as video/webm\n" );
541 return "video/webm";
542 }
543 }
544 wfDebug( __METHOD__ . ": unknown EBML file\n" );
545 return "unknown/unknown";
546 }
547
548 /*
549 * Look for PHP. Check for this before HTML/XML... Warning: this is a
550 * heuristic, and won't match a file with a lot of non-PHP before. It
551 * will also match text files which could be PHP. :)
552 *
553 * FIXME: For this reason, the check is probably useless -- an attacker
554 * could almost certainly just pad the file with a lot of nonsense to
555 * circumvent the check in any case where it would be a security
556 * problem. On the other hand, it causes harmful false positives (bug
557 * 16583). The heuristic has been cut down to exclude three-character
558 * strings like "<? ", but should it be axed completely?
559 */
560 if( ( strpos( $head, '<?php' ) !== false ) ||
561
562 ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
563 ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
564 ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
565 ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
566 ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
567
568 wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
569 return "application/x-php";
570 }
571
572 /*
573 * look for XML formats (XHTML and SVG)
574 */
575 $xml = new XmlTypeCheck( $file );
576 if( $xml->wellFormed ) {
577 global $wgXMLMimeTypes;
578 if( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
579 return $wgXMLMimeTypes[$xml->getRootElement()];
580 } else {
581 return 'application/xml';
582 }
583 }
584
585 /*
586 * look for shell scripts
587 */
588 $script_type = null;
589
590 # detect by shebang
591 if ( substr( $head, 0, 2) == "#!" ) {
592 $script_type = "ASCII";
593 } elseif ( substr( $head, 0, 5) == "\xef\xbb\xbf#!" ) {
594 $script_type = "UTF-8";
595 } elseif ( substr( $head, 0, 7) == "\xfe\xff\x00#\x00!" ) {
596 $script_type = "UTF-16BE";
597 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
598 $script_type= "UTF-16LE";
599 }
600
601 if ( $script_type ) {
602 if ( $script_type !== "UTF-8" && $script_type !== "ASCII") {
603 // Quick and dirty fold down to ASCII!
604 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
605 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
606 $head = '';
607 foreach( $chars as $codepoint ) {
608 if( $codepoint < 128 ) {
609 $head .= chr( $codepoint );
610 } else {
611 $head .= '?';
612 }
613 }
614 }
615
616 $match = array();
617
618 if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
619 $mime = "application/x-{$match[2]}";
620 wfDebug( __METHOD__.": shell script recognized as $mime\n" );
621 return $mime;
622 }
623 }
624
625 // Check for ZIP variants (before getimagesize)
626 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
627 wfDebug( __METHOD__.": ZIP header present in $file\n" );
628 return $this->detectZipType( $head, $tail, $ext );
629 }
630
631 wfSuppressWarnings();
632 $gis = getimagesize( $file );
633 wfRestoreWarnings();
634
635 if( $gis && isset( $gis['mime'] ) ) {
636 $mime = $gis['mime'];
637 wfDebug( __METHOD__.": getimagesize detected $file as $mime\n" );
638 return $mime;
639 }
640
641 // Also test DjVu
642 $deja = new DjVuImage( $file );
643 if( $deja->isValid() ) {
644 wfDebug( __METHOD__.": detected $file as image/vnd.djvu\n" );
645 return 'image/vnd.djvu';
646 }
647
648 return false;
649 }
650
651 /**
652 * Detect application-specific file type of a given ZIP file from its
653 * header data. Currently works for OpenDocument and OpenXML types...
654 * If can't tell, returns 'application/zip'.
655 *
656 * @param $header String: some reasonably-sized chunk of file header
657 * @param $tail String: the tail of the file
658 * @param $ext Mixed: the file extension, or true to extract it from the filename.
659 * Set it to false (default) to ignore the extension. DEPRECATED! Set to false,
660 * use improveTypeFromExtension($mime, $ext) later to improve mime type.
661 *
662 * @return string
663 */
664 function detectZipType( $header, $tail = null, $ext = false ) {
665 if( $ext ) { # TODO: remove $ext param
666 wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
667 }
668
669 $mime = 'application/zip';
670 $opendocTypes = array(
671 'chart-template',
672 'chart',
673 'formula-template',
674 'formula',
675 'graphics-template',
676 'graphics',
677 'image-template',
678 'image',
679 'presentation-template',
680 'presentation',
681 'spreadsheet-template',
682 'spreadsheet',
683 'text-template',
684 'text-master',
685 'text-web',
686 'text' );
687
688 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
689 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
690 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
691
692 $openxmlRegex = "/^\[Content_Types\].xml/";
693
694 if( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
695 $mime = $matches[1];
696 wfDebug( __METHOD__.": detected $mime from ZIP archive\n" );
697 } elseif( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
698 $mime = "application/x-opc+zip";
699 # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
700 if( $ext !== true && $ext !== false ) {
701 /** This is the mode used by getPropsFromPath
702 * These mime's are stored in the database, where we don't really want
703 * x-opc+zip, because we use it only for internal purposes
704 */
705 if( $this->isMatchingExtension( $ext, $mime) ) {
706 /* A known file extension for an OPC file,
707 * find the proper mime type for that file extension */
708 $mime = $this->guessTypesForExtension( $ext );
709 } else {
710 $mime = "application/zip";
711 }
712 }
713 wfDebug( __METHOD__.": detected an Open Packaging Conventions archive: $mime\n" );
714 } else if( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" &&
715 ($headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
716 preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
717 if( substr( $header, 512, 4) == "\xEC\xA5\xC1\x00" ) {
718 $mime = "application/msword";
719 }
720 switch( substr( $header, 512, 6) ) {
721 case "\xEC\xA5\xC1\x00\x0E\x00":
722 case "\xEC\xA5\xC1\x00\x1C\x00":
723 case "\xEC\xA5\xC1\x00\x43\x00":
724 $mime = "application/vnd.ms-powerpoint";
725 break;
726 case "\xFD\xFF\xFF\xFF\x10\x00":
727 case "\xFD\xFF\xFF\xFF\x1F\x00":
728 case "\xFD\xFF\xFF\xFF\x22\x00":
729 case "\xFD\xFF\xFF\xFF\x23\x00":
730 case "\xFD\xFF\xFF\xFF\x28\x00":
731 case "\xFD\xFF\xFF\xFF\x29\x00":
732 case "\xFD\xFF\xFF\xFF\x10\x02":
733 case "\xFD\xFF\xFF\xFF\x1F\x02":
734 case "\xFD\xFF\xFF\xFF\x22\x02":
735 case "\xFD\xFF\xFF\xFF\x23\x02":
736 case "\xFD\xFF\xFF\xFF\x28\x02":
737 case "\xFD\xFF\xFF\xFF\x29\x02":
738 $mime = "application/vnd.msexcel";
739 break;
740 }
741
742 wfDebug( __METHOD__.": detected a MS Office document with OPC trailer\n");
743 } else {
744 wfDebug( __METHOD__.": unable to identify type of ZIP archive\n" );
745 }
746 return $mime;
747 }
748
749 /** Internal mime type detection, please use guessMimeType() for application code instead.
750 * Detection is done using an external program, if $wgMimeDetectorCommand is set.
751 * Otherwise, the fileinfo extension and mime_content_type are tried (in this order), if they are available.
752 * If the dections fails and $ext is not false, the mime type is guessed from the file extension, using
753 * guessTypesForExtension.
754 * If the mime type is still unknown, getimagesize is used to detect the mime type if the file is an image.
755 * If no mime type can be determined, this function returns "unknown/unknown".
756 *
757 * @param $file String: the file to check
758 * @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
759 * Set it to false to ignore the extension. DEPRECATED! Set to false, use
760 * improveTypeFromExtension($mime, $ext) later to improve mime type.
761 *
762 * @return string the mime type of $file
763 * @access private
764 */
765 private function detectMimeType( $file, $ext = true ) {
766 global $wgMimeDetectorCommand;
767
768 if( $ext ) { # TODO: make $ext default to false. Or better, remove it.
769 wfDebug( __METHOD__.": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
770 }
771
772 $m = null;
773 if ( $wgMimeDetectorCommand ) {
774 $fn = wfEscapeShellArg( $file );
775 $m = `$wgMimeDetectorCommand $fn`;
776 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
777
778 # This required the fileinfo extension by PECL,
779 # see http://pecl.php.net/package/fileinfo
780 # This must be compiled into PHP
781 #
782 # finfo is the official replacement for the deprecated
783 # mime_content_type function, see below.
784 #
785 # If you may need to load the fileinfo extension at runtime, set
786 # $wgLoadFileinfoExtension in LocalSettings.php
787
788 $mime_magic_resource = finfo_open(FILEINFO_MIME); /* return mime type ala mimetype extension */
789
790 if ($mime_magic_resource) {
791 $m = finfo_file( $mime_magic_resource, $file );
792 finfo_close( $mime_magic_resource );
793 } else {
794 wfDebug( __METHOD__.": finfo_open failed on ".FILEINFO_MIME."!\n" );
795 }
796 } elseif ( function_exists( "mime_content_type" ) ) {
797
798 # NOTE: this function is available since PHP 4.3.0, but only if
799 # PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
800 #
801 # On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundeled with PHP;
802 # sometimes, this may even be needed under linus/unix.
803 #
804 # Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
805 # see http://www.php.net/manual/en/ref.mime-magic.php for details.
806
807 $m = mime_content_type($file);
808 } else {
809 wfDebug( __METHOD__.": no magic mime detector found!\n" );
810 }
811
812 if ( $m ) {
813 # normalize
814 $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
815 $m = trim( $m );
816 $m = strtolower( $m );
817
818 if ( strpos( $m, 'unknown' ) !== false ) {
819 $m = null;
820 } else {
821 wfDebug( __METHOD__.": magic mime type of $file: $m\n" );
822 return $m;
823 }
824 }
825
826 # if desired, look at extension as a fallback.
827 if ( $ext === true ) {
828 $i = strrpos( $file, '.' );
829 $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
830 }
831 if ( $ext ) {
832 if( $this->isRecognizableExtension( $ext ) ) {
833 wfDebug( __METHOD__. ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
834 } else {
835 $m = $this->guessTypesForExtension( $ext );
836 if ( $m ) {
837 wfDebug( __METHOD__.": extension mime type of $file: $m\n" );
838 return $m;
839 }
840 }
841 }
842
843 #unknown type
844 wfDebug( __METHOD__.": failed to guess mime type for $file!\n" );
845 return "unknown/unknown";
846 }
847
848 /**
849 * Determine the media type code for a file, using its mime type, name and possibly
850 * its contents.
851 *
852 * This function relies on the findMediaType(), mapping extensions and mime
853 * types to media types.
854 *
855 * @todo analyse file if need be
856 * @todo look at multiple extension, separately and together.
857 *
858 * @param $path String: full path to the image file, in case we have to look at the contents
859 * (if null, only the mime type is used to determine the media type code).
860 * @param $mime String: mime type. If null it will be guessed using guessMimeType.
861 *
862 * @return (int?string?) a value to be used with the MEDIATYPE_xxx constants.
863 */
864 function getMediaType( $path = null, $mime = null ) {
865 if( !$mime && !$path ) return MEDIATYPE_UNKNOWN;
866
867 # If mime type is unknown, guess it
868 if( !$mime ) $mime = $this->guessMimeType( $path, false );
869
870 # Special code for ogg - detect if it's video (theora),
871 # else label it as sound.
872 if( $mime == "application/ogg" && file_exists( $path ) ) {
873
874 // Read a chunk of the file
875 $f = fopen( $path, "rt" );
876 if ( !$f ) return MEDIATYPE_UNKNOWN;
877 $head = fread( $f, 256 );
878 fclose( $f );
879
880 $head = strtolower( $head );
881
882 # This is an UGLY HACK, file should be parsed correctly
883 if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
884 elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
885 elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
886 elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
887 else return MEDIATYPE_MULTIMEDIA;
888 }
889
890 # check for entry for full mime type
891 if( $mime ) {
892 $type = $this->findMediaType( $mime );
893 if( $type !== MEDIATYPE_UNKNOWN ) return $type;
894 }
895
896 # Check for entry for file extension
897 $e = null;
898 if ( $path ) {
899 $i = strrpos( $path, '.' );
900 $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
901
902 # TODO: look at multi-extension if this fails, parse from full path
903
904 $type = $this->findMediaType( '.' . $e );
905 if ( $type !== MEDIATYPE_UNKNOWN ) return $type;
906 }
907
908 # Check major mime type
909 if( $mime ) {
910 $i = strpos( $mime, '/' );
911 if( $i !== false ) {
912 $major = substr( $mime, 0, $i );
913 $type = $this->findMediaType( $major );
914 if( $type !== MEDIATYPE_UNKNOWN ) return $type;
915 }
916 }
917
918 if( !$type ) $type = MEDIATYPE_UNKNOWN;
919
920 return $type;
921 }
922
923 /** returns a media code matching the given mime type or file extension.
924 * File extensions are represented by a string starting with a dot (.) to
925 * distinguish them from mime types.
926 *
927 * This funktion relies on the mapping defined by $this->mMediaTypes
928 * @access private
929 */
930 function findMediaType( $extMime ) {
931 if ( strpos( $extMime, '.' ) === 0 ) { #if it's an extension, look up the mime types
932 $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
933 if ( !$m ) return MEDIATYPE_UNKNOWN;
934
935 $m = explode( ' ', $m );
936 } else {
937 # Normalize mime type
938 if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
939 $extMime = $this->mMimeTypeAliases[$extMime];
940 }
941
942 $m = array($extMime);
943 }
944
945 foreach ( $m as $mime ) {
946 foreach ( $this->mMediaTypes as $type => $codes ) {
947 if ( in_array($mime, $codes, true ) ) {
948 return $type;
949 }
950 }
951 }
952
953 return MEDIATYPE_UNKNOWN;
954 }
955
956 /**
957 * Get the MIME types that various versions of Internet Explorer would
958 * detect from a chunk of the content.
959 *
960 * @param $fileName String: the file name (unused at present)
961 * @param $chunk String: the first 256 bytes of the file
962 * @param $proposed String: the MIME type proposed by the server
963 */
964 public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
965 $ca = $this->getIEContentAnalyzer();
966 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
967 }
968
969 /**
970 * Get a cached instance of IEContentAnalyzer
971 */
972 protected function getIEContentAnalyzer() {
973 if ( is_null( $this->mIEAnalyzer ) ) {
974 $this->mIEAnalyzer = new IEContentAnalyzer;
975 }
976 return $this->mIEAnalyzer;
977 }
978 }