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