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