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