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