Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
66.58% covered (warning)
66.58%
251 / 377
46.15% covered (danger)
46.15%
12 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
MimeAnalyzer
66.76% covered (warning)
66.76%
251 / 376
46.15% covered (danger)
46.15%
12 / 26
1191.71
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 loadFiles
73.08% covered (warning)
73.08%
19 / 26
0.00% covered (danger)
0.00%
0 / 1
14.81
 parseMimeTypes
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
7.06
 parseMimeInfo
70.00% covered (warning)
70.00%
21 / 30
0.00% covered (danger)
0.00%
0 / 1
14.27
 setLogger
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addExtraTypes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addExtraInfo
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getExtensionsForType
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 getExtensionsFromMimeType
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getMimeTypesFromExtension
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getMimeTypeFromExtensionOrNull
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 guessTypesForExtension
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getTypesForExtension
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 getExtensionFromMimeTypeOrNull
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 isMatchingExtension
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 isRecognizableExtension
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 improveTypeFromExtension
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
11
 guessMimeType
53.85% covered (warning)
53.85%
7 / 13
0.00% covered (danger)
0.00%
0 / 1
5.57
 doGuessMimeType
55.17% covered (warning)
55.17%
64 / 116
0.00% covered (danger)
0.00%
0 / 1
295.58
 detectZipTypeFromFile
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
8.03
 detectMicrosoftBinaryType
50.00% covered (danger)
50.00%
4 / 8
0.00% covered (danger)
0.00%
0 / 1
4.12
 detectMimeType
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
110
 getMediaType
81.40% covered (warning)
81.40%
35 / 43
0.00% covered (danger)
0.00%
0 / 1
25.12
 findMediaType
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
7
 getMediaTypes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isValidMajorMimeType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace Wikimedia\Mime;
