* Improved upload file type detection for OpenDocument formats
[lhc/web/wiklou.git] / includes / MimeMagic.php
1 <?php
2 /** Module defining helper functions for detecting and dealing with mime types.
3 *
4 */
5
6 /** Defines a set of well known mime types
7 * This is used as a fallback to mime.types files.
8 * An extensive list of well known mime types is provided by
9 * the file mime.types in the includes directory.
10 */
11 define('MM_WELL_KNOWN_MIME_TYPES',<<<END_STRING
12 application/ogg ogg ogm ogv
13 application/pdf pdf
14 application/vnd.oasis.opendocument.chart odc
15 application/vnd.oasis.opendocument.chart-template otc
16 application/vnd.oasis.opendocument.formula odf
17 application/vnd.oasis.opendocument.formula-template otf
18 application/vnd.oasis.opendocument.graphics odg
19 application/vnd.oasis.opendocument.graphics-template otg
20 application/vnd.oasis.opendocument.image odi
21 application/vnd.oasis.opendocument.image-template oti
22 application/vnd.oasis.opendocument.presentation odp
23 application/vnd.oasis.opendocument.presentation-template otp
24 application/vnd.oasis.opendocument.spreadsheet ods
25 application/vnd.oasis.opendocument.spreadsheet-template ots
26 application/vnd.oasis.opendocument.text odt
27 application/vnd.oasis.opendocument.text-template ott
28 application/vnd.oasis.opendocument.text-master otm
29 application/vnd.oasis.opendocument.text-web oth
30 application/x-javascript js
31 application/x-shockwave-flash swf
32 audio/midi mid midi kar
33 audio/mpeg mpga mpa mp2 mp3
34 audio/x-aiff aif aiff aifc
35 audio/x-wav wav
36 audio/ogg ogg
37 image/x-bmp bmp
38 image/gif gif
39 image/jpeg jpeg jpg jpe
40 image/png png
41 image/svg+xml image/svg svg
42 image/tiff tiff tif
43 image/vnd.djvu image/x.djvu image/x-djvu djvu
44 image/x-portable-pixmap ppm
45 image/x-xcf xcf
46 text/plain txt
47 text/html html htm
48 video/ogg ogm ogg ogv
49 video/mpeg mpg mpeg
50 END_STRING
51 );
52
53 /** Defines a set of well known mime info entries
54 * This is used as a fallback to mime.info files.
55 * An extensive list of well known mime types is provided by
56 * the file mime.info in the includes directory.
57 */
58 define('MM_WELL_KNOWN_MIME_INFO', <<<END_STRING
59 application/pdf [OFFICE]
60 application/vnd.oasis.opendocument.chart [OFFICE]
61 application/vnd.oasis.opendocument.chart-template [OFFICE]
62 application/vnd.oasis.opendocument.formula [OFFICE]
63 application/vnd.oasis.opendocument.formula-template [OFFICE]
64 application/vnd.oasis.opendocument.graphics [OFFICE]
65 application/vnd.oasis.opendocument.graphics-template [OFFICE]
66 application/vnd.oasis.opendocument.image [OFFICE]
67 application/vnd.oasis.opendocument.image-template [OFFICE]
68 application/vnd.oasis.opendocument.presentation [OFFICE]
69 application/vnd.oasis.opendocument.presentation-template [OFFICE]
70 application/vnd.oasis.opendocument.spreadsheet [OFFICE]
71 application/vnd.oasis.opendocument.spreadsheet-template [OFFICE]
72 application/vnd.oasis.opendocument.text [OFFICE]
73 application/vnd.oasis.opendocument.text-template [OFFICE]
74 application/vnd.oasis.opendocument.text-master [OFFICE]
75 application/vnd.oasis.opendocument.text-web [OFFICE]
76 text/javascript application/x-javascript [EXECUTABLE]
77 application/x-shockwave-flash [MULTIMEDIA]
78 audio/midi [AUDIO]
79 audio/x-aiff [AUDIO]
80 audio/x-wav [AUDIO]
81 audio/mp3 audio/mpeg [AUDIO]
82 application/ogg audio/ogg video/ogg [MULTIMEDIA]
83 image/x-bmp image/bmp [BITMAP]
84 image/gif [BITMAP]
85 image/jpeg [BITMAP]
86 image/png [BITMAP]
87 image/svg+xml [DRAWING]
88 image/tiff [BITMAP]
89 image/vnd.djvu [BITMAP]
90 image/x-xcf [BITMAP]
91 image/x-portable-pixmap [BITMAP]
92 text/plain [TEXT]
93 text/html [TEXT]
94 video/ogg [VIDEO]
95 video/mpeg [VIDEO]
96 unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
97 END_STRING
98 );
99
100 #note: because this file is possibly included by a function,
101 #we need to access the global scope explicitely!
102 global $wgLoadFileinfoExtension;
103
104 if ($wgLoadFileinfoExtension) {
105 if(!extension_loaded('fileinfo')) dl('fileinfo.' . PHP_SHLIB_SUFFIX);
106 }
107
108 /**
109 * Implements functions related to mime types such as detection and mapping to
110 * file extension.
111 *
112 * Instances of this class are stateles, there only needs to be one global instance
113 * of MimeMagic. Please use MimeMagic::singleton() to get that instance.
114 */
115 class MimeMagic {
116
117 /**
118 * Mapping of media types to arrays of mime types.
119 * This is used by findMediaType and getMediaType, respectively
120 */
121 var $mMediaTypes= NULL;
122
123 /** Map of mime type aliases
124 */
125 var $mMimeTypeAliases= NULL;
126
127 /** map of mime types to file extensions (as a space seprarated list)
128 */
129 var $mMimeToExt= NULL;
130
131 /** map of file extensions types to mime types (as a space seprarated list)
132 */
133 var $mExtToMime= NULL;
134
135 /** The singleton instance
136 */
137 private static $instance;
138
139 /** Initializes the MimeMagic object. This is called by MimeMagic::singleton().
140 *
141 * This constructor parses the mime.types and mime.info files and build internal mappings.
142 */
143 function __construct() {
144 /*
145 * --- load mime.types ---
146 */
147
148 global $wgMimeTypeFile, $IP;
149
150 $types = MM_WELL_KNOWN_MIME_TYPES;
151
152 if ( $wgMimeTypeFile == 'includes/mime.types' ) {
153 $wgMimeTypeFile = "$IP/$wgMimeTypeFile";
154 }
155
156 if ( $wgMimeTypeFile ) {
157 if ( is_file( $wgMimeTypeFile ) and is_readable( $wgMimeTypeFile ) ) {
158 wfDebug( __METHOD__.": loading mime types from $wgMimeTypeFile\n" );
159 $types .= "\n";
160 $types .= file_get_contents( $wgMimeTypeFile );
161 } else {
162 wfDebug( __METHOD__.": can't load mime types from $wgMimeTypeFile\n" );
163 }
164 } else {
165 wfDebug( __METHOD__.": no mime types file defined, using build-ins only.\n" );
166 }
167
168 $types = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $types );
169 $types = str_replace( "\t", " ", $types );
170
171 $this->mMimeToExt = array();
172 $this->mToMime = array();
173
174 $lines = explode( "\n",$types );
175 foreach ( $lines as $s ) {
176 $s = trim( $s );
177 if ( empty( $s ) ) continue;
178 if ( strpos( $s, '#' ) === 0 ) continue;
179
180 $s = strtolower( $s );
181 $i = strpos( $s, ' ' );
182
183 if ( $i === false ) continue;
184
185 #print "processing MIME line $s<br>";
186
187 $mime = substr( $s, 0, $i );
188 $ext = trim( substr($s, $i+1 ) );
189
190 if ( empty( $ext ) ) continue;
191
192 if ( !empty( $this->mMimeToExt[$mime] ) ) {
193 $this->mMimeToExt[$mime] .= ' ' . $ext;
194 } else {
195 $this->mMimeToExt[$mime] = $ext;
196 }
197
198 $extensions = explode( ' ', $ext );
199
200 foreach ( $extensions as $e ) {
201 $e = trim( $e );
202 if ( empty( $e ) ) continue;
203
204 if ( !empty( $this->mExtToMime[$e] ) ) {
205 $this->mExtToMime[$e] .= ' ' . $mime;
206 } else {
207 $this->mExtToMime[$e] = $mime;
208 }
209 }
210 }
211
212 /*
213 * --- load mime.info ---
214 */
215
216 global $wgMimeInfoFile;
217 if ( $wgMimeInfoFile == 'includes/mime.info' ) {
218 $wgMimeInfoFile = "$IP/$wgMimeInfoFile";
219 }
220
221 $info = MM_WELL_KNOWN_MIME_INFO;
222
223 if ( $wgMimeInfoFile ) {
224 if ( is_file( $wgMimeInfoFile ) and is_readable( $wgMimeInfoFile ) ) {
225 wfDebug( __METHOD__.": loading mime info from $wgMimeInfoFile\n" );
226 $info .= "\n";
227 $info .= file_get_contents( $wgMimeInfoFile );
228 } else {
229 wfDebug(__METHOD__.": can't load mime info from $wgMimeInfoFile\n");
230 }
231 } else {
232 wfDebug(__METHOD__.": no mime info file defined, using build-ins only.\n");
233 }
234
235 $info = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $info);
236 $info = str_replace( "\t", " ", $info );
237
238 $this->mMimeTypeAliases = array();
239 $this->mMediaTypes = array();
240
241 $lines = explode( "\n", $info );
242 foreach ( $lines as $s ) {
243 $s = trim( $s );
244 if ( empty( $s ) ) continue;
245 if ( strpos( $s, '#' ) === 0 ) continue;
246
247 $s = strtolower( $s );
248 $i = strpos( $s, ' ' );
249
250 if ( $i === false ) continue;
251
252 #print "processing MIME INFO line $s<br>";
253
254 $match = array();
255 if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
256 $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
257 $mtype = trim( strtoupper( $match[1] ) );
258 } else {
259 $mtype = MEDIATYPE_UNKNOWN;
260 }
261
262 $m = explode( ' ', $s );
263
264 if ( !isset( $this->mMediaTypes[$mtype] ) ) {
265 $this->mMediaTypes[$mtype] = array();
266 }
267
268 foreach ( $m as $mime ) {
269 $mime = trim( $mime );
270 if ( empty( $mime ) ) continue;
271
272 $this->mMediaTypes[$mtype][] = $mime;
273 }
274
275 if ( sizeof( $m ) > 1 ) {
276 $main = $m[0];
277 for ( $i=1; $i<sizeof($m); $i += 1 ) {
278 $mime = $m[$i];
279 $this->mMimeTypeAliases[$mime] = $main;
280 }
281 }
282 }
283
284 }
285
286 /**
287 * Get an instance of this class
288 */
289 static function &singleton() {
290 if ( !isset( self::$instance ) ) {
291 self::$instance = new MimeMagic;
292 }
293 return self::$instance;
294 }
295
296 /** returns a list of file extensions for a given mime type
297 * as a space separated string.
298 */
299 function getExtensionsForType( $mime ) {
300 $mime = strtolower( $mime );
301
302 $r = @$this->mMimeToExt[$mime];
303
304 if ( @!$r and isset( $this->mMimeTypeAliases[$mime] ) ) {
305 $mime = $this->mMimeTypeAliases[$mime];
306 $r = @$this->mMimeToExt[$mime];
307 }
308
309 return $r;
310 }
311
312 /** returns a list of mime types for a given file extension
313 * as a space separated string.
314 */
315 function getTypesForExtension( $ext ) {
316 $ext = strtolower( $ext );
317
318 $r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null;
319 return $r;
320 }
321
322 /** returns a single mime type for a given file extension.
323 * This is always the first type from the list returned by getTypesForExtension($ext).
324 */
325 function guessTypesForExtension( $ext ) {
326 $m = $this->getTypesForExtension( $ext );
327 if ( is_null( $m ) ) return NULL;
328
329 $m = trim( $m );
330 $m = preg_replace( '/\s.*$/', '', $m );
331
332 return $m;
333 }
334
335
336 /** tests if the extension matches the given mime type.
337 * returns true if a match was found, NULL if the mime type is unknown,
338 * and false if the mime type is known but no matches where found.
339 */
340 function isMatchingExtension( $extension, $mime ) {
341 $ext = $this->getExtensionsForType( $mime );
342
343 if ( !$ext ) {
344 return NULL; //unknown
345 }
346
347 $ext = explode( ' ', $ext );
348
349 $extension = strtolower( $extension );
350 if ( in_array( $extension, $ext ) ) {
351 return true;
352 }
353
354 return false;
355 }
356
357 /** returns true if the mime type is known to represent
358 * an image format supported by the PHP GD library.
359 */
360 function isPHPImageType( $mime ) {
361 #as defined by imagegetsize and image_type_to_mime
362 static $types = array(
363 'image/gif', 'image/jpeg', 'image/png',
364 'image/x-bmp', 'image/xbm', 'image/tiff',
365 'image/jp2', 'image/jpeg2000', 'image/iff',
366 'image/xbm', 'image/x-xbitmap',
367 'image/vnd.wap.wbmp', 'image/vnd.xiff',
368 'image/x-photoshop',
369 'application/x-shockwave-flash',
370 );
371
372 return in_array( $mime, $types );
373 }
374
375 /**
376 * Returns true if the extension represents a type which can
377 * be reliably detected from its content. Use this to determine
378 * whether strict content checks should be applied to reject
379 * invalid uploads; if we can't identify the type we won't
380 * be able to say if it's invalid.
381 *
382 * @todo Be more accurate when using fancy mime detector plugins;
383 * right now this is the bare minimum getimagesize() list.
384 * @return bool
385 */
386 function isRecognizableExtension( $extension ) {
387 static $types = array(
388 // Types recognized by getimagesize()
389 'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
390 'bmp', 'tiff', 'tif', 'jpc', 'jp2',
391 'jpx', 'jb2', 'swc', 'iff', 'wbmp',
392 'xbm',
393
394 // Formats we recognize magic numbers for
395 'djvu', 'ogg', 'ogv', 'mid', 'pdf', 'wmf', 'xcf',
396
397 // XML formats we sure hope we recognize reliably
398 'svg',
399 );
400 return in_array( strtolower( $extension ), $types );
401 }
402
403
404 /** mime type detection. This uses detectMimeType to detect the mime type of the file,
405 * but applies additional checks to determine some well known file formats that may be missed
406 * or misinterpreter by the default mime detection (namely xml based formats like XHTML or SVG).
407 *
408 * @param string $file The file to check
409 * @param mixed $ext The file extension, or true to extract it from the filename.
410 * Set it to false to ignore the extension.
411 *
412 * @return string the mime type of $file
413 */
414 function guessMimeType( $file, $ext = true ) {
415 $mime = $this->doGuessMimeType( $file, $ext );
416
417 if( !$mime ) {
418 wfDebug( __METHOD__.": internal type detection failed for $file (.$ext)...\n" );
419 $mime = $this->detectMimeType( $file, $ext );
420 }
421
422 if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
423 $mime = $this->mMimeTypeAliases[$mime];
424 }
425
426 wfDebug(__METHOD__.": final mime type of $file: $mime\n");
427 return $mime;
428 }
429
430 function doGuessMimeType( $file, $ext = true ) {
431 // Read a chunk of the file
432 wfSuppressWarnings();
433 $f = fopen( $file, "rt" );
434 wfRestoreWarnings();
435 if( !$f ) return "unknown/unknown";
436 $head = fread( $f, 1024 );
437 fseek( $f, -65558, SEEK_END );
438 $tail = fread( $f, 65558 ); // 65558 = maximum size of a zip EOCDR
439 fclose( $f );
440
441 // Hardcode a few magic number checks...
442 $headers = array(
443 // Multimedia...
444 'MThd' => 'audio/midi',
445 'OggS' => 'application/ogg',
446
447 // Image formats...
448 // Note that WMF may have a bare header, no magic number.
449 "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
450 "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
451 '%PDF' => 'application/pdf',
452 'gimp xcf' => 'image/x-xcf',
453
454 // Some forbidden fruit...
455 'MZ' => 'application/octet-stream', // DOS/Windows executable
456 "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
457 "\x7fELF" => 'application/octet-stream', // ELF binary
458 );
459
460 foreach( $headers as $magic => $candidate ) {
461 if( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
462 wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
463 return $candidate;
464 }
465 }
466
467 /*
468 * look for PHP
469 * Check for this before HTML/XML...
470 * Warning: this is a heuristic, and won't match a file with a lot of non-PHP before.
471 * It will also match text files which could be PHP. :)
472 */
473 if( ( strpos( $head, '<?php' ) !== false ) ||
474 ( strpos( $head, '<? ' ) !== false ) ||
475 ( strpos( $head, "<?\n" ) !== false ) ||
476 ( strpos( $head, "<?\t" ) !== false ) ||
477 ( strpos( $head, "<?=" ) !== false ) ||
478
479 ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
480 ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
481 ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
482 ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
483 ( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
484
485 wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
486 return "application/x-php";
487 }
488
489 /*
490 * look for XML formats (XHTML and SVG)
491 */
492 $xml = new XmlTypeCheck( $file );
493 if( $xml->wellFormed ) {
494 global $wgXMLMimeTypes;
495 if( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
496 return $wgXMLMimeTypes[$xml->getRootElement()];
497 } else {
498 return 'application/xml';
499 }
500 }
501
502 /*
503 * look for shell scripts
504 */
505 $script_type = NULL;
506
507 # detect by shebang
508 if ( substr( $head, 0, 2) == "#!" ) {
509 $script_type = "ASCII";
510 } elseif ( substr( $head, 0, 5) == "\xef\xbb\xbf#!" ) {
511 $script_type = "UTF-8";
512 } elseif ( substr( $head, 0, 7) == "\xfe\xff\x00#\x00!" ) {
513 $script_type = "UTF-16BE";
514 } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
515 $script_type= "UTF-16LE";
516 }
517
518 if ( $script_type ) {
519 if ( $script_type !== "UTF-8" && $script_type !== "ASCII") {
520 // Quick and dirty fold down to ASCII!
521 $pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
522 $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
523 $head = '';
524 foreach( $chars as $codepoint ) {
525 if( $codepoint < 128 ) {
526 $head .= chr( $codepoint );
527 } else {
528 $head .= '?';
529 }
530 }
531 }
532
533 $match = array();
534
535 if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
536 $mime = "application/x-{$match[2]}";
537 wfDebug( __METHOD__.": shell script recognized as $mime\n" );
538 return $mime;
539 }
540 }
541
542 // Check for ZIP (before getimagesize)
543 if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
544 wfDebug( __METHOD__.": ZIP header present at end of $file\n" );
545 return $this->detectZipType( $head );
546 }
547
548 wfSuppressWarnings();
549 $gis = getimagesize( $file );
550 wfRestoreWarnings();
551
552 if( $gis && isset( $gis['mime'] ) ) {
553 $mime = $gis['mime'];
554 wfDebug( __METHOD__.": getimagesize detected $file as $mime\n" );
555 return $mime;
556 }
557
558 // Also test DjVu
559 $deja = new DjVuImage( $file );
560 if( $deja->isValid() ) {
561 wfDebug( __METHOD__.": detected $file as image/vnd.djvu\n" );
562 return 'image/vnd.djvu';
563 }
564
565 return false;
566 }
567
568 /**
569 * Detect application-specific file type of a given ZIP file from its
570 * header data. Currently works for OpenDocument types...
571 * If can't tell, returns 'application/zip'.
572 *
573 * @param string $header Some reasonably-sized chunk of file header
574 * @return string
575 */
576 function detectZipType( $header ) {
577 $opendocTypes = array(
578 'chart',
579 'chart-template',
580 'formula',
581 'formula-template',
582 'graphics',
583 'graphics-template',
584 'image',
585 'image-template',
586 'presentation',
587 'presentation-template',
588 'spreadsheet',
589 'spreadsheet-template',
590 'text',
591 'text-template',
592 'text-master',
593 'text-web' );
594
595 // http://lists.oasis-open.org/archives/office/200505/msg00006.html
596 $types = '(?:' . implode( '|', $opendocTypes ) . ')';
597 $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
598 wfDebug( __METHOD__.": $opendocRegex\n" );
599
600 if( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
601 $mime = $matches[1];
602 wfDebug( __METHOD__.": detected $mime from ZIP archive\n" );
603 return $mime;
604 } else {
605 wfDebug( __METHOD__.": unable to identify type of ZIP archive\n" );
606 return 'application/zip';
607 }
608 }
609
610 /** Internal mime type detection, please use guessMimeType() for application code instead.
611 * Detection is done using an external program, if $wgMimeDetectorCommand is set.
612 * Otherwise, the fileinfo extension and mime_content_type are tried (in this order), if they are available.
613 * If the dections fails and $ext is not false, the mime type is guessed from the file extension, using
614 * guessTypesForExtension.
615 * If the mime type is still unknown, getimagesize is used to detect the mime type if the file is an image.
616 * If no mime type can be determined, this function returns "unknown/unknown".
617 *
618 * @param string $file The file to check
619 * @param mixed $ext The file extension, or true to extract it from the filename.
620 * Set it to false to ignore the extension.
621 *
622 * @return string the mime type of $file
623 * @access private
624 */
625 function detectMimeType( $file, $ext = true ) {
626 global $wgMimeDetectorCommand;
627
628 $m = NULL;
629 if ( $wgMimeDetectorCommand ) {
630 $fn = wfEscapeShellArg( $file );
631 $m = `$wgMimeDetectorCommand $fn`;
632 } elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
633
634 # This required the fileinfo extension by PECL,
635 # see http://pecl.php.net/package/fileinfo
636 # This must be compiled into PHP
637 #
638 # finfo is the official replacement for the deprecated
639 # mime_content_type function, see below.
640 #
641 # If you may need to load the fileinfo extension at runtime, set
642 # $wgLoadFileinfoExtension in LocalSettings.php
643
644 $mime_magic_resource = finfo_open(FILEINFO_MIME); /* return mime type ala mimetype extension */
645
646 if ($mime_magic_resource) {
647 $m = finfo_file( $mime_magic_resource, $file );
648 finfo_close( $mime_magic_resource );
649 } else {
650 wfDebug( __METHOD__.": finfo_open failed on ".FILEINFO_MIME."!\n" );
651 }
652 } elseif ( function_exists( "mime_content_type" ) ) {
653
654 # NOTE: this function is available since PHP 4.3.0, but only if
655 # PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
656 #
657 # On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundeled with PHP;
658 # sometimes, this may even be needed under linus/unix.
659 #
660 # Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
661 # see http://www.php.net/manual/en/ref.mime-magic.php for details.
662
663 $m = mime_content_type($file);
664 } else {
665 wfDebug( __METHOD__.": no magic mime detector found!\n" );
666 }
667
668 if ( $m ) {
669 # normalize
670 $m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
671 $m = trim( $m );
672 $m = strtolower( $m );
673
674 if ( strpos( $m, 'unknown' ) !== false ) {
675 $m = NULL;
676 } else {
677 wfDebug( __METHOD__.": magic mime type of $file: $m\n" );
678 return $m;
679 }
680 }
681
682 # if desired, look at extension as a fallback.
683 if ( $ext === true ) {
684 $i = strrpos( $file, '.' );
685 $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
686 }
687 if ( $ext ) {
688 if( $this->isRecognizableExtension( $ext ) ) {
689 wfDebug( __METHOD__. ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
690 } else {
691 $m = $this->guessTypesForExtension( $ext );
692 if ( $m ) {
693 wfDebug( __METHOD__.": extension mime type of $file: $m\n" );
694 return $m;
695 }
696 }
697 }
698
699 #unknown type
700 wfDebug( __METHOD__.": failed to guess mime type for $file!\n" );
701 return "unknown/unknown";
702 }
703
704 /**
705 * Determine the media type code for a file, using its mime type, name and possibly
706 * its contents.
707 *
708 * This function relies on the findMediaType(), mapping extensions and mime
709 * types to media types.
710 *
711 * @todo analyse file if need be
712 * @todo look at multiple extension, separately and together.
713 *
714 * @param string $path full path to the image file, in case we have to look at the contents
715 * (if null, only the mime type is used to determine the media type code).
716 * @param string $mime mime type. If null it will be guessed using guessMimeType.
717 *
718 * @return (int?string?) a value to be used with the MEDIATYPE_xxx constants.
719 */
720 function getMediaType( $path = NULL, $mime = NULL ) {
721 if( !$mime && !$path ) return MEDIATYPE_UNKNOWN;
722
723 # If mime type is unknown, guess it
724 if( !$mime ) $mime = $this->guessMimeType( $path, false );
725
726 # Special code for ogg - detect if it's video (theora),
727 # else label it as sound.
728 if( $mime == "application/ogg" && file_exists( $path ) ) {
729
730 // Read a chunk of the file
731 $f = fopen( $path, "rt" );
732 if ( !$f ) return MEDIATYPE_UNKNOWN;
733 $head = fread( $f, 256 );
734 fclose( $f );
735
736 $head = strtolower( $head );
737
738 # This is an UGLY HACK, file should be parsed correctly
739 if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
740 elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
741 elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
742 elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
743 else return MEDIATYPE_MULTIMEDIA;
744 }
745
746 # check for entry for full mime type
747 if( $mime ) {
748 $type = $this->findMediaType( $mime );
749 if( $type !== MEDIATYPE_UNKNOWN ) return $type;
750 }
751
752 # Check for entry for file extension
753 $e = NULL;
754 if ( $path ) {
755 $i = strrpos( $path, '.' );
756 $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
757
758 # TODO: look at multi-extension if this fails, parse from full path
759
760 $type = $this->findMediaType( '.' . $e );
761 if ( $type !== MEDIATYPE_UNKNOWN ) return $type;
762 }
763
764 # Check major mime type
765 if( $mime ) {
766 $i = strpos( $mime, '/' );
767 if( $i !== false ) {
768 $major = substr( $mime, 0, $i );
769 $type = $this->findMediaType( $major );
770 if( $type !== MEDIATYPE_UNKNOWN ) return $type;
771 }
772 }
773
774 if( !$type ) $type = MEDIATYPE_UNKNOWN;
775
776 return $type;
777 }
778
779 /** returns a media code matching the given mime type or file extension.
780 * File extensions are represented by a string starting with a dot (.) to
781 * distinguish them from mime types.
782 *
783 * This funktion relies on the mapping defined by $this->mMediaTypes
784 * @access private
785 */
786 function findMediaType( $extMime ) {
787 if ( strpos( $extMime, '.' ) === 0 ) { #if it's an extension, look up the mime types
788 $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
789 if ( !$m ) return MEDIATYPE_UNKNOWN;
790
791 $m = explode( ' ', $m );
792 } else {
793 # Normalize mime type
794 if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
795 $extMime = $this->mMimeTypeAliases[$extMime];
796 }
797
798 $m = array($extMime);
799 }
800
801 foreach ( $m as $mime ) {
802 foreach ( $this->mMediaTypes as $type => $codes ) {
803 if ( in_array($mime, $codes, true ) ) {
804 return $type;
805 }
806 }
807 }
808
809 return MEDIATYPE_UNKNOWN;
810 }
811 }