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