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