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