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