MediaWiki REL1_32
MimeAnalyzer.php
Go to the documentation of this file.
1<?php
22use Psr\Log\LoggerAwareInterface;
23use Psr\Log\LoggerInterface;
24
30class MimeAnalyzer implements LoggerAwareInterface {
32 protected $typeFile;
34 protected $infoFile;
36 protected $xmlTypes;
38 protected $initCallback;
40 protected $detectCallback;
42 protected $guessCallback;
44 protected $extCallback;
46 protected $mediaTypes = null;
48 protected $mimeTypeAliases = null;
50 protected $mimetoExt = null;
51
53 public $mExtToMime = null; // legacy name; field accessed by hooks
54
56 protected $IEAnalyzer;
57
59 private $extraTypes = '';
61 private $extraInfo = '';
62
64 private $logger;
65
85 protected static $wellKnownTypes = <<<EOT
86application/ogg ogx ogg ogm ogv oga spx opus
87application/pdf pdf
88application/vnd.oasis.opendocument.chart odc
89application/vnd.oasis.opendocument.chart-template otc
90application/vnd.oasis.opendocument.database odb
91application/vnd.oasis.opendocument.formula odf
92application/vnd.oasis.opendocument.formula-template otf
93application/vnd.oasis.opendocument.graphics odg
94application/vnd.oasis.opendocument.graphics-template otg
95application/vnd.oasis.opendocument.image odi
96application/vnd.oasis.opendocument.image-template oti
97application/vnd.oasis.opendocument.presentation odp
98application/vnd.oasis.opendocument.presentation-template otp
99application/vnd.oasis.opendocument.spreadsheet ods
100application/vnd.oasis.opendocument.spreadsheet-template ots
101application/vnd.oasis.opendocument.text odt
102application/vnd.oasis.opendocument.text-master otm
103application/vnd.oasis.opendocument.text-template ott
104application/vnd.oasis.opendocument.text-web oth
105application/javascript js
106application/x-shockwave-flash swf
107audio/midi mid midi kar
108audio/mpeg mpga mpa mp2 mp3
109audio/x-aiff aif aiff aifc
110audio/x-wav wav
111audio/ogg oga spx ogg opus
112audio/opus opus ogg oga ogg spx
113image/x-bmp bmp
114image/gif gif
115image/jpeg jpeg jpg jpe
116image/png png
117image/svg+xml svg
118image/svg svg
119image/tiff tiff tif
120image/vnd.djvu djvu
121image/x.djvu djvu
122image/x-djvu djvu
123image/x-portable-pixmap ppm
124image/x-xcf xcf
125text/plain txt
126text/html html htm
127video/ogg ogv ogm ogg
128video/mpeg mpg mpeg
129EOT;
130
137 protected static $wellKnownInfo = <<<EOT
138application/pdf [OFFICE]
139application/vnd.oasis.opendocument.chart [OFFICE]
140application/vnd.oasis.opendocument.chart-template [OFFICE]
141application/vnd.oasis.opendocument.database [OFFICE]
142application/vnd.oasis.opendocument.formula [OFFICE]
143application/vnd.oasis.opendocument.formula-template [OFFICE]
144application/vnd.oasis.opendocument.graphics [OFFICE]
145application/vnd.oasis.opendocument.graphics-template [OFFICE]
146application/vnd.oasis.opendocument.image [OFFICE]
147application/vnd.oasis.opendocument.image-template [OFFICE]
148application/vnd.oasis.opendocument.presentation [OFFICE]
149application/vnd.oasis.opendocument.presentation-template [OFFICE]
150application/vnd.oasis.opendocument.spreadsheet [OFFICE]
151application/vnd.oasis.opendocument.spreadsheet-template [OFFICE]
152application/vnd.oasis.opendocument.text [OFFICE]
153application/vnd.oasis.opendocument.text-template [OFFICE]
154application/vnd.oasis.opendocument.text-master [OFFICE]
155application/vnd.oasis.opendocument.text-web [OFFICE]
156application/javascript text/javascript application/x-javascript [EXECUTABLE]
157application/x-shockwave-flash [MULTIMEDIA]
158audio/midi [AUDIO]
159audio/x-aiff [AUDIO]
160audio/x-wav [AUDIO]
161audio/mp3 audio/mpeg [AUDIO]
162application/ogg audio/ogg video/ogg [MULTIMEDIA]
163image/x-bmp image/x-ms-bmp image/bmp [BITMAP]
164image/gif [BITMAP]
165image/jpeg [BITMAP]
166image/png [BITMAP]
167image/svg+xml [DRAWING]
168image/tiff [BITMAP]
169image/vnd.djvu [BITMAP]
170image/x-xcf [BITMAP]
171image/x-portable-pixmap [BITMAP]
172text/plain [TEXT]
173text/html [TEXT]
174video/ogg [VIDEO]
175video/mpeg [VIDEO]
176unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
177EOT;
178
194 public function __construct( array $params ) {
195 $this->typeFile = $params['typeFile'];
196 $this->infoFile = $params['infoFile'];
197 $this->xmlTypes = $params['xmlTypes'];
198 $this->initCallback = $params['initCallback'] ?? null;
199 $this->detectCallback = $params['detectCallback'] ?? null;
200 $this->guessCallback = $params['guessCallback'] ?? null;
201 $this->extCallback = $params['extCallback'] ?? null;
202 $this->logger = $params['logger'] ?? new \Psr\Log\NullLogger();
203
204 $this->loadFiles();
205 }
206
207 protected function loadFiles() {
212 # Allow media handling extensions adding MIME-types and MIME-info
213 if ( $this->initCallback ) {
214 call_user_func( $this->initCallback, $this );
215 }
216
217 $types = self::$wellKnownTypes;
218
219 $mimeTypeFile = $this->typeFile;
220 if ( $mimeTypeFile ) {
221 if ( is_file( $mimeTypeFile ) && is_readable( $mimeTypeFile ) ) {
222 $this->logger->info( __METHOD__ . ": loading mime types from $mimeTypeFile\n" );
223 $types .= "\n";
224 $types .= file_get_contents( $mimeTypeFile );
225 } else {
226 $this->logger->info( __METHOD__ . ": can't load mime types from $mimeTypeFile\n" );
227 }
228 } else {
229 $this->logger->info( __METHOD__ .
230 ": no mime types file defined, using built-ins only.\n" );
231 }
232
233 $types .= "\n" . $this->extraTypes;
234
235 $types = str_replace( [ "\r\n", "\n\r", "\n\n", "\r\r", "\r" ], "\n", $types );
236 $types = str_replace( "\t", " ", $types );
237
238 $this->mimetoExt = [];
239 $this->mExtToMime = [];
240
241 $lines = explode( "\n", $types );
242 foreach ( $lines as $s ) {
243 $s = trim( $s );
244 if ( empty( $s ) ) {
245 continue;
246 }
247 if ( strpos( $s, '#' ) === 0 ) {
248 continue;
249 }
250
251 $s = strtolower( $s );
252 $i = strpos( $s, ' ' );
253
254 if ( $i === false ) {
255 continue;
256 }
257
258 $mime = substr( $s, 0, $i );
259 $ext = trim( substr( $s, $i + 1 ) );
260
261 if ( empty( $ext ) ) {
262 continue;
263 }
264
265 if ( !empty( $this->mimetoExt[$mime] ) ) {
266 $this->mimetoExt[$mime] .= ' ' . $ext;
267 } else {
268 $this->mimetoExt[$mime] = $ext;
269 }
270
271 $extensions = explode( ' ', $ext );
272
273 foreach ( $extensions as $e ) {
274 $e = trim( $e );
275 if ( empty( $e ) ) {
276 continue;
277 }
278
279 if ( !empty( $this->mExtToMime[$e] ) ) {
280 $this->mExtToMime[$e] .= ' ' . $mime;
281 } else {
282 $this->mExtToMime[$e] = $mime;
283 }
284 }
285 }
286
291 $mimeInfoFile = $this->infoFile;
292
293 $info = self::$wellKnownInfo;
294
295 if ( $mimeInfoFile ) {
296 if ( is_file( $mimeInfoFile ) && is_readable( $mimeInfoFile ) ) {
297 $this->logger->info( __METHOD__ . ": loading mime info from $mimeInfoFile\n" );
298 $info .= "\n";
299 $info .= file_get_contents( $mimeInfoFile );
300 } else {
301 $this->logger->info( __METHOD__ . ": can't load mime info from $mimeInfoFile\n" );
302 }
303 } else {
304 $this->logger->info( __METHOD__ .
305 ": no mime info file defined, using built-ins only.\n" );
306 }
307
308 $info .= "\n" . $this->extraInfo;
309
310 $info = str_replace( [ "\r\n", "\n\r", "\n\n", "\r\r", "\r" ], "\n", $info );
311 $info = str_replace( "\t", " ", $info );
312
313 $this->mimeTypeAliases = [];
314 $this->mediaTypes = [];
315
316 $lines = explode( "\n", $info );
317 foreach ( $lines as $s ) {
318 $s = trim( $s );
319 if ( empty( $s ) ) {
320 continue;
321 }
322 if ( strpos( $s, '#' ) === 0 ) {
323 continue;
324 }
325
326 $s = strtolower( $s );
327 $i = strpos( $s, ' ' );
328
329 if ( $i === false ) {
330 continue;
331 }
332
333 # print "processing MIME INFO line $s<br>";
334
335 $match = [];
336 if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
337 $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
338 $mtype = trim( strtoupper( $match[1] ) );
339 } else {
340 $mtype = MEDIATYPE_UNKNOWN;
341 }
342
343 $m = explode( ' ', $s );
344
345 if ( !isset( $this->mediaTypes[$mtype] ) ) {
346 $this->mediaTypes[$mtype] = [];
347 }
348
349 foreach ( $m as $mime ) {
350 $mime = trim( $mime );
351 if ( empty( $mime ) ) {
352 continue;
353 }
354
355 $this->mediaTypes[$mtype][] = $mime;
356 }
357
358 if ( count( $m ) > 1 ) {
359 $main = $m[0];
360 $mCount = count( $m );
361 for ( $i = 1; $i < $mCount; $i += 1 ) {
362 $mime = $m[$i];
363 $this->mimeTypeAliases[$mime] = $main;
364 }
365 }
366 }
367 }
368
369 public function setLogger( LoggerInterface $logger ) {
370 $this->logger = $logger;
371 }
372
379 public function addExtraTypes( $types ) {
380 $this->extraTypes .= "\n" . $types;
381 }
382
389 public function addExtraInfo( $info ) {
390 $this->extraInfo .= "\n" . $info;
391 }
392
401 public function getExtensionsForType( $mime ) {
402 $mime = strtolower( $mime );
403
404 // Check the mime-to-ext map
405 if ( isset( $this->mimetoExt[$mime] ) ) {
406 return $this->mimetoExt[$mime];
407 }
408
409 // Resolve the MIME type to the canonical type
410 if ( isset( $this->mimeTypeAliases[$mime] ) ) {
411 $mime = $this->mimeTypeAliases[$mime];
412 if ( isset( $this->mimetoExt[$mime] ) ) {
413 return $this->mimetoExt[$mime];
414 }
415 }
416
417 return null;
418 }
419
427 public function getTypesForExtension( $ext ) {
428 $ext = strtolower( $ext );
429
430 $r = $this->mExtToMime[$ext] ?? null;
431 return $r;
432 }
433
441 public function guessTypesForExtension( $ext ) {
442 $m = $this->getTypesForExtension( $ext );
443 if ( is_null( $m ) ) {
444 return null;
445 }
446
447 // TODO: Check if this is needed; strtok( $m, ' ' ) should be sufficient
448 $m = trim( $m );
449 $m = preg_replace( '/\s.*$/', '', $m );
450
451 return $m;
452 }
453
463 public function isMatchingExtension( $extension, $mime ) {
464 $ext = $this->getExtensionsForType( $mime );
465
466 if ( !$ext ) {
467 return null; // Unknown MIME type
468 }
469
470 $ext = explode( ' ', $ext );
471
472 $extension = strtolower( $extension );
473 return in_array( $extension, $ext );
474 }
475
484 public function isPHPImageType( $mime ) {
485 // As defined by imagegetsize and image_type_to_mime
486 static $types = [
487 'image/gif', 'image/jpeg', 'image/png',
488 'image/x-bmp', 'image/xbm', 'image/tiff',
489 'image/jp2', 'image/jpeg2000', 'image/iff',
490 'image/xbm', 'image/x-xbitmap',
491 'image/vnd.wap.wbmp', 'image/vnd.xiff',
492 'image/x-photoshop',
493 'application/x-shockwave-flash',
494 ];
495
496 return in_array( $mime, $types );
497 }
498
511 function isRecognizableExtension( $extension ) {
512 static $types = [
513 // Types recognized by getimagesize()
514 'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
515 'bmp', 'tiff', 'tif', 'jpc', 'jp2',
516 'jpx', 'jb2', 'swc', 'iff', 'wbmp',
517 'xbm',
518
519 // Formats we recognize magic numbers for
520 'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx', 'opus',
521 'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
522 'webp', 'mp3',
523
524 // XML formats we sure hope we recognize reliably
525 'svg',
526
527 // 3D formats
528 'stl',
529 ];
530 return in_array( strtolower( $extension ), $types );
531 }
532
544 public function improveTypeFromExtension( $mime, $ext ) {
545 if ( $mime === 'unknown/unknown' ) {
546 if ( $this->isRecognizableExtension( $ext ) ) {
547 $this->logger->info( __METHOD__ . ': refusing to guess mime type for .' .
548 "$ext file, we should have recognized it\n" );
549 } else {
550 // Not something we can detect, so simply
551 // trust the file extension
552 $mime = $this->guessTypesForExtension( $ext );
553 }
554 } elseif ( $mime === 'application/x-opc+zip' ) {
555 if ( $this->isMatchingExtension( $ext, $mime ) ) {
556 // A known file extension for an OPC file,
557 // find the proper MIME type for that file extension
558 $mime = $this->guessTypesForExtension( $ext );
559 } else {
560 $this->logger->info( __METHOD__ .
561 ": refusing to guess better type for $mime file, " .
562 ".$ext is not a known OPC extension.\n" );
563 $mime = 'application/zip';
564 }
565 } elseif ( $mime === 'text/plain' && $this->findMediaType( ".$ext" ) === MEDIATYPE_TEXT ) {
566 // Textual types are sometimes not recognized properly.
567 // If detected as text/plain, and has an extension which is textual
568 // improve to the extension's type. For example, csv and json are often
569 // misdetected as text/plain.
570 $mime = $this->guessTypesForExtension( $ext );
571 }
572
573 # Media handling extensions can improve the MIME detected
574 $callback = $this->extCallback;
575 if ( $callback ) {
576 $callback( $this, $ext, $mime /* by reference */ );
577 }
578
579 if ( isset( $this->mimeTypeAliases[$mime] ) ) {
580 $mime = $this->mimeTypeAliases[$mime];
581 }
582
583 $this->logger->info( __METHOD__ . ": improved mime type for .$ext: $mime\n" );
584 return $mime;
585 }
586
601 public function guessMimeType( $file, $ext = true ) {
602 if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
603 $this->logger->info( __METHOD__ .
604 ": WARNING: use of the \$ext parameter is deprecated. " .
605 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
606 }
607
608 $mime = $this->doGuessMimeType( $file, $ext );
609
610 if ( !$mime ) {
611 $this->logger->info( __METHOD__ .
612 ": internal type detection failed for $file (.$ext)...\n" );
613 $mime = $this->detectMimeType( $file, $ext );
614 }
615
616 if ( isset( $this->mimeTypeAliases[$mime] ) ) {
617 $mime = $this->mimeTypeAliases[$mime];
618 }
619
620 $this->logger->info( __METHOD__ . ": guessed mime type of $file: $mime\n" );
621 return $mime;
622 }
623
634 private function doGuessMimeType( $file, $ext ) {
635 // Read a chunk of the file
636 Wikimedia\suppressWarnings();
637 $f = fopen( $file, 'rb' );
638 Wikimedia\restoreWarnings();
639
640 if ( !$f ) {
641 return 'unknown/unknown';
642 }
643
644 $fsize = filesize( $file );
645 if ( $fsize === false ) {
646 return 'unknown/unknown';
647 }
648
649 $head = fread( $f, 1024 );
650 $tailLength = min( 65558, $fsize ); // 65558 = maximum size of a zip EOCDR
651 if ( fseek( $f, -1 * $tailLength, SEEK_END ) === -1 ) {
652 throw new UnexpectedValueException(
653 "Seeking $tailLength bytes from EOF failed in " . __METHOD__ );
654 }
655 $tail = $tailLength ? fread( $f, $tailLength ) : '';
656 fclose( $f );
657
658 $this->logger->info( __METHOD__ .
659 ": analyzing head and tail of $file for magic numbers.\n" );
660
661 // Hardcode a few magic number checks...
662 $headers = [
663 // Multimedia...
664 'MThd' => 'audio/midi',
665 'OggS' => 'application/ogg',
666 'ID3' => 'audio/mpeg',
667 "\xff\xfb" => 'audio/mpeg', // MPEG-1 layer 3
668 "\xff\xf3" => 'audio/mpeg', // MPEG-2 layer 3 (lower sample rates)
669 "\xff\xe3" => 'audio/mpeg', // MPEG-2.5 layer 3 (very low sample rates)
670
671 // Image formats...
672 // Note that WMF may have a bare header, no magic number.
673 "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
674 "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
675 '%PDF' => 'application/pdf',
676 'gimp xcf' => 'image/x-xcf',
677
678 // Some forbidden fruit...
679 'MZ' => 'application/octet-stream', // DOS/Windows executable
680 "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
681 "\x7fELF" => 'application/octet-stream', // ELF binary
682 ];
683
684 foreach ( $headers as $magic => $candidate ) {
685 if ( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
686 $this->logger->info( __METHOD__ .
687 ": magic header in $file recognized as $candidate\n" );
688 return $candidate;
689 }
690 }
691
692 /* Look for WebM and Matroska files */
693 if ( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
694 $doctype = strpos( $head, "\x42\x82" );
695 if ( $doctype ) {
696 // Next byte is datasize, then data (sizes larger than 1 byte are stupid muxers)
697 $data = substr( $head, $doctype + 3, 8 );
698 if ( strncmp( $data, "matroska", 8 ) == 0 ) {
699 $this->logger->info( __METHOD__ . ": recognized file as video/x-matroska\n" );
700 return "video/x-matroska";
701 } elseif ( strncmp( $data, "webm", 4 ) == 0 ) {
702 // XXX HACK look for a video track, if we don't find it, this is an audio file
703 $videotrack = strpos( $head, "\x86\x85V_VP" );
704
705 if ( $videotrack ) {
706 // There is a video track, so this is a video file.
707 $this->logger->info( __METHOD__ . ": recognized file as video/webm\n" );
708 return "video/webm";
709 }
710
711 $this->logger->info( __METHOD__ . ": recognized file as audio/webm\n" );
712 return "audio/webm";
713 }
714 }
715 $this->logger->info( __METHOD__ . ": unknown EBML file\n" );
716 return "unknown/unknown";
717 }
718
719 /* Look for WebP */
720 if ( strncmp( $head, "RIFF", 4 ) == 0 &&
721 strncmp( substr( $head, 8, 7 ), "WEBPVP8", 7 ) == 0
722 ) {
723 $this->logger->info( __METHOD__ . ": recognized file as image/webp\n" );
724 return "image/webp";
725 }
726
739 if ( ( strpos( $head, '<?php' ) !== false ) ||
740 ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
741 ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
742 ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
743 ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
744 ( strpos( $head, "<\x00?\x00=" ) !== false )
745 ) {
746 $this->logger->info( __METHOD__ . ": recognized $file as application/x-php\n" );
747 return 'application/x-php';
748 }
749
753 Wikimedia\suppressWarnings();
754 $xml = new XmlTypeCheck( $file );
755 Wikimedia\restoreWarnings();
756 if ( $xml->wellFormed ) {
757 $xmlTypes = $this->xmlTypes;
758 if ( isset( $xmlTypes[$xml->getRootElement()] ) ) {
759 return $xmlTypes[$xml->getRootElement()];
760 } else {
761 return 'application/xml';
762 }
763 }
764
768 $script_type = null;
769
770 # detect by shebang
771 if ( substr( $head, 0, 2 ) == "#!" ) {
772 $script_type = "ASCII";
773 } elseif ( substr( $head, 0, 5 ) == "\xef\xbb\xbf#!" ) {
774 $script_type = "UTF-8";
775 } elseif ( substr( $head, 0, 7 ) == "\xfe\xff\x00#\x00!" ) {
776 $script_type = "UTF-16BE";
777 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
778 $script_type = "UTF-16LE";
779 }
780
781 if ( $script_type ) {
782 if ( $script_type !== "UTF-8" && $script_type !== "ASCII" ) {
783 // Quick and dirty fold down to ASCII!
784 $pack = [ 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' ];
785 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
786 $head = '';
787 foreach ( $chars as $codepoint ) {
788 if ( $codepoint < 128 ) {
789 $head .= chr( $codepoint );
790 } else {
791 $head .= '?';
792 }
793 }
794 }
795
796 $match = [];
797
798 if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
799 $mime = "application/x-{$match[2]}";
800 $this->logger->info( __METHOD__ . ": shell script recognized as $mime\n" );
801 return $mime;
802 }
803 }
804
805 // Check for ZIP variants (before getimagesize)
806 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
807 $this->logger->info( __METHOD__ . ": ZIP header present in $file\n" );
808 return $this->detectZipType( $head, $tail, $ext );
809 }
810
811 // Check for STL (3D) files
812 // @see https://en.wikipedia.org/wiki/STL_(file_format)
813 if ( $fsize >= 15 &&
814 stripos( $head, 'SOLID ' ) === 0 &&
815 preg_match( '/\RENDSOLID .*$/i', $tail ) ) {
816 // ASCII STL file
817 return 'application/sla';
818 } elseif ( $fsize > 84 ) {
819 // binary STL file
820 $triangles = substr( $head, 80, 4 );
821 $triangles = unpack( 'V', $triangles );
822 $triangles = reset( $triangles );
823 if ( $triangles !== false && $fsize === 84 + ( $triangles * 50 ) ) {
824 return 'application/sla';
825 }
826 }
827
828 Wikimedia\suppressWarnings();
829 $gis = getimagesize( $file );
830 Wikimedia\restoreWarnings();
831
832 if ( $gis && isset( $gis['mime'] ) ) {
833 $mime = $gis['mime'];
834 $this->logger->info( __METHOD__ . ": getimagesize detected $file as $mime\n" );
835 return $mime;
836 }
837
838 # Media handling extensions can guess the MIME by content
839 # It's intentionally here so that if core is wrong about a type (false positive),
840 # people will hopefully nag and submit patches :)
841 $mime = false;
842 # Some strings by reference for performance - assuming well-behaved hooks
843 $callback = $this->guessCallback;
844 if ( $callback ) {
845 $callback( $this, $head, $tail, $file, $mime /* by reference */ );
846 };
847
848 return $mime;
849 }
850
864 function detectZipType( $header, $tail = null, $ext = false ) {
865 if ( $ext ) { # TODO: remove $ext param
866 $this->logger->info( __METHOD__ .
867 ": WARNING: use of the \$ext parameter is deprecated. " .
868 "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
869 }
870
871 $mime = 'application/zip';
872 $opendocTypes = [
873 'chart-template',
874 'chart',
875 'formula-template',
876 'formula',
877 'graphics-template',
878 'graphics',
879 'image-template',
880 'image',
881 'presentation-template',
882 'presentation',
883 'spreadsheet-template',
884 'spreadsheet',
885 'text-template',
886 'text-master',
887 'text-web',
888 'text' ];
889
890 // https://lists.oasis-open.org/archives/office/200505/msg00006.html
891 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
892 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
893
894 $openxmlRegex = "/^\[Content_Types\].xml/";
895
896 if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
897 $mime = $matches[1];
898 $this->logger->info( __METHOD__ . ": detected $mime from ZIP archive\n" );
899 } elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
900 $mime = "application/x-opc+zip";
901 # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
902 if ( $ext !== true && $ext !== false ) {
907 if ( $this->isMatchingExtension( $ext, $mime ) ) {
908 /* A known file extension for an OPC file,
909 * find the proper mime type for that file extension
910 */
911 $mime = $this->guessTypesForExtension( $ext );
912 } else {
913 $mime = "application/zip";
914 }
915 }
916 $this->logger->info( __METHOD__ .
917 ": detected an Open Packaging Conventions archive: $mime\n" );
918 } elseif ( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" &&
919 ( $headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
920 preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
921 if ( substr( $header, 512, 4 ) == "\xEC\xA5\xC1\x00" ) {
922 $mime = "application/msword";
923 }
924 switch ( substr( $header, 512, 6 ) ) {
925 case "\xEC\xA5\xC1\x00\x0E\x00":
926 case "\xEC\xA5\xC1\x00\x1C\x00":
927 case "\xEC\xA5\xC1\x00\x43\x00":
928 $mime = "application/vnd.ms-powerpoint";
929 break;
930 case "\xFD\xFF\xFF\xFF\x10\x00":
931 case "\xFD\xFF\xFF\xFF\x1F\x00":
932 case "\xFD\xFF\xFF\xFF\x22\x00":
933 case "\xFD\xFF\xFF\xFF\x23\x00":
934 case "\xFD\xFF\xFF\xFF\x28\x00":
935 case "\xFD\xFF\xFF\xFF\x29\x00":
936 case "\xFD\xFF\xFF\xFF\x10\x02":
937 case "\xFD\xFF\xFF\xFF\x1F\x02":
938 case "\xFD\xFF\xFF\xFF\x22\x02":
939 case "\xFD\xFF\xFF\xFF\x23\x02":
940 case "\xFD\xFF\xFF\xFF\x28\x02":
941 case "\xFD\xFF\xFF\xFF\x29\x02":
942 $mime = "application/vnd.msexcel";
943 break;
944 }
945
946 $this->logger->info( __METHOD__ .
947 ": detected a MS Office document with OPC trailer\n" );
948 } else {
949 $this->logger->info( __METHOD__ . ": unable to identify type of ZIP archive\n" );
950 }
951 return $mime;
952 }
953
971 private function detectMimeType( $file, $ext = true ) {
973 if ( $ext ) {
974 $this->logger->info( __METHOD__ .
975 ": WARNING: use of the \$ext parameter is deprecated. "
976 . "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
977 }
978
979 $callback = $this->detectCallback;
980 $m = null;
981 if ( $callback ) {
982 $m = $callback( $file );
983 } else {
984 $m = mime_content_type( $file );
985 }
986
987 if ( $m ) {
988 # normalize
989 $m = preg_replace( '![;, ].*$!', '', $m ); # strip charset, etc
990 $m = trim( $m );
991 $m = strtolower( $m );
992
993 if ( strpos( $m, 'unknown' ) !== false ) {
994 $m = null;
995 } else {
996 $this->logger->info( __METHOD__ . ": magic mime type of $file: $m\n" );
997 return $m;
998 }
999 }
1000
1001 // If desired, look at extension as a fallback.
1002 if ( $ext === true ) {
1003 $i = strrpos( $file, '.' );
1004 $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
1005 }
1006 if ( $ext ) {
1007 if ( $this->isRecognizableExtension( $ext ) ) {
1008 $this->logger->info( __METHOD__ . ": refusing to guess mime type for .$ext file, "
1009 . "we should have recognized it\n" );
1010 } else {
1011 $m = $this->guessTypesForExtension( $ext );
1012 if ( $m ) {
1013 $this->logger->info( __METHOD__ . ": extension mime type of $file: $m\n" );
1014 return $m;
1015 }
1016 }
1017 }
1018
1019 // Unknown type
1020 $this->logger->info( __METHOD__ . ": failed to guess mime type for $file!\n" );
1021 return 'unknown/unknown';
1022 }
1023
1040 function getMediaType( $path = null, $mime = null ) {
1041 if ( !$mime && !$path ) {
1042 return MEDIATYPE_UNKNOWN;
1043 }
1044
1045 // If MIME type is unknown, guess it
1046 if ( !$mime ) {
1047 $mime = $this->guessMimeType( $path, false );
1048 }
1049
1050 // Special code for ogg - detect if it's video (theora),
1051 // else label it as sound.
1052 if ( $mime == 'application/ogg' && file_exists( $path ) ) {
1053 // Read a chunk of the file
1054 $f = fopen( $path, "rt" );
1055 if ( !$f ) {
1056 return MEDIATYPE_UNKNOWN;
1057 }
1058 $head = fread( $f, 256 );
1059 fclose( $f );
1060
1061 $head = str_replace( 'ffmpeg2theora', '', strtolower( $head ) );
1062
1063 // This is an UGLY HACK, file should be parsed correctly
1064 if ( strpos( $head, 'theora' ) !== false ) {
1065 return MEDIATYPE_VIDEO;
1066 } elseif ( strpos( $head, 'vorbis' ) !== false ) {
1067 return MEDIATYPE_AUDIO;
1068 } elseif ( strpos( $head, 'flac' ) !== false ) {
1069 return MEDIATYPE_AUDIO;
1070 } elseif ( strpos( $head, 'speex' ) !== false ) {
1071 return MEDIATYPE_AUDIO;
1072 } elseif ( strpos( $head, 'opus' ) !== false ) {
1073 return MEDIATYPE_AUDIO;
1074 } else {
1075 return MEDIATYPE_MULTIMEDIA;
1076 }
1077 }
1078
1079 $type = null;
1080 // Check for entry for full MIME type
1081 if ( $mime ) {
1082 $type = $this->findMediaType( $mime );
1083 if ( $type !== MEDIATYPE_UNKNOWN ) {
1084 return $type;
1085 }
1086 }
1087
1088 // Check for entry for file extension
1089 if ( $path ) {
1090 $i = strrpos( $path, '.' );
1091 $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1092
1093 // TODO: look at multi-extension if this fails, parse from full path
1094 $type = $this->findMediaType( '.' . $e );
1095 if ( $type !== MEDIATYPE_UNKNOWN ) {
1096 return $type;
1097 }
1098 }
1099
1100 // Check major MIME type
1101 if ( $mime ) {
1102 $i = strpos( $mime, '/' );
1103 if ( $i !== false ) {
1104 $major = substr( $mime, 0, $i );
1105 $type = $this->findMediaType( $major );
1106 if ( $type !== MEDIATYPE_UNKNOWN ) {
1107 return $type;
1108 }
1109 }
1110 }
1111
1112 if ( !$type ) {
1114 }
1115
1116 return $type;
1117 }
1118
1129 function findMediaType( $extMime ) {
1130 if ( strpos( $extMime, '.' ) === 0 ) {
1131 // If it's an extension, look up the MIME types
1132 $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
1133 if ( !$m ) {
1134 return MEDIATYPE_UNKNOWN;
1135 }
1136
1137 $m = explode( ' ', $m );
1138 } else {
1139 // Normalize MIME type
1140 if ( isset( $this->mimeTypeAliases[$extMime] ) ) {
1141 $extMime = $this->mimeTypeAliases[$extMime];
1142 }
1143
1144 $m = [ $extMime ];
1145 }
1146
1147 foreach ( $m as $mime ) {
1148 foreach ( $this->mediaTypes as $type => $codes ) {
1149 if ( in_array( $mime, $codes, true ) ) {
1150 return $type;
1151 }
1152 }
1153 }
1154
1155 return MEDIATYPE_UNKNOWN;
1156 }
1157
1163 public function getMediaTypes() {
1164 return array_keys( $this->mediaTypes );
1165 }
1166
1176 public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
1177 $ca = $this->getIEContentAnalyzer();
1178 return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
1179 }
1180
1186 protected function getIEContentAnalyzer() {
1187 if ( is_null( $this->IEAnalyzer ) ) {
1188 $this->IEAnalyzer = new IEContentAnalyzer;
1189 }
1190 return $this->IEAnalyzer;
1191 }
1192}
This class simulates Microsoft Internet Explorer's terribly broken and insecure MIME type detection a...
either a plain
Definition hooks.txt:2105
for adding new MIME info to the list Use $mimeMagic addExtraTypes( $stringOfTypes)
returning false will NOT prevent logging $e
Definition hooks.txt:2226
This document describes how event hooks work in the Renameuser extension For a more comprehensive guide to navigate to your root MediaWiki directory and read docs hooks txt
Definition hooks.txt:6
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
const MEDIATYPE_VIDEO
Definition defines.php:35
const MEDIATYPE_UNKNOWN
Definition defines.php:26
const MEDIATYPE_AUDIO
Definition defines.php:32
const MEDIATYPE_TEXT
Definition defines.php:41
const MEDIATYPE_MULTIMEDIA
Definition defines.php:37
if( $ext=='php'|| $ext=='php5') $mime
Definition router.php:59
$lines
Definition router.php:61
if(!is_readable( $file)) $ext
Definition router.php:55
$params
$header