Merge "Improve the shell cgroup feature"
[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 ( count( $m ) > 1 ) {
334 $main = $m[0];
335 for ( $i = 1; $i < count( $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 ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
665 ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
666 ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
667 ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
668 ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
669
670 wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
671 return 'application/x-php';
672 }
673
674 /**
675 * look for XML formats (XHTML and SVG)
676 */
677 $xml = new XmlTypeCheck( $file );
678 if ( $xml->wellFormed ) {
679 global $wgXMLMimeTypes;
680 if ( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
681 return $wgXMLMimeTypes[$xml->getRootElement()];
682 } else {
683 return 'application/xml';
684 }
685 }
686
687 /**
688 * look for shell scripts
689 */
690 $script_type = null;
691
692 # detect by shebang
693 if ( substr( $head, 0, 2) == "#!" ) {
694 $script_type = "ASCII";
695 } elseif ( substr( $head, 0, 5) == "\xef\xbb\xbf#!" ) {
696 $script_type = "UTF-8";
697 } elseif ( substr( $head, 0, 7) == "\xfe\xff\x00#\x00!" ) {
698 $script_type = "UTF-16BE";
699 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
700 $script_type = "UTF-16LE";
701 }
702
703 if ( $script_type ) {
704 if ( $script_type !== "UTF-8" && $script_type !== "ASCII") {
705 // Quick and dirty fold down to ASCII!
706 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
707 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
708 $head = '';
709 foreach( $chars as $codepoint ) {
710 if( $codepoint < 128 ) {
711 $head .= chr( $codepoint );
712 } else {
713 $head .= '?';
714 }
715 }
716 }
717
718 $match = array();
719
720 if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
721 $mime = "application/x-{$match[2]}";
722 wfDebug( __METHOD__ . ": shell script recognized as $mime\n" );
723 return $mime;
724 }
725 }
726
727 // Check for ZIP variants (before getimagesize)
728 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
729 wfDebug( __METHOD__ . ": ZIP header present in $file\n" );
730 return $this->detectZipType( $head, $tail, $ext );
731 }
732
733 wfSuppressWarnings();
734 $gis = getimagesize( $file );
735 wfRestoreWarnings();
736
737 if( $gis && isset( $gis['mime'] ) ) {
738 $mime = $gis['mime'];
739 wfDebug( __METHOD__ . ": getimagesize detected $file as $mime\n" );
740 return $mime;
741 }
742
743 // Also test DjVu
744 $deja = new DjVuImage( $file );
745 if( $deja->isValid() ) {
746 wfDebug( __METHOD__ . ": detected $file as image/vnd.djvu\n" );
747 return 'image/vnd.djvu';
748 }
749
750 return false;
751 }
752
753 /**
754 * Detect application-specific file type of a given ZIP file from its
755 * header data. Currently works for OpenDocument and OpenXML types...
756 * If can't tell, returns 'application/zip'.
757 *
758 * @param $header String: some reasonably-sized chunk of file header
759 * @param $tail String: the tail of the file
760 * @param $ext Mixed: the file extension, or true to extract it from the filename.
761 * Set it to false (default) to ignore the extension. DEPRECATED! Set to false,
762 * use improveTypeFromExtension($mime, $ext) later to improve mime type.
763 *
764 * @return string
765 */
766 function detectZipType( $header, $tail = null, $ext = false ) {
767 if( $ext ) { # TODO: remove $ext param
768 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. " .
769 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
770 }
771
772 $mime = 'application/zip';
773 $opendocTypes = array(
774 'chart-template',
775 'chart',
776 'formula-template',
777 'formula',
778 'graphics-template',
779 'graphics',
780 'image-template',
781 'image',
782 'presentation-template',
783 'presentation',
784 'spreadsheet-template',
785 'spreadsheet',
786 'text-template',
787 'text-master',
788 'text-web',
789 'text' );
790
791 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
792 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
793 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
794
795 $openxmlRegex = "/^\[Content_Types\].xml/";
796
797 if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
798 $mime = $matches[1];
799 wfDebug( __METHOD__ . ": detected $mime from ZIP archive\n" );
800 } elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
801 $mime = "application/x-opc+zip";
802 # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
803 if ( $ext !== true && $ext !== false ) {
804 /** This is the mode used by getPropsFromPath
805 * These mime's are stored in the database, where we don't really want
806 * x-opc+zip, because we use it only for internal purposes
807 */
808 if ( $this->isMatchingExtension( $ext, $mime) ) {
809 /* A known file extension for an OPC file,
810 * find the proper mime type for that file extension */
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 dections 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 $file String: the file to check
864 * @param $ext Mixed: 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 if ( $ext ) { # TODO: make $ext default to false. Or better, remove it.
874 wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
875 }
876
877 $m = null;
878 if ( $wgMimeDetectorCommand ) {
879 // @todo FIXME: Use wfShellExec
880 $fn = wfEscapeShellArg( $file );
881 $m = `$wgMimeDetectorCommand $fn`;
882 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
883
884 # This required the fileinfo extension by PECL,
885 # see http://pecl.php.net/package/fileinfo
886 # This must be compiled into PHP
887 #
888 # finfo is the official replacement for the deprecated
889 # mime_content_type function, see below.
890 #
891 # If you may need to load the fileinfo extension at runtime, set
892 # $wgLoadFileinfoExtension in LocalSettings.php
893
894 $mime_magic_resource = finfo_open( FILEINFO_MIME ); /* return mime type ala mimetype extension */
895
896 if ( $mime_magic_resource ) {
897 $m = finfo_file( $mime_magic_resource, $file );
898 finfo_close( $mime_magic_resource );
899 } else {
900 wfDebug( __METHOD__ . ": finfo_open failed on ".FILEINFO_MIME."!\n" );
901 }
902 } elseif ( function_exists( "mime_content_type" ) ) {
903
904 # NOTE: this function is available since PHP 4.3.0, but only if
905 # PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
906 #
907 # On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundeled with PHP;
908 # sometimes, this may even be needed under linus/unix.
909 #
910 # Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
911 # see http://www.php.net/manual/en/ref.mime-magic.php for details.
912
913 $m = mime_content_type( $file );
914 } else {
915 wfDebug( __METHOD__ . ": no magic mime detector found!\n" );
916 }
917
918 if ( $m ) {
919 # normalize
920 $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
921 $m = trim( $m );
922 $m = strtolower( $m );
923
924 if ( strpos( $m, 'unknown' ) !== false ) {
925 $m = null;
926 } else {
927 wfDebug( __METHOD__ . ": magic mime type of $file: $m\n" );
928 return $m;
929 }
930 }
931
932 // If desired, look at extension as a fallback.
933 if ( $ext === true ) {
934 $i = strrpos( $file, '.' );
935 $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
936 }
937 if ( $ext ) {
938 if( $this->isRecognizableExtension( $ext ) ) {
939 wfDebug( __METHOD__ . ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
940 } else {
941 $m = $this->guessTypesForExtension( $ext );
942 if ( $m ) {
943 wfDebug( __METHOD__ . ": extension mime type of $file: $m\n" );
944 return $m;
945 }
946 }
947 }
948
949 // Unknown type
950 wfDebug( __METHOD__ . ": failed to guess mime type for $file!\n" );
951 return 'unknown/unknown';
952 }
953
954 /**
955 * Determine the media type code for a file, using its mime type, name and
956 * possibly its contents.
957 *
958 * This function relies on the findMediaType(), mapping extensions and mime
959 * types to media types.
960 *
961 * @todo analyse file if need be
962 * @todo look at multiple extension, separately and together.
963 *
964 * @param $path String: full path to the image file, in case we have to look at the contents
965 * (if null, only the mime type is used to determine the media type code).
966 * @param $mime String: mime type. If null it will be guessed using guessMimeType.
967 *
968 * @return (int?string?) a value to be used with the MEDIATYPE_xxx constants.
969 */
970 function getMediaType( $path = null, $mime = null ) {
971 if( !$mime && !$path ) {
972 return MEDIATYPE_UNKNOWN;
973 }
974
975 // If mime type is unknown, guess it
976 if( !$mime ) {
977 $mime = $this->guessMimeType( $path, false );
978 }
979
980 // Special code for ogg - detect if it's video (theora),
981 // else label it as sound.
982 if ( $mime == 'application/ogg' && file_exists( $path ) ) {
983
984 // Read a chunk of the file
985 $f = fopen( $path, "rt" );
986 if ( !$f ) return MEDIATYPE_UNKNOWN;
987 $head = fread( $f, 256 );
988 fclose( $f );
989
990 $head = strtolower( $head );
991
992 // This is an UGLY HACK, file should be parsed correctly
993 if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
994 elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
995 elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
996 elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
997 else return MEDIATYPE_MULTIMEDIA;
998 }
999
1000 // Check for entry for full mime type
1001 if( $mime ) {
1002 $type = $this->findMediaType( $mime );
1003 if ( $type !== MEDIATYPE_UNKNOWN ) {
1004 return $type;
1005 }
1006 }
1007
1008 // Check for entry for file extension
1009 if ( $path ) {
1010 $i = strrpos( $path, '.' );
1011 $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1012
1013 // TODO: look at multi-extension if this fails, parse from full path
1014 $type = $this->findMediaType( '.' . $e );
1015 if ( $type !== MEDIATYPE_UNKNOWN ) {
1016 return $type;
1017 }
1018 }
1019
1020 // Check major mime type
1021 if ( $mime ) {
1022 $i = strpos( $mime, '/' );
1023 if ( $i !== false ) {
1024 $major = substr( $mime, 0, $i );
1025 $type = $this->findMediaType( $major );
1026 if ( $type !== MEDIATYPE_UNKNOWN ) {
1027 return $type;
1028 }
1029 }
1030 }
1031
1032 if( !$type ) {
1033 $type = MEDIATYPE_UNKNOWN;
1034 }
1035
1036 return $type;
1037 }
1038
1039 /**
1040 * Returns a media code matching the given mime type or file extension.
1041 * File extensions are represented by a string starting with a dot (.) to
1042 * distinguish them from mime types.
1043 *
1044 * This funktion relies on the mapping defined by $this->mMediaTypes
1045 * @access private
1046 * @return int|string
1047 */
1048 function findMediaType( $extMime ) {
1049 if ( strpos( $extMime, '.' ) === 0 ) {
1050 // If it's an extension, look up the mime types
1051 $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
1052 if ( !$m ) {
1053 return MEDIATYPE_UNKNOWN;
1054 }
1055
1056 $m = explode( ' ', $m );
1057 } else {
1058 // Normalize mime type
1059 if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
1060 $extMime = $this->mMimeTypeAliases[$extMime];
1061 }
1062
1063 $m = array( $extMime );
1064 }
1065
1066 foreach ( $m as $mime ) {
1067 foreach ( $this->mMediaTypes as $type => $codes ) {
1068 if ( in_array( $mime, $codes, true ) ) {
1069 return $type;
1070 }
1071 }
1072 }
1073
1074 return MEDIATYPE_UNKNOWN;
1075 }
1076
1077 /**
1078 * Get the MIME types that various versions of Internet Explorer would
1079 * detect from a chunk of the content.
1080 *
1081 * @param $fileName String: the file name (unused at present)
1082 * @param $chunk String: the first 256 bytes of the file
1083 * @param $proposed String: the MIME type proposed by the server
1084 * @return Array
1085 */
1086 public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
1087 $ca = $this->getIEContentAnalyzer();
1088 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
1089 }
1090
1091 /**
1092 * Get a cached instance of IEContentAnalyzer
1093 *
1094 * @return IEContentAnalyzer
1095 */
1096 protected function getIEContentAnalyzer() {
1097 if ( is_null( $this->mIEAnalyzer ) ) {
1098 $this->mIEAnalyzer = new IEContentAnalyzer;
1099 }
1100 return $this->mIEAnalyzer;
1101 }
1102 }