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