Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
14.81% covered (danger)
14.81%
28 / 189
1.79% covered (danger)
1.79%
1 / 56
CRAP
0.00% covered (danger)
0.00%
0 / 1
MediaHandler
14.81% covered (danger)
14.81%
28 / 189
1.79% covered (danger)
1.79%
1 / 56
5555.95
0.00% covered (danger)
0.00%
0 / 1
 getHandler
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getParamMap
n/a
0 / 0
n/a
0 / 0
0
 validateParam
n/a
0 / 0
n/a
0 / 0
0
 makeParamString
n/a
0 / 0
n/a
0 / 0
0
 parseParamString
n/a
0 / 0
n/a
0 / 0
0
 normaliseParams
n/a
0 / 0
n/a
0 / 0
0
 getImageSize
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getSizeAndMetadata
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getMetadata
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 useLegacyMetadata
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 hasMostDerivedMethod
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getSizeAndMetadataWithFallback
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
182
 getMetadataVersion
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 convertMetadataVersion
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getMetadataType
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isMetadataValid
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isFileMetadataValid
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getCommonMetaArray
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getScriptedTransform
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getTransform
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 doTransform
n/a
0 / 0
n/a
0 / 0
0
 getThumbType
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 canRender
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 mustRender
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isMultiPage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pageCount
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isVectorized
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isAnimatedImage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 canAnimateThumbnail
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isEnabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getPageDimensions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getPageText
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getEntireText
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 formatMetadata
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 formatMetadataHelper
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
7.03
 formatTag
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 visibleMetadataFields
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addMeta
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 getShortDesc
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getLongDesc
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getGeneralShortDesc
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getGeneralLongDesc
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 fitBoxWidth
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getDimensionsString
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 parserTransformHook
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 verifyUpload
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 removeBadFile
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 filterThumbnailPurgeList
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 canRotate
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRotation
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 logErrorForExternalProcess
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getAvailableLanguages
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getMatchedLanguage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDefaultRenderLanguage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getLength
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isExpensiveToThumbnail
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 supportsBucketing
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 sanitizeParamsForBucketing
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getWarningConfig
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getPageRangesByDimensions
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
56
 getContentHeaders
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 useSplitMetadata
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7use MediaWiki\Context\IContextSource;
8use MediaWiki\FileRepo\File\File;
9use MediaWiki\FileRepo\File\LocalFile;
10use MediaWiki\HookContainer\HookRunner;
11use MediaWiki\MediaWikiServices;
12use MediaWiki\Parser\Parser;
13use MediaWiki\Status\Status;
14use Wikimedia\FileBackend\FSFile\FSFile;
15
16/**
17 * @defgroup Media Media
18 *
19 * Media handlers and other classes relating to Multimedia support,
20 * with the exception of FileRepo and FileBackend, which have their own groups.
21 */
22
23/**
24 * Base media handler class
25 *
26 * @stable to extend
27 * @ingroup Media
28 */
29abstract class MediaHandler {
30    public const TRANSFORM_LATER = 1;
31    public const METADATA_GOOD = true;
32    public const METADATA_BAD = false;
33    public const METADATA_COMPATIBLE = 2; // for old but backwards compatible.
34    /**
35     * Max length of error logged by logErrorForExternalProcess()
36     */
37    private const MAX_ERR_LOG_SIZE = 65535;
38
39    /**
40     * Get a MediaHandler for a given MIME type from the instance cache
41     *
42     * @param string $type
43     * @return MediaHandler|false
44     */
45    public static function getHandler( $type ) {
46        return MediaWikiServices::getInstance()
47            ->getMediaHandlerFactory()->getHandler( $type );
48    }
49
50    /**
51     * Get an associative array mapping magic word IDs to parameter names.
52     * Will be used by the parser to identify parameters.
53     * @return string[]
54     */
55    abstract public function getParamMap();
56
57    /**
58     * Validate a thumbnail parameter at parse time.
59     * Return true to accept the parameter, and false to reject it.
60     * If you return false, the parser will do something quiet and forgiving.
61     *
62     * @param string $name
63     * @param mixed $value
64     * @return bool
65     */
66    abstract public function validateParam( $name, $value );
67
68    /**
69     * Merge a parameter array into a string appropriate for inclusion in filenames
70     *
71     * @param array $params Array of parameters that have been through normaliseParams.
72     * @return string
73     */
74    abstract public function makeParamString( $params );
75
76    /**
77     * Parse a param string made with makeParamString back into an array
78     *
79     * @param string $str The parameter string without file name (e.g. 122px)
80     * @return array|false Array of parameters or false on failure.
81     */
82    abstract public function parseParamString( $str );
83
84    /**
85     * Changes the parameter array as necessary, ready for transformation.
86     * Should be idempotent.
87     * Returns false if the parameters are unacceptable and the transform should fail
88     * @param File $image
89     * @param array &$params
90     * @return bool
91     */
92    abstract public function normaliseParams( $image, &$params );
93
94    /**
95     * Get an image size array like that returned by getimagesize(), or false if it
96     * can't be determined.
97     *
98     * This function is used for determining the width, height and bitdepth directly
99     * from an image. The results are stored in the database in the img_width,
100     * img_height, img_bits fields.
101     *
102     * @note If this is a multipage file, return the width and height of the
103     *  first page.
104     *
105     * @deprecated since 1.37, override getSizeAndMetadata instead
106     *
107     * @param File|FSFile|false $image The image object, or false if there isn't one.
108     *   Warning, FSFile::getPropsFromPath might pass an FSFile instead of File (!)
109     * @param string $path The filename
110     * @return array|false Follow the format of PHP getimagesize() internal function.
111     *   See https://www.php.net/getimagesize. MediaWiki will only ever use the
112     *   first two array keys (the width and height), and the 'bits' associative
113     *   key. All other array keys are ignored. Returning a 'bits' key is optional
114     *   as not all formats have a notion of "bitdepth". Returns false on failure.
115     */
116    public function getImageSize( $image, $path ) {
117        return false;
118    }
119
120    /**
121     * Get image size information and metadata array.
122     *
123     * If this returns null, the caller will fall back to getImageSize() and
124     * getMetadata().
125     *
126     * If getImageSize() or getMetadata() are implemented in the most derived
127     * class, they will be used instead of this function. To override this
128     * behaviour, override useLegacyMetadata().
129     *
130     * @stable to override
131     * @since 1.37
132     *
133     * @param MediaHandlerState $state An object for saving process-local state.
134     *   This is normally a File object which will be passed back to other
135     *   MediaHandler methods like pageCount(), if they are called in the same
136     *   request. The handler can use this object to save its state.
137     * @param string $path The filename
138     * @return array|null Null to fall back to getImageSize(), or an array with
139     *   the following keys. All keys are optional.
140     *     - width: The width. If multipage, return the first page width. (optional)
141     *     - height: The height. If multipage, return the first page height. (optional)
142     *     - bits: The number of bits for each color (optional)
143     *     - metadata: A JSON-serializable array of metadata (optional)
144     */
145    public function getSizeAndMetadata( $state, $path ) {
146        return null;
147    }
148
149    /**
150     * Get handler-specific metadata which will be saved in the img_metadata field.
151     * @deprecated since 1.37 override getSizeAndMetadata() instead
152     *
153     * @param File|FSFile|false $image The image object, or false if there isn't one.
154     *   Warning, FSFile::getPropsFromPath might pass an FSFile instead of File (!)
155     * @param string $path The filename
156     * @return string A string of metadata in php serialized form (Run through serialize())
157     */
158    public function getMetadata( $image, $path ) {
159        return '';
160    }
161
162    /**
163     * If this returns true, the new method getSizeAndMetadata() will not be
164     * called. The legacy methods getMetadata() and getImageSize() will be used
165     * instead.
166     *
167     * @since 1.37
168     * @stable to override
169     * @return bool
170     */
171    protected function useLegacyMetadata() {
172        return $this->hasMostDerivedMethod( 'getMetadata' )
173            || $this->hasMostDerivedMethod( 'getImageSize' );
174    }
175
176    /**
177     * Check whether a method is implemented in the most derived class.
178     *
179     * @since 1.37
180     * @param string $name
181     * @return bool
182     */
183    protected function hasMostDerivedMethod( $name ) {
184        $rc = new ReflectionClass( $this );
185        $rm = new ReflectionMethod( $this, $name );
186        return $rm->getDeclaringClass()->getName() === $rc->getName();
187    }
188
189    /**
190     * Get the metadata array and the image size, with b/c fallback.
191     *
192     * The legacy methods will be used if useLegacyMetadata() returns true or
193     * if getSizeAndMetadata() returns null.
194     *
195     * Absent metadata will be normalized to an empty array. Absent width and
196     * height will be normalized to zero.
197     *
198     * @param File|FSFile $file This must be a File or FSFile to support the
199     *   legacy methods. When the legacy methods are removed, this will be
200     *   narrowed to MediaHandlerState.
201     * @param string $path
202     * @return array|false|null False on failure, or an array with the following keys:
203     *   - width: The width. If multipage, return the first page width.
204     *   - height: The height. If multipage, return the first page height.
205     *   - bits: The number of bits for each color (optional)
206     *   - metadata: A JSON-serializable array of metadata
207     * @since 1.37
208     */
209    final public function getSizeAndMetadataWithFallback( $file, $path ) {
210        if ( !$this->useLegacyMetadata() ) {
211            if ( $file instanceof MediaHandlerState ) {
212                $state = $file;
213            } else {
214                $state = new TrivialMediaHandlerState;
215            }
216            $info = $this->getSizeAndMetadata( $state, $path );
217            if ( $info === false ) {
218                return false;
219            }
220            if ( $info !== null ) {
221                $info += [ 'width' => 0, 'height' => 0, 'metadata' => [] ];
222                if ( !is_array( $info['metadata'] ) ) {
223                    throw new InvalidArgumentException( 'Media handler ' .
224                        static::class . ' returned ' . get_debug_type( $info['metadata'] ) .
225                        ' for metadata, should be array' );
226                }
227                return $info;
228            }
229        }
230
231        $blob = $this->getMetadata( $file, $path );
232        // @phan-suppress-next-line PhanParamTooMany
233        $size = $this->getImageSize(
234            $file,
235            $path,
236            $blob // Secret TimedMediaHandler parameter
237        );
238        if ( $blob === false && $size === false ) {
239            return false;
240        }
241        if ( $size ) {
242            $info = [
243                'width' => $size[0] ?? 0,
244                'height' => $size[1] ?? 0
245            ];
246            if ( isset( $size['bits'] ) ) {
247                $info['bits'] = $size['bits'];
248            }
249        } else {
250            $info = [ 'width' => 0, 'height' => 0 ];
251        }
252        if ( $blob !== false ) {
253            // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
254            $metadata = @unserialize( $blob );
255            if ( $metadata === false ) {
256                // Unserialize error
257                $metadata = [ '_error' => $blob ];
258            } elseif ( !is_array( $metadata ) ) {
259                $metadata = [];
260            }
261            $info['metadata'] = $metadata;
262        } else {
263            $info['metadata'] = [];
264        }
265        return $info;
266    }
267
268    /**
269     * Get metadata version.
270     *
271     * This is not used for validating metadata, this is used for the api when returning
272     * metadata, since api content formats should stay the same over time, and so things
273     * using ForeignApiRepo can keep backwards compatibility
274     *
275     * All core media handlers share a common version number, and extensions can
276     * use the GetMetadataVersion hook to append to the array (they should append a unique
277     * string so not to get confusing). If there was a media handler named 'foo' with metadata
278     * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
279     * version is 2, the end version string would look like '2;foo=3'.
280     *
281     * @stable to override
282     *
283     * @return string Version string
284     */
285    public static function getMetadataVersion() {
286        $version = [ '2' ]; // core metadata version
287        ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onGetMetadataVersion( $version );
288
289        return implode( ';', $version );
290    }
291
292    /**
293     * Convert metadata version.
294     *
295     * By default just returns $metadata, but can be used to allow
296     * media handlers to convert between metadata versions.
297     * @stable to override
298     *
299     * @param array $metadata Metadata array
300     * @param int|string $version Target version
301     * @return array Serialized metadata in specified version, or $metadata on fail.
302     */
303    public function convertMetadataVersion( $metadata, $version = 1 ) {
304        return $metadata;
305    }
306
307    /**
308     * Get a string describing the type of metadata, for display purposes.
309     * @stable to override
310     *
311     * @note This method is currently unused.
312     * @param File $image
313     * @return string|false
314     */
315    public function getMetadataType( $image ) {
316        return false;
317    }
318
319    /**
320     * Check if the metadata string is valid for this handler.
321     * If it returns MediaHandler::METADATA_BAD (or false), Image
322     * will reload the metadata from the file and update the database.
323     * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
324     * MediaHandler::METADATA_COMPATIBLE if metadata is old but backwards
325     * compatible (which may or may not trigger a metadata reload).
326     *
327     * @note Returning self::METADATA_BAD will trigger a metadata reload from
328     *  file on page view. Always returning this from a broken file, or suddenly
329     *  triggering as bad metadata for a large number of files can cause
330     *  performance problems.
331     *
332     * @deprecated since 1.37 use isFileMetadataValid
333     * @param File $image
334     * @param string $metadata The metadata in serialized form
335     * @return bool|int
336     */
337    public function isMetadataValid( $image, $metadata ) {
338        return self::METADATA_GOOD;
339    }
340
341    /**
342     * Check if the metadata is valid for this handler.
343     * If it returns MediaHandler::METADATA_BAD (or false), Image
344     * will reload the metadata from the file and update the database.
345     * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
346     * MediaHandler::METADATA_COMPATIBLE if metadata is old but backwards
347     * compatible (which may or may not trigger a metadata reload).
348     *
349     * @note Returning self::METADATA_BAD will trigger a metadata reload from
350     *  file on page view. Always returning this from a broken file, or suddenly
351     *  triggering as bad metadata for a large number of files can cause
352     *  performance problems.
353     *
354     * This was introduced in 1.37 to replace isMetadataValid(), which took a
355     * serialized string as a parameter. Handlers overriding this method are
356     * expected to use accessors to get the metadata out of the File. The
357     * reasons for the change were to get rid of serialization, and to allow
358     * handlers to partially load metadata with getMetadataItem(). For example
359     * a handler could just validate a version number.
360     *
361     * @stable to override
362     * @since 1.37
363     * @param File $image
364     * @return bool|int
365     */
366    public function isFileMetadataValid( $image ) {
367        return self::METADATA_GOOD;
368    }
369
370    /**
371     * Get an array of standard (FormatMetadata type) metadata values.
372     *
373     * The returned data is largely the same as that from getMetadata(),
374     * but formatted in a standard, stable, handler-independent way.
375     * The idea being that some values like ImageDescription or Artist
376     * are universal and should be retrievable in a handler generic way.
377     *
378     * The specific properties are the type of properties that can be
379     * handled by the FormatMetadata class. These values are exposed to the
380     * user via the filemetadata parser function.
381     *
382     * Details of the response format of this function can be found at
383     * https://www.mediawiki.org/wiki/Manual:File_metadata_handling
384     * tl/dr: the response is an associative array of
385     * properties keyed by name, but the value can be complex. You probably
386     * want to call one of the FormatMetadata::flatten* functions on the
387     * property values before using them, or call
388     * FormatMetadata::getFormattedData() on the full response array, which
389     * transforms all values into prettified, human-readable text.
390     *
391     * Subclasses overriding this function must return a value which is a
392     * valid API response fragment (all associative array keys are valid
393     * XML tagnames).
394     *
395     * Note, if the file simply has no metadata, but the handler supports
396     * this interface, it should return an empty array, not false.
397     *
398     * @stable to override
399     *
400     * @param File $file
401     * @return array|false False if interface not supported
402     * @since 1.23
403     */
404    public function getCommonMetaArray( File $file ) {
405        return false;
406    }
407
408    /**
409     * Get a MediaTransformOutput object representing an alternate of the transformed
410     * output which will call an intermediary thumbnail assist script.
411     *
412     * Used when the repository has a thumbnailScriptUrl option configured.
413     *
414     * Return false to fall back to the regular getTransform().
415     *
416     * @stable to override
417     *
418     * @param File $image
419     * @param string $script
420     * @param array $params
421     * @return ThumbnailImage|false
422     */
423    public function getScriptedTransform( $image, $script, $params ) {
424        return false;
425    }
426
427    /**
428     * Get a MediaTransformOutput object representing the transformed output. Does not
429     * actually do the transform.
430     *
431     * @stable to override
432     *
433     * @param File $image
434     * @param string $dstPath Filesystem destination path
435     * @param string $dstUrl Destination URL to use in output HTML
436     * @param array $params Arbitrary set of parameters validated by $this->validateParam()
437     * @return MediaTransformOutput
438     */
439    final public function getTransform( $image, $dstPath, $dstUrl, $params ) {
440        return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
441    }
442
443    /**
444     * Get a MediaTransformOutput object representing the transformed output. Does the
445     * transform unless $flags contains self::TRANSFORM_LATER.
446     *
447     * @stable to override
448     *
449     * @param File $image
450     * @param string $dstPath Filesystem destination path
451     * @param string $dstUrl Destination URL to use in output HTML
452     * @param array $params Arbitrary set of parameters validated by $this->validateParam()
453     *   Note: These parameters have *not* gone through $this->normaliseParams()
454     * @param int $flags A bitfield, may contain self::TRANSFORM_LATER
455     * @return MediaTransformOutput
456     */
457    abstract public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
458
459    /**
460     * Get the thumbnail extension and MIME type for a given source MIME type
461     *
462     * @stable to override
463     *
464     * @param string $ext Extension of original file
465     * @param string $mime MIME type of original file
466     * @param array|null $params Handler specific rendering parameters
467     * @return array Thumbnail extension and MIME type
468     */
469    public function getThumbType( $ext, $mime, $params = null ) {
470        $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
471        if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
472            // The extension is not valid for this MIME type and we do
473            // recognize the MIME type
474            $knownExt = $magic->getExtensionFromMimeTypeOrNull( $mime );
475            if ( $knownExt !== null ) {
476                return [ $knownExt, $mime ];
477            }
478        }
479
480        // The extension is correct (true) or the MIME type is unknown to
481        // MediaWiki (null)
482        return [ $ext, $mime ];
483    }
484
485    /**
486     * True if the handled types can be transformed
487     *
488     * @stable to override
489     *
490     * @param File $file
491     * @return bool
492     */
493    public function canRender( $file ) {
494        return true;
495    }
496
497    /**
498     * True if handled types cannot be displayed directly in a browser
499     * but can be rendered
500     *
501     * @stable to override
502     *
503     * @param File $file
504     * @return bool
505     */
506    public function mustRender( $file ) {
507        return false;
508    }
509
510    /**
511     * True if the type has multi-page capabilities
512     *
513     * @stable to override
514     *
515     * @param File $file
516     * @return bool
517     */
518    public function isMultiPage( $file ) {
519        return false;
520    }
521
522    /**
523     * Page count for a multi-page document, false if unsupported or unknown
524     *
525     * @stable to override
526     *
527     * @param File $file
528     * @return int|false
529     */
530    public function pageCount( File $file ) {
531        return false;
532    }
533
534    /**
535     * The material is vectorized and thus scaling is lossless
536     *
537     * @stable to override
538     *
539     * @param File $file
540     * @return bool
541     */
542    public function isVectorized( $file ) {
543        return false;
544    }
545
546    /**
547     * The material is an image, and is animated.
548     * In particular, video material need not return true.
549     * @note Before 1.20, this was a method of ImageHandler only
550     *
551     * @stable to override
552     *
553     * @param File $file
554     * @return bool
555     */
556    public function isAnimatedImage( $file ) {
557        return false;
558    }
559
560    /**
561     * If the material is animated, we can animate the thumbnail
562     * @since 1.20
563     *
564     * @stable to override
565     *
566     * @param File $file
567     * @return bool If material is not animated, handler may return any value.
568     */
569    public function canAnimateThumbnail( $file ) {
570        return true;
571    }
572
573    /**
574     * False if the handler is disabled for all files
575     * @stable to override
576     *
577     * @return bool
578     */
579    public function isEnabled() {
580        return true;
581    }
582
583    /**
584     * Get an associative array of page dimensions
585     * Currently "width" and "height" are understood, but this might be
586     * expanded in the future.
587     * Returns false if unknown.
588     *
589     * For a single page document format (!isMultipage()), this should return
590     * false.
591     *
592     * @note For non-paged media, use getImageSize.
593     *
594     * @stable to override
595     *
596     * @param File $image
597     * @param int $page What page to get dimensions of
598     * @return array|false
599     */
600    public function getPageDimensions( File $image, $page ) {
601        return false;
602    }
603
604    /**
605     * Generic getter for text layer.
606     * Currently overloaded by PDF and DjVu handlers
607     * @stable to override
608     *
609     * @param File $image
610     * @param int $page Page number to get information for
611     * @return string|false Page text or false when no text found or if
612     *   unsupported.
613     */
614    public function getPageText( File $image, $page ) {
615        return false;
616    }
617
618    /**
619     * Get the text of the entire document.
620     * @param File $file
621     * @return string|false The text of the document or false if unsupported.
622     */
623    public function getEntireText( File $file ) {
624        $numPages = $file->pageCount();
625        if ( !$numPages ) {
626            // Not a multipage document
627            return $this->getPageText( $file, 1 );
628        }
629        $document = '';
630        for ( $i = 1; $i <= $numPages; $i++ ) {
631            $curPage = $this->getPageText( $file, $i );
632            if ( is_string( $curPage ) ) {
633                $document .= $curPage . "\n";
634            }
635        }
636        if ( $document !== '' ) {
637            return $document;
638        }
639        return false;
640    }
641
642    /**
643     * Get an array structure that looks like this:
644     *
645     * [
646     *    'visible' => [
647     *       'Human-readable name' => 'Human readable value',
648     *       ...
649     *    ],
650     *    'collapsed' => [
651     *       'Human-readable name' => 'Human readable value',
652     *       ...
653     *    ]
654     * ]
655     * The UI will format this into a table where the visible fields are always
656     * visible, and the collapsed fields are optionally visible.
657     *
658     * The function should return false if there is no metadata to display.
659     */
660
661    /**
662     * @todo FIXME: This interface is not very flexible. The media handler
663     * should generate HTML instead. It can do all the formatting according
664     * to some standard. That makes it possible to do things like visual
665     * indication of grouped and chained streams in ogg container files.
666     * @stable to override
667     *
668     * @param File $image
669     * @param IContextSource|false $context
670     * @return array|false
671     */
672    public function formatMetadata( $image, $context = false ) {
673        return false;
674    }
675
676    /** sorts the visible/invisible field.
677     * Split off from ImageHandler::formatMetadata, as used by more than
678     * one type of handler.
679     *
680     * This is used by the media handlers that use the FormatMetadata class
681     *
682     * @stable to override
683     *
684     * @param array $metadataArray
685     * @param IContextSource|false $context
686     * @return array[] Array for use displaying metadata.
687     */
688    protected function formatMetadataHelper( $metadataArray, $context = false ) {
689        $result = [
690            'visible' => [],
691            'collapsed' => []
692        ];
693
694        // Allow this MediaHandler to override formatting on certain values
695        foreach ( $metadataArray as $tag => $vals ) {
696            $v = $this->formatTag( $tag, $vals, $context );
697            if ( $v === false ) {
698                // Use default formatting
699                continue;
700            }
701            if ( $v === null ) {
702                // Remove this tag, don't format it for display
703                unset( $metadataArray[$tag] );
704            } else {
705                // Allow subclass to override default formatting.
706                $metadataArray[$tag] = [ '_formatted' => $v ];
707                if ( isset( $v['_type'] ) ) {
708                    $metadataArray[$tag]['_type'] = $v['_type'];
709                    unset( $metadataArray[$tag]['_formatted']['_type'] );
710                }
711            }
712        }
713
714        $formatted = FormatMetadata::getFormattedData( $metadataArray, $context );
715        // Sort fields into visible and collapsed
716        $visibleFields = $this->visibleMetadataFields();
717        foreach ( $formatted as $name => $value ) {
718            $tag = strtolower( $name );
719            self::addMeta( $result,
720                in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
721                'exif',
722                $tag,
723                $value
724            );
725        }
726
727        return $result;
728    }
729
730    /**
731     * Override default formatting for the given metadata field.
732     *
733     * @stable to override
734     *
735     * @param string $key The metadata field key
736     * @param string|array $vals The unformatted value of this metadata field
737     * @param IContextSource|false $context Context to use (optional)
738     * @return false|null|string|array False to use default formatting, null
739     *   to remove this tag from the formatted list; otherwise return
740     *   a formatted HTML string (or array of them).
741     */
742    protected function formatTag( string $key, $vals, $context = false ) {
743        return false; // Use default formatting
744    }
745
746    /**
747     * Get a list of metadata items which should be displayed when
748     * the metadata table is collapsed.
749     *
750     * @stable to override
751     *
752     * @return string[]
753     */
754    protected function visibleMetadataFields() {
755        return FormatMetadata::getVisibleFields();
756    }
757
758    /**
759     * This is used to generate an array element for each metadata value
760     * That array is then used to generate the table of metadata values
761     * on the image page
762     *
763     * @param array &$array An array containing elements for each type of visibility
764     *   and each of those elements being an array of metadata items. This function adds
765     *   a value to that array.
766     * @param string $visibility ('visible' or 'collapsed') if this value is hidden
767     *   by default.
768     * @param string $type Type of metadata tag (currently always 'exif')
769     * @param string $id The name of the metadata tag (like 'artist' for example).
770     *   its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
771     * @param string $value Thingy goes into a wikitext table; it used to be escaped but
772     *   that was incompatible with previous practise of customized display
773     *   with wikitext formatting via messages such as 'exif-model-value'.
774     *   So the escaping is taken back out, but generally this seems a confusing
775     *   interface.
776     * @param bool|string $param Value to pass to the message for the name of the field
777     *   as $1. Currently this parameter doesn't seem to ever be used.
778     *
779     * Note, everything here is passed through the parser later on (!)
780     */
781    protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
782        $msg = wfMessage( "$type-$id", (string)$param );
783        if ( $msg->exists() ) {
784            $name = $msg->text();
785        } else {
786            // This is for future compatibility when using instant commons.
787            // So as to not display as ugly a name if a new metadata
788            // property is defined that we don't know about
789            // (not a major issue since such a property would be collapsed
790            // by default).
791            wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id );
792            $name = wfEscapeWikiText( $id );
793        }
794        $array[$visibility][] = [
795            'id' => "$type-$id",
796            'name' => $name,
797            'value' => $value
798        ];
799    }
800
801    /**
802     * Short description. Shown on Special:Search results.
803     *
804     * Until MediaWiki 1.45, the return value was poorly documented, and some subclasses returned HTML
805     * while others returned plain text. When overriding this method, you should return safe HTML,
806     * e.g. using `Message::escaped()`. When calling this method, you should treat it as returning
807     * unsafe HTML, and call `Sanitizer::removeSomeTags()` on the result.
808     *
809     * @stable to override
810     *
811     * @param File $file
812     * @return string HTML (possibly unsafe, call `Sanitizer::removeSomeTags()` on the result)
813     * @return-taint tainted
814     */
815    public function getShortDesc( $file ) {
816        return self::getGeneralShortDesc( $file );
817    }
818
819    /**
820     * Long description. Shown under image on image description page surrounded by ().
821     *
822     * Until MediaWiki 1.45, the return value was poorly documented, and some subclasses returned HTML
823     * while others returned plain text. When overriding this method, you should return safe HTML,
824     * e.g. using `Message::escaped()`. When calling this method, you should treat it as returning
825     * unsafe HTML, and call `Sanitizer::removeSomeTags()` on the result.
826     *
827     * @stable to override
828     *
829     * @param File $file
830     * @return string HTML (possibly unsafe, call `Sanitizer::removeSomeTags()` on the result)
831     * @return-taint tainted
832     */
833    public function getLongDesc( $file ) {
834        return self::getGeneralLongDesc( $file );
835    }
836
837    /**
838     * Used instead of getShortDesc if there is no handler registered for file.
839     *
840     * @param File $file
841     * @return string HTML
842     */
843    public static function getGeneralShortDesc( $file ) {
844        global $wgLang;
845
846        return htmlspecialchars( $wgLang->formatSize( $file->getSize() ), ENT_QUOTES );
847    }
848
849    /**
850     * Used instead of getLongDesc if there is no handler registered for file.
851     *
852     * @param File $file
853     * @return string HTML
854     */
855    public static function getGeneralLongDesc( $file ) {
856        return wfMessage( 'file-info' )
857            ->sizeParams( $file->getSize() )
858            ->params( '<span class="mime-type">' . $file->getMimeType() . '</span>' )
859            ->parse();
860    }
861
862    /**
863     * Calculate the largest thumbnail width for a given original file size
864     * such that the thumbnail's height is at most $maxHeight.
865     * @param int $boxWidth Width of the thumbnail box.
866     * @param int $boxHeight Height of the thumbnail box.
867     * @param int $maxHeight Maximum height expected for the thumbnail.
868     * @return int
869     */
870    public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
871        $idealWidth = $boxWidth * $maxHeight / $boxHeight;
872        $roundedUp = ceil( $idealWidth );
873        if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
874            return (int)floor( $idealWidth );
875        }
876        return $roundedUp;
877    }
878
879    /**
880     * Shown in file history box on image description page.
881     *
882     * @stable to override
883     *
884     * @param File $file
885     * @return string Dimensions (plain text)
886     */
887    public function getDimensionsString( $file ) {
888        return '';
889    }
890
891    /**
892     * Modify the parser object post-transform.
893     *
894     * This is often used to do $parser->addOutputHook(),
895     * in order to add some javascript to render a viewer.
896     * See TimedMediaHandler or OggHandler for an example.
897     *
898     * @stable to override
899     *
900     * @param Parser $parser
901     * @param File $file
902     */
903    public function parserTransformHook( $parser, $file ) {
904    }
905
906    /**
907     * File validation hook called on upload.
908     *
909     * If the file at the given local path is not valid, or its MIME type does not
910     * match the handler class, a Status object should be returned containing
911     * relevant errors.
912     *
913     * @stable to override
914     *
915     * @param string $fileName The local path to the file.
916     * @return Status
917     */
918    public function verifyUpload( $fileName ) {
919        return Status::newGood();
920    }
921
922    /**
923     * Check for zero-sized thumbnails. These can be generated when
924     * no disk space is available or some other error occurs
925     *
926     * @stable to override
927     *
928     * @param string $dstPath The location of the suspect file
929     * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
930     * @return bool True if removed, false otherwise
931     */
932    public function removeBadFile( $dstPath, $retval = 0 ) {
933        if ( file_exists( $dstPath ) ) {
934            $thumbstat = stat( $dstPath );
935            if ( $thumbstat['size'] == 0 || $retval != 0 ) {
936                $result = unlink( $dstPath );
937
938                if ( $result ) {
939                    wfDebugLog( 'thumbnail',
940                        sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
941                            $thumbstat['size'], $dstPath ) );
942                } else {
943                    wfDebugLog( 'thumbnail',
944                        sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
945                            $thumbstat['size'], $dstPath ) );
946                }
947
948                return true;
949            }
950        }
951
952        return false;
953    }
954
955    /**
956     * Remove files from the purge list.
957     *
958     * This is used by some video handlers to prevent ?action=purge
959     * from removing a transcoded video, which is expensive to
960     * regenerate.
961     *
962     * @see LocalFile::purgeThumbnails
963     * @stable to override
964     *
965     * @param array &$files
966     * @param array $options Purge options. Currently will always be
967     *  an array with a single key 'forThumbRefresh' set to true.
968     */
969    public function filterThumbnailPurgeList( &$files, $options ) {
970        // Do nothing
971    }
972
973    /**
974     * True if the handler can rotate the media
975     * @since 1.24 non-static. From 1.21-1.23 was static
976     * @stable to override
977     *
978     * @return bool
979     */
980    public function canRotate() {
981        return false;
982    }
983
984    /**
985     * On supporting image formats, try to read out the low-level orientation
986     * of the file and return the angle that the file needs to be rotated to
987     * be viewed.
988     *
989     * This information is only useful when manipulating the original file;
990     * the width and height we normally work with is logical, and will match
991     * any produced output views.
992     *
993     * For files we don't know, we return 0.
994     *
995     * @stable to override
996     *
997     * @param File $file
998     * @return int 0, 90, 180 or 270
999     */
1000    public function getRotation( $file ) {
1001        return 0;
1002    }
1003
1004    /**
1005     * Log an error that occurred in an external process
1006     *
1007     * Moved from BitmapHandler to MediaHandler with MediaWiki 1.23
1008     *
1009     * @since 1.23
1010     * @param int $retval
1011     * @param string $err Error reported by command. Anything longer than
1012     * MediaHandler::MAX_ERR_LOG_SIZE is stripped off.
1013     * @param string $cmd
1014     */
1015    protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
1016        # Keep error output limited (T59985)
1017        $errMessage = trim( substr( $err, 0, self::MAX_ERR_LOG_SIZE ) );
1018
1019        wfDebugLog( 'thumbnail',
1020            sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1021                    wfHostname(), $retval, $errMessage, $cmd ) );
1022    }
1023
1024    /**
1025     * Get list of languages file can be viewed in.
1026     *
1027     * @stable to override
1028     *
1029     * @param File $file
1030     * @return string[] Array of IETF language codes, or empty array if unsupported.
1031     * @since 1.23
1032     */
1033    public function getAvailableLanguages( File $file ) {
1034        return [];
1035    }
1036
1037    /**
1038     * When overridden in a descendant class, returns a language code most suiting
1039     *
1040     * @stable to override
1041     *
1042     * @since 1.32
1043     *
1044     * @param string $userPreferredLanguage IETF Language code requested
1045     * @param string[] $availableLanguages IETF Languages present in the file
1046     * @return string|null IETF Language code picked or null if not supported/available
1047     */
1048    public function getMatchedLanguage( $userPreferredLanguage, array $availableLanguages ) {
1049        return null;
1050    }
1051
1052    /**
1053     * On file types that support renderings in multiple languages,
1054     * which language is used by default if unspecified.
1055     *
1056     * If getAvailableLanguages returns a non-empty array, this must return
1057     * a valid language code. Otherwise can return null if files of this
1058     * type do not support alternative language renderings.
1059     * It can also return 'und' for explicitly requesting an undetermined language
1060     *
1061     * @stable to override
1062     *
1063     * @param File $file
1064     * @return string|null IETF Language code or null if multi-language not supported for filetype.
1065     * @since 1.23
1066     */
1067    public function getDefaultRenderLanguage( File $file ) {
1068        return null;
1069    }
1070
1071    /**
1072     * If it's an audio file, return the length of the file. Otherwise 0.
1073     *
1074     * File::getLength() existed for a long time, but was calling a method
1075     * that only existed in some subclasses of this class (The TMH ones).
1076     *
1077     * @stable to override
1078     *
1079     * @param File $file
1080     * @return float Length in seconds
1081     * @since 1.23
1082     */
1083    public function getLength( $file ) {
1084        return 0.0;
1085    }
1086
1087    /**
1088     * True if creating thumbnails from the file is large or otherwise resource-intensive.
1089     * @stable to override
1090     *
1091     * @param File $file
1092     * @return bool
1093     */
1094    public function isExpensiveToThumbnail( $file ) {
1095        return false;
1096    }
1097
1098    /**
1099     * Returns whether or not this handler supports the chained generation of thumbnails according
1100     * to buckets
1101     * @stable to override
1102     *
1103     * @return bool
1104     * @since 1.24
1105     */
1106    public function supportsBucketing() {
1107        return false;
1108    }
1109
1110    /**
1111     * Returns a normalised params array for which parameters have been cleaned up for bucketing
1112     * purposes
1113     * @stable to override
1114     *
1115     * @param array $params
1116     * @return array
1117     */
1118    public function sanitizeParamsForBucketing( $params ) {
1119        return $params;
1120    }
1121
1122    /**
1123     * Gets configuration for the file warning message. Return value of
1124     * the following structure:
1125     *   [
1126     *     // Required, module with messages loaded for the client
1127     *     'module' => 'example.filewarning.messages',
1128     *     // Required, array of names of messages
1129     *     'messages' => [
1130     *       // Required, main warning message
1131     *       'main' => 'example-filewarning-main',
1132     *       // Optional, header for warning dialog
1133     *       'header' => 'example-filewarning-header',
1134     *       // Optional, footer for warning dialog
1135     *       'footer' => 'example-filewarning-footer',
1136     *       // Optional, text for more-information link (see below)
1137     *       'info' => 'example-filewarning-info',
1138     *     ],
1139     *     // Optional, link for more information
1140     *     'link' => 'http://example.com',
1141     *   ]
1142     *
1143     * Returns null if no warning is necessary.
1144     * @stable to override
1145     * @param File $file
1146     * @return array|null
1147     */
1148    public function getWarningConfig( $file ) {
1149        return null;
1150    }
1151
1152    /**
1153     * Converts a dimensions array about a potentially multipage document from an
1154     * exhaustive list of ordered page numbers to a list of page ranges
1155     * @param array[] $pagesByDimensions
1156     * @return string
1157     * @since 1.30
1158     */
1159    public static function getPageRangesByDimensions( $pagesByDimensions ) {
1160        $pageRangesByDimensions = [];
1161
1162        foreach ( $pagesByDimensions as $dimensions => $pageList ) {
1163            $ranges = [];
1164            $firstPage = $pageList[0];
1165            $lastPage = $firstPage - 1;
1166
1167            foreach ( $pageList as $page ) {
1168                if ( $page > $lastPage + 1 ) {
1169                    if ( $firstPage !== $lastPage ) {
1170                        $ranges[] = "$firstPage-$lastPage";
1171                    } else {
1172                        $ranges[] = "$firstPage";
1173                    }
1174
1175                    $firstPage = $page;
1176                }
1177
1178                $lastPage = $page;
1179            }
1180
1181            if ( $firstPage != $lastPage ) {
1182                $ranges[] = "$firstPage-$lastPage";
1183            } else {
1184                $ranges[] = "$firstPage";
1185            }
1186
1187            $pageRangesByDimensions[ $dimensions ] = $ranges;
1188        }
1189
1190        $dimensionsString = [];
1191        foreach ( $pageRangesByDimensions as $dimensions => $pageRanges ) {
1192            $dimensionsString[] = "$dimensions:" . implode( ',', $pageRanges );
1193        }
1194
1195        return implode( '/', $dimensionsString );
1196    }
1197
1198    /**
1199     * Get useful response headers for GET/HEAD requests for a file with the given metadata
1200     * @stable to override
1201     *
1202     * @param array $metadata Contains this handler's unserialized getMetadata() for a file
1203     * @return array
1204     * @since 1.30
1205     */
1206    public function getContentHeaders( $metadata ) {
1207        return [ 'X-Content-Dimensions' => '' ]; // T175689
1208    }
1209
1210    /**
1211     * If this returns true, LocalFile may split metadata up and store its
1212     * constituent items separately. This only makes sense if the handler calls
1213     * File::getMetadataItem() or File::getMetadataItems() instead of
1214     * requesting the whole array at once.
1215     *
1216     * @return bool
1217     */
1218    public function useSplitMetadata() {
1219        return false;
1220    }
1221}