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