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