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