8
9use Psr\Log\LoggerAwareInterface;
10use Psr\Log\LoggerInterface;
11use Psr\Log\NullLogger;
12use UnexpectedValueException;
13
14/**
15 * @defgroup Mime Mime
16 *
17 * @ingroup Media
18 */
19
20/**
21 * MIME type analyzer for MediaWiki.
22 *
23 * This class prioritizes built-in MIME type guesses over external detection
24 * (e.g., PHP's finfo or OS-level tools) for security reasons.
25 *
26 * Public wikis accept file uploads from untrusted users. Some file types
27 * (like .docx or .xlsx) are valid ZIP archives and may be misidentified
28 * by general-purpose detectors as "application/zip". Serving them as ZIP
29 * could enable unexpected behavior or security risks.
30 *
31 * MediaWiki’s internal mapping ensures consistent, secure handling of known
32 * file types across all platforms. External detection is used only as a fallback
33 * when no built-in rule matches.
34 *
35 * @since 1.28
36 * @ingroup Mime
37 * @see https://www.mediawiki.org/wiki/Manual:MIME_type_detection
38 */
39class MimeAnalyzer implements LoggerAwareInterface {
40
41    /** Use the full, built-in MIME mapping rather than load from a file */
42    public const USE_INTERNAL = 'internal';
43
44    private const MAGIC_NUMBERS = [
45        // Multimedia...
46        'MThd'             => 'audio/midi',
47        'OggS'             => 'application/ogg',
48        'ID3'              => 'audio/mpeg',
49        "\xff\xfb"         => 'audio/mpeg', // MPEG-1 layer 3
50        "\xff\xf3"         => 'audio/mpeg', // MPEG-2 layer 3 (lower sample rates)
51        "\xff\xe3"         => 'audio/mpeg', // MPEG-2.5 layer 3 (very low sample rates)
52
53        // Image formats...
54        // Note that WMF may have a bare header, no magic number.
55        "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
56        "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
57        '%PDF'             => 'application/pdf',
58        'gimp xcf'         => 'image/x-xcf',
59        "\xff\x0a"         => 'image/jxl',
60        "\x00\x00\x00\x0C\x4A\x58\x4C\x20\x0D\x0A\x87\x0A" => 'image/jxl',
61
62        // 3D
63        'glTF'             => 'model/gltf-binary',
64
65        // archive
66        "PK\x03\x04"       => 'application/epub+zip',
67
68        // Some forbidden fruit...
69        'MZ'               => 'application/octet-stream', // DOS/Windows executable
70        "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
71        "\x7fELF"          => 'application/octet-stream', // ELF binary
72    ];
73
74    private const RECOGNIZABLE_EXTENSIONS = [
75        // Types recognized by getimagesize()
76        'gif' => true,
77        'jpeg' => true,
78        'jpg' => true,
79        'png' => true,
80        'swf' => true,
81        'psd' => true,
82        'bmp' => true,
83        'tiff' => true,
84        'tif' => true,
85        'jpc' => true,
86        'jp2' => true,
87        'jpx' => true,
88        'jb2' => true,
89        'swc' => true,
90        'iff' => true,
91        'wbmp' => true,
92        'xbm' => true,
93
94        // Formats we recognize magic numbers for
95        'djvu' => true,
96        'ogx' => true,
97        'ogg' => true,
98        'ogv' => true,
99        'oga' => true,
100        'spx' => true,
101        'opus' => true,
102        'mid' => true,
103        'pdf' => true,
104        'wmf' => true,
105        'xcf' => true,
106        'webm' => true,
107        'mkv' => true,
108        'mka' => true,
109        'webp' => true,
110        'mp3' => true,
111        'jxl' => true,
112
113        // XML formats we sure hope we recognize reliably
114        'svg' => true,
115
116        // 3D formats
117        'stl' => true,
118        'glb' => true,
119    ];
120
121    private const MAJOR_MIME_TYPES = [
122        // See the definition of the `img_major_mime` enum in tables-generated.sql
123        'unknown' => true,
124        'application' => true,
125        'audio' => true,
126        'image' => true,
127        'text' => true,
128        'video' => true,
129        'message' => true,
130        'model' => true,
131        'multipart' => true,
132        'chemical' => true,
133    ];
134
135    private const PACK_MASKS = [
136        'UTF-16BE' => 'n*',
137        'UTF-16LE' => 'v*',
138    ];
139
140    /** @var string */
141    protected $typeFile;
142    /** @var string */
143    protected $infoFile;
144    /** @var string */
145    protected $xmlTypes;
146    /** @var callable */
147    protected $initCallback;
148    /** @var callable */
149    protected $detectCallback;
150    /** @var callable */
151    protected $guessCallback;
152    /** @var callable */
153    protected $extCallback;
154    /** @var array Mapping of media types to arrays of MIME types */
155    protected $mediaTypes = null;
156    /** @var array Map of MIME type aliases */
157    protected $mimeTypeAliases = null;
158    /** @var array<string,string[]> Map of MIME types to file extensions */
159    protected $mimeToExts = [];
160    /** @var array<string,string[]> Map of file extensions to MIME types */
161    protected $extToMimes = [];
162
163    /** @var array Map of file extensions types to MIME types (as a space separated list) */
164    public $mExtToMime = []; // legacy name; field accessed by hooks
165
166    /** @var string Extra MIME types, set for example by media handling extensions */
167    private $extraTypes = '';
168    /** @var string Extra MIME info, set for example by media handling extensions */
169    private $extraInfo = '';
170
171    /** @var LoggerInterface */
172    private $logger;
173
174    /**
175     * @param array $params Configuration map, includes:
176     *   - typeFile: path to file with the list of known MIME types
177     *   - infoFile: path to file with the MIME type info
178     *   - xmlTypes: map of root element names to XML MIME types
179     *   - initCallback: initialization callback that is passed this object [optional]
180     *   - detectCallback: alternative to finfo that returns the mime type for a file.
181     *      For example, the callback can return the output of "file -bi". [optional]
182     *   - guessCallback: callback to improve the guessed MIME type using the file data.
183     *      This is intended for fixing mistakes in fileinfo or "detectCallback". [optional]
184     *   - extCallback: callback to improve the guessed MIME type using the extension. [optional]
185     *   - logger: PSR-3 logger [optional]
186     * @note Constructing these instances is expensive due to file reads.
187     *  A service or singleton pattern should be used to avoid creating instances again and again.
188     */
189    public function __construct( array $params ) {
190        $this->typeFile = $params['typeFile'];
191        $this->infoFile = $params['infoFile'];
192        $this->xmlTypes = $params['xmlTypes'];
193        $this->initCallback = $params['initCallback'] ?? null;
194        $this->detectCallback = $params['detectCallback'] ?? null;
195        $this->guessCallback = $params['guessCallback'] ?? null;
196        $this->extCallback = $params['extCallback'] ?? null;
197        $this->logger = $params['logger'] ?? new NullLogger();
198
199        $this->loadFiles();
200    }
201
202    protected function loadFiles(): void {
203        # Allow media handling extensions adding MIME-types and MIME-info
204        if ( $this->initCallback ) {
205            ( $this->initCallback )( $this );
206        }
207
208        $rawTypes = $this->extraTypes;
209        if ( $this->typeFile === self::USE_INTERNAL ) {
210            $this->mimeToExts = MimeMap::MIME_EXTENSIONS;
211        } else {
212            $this->mimeToExts = MimeMapMinimal::MIME_EXTENSIONS;
213            if ( $this->typeFile ) {
214                $rawTypes = file_get_contents( $this->typeFile ) . "\n" . $this->extraTypes;
215            }
216        }
217        if ( $rawTypes ) {
218            $this->parseMimeTypes( $rawTypes );
219        }
220
221        // Build the reverse mapping (extension => MIME type).
222        foreach ( $this->mimeToExts as $mime => $exts ) {
223            foreach ( $exts as $ext ) {
224                $this->extToMimes[$ext][] = $mime;
225            }
226        }
227
228        // Migrate items from the legacy $this->mExtToMime field.
229        // TODO: Remove this when mExtToMime is finally removed.
230        foreach ( $this->mExtToMime as $ext => $mimes ) {
231            foreach ( explode( ' ', $mimes ) as $mime ) {
232                $this->extToMimes[$ext][] = $mime;
233            }
234        }
235
236        $rawInfo = $this->extraInfo;
237        if ( $this->infoFile === self::USE_INTERNAL ) {
238            $this->mimeTypeAliases = MimeMap::MIME_TYPE_ALIASES;
239            $this->mediaTypes = MimeMap::MEDIA_TYPES;
240        } else {
241            $this->mimeTypeAliases = MimeMapMinimal::MIME_TYPE_ALIASES;
242            $this->mediaTypes = MimeMapMinimal::MEDIA_TYPES;
243            if ( $this->infoFile ) {
244                $rawInfo = file_get_contents( $this->infoFile ) . "\n" . $this->extraInfo;
245            }
246        }
247        if ( $rawInfo ) {
248            $this->parseMimeInfo( $rawInfo );
249        }
250    }
251
252    protected function parseMimeTypes( string $rawMimeTypes ): void {
253        $rawMimeTypes = str_replace( [ "\r\n", "\n\r", "\n\n", "\r\r", "\r" ], "\n", $rawMimeTypes );
254        $rawMimeTypes = str_replace( "\t", " ", $rawMimeTypes );
255
256        $lines = explode( "\n", $rawMimeTypes );
257        foreach ( $lines as $s ) {
258            $s = trim( $s );
259            if ( $s === '' || str_starts_with( $s, '#' ) ) {
260                continue;
261            }
262
263            $s = strtolower( $s );
264            $i = strpos( $s, ' ' );
265
266            if ( $i === false ) {
267                continue;
268            }
269
270            $ext = trim( substr( $s, $i + 1 ) );
271
272            if ( !$ext ) {
273                continue;
274            }
275
276            $tokens = preg_split( '/\s+/', $s, -1, PREG_SPLIT_NO_EMPTY );
277            if ( count( $tokens ) > 1 ) {
278                $mime = array_shift( $tokens );
279                $this->mimeToExts[$mime] = array_values( array_unique(
280                    array_merge( $this->mimeToExts[$mime] ?? [], $tokens ) ) );
281            }
282        }
283    }
284
285    protected function parseMimeInfo( string $rawMimeInfo ): void {
286        $rawMimeInfo = str_replace( [ "\r\n", "\n\r", "\n\n", "\r\r", "\r" ], "\n", $rawMimeInfo );
287        $rawMimeInfo = str_replace( "\t", " ", $rawMimeInfo );
288
289        $lines = explode( "\n", $rawMimeInfo );
290        foreach ( $lines as $s ) {
291            $s = trim( $s );
292            if ( $s === '' || str_starts_with( $s, '#' ) ) {
293                continue;
294            }
295
296            $s = strtolower( $s );
297            $i = strpos( $s, ' ' );
298
299            if ( $i === false ) {
300                continue;
301            }
302
303            # print "processing MIME INFO line $s<br>";
304
305            $match = [];
306            if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
307                $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
308                $mtype = trim( strtoupper( $match[1] ) );
309            } else {
310                $mtype = MEDIATYPE_UNKNOWN;
311            }
312
313            $m = preg_split( '/\s+/', $s, -1, PREG_SPLIT_NO_EMPTY );
314
315            if ( !isset( $this->mediaTypes[$mtype] ) ) {
316                $this->mediaTypes[$mtype] = [];
317            }
318
319            foreach ( $m as $mime ) {
320                $mime = trim( $mime );
321                if ( !$mime ) {
322                    continue;
323                }
324
325                $this->mediaTypes[$mtype][] = $mime;
326            }
327
328            if ( count( $m ) > 1 ) {
329                $main = $m[0];
330                $mCount = count( $m );
331                for ( $i = 1; $i < $mCount; $i += 1 ) {
332                    $mime = $m[$i];
333                    $this->mimeTypeAliases[$mime] = $main;
334                }
335            }
336        }
337    }
338
339    public function setLogger( LoggerInterface $logger ): void {
340        $this->logger = $logger;
341    }
342
343    /**
344     * Adds to the list mapping MIME to file extensions.
345     *
346     * As an extension author, you are encouraged to submit patches to
347     * MediaWiki's core to add new MIME types to MimeMap.php.
348     */
349    public function addExtraTypes( string $types ): void {
350        $this->extraTypes .= "\n" . $types;
351    }
352
353    /**
354     * Adds to the list mapping MIME to media type.
355     *
356     * As an extension author, you are encouraged to submit patches to
357     * MediaWiki's core to add new MIME info to MimeMap.php.
358     */
359    public function addExtraInfo( string $info ): void {
360        $this->extraInfo .= "\n" . $info;
361    }
362
363    /**
364     * Returns a list of file extensions for a given MIME type as a space
365     * separated string or null if the MIME type was unrecognized. Resolves
366     * MIME type aliases.
367     *
368     * @deprecated since 1.35 Use getExtensionsFromMimeType() instead.
369     * @param string $mime
370     * @return string|null
371     */
372    public function getExtensionsForType( $mime ) {
373        $exts = $this->getExtensionsFromMimeType( $mime );
374        return $exts ? implode( ' ', $exts ) : null;
375    }
376
377    /**
378     * Returns an array of file extensions associated with a given MIME type.
379     * The returned array is empty if the MIME type was unrecognized. Resolves
380     * MIME type aliases.
381     *
382     * @since 1.35
383     * @param string $mime
384     * @return string[]
385     */
386    public function getExtensionsFromMimeType( string $mime ): array {
387        $mime = strtolower( $mime );
388        if ( !isset( $this->mimeToExts[$mime] ) && isset( $this->mimeTypeAliases[$mime] ) ) {
389            $mime = $this->mimeTypeAliases[$mime];
390        }
391        return $this->mimeToExts[$mime] ?? [];
392    }
393
394    /**
395     * Returns an array of MIME types associated with a given file extension.
396     * The returned array is empty if the file extension is not associated with
397     * any MIME types.
398     *
399     * @since 1.35
400     * @param string $ext
401     * @return string[]
402     */
403    public function getMimeTypesFromExtension( string $ext ): array {
404        $ext = strtolower( $ext );
405        return $this->extToMimes[$ext] ?? [];
406    }
407
408    /**
409     * Returns a single MIME type for a given file extension or null if unknown.
410     * This is always the first type from the list returned by getMimeTypesFromExtension($ext).
411     *
412     * @since 1.35
413     * @param string $ext
414     * @return string|null
415     */
416    public function getMimeTypeFromExtensionOrNull( string $ext ): ?string {
417        $types = $this->getMimeTypesFromExtension( $ext );
418        return $types[0] ?? null;
419    }
420
421    /**
422     * Returns a single file extension for a given MIME type or null if unknown.
423     * This is always the first type from the list returned by getExtensionsFromMimeType($mime).
424     *
425     * @deprecated since 1.35 Use getMimeTypeFromExtensionOrNull() instead.
426     * @param string $ext
427     * @return string|null
428     */
429    public function guessTypesForExtension( $ext ) {
430        return $this->getMimeTypeFromExtensionOrNull( $ext );
431    }
432
433    /**
434     * Returns a list of MIME types for a given file extension as a space
435     * separated string or null if the extension was unrecognized.
436     *
437     * @deprecated since 1.35 Use getMimeTypesFromExtension() instead.
438     * @param string $ext
439     * @return string|null
440     */
441    public function getTypesForExtension( $ext ) {
442        $types = $this->getMimeTypesFromExtension( $ext );
443        return $types ? implode( ' ', $types ) : null;
444    }
445
446    /**
447     * Returns a single file extension for a given MIME type or null if unknown.
448     * This is always the first type from the list returned by getExtensionsFromMimeType($mime).
449     *
450     * @since 1.35
451     * @param string $mime
452     * @return string|null
453     */
454    public function getExtensionFromMimeTypeOrNull( string $mime ): ?string {
455        $exts = $this->getExtensionsFromMimeType( $mime );
456        return $exts[0] ?? null;
457    }
458
459    /**
460     * Tests if the extension matches the given MIME type. Returns true if a
461     * match was found, null if the MIME type is unknown, and false if the
462     * MIME type is known but no matches where found.
463     *
464     * @param string $extension
465     * @param string $mime
466     * @return bool|null
467     */
468    public function isMatchingExtension( string $extension, string $mime ): ?bool {
469        $exts = $this->getExtensionsFromMimeType( $mime );
470
471        if ( !$exts ) {
472            return null; // Unknown MIME type
473        }
474
475        return in_array( strtolower( $extension ), $exts );
476    }
477
478    /**
479     * Returns true if the extension represents a type which can
480     * be reliably detected from its content. Use this to determine
481     * whether strict content checks should be applied to reject
482     * invalid uploads; if we can't identify the type we won't
483     * be able to say if it's invalid.
484     *
485     * @todo Be more accurate when using fancy MIME detector plugins;
486     *       right now this is the bare minimum getimagesize() list.
487     * @param string $extension
488     * @return bool
489     */
490    public function isRecognizableExtension( string $extension ): bool {
491        return isset( self::RECOGNIZABLE_EXTENSIONS[strtolower( $extension )] );
492    }
493
494    /**
495     * Improves a MIME type using the file extension. Some file formats are very generic,
496     * so their MIME type is not very meaningful. A more useful MIME type can be derived
497     * by looking at the file extension. Typically, this method would be called on the
498     * result of guessMimeType().
499     *
500     * XXX: Null-returning behavior is probably an accident and definitely confusing (T253483).
501     *
502     * @param string $mime The MIME type, typically guessed from a file's content.
503     * @param string $ext The file extension, as taken from the file name
504     * @return string|null The improved MIME type, or null if the MIME type is
505     *   unknown/unknown and the extension is not recognized.
506     */
507    public function improveTypeFromExtension( string $mime, string $ext ): ?string {
508        if ( $mime === 'unknown/unknown' ) {
509            if ( $this->isRecognizableExtension( $ext ) ) {
510                $this->logger->info( __METHOD__ . ': refusing to guess mime type for .' .
511                    "$ext file, we should have recognized it" );
512            } else {
513                // Not something we can detect, so simply
514                // trust the file extension
515                $mime = $this->getMimeTypeFromExtensionOrNull( $ext );
516            }
517        } elseif ( $mime === 'application/x-opc+zip'
518            || $mime === 'application/vnd.oasis.opendocument'
519        ) {
520            if ( $this->isMatchingExtension( $ext, $mime ) ) {
521                // A known file extension for an OPC/ODF file,
522                // find the proper MIME type for that file extension
523                $mime = $this->getMimeTypeFromExtensionOrNull( $ext );
524            } else {
525                $this->logger->info( __METHOD__ .
526                    ": refusing to guess better type for $mime file, " .
527                    ".$ext is not a known OPC/ODF extension." );
528                $mime = 'application/zip';
529            }
530        } elseif ( $mime === 'text/plain' && $this->findMediaType( ".$ext" ) === MEDIATYPE_TEXT ) {
531            // Textual types are sometimes not recognized properly.
532            // If detected as text/plain, and has an extension which is textual
533            // improve to the extension's type. For example, csv and json are often
534            // misdetected as text/plain.
535            $mime = $this->getMimeTypeFromExtensionOrNull( $ext );
536        }
537
538        # Media handling extensions can improve the MIME detected
539        $callback = $this->extCallback;
540        if ( $callback ) {
541            $callback( $this, $ext, $mime /* by reference */ );
542        }
543
544        if ( $mime !== null && isset( $this->mimeTypeAliases[$mime] ) ) {
545            $mime = $this->mimeTypeAliases[$mime];
546        }
547
548        $this->logger->info( __METHOD__ . ": improved mime type for .$ext$mime" );
549        return $mime;
550    }
551
552    /**
553     * MIME type detection. This uses detectMimeType to detect the MIME type
554     * of the file, but applies additional checks to determine some well known
555     * file formats that may be missed or misinterpreted by the default MIME
556     * detection (namely XML based formats like XHTML or SVG, as well as ZIP
557     * based formats like OPC/ODF files).
558     *
559     * @param string $file The file to check
560     * @param string|bool $ext The file extension, or true (default) to extract
561     * it from the filename. Set it to false to ignore the extension. DEPRECATED!
562     * Set to false, use improveTypeFromExtension($mime, $ext) later to improve MIME type.
563     * @return string The MIME type of $file
564     */
565    public function guessMimeType( string $file, $ext = true ): string {
566        if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
567            $this->logger->info( __METHOD__ .
568                ": WARNING: use of the \$ext parameter is deprecated. " .
569                "Use improveTypeFromExtension(\$mime, \$ext) instead." );
570        }
571
572        $mime = $this->doGuessMimeType( $file );
573
574        if ( !$mime ) {
575            $this->logger->info( __METHOD__ .
576                ": internal type detection failed for $file (.$ext)..." );
577            $mime = $this->detectMimeType( $file, $ext );
578        }
579
580        if ( isset( $this->mimeTypeAliases[$mime] ) ) {
581            $mime = $this->mimeTypeAliases[$mime];
582        }
583
584        $this->logger->info( __METHOD__ . ": guessed mime type of $file$mime" );
585        return $mime;
586    }
587
588    /**
589     * Guess the MIME type from the file contents.
590     *
591     * @param string $file
592     * @return bool|string
593     * @throws UnexpectedValueException
594     */
595    private function doGuessMimeType( string $file ) {
596        // Read a chunk of the file
597        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
598        $f = @fopen( $file, 'rb' );
599
600        if ( !$f ) {
601            return 'unknown/unknown';
602        }
603
604        $fsize = filesize( $file );
605        if ( $fsize === false ) {
606            return 'unknown/unknown';
607        }
608
609        $head = fread( $f, 1024 );
610        $head16k = $head . fread( $f, 16384 - 1024 ); // some WebM files have big headers
611        $tailLength = min( 65558, $fsize ); // 65558 = maximum size of a zip EOCDR
612        if ( fseek( $f, -1 * $tailLength, SEEK_END ) === -1 ) {
613            throw new UnexpectedValueException(
614                "Seeking $tailLength bytes from EOF failed in " . __METHOD__ );
615        }
616        $tail = $tailLength ? fread( $f, $tailLength ) : '';
617
618        $this->logger->info( __METHOD__ .
619            ": analyzing head and tail of $file for magic numbers." );
620
621        // Hardcode a few magic number checks...
622        foreach ( self::MAGIC_NUMBERS as $magic => $candidate ) {
623            if ( str_starts_with( $head, $magic ) ) {
624                $this->logger->info( __METHOD__ .
625                    ": magic header in $file recognized as $candidate" );
626                return $candidate;
627            }
628        }
629
630        /* Look for WebM and Matroska files */
631        if ( str_starts_with( $head16k, "\x1a\x45\xdf\xa3" ) ) {
632            $doctype = strpos( $head16k, "\x42\x82" );
633            if ( $doctype ) {
634                // Next byte is datasize, then data (sizes larger than 1 byte are stupid muxers)
635                $data = substr( $head16k, $doctype + 3, 8 );
636                if ( str_starts_with( $data, "matroska" ) ) {
637                    $this->logger->info( __METHOD__ . ": recognized file as video/matroska" );
638                    return "video/matroska";
639                }
640
641                if ( str_starts_with( $data, "webm" ) ) {
642                    // XXX HACK look for a video track, if we don't find it, this is an audio file
643                    // This detection is very naive and doesn't parse the actual fields
644                    // 0x86 byte indicates start of codecname field
645                    // next byte is a variable length integer (vint) for the size of the value following it
646                    // 8 (first bit is 1) indicates the smallest size vint, a single byte
647                    // (unlikely we see larger vints here)
648                    // 5 indicates a length of 5 ( V_VP8 or V_VP9 or V_AV1 )
649                    // Sometimes we see 0x86 instead of 0x85 because a
650                    // non-conforming muxer wrote a null terminated string
651                    $videotrack = str_contains( $head16k, "\x86\x85V_VP8" ) ||
652                        str_contains( $head16k, "\x86\x85V_VP9" ) ||
653                        str_contains( $head16k, "\x86\x85V_AV1" ) ||
654                        str_contains( $head16k, "\x86\x86V_VP8\x0" ) ||
655                        str_contains( $head16k, "\x86\x86V_VP9\x0" ) ||
656                        str_contains( $head16k, "\x86\x86V_AV1\x0" );
657
658                    if ( $videotrack ) {
659                        // There is a video track, so this is a video file.
660                        $this->logger->info( __METHOD__ . ": recognized file as video/webm" );
661                        return "video/webm";
662                    }
663
664                    $this->logger->info( __METHOD__ . ": recognized file as audio/webm" );
665                    return "audio/webm";
666                }
667            }
668            $this->logger->info( __METHOD__ . ": unknown EBML file" );
669            return "unknown/unknown";
670        }
671
672        /* Look for WebP */
673        if ( str_starts_with( $head, "RIFF" ) && substr( $head, 8, 7 ) === "WEBPVP8" ) {
674            $this->logger->info( __METHOD__ . ": recognized file as image/webp" );
675            return "image/webp";
676        }
677
678        /* Look for JPEG2000 */
679        if ( str_starts_with( $head, "\x00\x00\x00\x0cjP\x20\x20\x0d\x0a\x87\x0a" ) ) {
680            $this->logger->info( __METHOD__ . ": recognized as JPEG2000" );
681            // we skip 4 bytes
682            if ( substr( $head, 16, 8 ) === "ftypjp2 " ) {
683                $this->logger->info( __METHOD__ . ": recognized file as image/jp2" );
684                return 'image/jp2';
685            } elseif ( substr( $head, 16, 8 ) === "ftypjpx " ) {
686                $this->logger->info( __METHOD__ . ": recognized file as image/jpx" );
687                return 'image/jpx';
688            }
689        }
690
691        /* Look for MS Compound Binary (OLE) files */
692        if ( str_starts_with( $head, "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" ) ) {
693            $this->logger->info( __METHOD__ . ': recognized MS CFB (OLE) file' );
694            return $this->detectMicrosoftBinaryType( $f );
695        }
696
697        /**
698         * Look for PHP.  Check for this before HTML/XML...  Warning: this is a
699         * heuristic, and won't match a file with a lot of non-PHP before.  It
700         * will also match text files which could be PHP. :)
701         *
702         * @todo FIXME: For this reason, the check is probably useless -- an attacker
703         * could almost certainly just pad the file with a lot of nonsense to
704         * circumvent the check in any case where it would be a security
705         * problem.  On the other hand, it causes harmful false positives (bug
706         * 16583).  The heuristic has been cut down to exclude three-character
707         * strings like "<? ", but should it be axed completely?
708         */
709        if ( str_contains( $head, '<?php' ) ||
710            str_contains( $head, "<\x00?\x00p\x00h\x00p" ) ||
711            str_contains( $head, "<\x00?\x00 " ) ||
712            str_contains( $head, "<\x00?\x00\n" ) ||
713            str_contains( $head, "<\x00?\x00\t" ) ||
714            str_contains( $head, "<\x00?\x00=" )
715        ) {
716            $this->logger->info( __METHOD__ . ": recognized $file as application/x-php" );
717            return 'application/x-php';
718        }
719
720        /**
721         * look for XML formats (XHTML and SVG)
722         */
723        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
724        $xml = @new XmlTypeCheck( $file );
725        if ( $xml->wellFormed ) {
726            $xmlTypes = $this->xmlTypes;
727            // @phan-suppress-next-line PhanTypeMismatchDimFetch False positive
728            return $xmlTypes[$xml->getRootElement()] ?? 'application/xml';
729        }
730
731        /**
732         * look for shell scripts
733         */
734        $script_type = null;
735
736        # detect by shebang
737        if ( str_starts_with( $head, "#!" ) ) {
738            $script_type = "ASCII";
739        } elseif ( str_starts_with( $head, "\xef\xbb\xbf#!" ) ) {
740            $script_type = "UTF-8";
741        } elseif ( str_starts_with( $head, "\xfe\xff\x00#\x00!" ) ) {
742            $script_type = "UTF-16BE";
743        } elseif ( str_starts_with( $head, "\xff\xfe#\x00!" ) ) {
744            $script_type = "UTF-16LE";
745        }
746
747        if ( $script_type ) {
748            if ( $script_type !== "UTF-8" && $script_type !== "ASCII" ) {
749                // Quick and dirty fold down to ASCII!
750                $chars = unpack( self::PACK_MASKS[$script_type], substr( $head, 2 ) );
751                $head = '';
752                foreach ( $chars as $codepoint ) {
753                    if ( $codepoint < 128 ) {
754                        $head .= chr( $codepoint );
755                    } else {
756                        $head .= '?';
757                    }
758                }
759            }
760
761            $match = [];
762
763            if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
764                $mime = "application/x-{$match[2]}";
765                $this->logger->info( __METHOD__ . ": shell script recognized as $mime" );
766                return $mime;
767            }
768        }
769
770        // Check for ZIP variants (before getimagesize)
771        $eocdrPos = strpos( $tail, "PK\x05\x06" );
772        if ( $eocdrPos !== false && $eocdrPos <= strlen( $tail ) - 22 ) {
773            $this->logger->info( __METHOD__ . ": ZIP signature present in $file" );
774            // Check if it really is a ZIP file, make sure the EOCDR is at the end (T40432)
775            $commentLength = unpack( "n", substr( $tail, $eocdrPos + 20 ) )[1];
776            if ( $eocdrPos + 22 + $commentLength !== strlen( $tail ) ) {
777                $this->logger->info( __METHOD__ . ": ZIP EOCDR not at end. Not a ZIP file." );
778            } else {
779                return $this->detectZipTypeFromFile( $f );
780            }
781        }
782
783        // Check for STL (3D) files
784        // @see https://en.wikipedia.org/wiki/STL_(file_format)
785        if ( $fsize >= 15 &&
786            stripos( $head, 'SOLID ' ) === 0 &&
787            preg_match( '/\RENDSOLID .*$/i', $tail ) ) {
788            // ASCII STL file
789            return 'application/sla';
790        } elseif ( $fsize > 84 ) {
791            // binary STL file
792            $triangles = substr( $head, 80, 4 );
793            $triangles = unpack( 'V', $triangles );
794            $triangles = reset( $triangles );
795            if ( $triangles !== false && $fsize === 84 + ( $triangles * 50 ) ) {
796                return 'application/sla';
797            }
798        }
799
800        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
801        $gis = @getimagesize( $file );
802
803        if ( $gis && isset( $gis['mime'] ) ) {
804            $mime = $gis['mime'];
805            $this->logger->info( __METHOD__ . ": getimagesize detected $file as $mime" );
806            return $mime;
807        }
808
809        # Media handling extensions can guess the MIME by content
810        # It's intentionally here so that if core is wrong about a type (false positive),
811        # people will hopefully nag and submit patches :)
812        $mime = false;
813        # Some strings by reference for performance - assuming well-behaved hooks
814        $callback = $this->guessCallback;
815        if ( $callback ) {
816            $callback( $this, $head, $tail, $file, $mime /* by reference */ );
817        }
818
819        return $mime;
820    }
821
822    /**
823     * Detect application-specific file type of a given ZIP file.
824     * If it can't tell, return 'application/zip'.
825     *
826     * @internal
827     * @param resource $handle
828     * @return string
829     */
830    public function detectZipTypeFromFile( $handle ) {
831        $types = [];
832        $status = ZipDirectoryReader::readHandle(
833            $handle,
834            static function ( $entry ) use ( &$types ) {
835                $name = $entry['name'];
836                $names = [ $name ];
837
838                // If there is a null character, cut off the name at it, because JDK's
839                // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
840                // were constructed which had ".class\0" followed by a string chosen to
841                // make the hash collide with the truncated name, that file could be
842                // returned in response to a request for the .class file.
843                $nullPos = strpos( $entry['name'], "\000" );
844                if ( $nullPos !== false ) {
845                    $names[] = substr( $entry['name'], 0, $nullPos );
846                }
847
848                // If there is a trailing slash in the file name, we have to strip it,
849                // because that's what ZIP_GetEntry() does.
850                if ( preg_grep( '!\.class/?$!', $names ) ) {
851                    $types[] = 'application/java';
852                }
853
854                if ( $name === '[Content_Types].xml' ) {
855                    $types[] = 'application/x-opc+zip';
856                } elseif ( $name === 'mimetype' ) {
857                    $types[] = 'application/vnd.oasis.opendocument';
858                }
859            }
860        );
861        if ( !$status->isOK() ) {
862            $this->logger->info( "Error reading zip file: " . (string)$status );
863            // This could be unknown/unknown but we have some weird phpunit test cases
864            return 'application/zip';
865        }
866        if ( in_array( 'application/java', $types ) ) {
867            // For security, java detection takes precedence
868            return 'application/java';
869        } elseif ( count( $types ) ) {
870            return $types[0];
871        } else {
872            return 'application/zip';
873        }
874    }
875
876    /**
877     * Detect the type of a Microsoft Compound Binary a.k.a. OLE file.
878     * These are old style pre-ODF files such as .doc and .xls
879     *
880     * @param resource $handle An opened seekable file handle
881     * @return string The detected MIME type
882     */
883    private function detectMicrosoftBinaryType( $handle ): string {
884        $info = MSCompoundFileReader::readHandle( $handle );
885        if ( !$info['valid'] ) {
886            $this->logger->info( __METHOD__ . ': invalid file format' );
887            return 'unknown/unknown';
888        }
889        if ( !$info['mime'] ) {
890            $this->logger->info( __METHOD__ . ": unrecognised document subtype" );
891            return 'unknown/unknown';
892        }
893        return $info['mime'];
894    }
895
896    /**
897     * Internal MIME type detection. Detection is done using the fileinfo
898     * extension if it is available. It can be overridden by callback, which could
899     * use an external program, for example. If detection fails and $ext is not false,
900     * the MIME type is guessed from the file extension, using getMimeTypeFromExtensionOrNull.
901     *
902     * If the MIME type is still unknown, getimagesize is used to detect the
903     * MIME type if the file is an image. If no MIME type can be determined,
904     * this function returns 'unknown/unknown'.
905     *
906     * @param string $file The file to check
907     * @param string|bool $ext The file extension, or true (default) to extract it from the filename.
908     * Set it to false to ignore the extension. DEPRECATED! Set to false, use
909     * improveTypeFromExtension($mime, $ext) later to improve MIME type.
910     * @return string The MIME type of $file
911     */
912    private function detectMimeType( string $file, $ext = true ): string {
913        /** @todo Make $ext default to false. Or better, remove it. */
914        if ( $ext ) {
915            $this->logger->info( __METHOD__ .
916                ": WARNING: use of the \$ext parameter is deprecated. "
917                . "Use improveTypeFromExtension(\$mime, \$ext) instead." );
918        }
919
920        $callback = $this->detectCallback;
921        if ( $callback ) {
922            $m = $callback( $file );
923        } else {
924            $m = mime_content_type( $file );
925        }
926
927        if ( $m ) {
928            # normalize
929            $m = preg_replace( '![;, ].*$!', '', $m ); # strip charset, etc
930            $m = trim( $m );
931            $m = strtolower( $m );
932
933            if ( !str_contains( $m, 'unknown' ) ) {
934                $this->logger->info( __METHOD__ . ": magic mime type of $file$m" );
935                return $m;
936            }
937        }
938
939        // If desired, look at extension as a fallback.
940        if ( $ext === true ) {
941            $i = strrpos( $file, '.' );
942            $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
943        }
944        if ( $ext ) {
945            if ( $this->isRecognizableExtension( $ext ) ) {
946                $this->logger->info( __METHOD__ . ": refusing to guess mime type for .$ext file, "
947                    . "we should have recognized it" );
948            } else {
949                $m = $this->getMimeTypeFromExtensionOrNull( $ext );
950                if ( $m ) {
951                    $this->logger->info( __METHOD__ . ": extension mime type of $file$m" );
952                    return $m;
953                }
954            }
955        }
956
957        // Unknown type
958        $this->logger->info( __METHOD__ . ": failed to guess mime type for $file!" );
959        return 'unknown/unknown';
960    }
961
962    /**
963     * Determine the media type code for a file, using its MIME type, name and
964     * possibly its contents.
965     *
966     * This function relies on the findMediaType(), mapping extensions and MIME
967     * types to media types.
968     *
969     * @todo analyse file if need be
970     * @todo look at multiple extension, separately and together.
971     *
972     * @param string|null $path Full path to the image file, in case we have to look at the contents
973     * (if null, only the MIME type is used to determine the media type code).
974     * @param string|null $mime MIME type. If null it will be guessed using guessMimeType.
975     * @return string A value to be used with the MEDIATYPE_xxx constants.
976     */
977    public function getMediaType( ?string $path = null, ?string $mime = null ): string {
978        if ( !$mime && !$path ) {
979            return MEDIATYPE_UNKNOWN;
980        }
981
982        // If MIME type is unknown, guess it
983        if ( !$mime ) {
984            // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
985            $mime = $this->guessMimeType( $path, false );
986        }
987
988        // Special code for ogg - detect if it's video (theora),
989        // else label it as sound.
990        if ( $mime == 'application/ogg' && is_string( $path ) && file_exists( $path ) ) {
991            // Read a chunk of the file
992            $f = fopen( $path, "rt" );
993            if ( !$f ) {
994                return MEDIATYPE_UNKNOWN;
995            }
996            $head = fread( $f, 256 );
997            fclose( $f );
998
999            $head = str_replace( 'ffmpeg2theora', '', strtolower( $head ) );
1000
1001            // This is an UGLY HACK, file should be parsed correctly
1002            if ( str_contains( $head, 'theora' ) ) {
1003                return MEDIATYPE_VIDEO;
1004            } elseif ( str_contains( $head, 'vorbis' ) ) {
1005                return MEDIATYPE_AUDIO;
1006            } elseif ( str_contains( $head, 'flac' ) ) {
1007                return MEDIATYPE_AUDIO;
1008            } elseif ( str_contains( $head, 'speex' ) ) {
1009                return MEDIATYPE_AUDIO;
1010            } elseif ( str_contains( $head, 'opus' ) ) {
1011                return MEDIATYPE_AUDIO;
1012            } else {
1013                return MEDIATYPE_MULTIMEDIA;
1014            }
1015        }
1016
1017        $type = null;
1018        // Check for entry for full MIME type
1019        if ( $mime ) {
1020            $type = $this->findMediaType( $mime );
1021            if ( $type !== MEDIATYPE_UNKNOWN ) {
1022                return $type;
1023            }
1024        }
1025
1026        // Check for entry for file extension
1027        if ( $path ) {
1028            $i = strrpos( $path, '.' );
1029            $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1030
1031            // TODO: look at multi-extension if this fails, parse from full path
1032            $type = $this->findMediaType( '.' . $e );
1033            if ( $type !== MEDIATYPE_UNKNOWN ) {
1034                return $type;
1035            }
1036        }
1037
1038        // Check major MIME type
1039        if ( $mime ) {
1040            $i = strpos( $mime, '/' );
1041            if ( $i !== false ) {
1042                $major = substr( $mime, 0, $i );
1043                $type = $this->findMediaType( $major );
1044                if ( $type !== MEDIATYPE_UNKNOWN ) {
1045                    return $type;
1046                }
1047            }
1048        }
1049
1050        if ( !$type ) {
1051            $type = MEDIATYPE_UNKNOWN;
1052        }
1053
1054        return $type;
1055    }
1056
1057    /**
1058     * Returns a media code matching the given MIME type or file extension.
1059     *
1060     * File extensions are represented by a string starting with a dot (.) to
1061     * distinguish them from MIME types.
1062     *
1063     * @param string $extMime
1064     * @return int|string
1065     */
1066    private function findMediaType( string $extMime ) {
1067        if ( str_starts_with( $extMime, '.' ) ) {
1068            // If it's an extension, look up the MIME types
1069            $m = $this->getMimeTypesFromExtension( substr( $extMime, 1 ) );
1070            if ( !$m ) {
1071                return MEDIATYPE_UNKNOWN;
1072            }
1073        } else {
1074            // Normalize MIME type
1075            if ( isset( $this->mimeTypeAliases[$extMime] ) ) {
1076                $extMime = $this->mimeTypeAliases[$extMime];
1077            }
1078
1079            $m = [ $extMime ];
1080        }
1081
1082        foreach ( $m as $mime ) {
1083            foreach ( $this->mediaTypes as $type => $codes ) {
1084                if ( in_array( $mime, $codes, true ) ) {
1085                    return $type;
1086                }
1087            }
1088        }
1089
1090        return MEDIATYPE_UNKNOWN;
1091    }
1092
1093    /**
1094     * Returns an array of media types (MEDIATYPE_xxx constants)
1095     *
1096     * @return string[]
1097     */
1098    public function getMediaTypes(): array {
1099        return array_keys( $this->mediaTypes );
1100    }
1101
1102    /**
1103     * Check if major_mime has a value accepted by enum in a database schema.
1104     *
1105     * @since 1.42.0 (also backported to 1.39.7, 1.40.3 and 1.41.1)
1106     *
1107     * @param string $type
1108     * @return bool
1109     */
1110    public function isValidMajorMimeType( string $type ): bool {
1111        return isset( self::MAJOR_MIME_TYPES[$type] );
1112    }
1113}
1114
1115/** @deprecated class alias since 1.43 */
1116class_alias( MimeAnalyzer::class, 'MimeAnalyzer' );