3 * Media-handling base classes and generic functionality.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Base media handler class
29 abstract class MediaHandler
{
30 const TRANSFORM_LATER
= 1;
31 const METADATA_GOOD
= true;
32 const METADATA_BAD
= false;
33 const METADATA_COMPATIBLE
= 2; // for old but backwards compatible.
38 static $handlers = array();
41 * Get a MediaHandler for a given MIME type from the instance cache
45 * @return MediaHandler
47 static function getHandler( $type ) {
48 global $wgMediaHandlers;
49 if ( !isset( $wgMediaHandlers[$type] ) ) {
50 wfDebug( __METHOD__
. ": no handler found for $type.\n" );
54 $class = $wgMediaHandlers[$type];
55 if ( !isset( self
::$handlers[$class] ) ) {
56 self
::$handlers[$class] = new $class;
57 if ( !self
::$handlers[$class]->isEnabled() ) {
58 self
::$handlers[$class] = false;
62 return self
::$handlers[$class];
66 * Get an associative array mapping magic word IDs to parameter names.
67 * Will be used by the parser to identify parameters.
69 abstract function getParamMap();
72 * Validate a thumbnail parameter at parse time.
73 * Return true to accept the parameter, and false to reject it.
74 * If you return false, the parser will do something quiet and forgiving.
79 abstract function validateParam( $name, $value );
82 * Merge a parameter array into a string appropriate for inclusion in filenames
84 * @param array $params Array of parameters that have been through normaliseParams.
87 abstract function makeParamString( $params );
90 * Parse a param string made with makeParamString back into an array
92 * @param string $str The parameter string without file name (e.g. 122px)
93 * @return array|bool Array of parameters or false on failure.
95 abstract function parseParamString( $str );
98 * Changes the parameter array as necessary, ready for transformation.
99 * Should be idempotent.
100 * Returns false if the parameters are unacceptable and the transform should fail
104 abstract function normaliseParams( $image, &$params );
107 * Get an image size array like that returned by getimagesize(), or false if it
108 * can't be determined.
110 * @param File $image The image object, or false if there isn't one
111 * @param string $path the filename
112 * @return array Follow the format of PHP getimagesize() internal function. See http://www.php.net/getimagesize
114 abstract function getImageSize( $image, $path );
117 * Get handler-specific metadata which will be saved in the img_metadata field.
119 * @param File $image The image object, or false if there isn't one.
120 * Warning, FSFile::getPropsFromPath might pass an (object)array() instead (!)
121 * @param string $path The filename
124 function getMetadata( $image, $path ) {
129 * Get metadata version.
131 * This is not used for validating metadata, this is used for the api when returning
132 * metadata, since api content formats should stay the same over time, and so things
133 * using ForiegnApiRepo can keep backwards compatibility
135 * All core media handlers share a common version number, and extensions can
136 * use the GetMetadataVersion hook to append to the array (they should append a unique
137 * string so not to get confusing). If there was a media handler named 'foo' with metadata
138 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
139 * version is 2, the end version string would look like '2;foo=3'.
141 * @return string Version string
143 static function getMetadataVersion() {
144 $version = array( '2' ); // core metadata version
145 wfRunHooks( 'GetMetadataVersion', array( &$version ) );
147 return implode( ';', $version );
151 * Convert metadata version.
153 * By default just returns $metadata, but can be used to allow
154 * media handlers to convert between metadata versions.
156 * @param mixed|string|array $metadata Metadata array (serialized if string)
157 * @param int $version Target version
158 * @return array Serialized metadata in specified version, or $metadata on fail.
160 function convertMetadataVersion( $metadata, $version = 1 ) {
161 if ( !is_array( $metadata ) ) {
163 //unserialize to keep return parameter consistent.
164 wfSuppressWarnings();
165 $ret = unserialize( $metadata );
175 * Get a string describing the type of metadata, for display purposes.
179 function getMetadataType( $image ) {
184 * Check if the metadata string is valid for this handler.
185 * If it returns MediaHandler::METADATA_BAD (or false), Image
186 * will reload the metadata from the file and update the database.
187 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
188 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
189 * compatible (which may or may not trigger a metadata reload).
192 function isMetadataValid( $image, $metadata ) {
193 return self
::METADATA_GOOD
;
197 * Get an array of standard (FormatMetadata type) metadata values.
199 * The returned data is largely the same as that from getMetadata(),
200 * but formatted in a standard, stable, handler-independent way.
201 * The idea being that some values like ImageDescription or Artist
202 * are universal and should be retrievable in a handler generic way.
204 * The specific properties are the type of properties that can be
205 * handled by the FormatMetadata class. These values are exposed to the
206 * user via the filemetadata parser function.
208 * Details of the response format of this function can be found at
209 * https://www.mediawiki.org/wiki/Manual:File_metadata_handling
210 * tl/dr: the response is an associative array of
211 * properties keyed by name, but the value can be complex. You probably
212 * want to call one of the FormatMetadata::flatten* functions on the
213 * property values before using them, or call
214 * FormatMetadata::getFormattedData() on the full response array, which
215 * transforms all values into prettified, human-readable text.
217 * Subclasses overriding this function must return a value which is a
218 * valid API response fragment (all associative array keys are valid
221 * Note, if the file simply has no metadata, but the handler supports
222 * this interface, it should return an empty array, not false.
226 * @return array|bool False if interface not supported
229 public function getCommonMetaArray( File
$file ) {
234 * Get a MediaTransformOutput object representing an alternate of the transformed
235 * output which will call an intermediary thumbnail assist script.
237 * Used when the repository has a thumbnailScriptUrl option configured.
239 * Return false to fall back to the regular getTransform().
242 function getScriptedTransform( $image, $script, $params ) {
247 * Get a MediaTransformOutput object representing the transformed output. Does not
248 * actually do the transform.
250 * @param File $image The image object
251 * @param string $dstPath filesystem destination path
252 * @param string $dstUrl Destination URL to use in output HTML
253 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
254 * @return MediaTransformOutput
256 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
257 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
261 * Get a MediaTransformOutput object representing the transformed output. Does the
262 * transform unless $flags contains self::TRANSFORM_LATER.
264 * @param File $image The image object
265 * @param string $dstPath filesystem destination path
266 * @param string $dstUrl destination URL to use in output HTML
267 * @param array $params arbitrary set of parameters validated by $this->validateParam()
268 * Note: These parameters have *not* gone through $this->normaliseParams()
269 * @param int $flags A bitfield, may contain self::TRANSFORM_LATER
271 * @return MediaTransformOutput
273 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
276 * Get the thumbnail extension and MIME type for a given source MIME type
278 * @param string $ext Extension of original file
279 * @param string $mime Mime type of original file
280 * @param array $params Handler specific rendering parameters
281 * @return array thumbnail extension and MIME type
283 function getThumbType( $ext, $mime, $params = null ) {
284 $magic = MimeMagic
::singleton();
285 if ( !$ext ||
$magic->isMatchingExtension( $ext, $mime ) === false ) {
286 // The extension is not valid for this mime type and we do
287 // recognize the mime type
288 $extensions = $magic->getExtensionsForType( $mime );
290 return array( strtok( $extensions, ' ' ), $mime );
294 // The extension is correct (true) or the mime type is unknown to
296 return array( $ext, $mime );
300 * Get useful response headers for GET/HEAD requests for a file with the given metadata
301 * @param mixed $metadata Result of the getMetadata() function of this handler for a file
304 public function getStreamHeaders( $metadata ) {
309 * True if the handled types can be transformed
312 function canRender( $file ) {
317 * True if handled types cannot be displayed directly in a browser
318 * but can be rendered
321 function mustRender( $file ) {
326 * True if the type has multi-page capabilities
329 function isMultiPage( $file ) {
334 * Page count for a multi-page document, false if unsupported or unknown
337 function pageCount( $file ) {
342 * The material is vectorized and thus scaling is lossless
345 function isVectorized( $file ) {
350 * The material is an image, and is animated.
351 * In particular, video material need not return true.
352 * @note Before 1.20, this was a method of ImageHandler only
355 function isAnimatedImage( $file ) {
360 * If the material is animated, we can animate the thumbnail
362 * @return bool If material is not animated, handler may return any value.
364 function canAnimateThumbnail( $file ) {
369 * False if the handler is disabled for all files
372 function isEnabled() {
377 * Get an associative array of page dimensions
378 * Currently "width" and "height" are understood, but this might be
379 * expanded in the future.
380 * Returns false if unknown.
382 * It is expected that handlers for paged media (e.g. DjVuHandler)
383 * will override this method so that it gives the correct results
384 * for each specific page of the file, using the $page argument.
386 * @note For non-paged media, use getImageSize.
389 * @param int $page What page to get dimensions of
392 function getPageDimensions( $image, $page ) {
393 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
405 * Generic getter for text layer.
406 * Currently overloaded by PDF and DjVu handlers
409 function getPageText( $image, $page ) {
414 * Get an array structure that looks like this:
417 * 'visible' => array(
418 * 'Human-readable name' => 'Human readable value',
421 * 'collapsed' => array(
422 * 'Human-readable name' => 'Human readable value',
426 * The UI will format this into a table where the visible fields are always
427 * visible, and the collapsed fields are optionally visible.
429 * The function should return false if there is no metadata to display.
433 * @todo FIXME: I don't really like this interface, it's not very flexible
434 * I think the media handler should generate HTML instead. It can do
435 * all the formatting according to some standard. That makes it possible
436 * to do things like visual indication of grouped and chained streams
437 * in ogg container files.
440 function formatMetadata( $image ) {
444 /** sorts the visible/invisible field.
445 * Split off from ImageHandler::formatMetadata, as used by more than
446 * one type of handler.
448 * This is used by the media handlers that use the FormatMetadata class
450 * @param array $metadataArray metadata array
451 * @return array for use displaying metadata.
453 function formatMetadataHelper( $metadataArray ) {
455 'visible' => array(),
456 'collapsed' => array()
459 $formatted = FormatMetadata
::getFormattedData( $metadataArray );
460 // Sort fields into visible and collapsed
461 $visibleFields = $this->visibleMetadataFields();
462 foreach ( $formatted as $name => $value ) {
463 $tag = strtolower( $name );
464 self
::addMeta( $result,
465 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
476 * Get a list of metadata items which should be displayed when
477 * the metadata table is collapsed.
479 * @return array of strings
482 function visibleMetadataFields() {
483 return FormatMetadata
::getVisibleFields();
487 * This is used to generate an array element for each metadata value
488 * That array is then used to generate the table of metadata values
491 * @param &$array Array An array containing elements for each type of visibility
492 * and each of those elements being an array of metadata items. This function adds
493 * a value to that array.
494 * @param string $visibility ('visible' or 'collapsed') if this value is hidden
496 * @param string $type type of metadata tag (currently always 'exif')
497 * @param string $id the name of the metadata tag (like 'artist' for example).
498 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
499 * @param string $value thingy goes into a wikitext table; it used to be escaped but
500 * that was incompatible with previous practise of customized display
501 * with wikitext formatting via messages such as 'exif-model-value'.
502 * So the escaping is taken back out, but generally this seems a confusing
504 * @param string $param value to pass to the message for the name of the field
505 * as $1. Currently this parameter doesn't seem to ever be used.
507 * Note, everything here is passed through the parser later on (!)
509 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
510 $msg = wfMessage( "$type-$id", $param );
511 if ( $msg->exists() ) {
512 $name = $msg->text();
514 // This is for future compatibility when using instant commons.
515 // So as to not display as ugly a name if a new metadata
516 // property is defined that we don't know about
517 // (not a major issue since such a property would be collapsed
519 wfDebug( __METHOD__
. ' Unknown metadata name: ' . $id . "\n" );
520 $name = wfEscapeWikiText( $id );
522 $array[$visibility][] = array(
530 * Used instead of getLongDesc if there is no handler registered for file.
535 function getShortDesc( $file ) {
538 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
542 * Short description. Shown on Special:Search results.
547 function getLongDesc( $file ) {
550 return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
551 $file->getMimeType() )->parse();
555 * Long description. Shown under image on image description page surounded by ().
560 static function getGeneralShortDesc( $file ) {
563 return $wgLang->formatSize( $file->getSize() );
567 * Used instead of getShortDesc if there is no handler registered for file.
572 static function getGeneralLongDesc( $file ) {
575 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
576 $file->getMimeType() )->parse();
580 * Calculate the largest thumbnail width for a given original file size
581 * such that the thumbnail's height is at most $maxHeight.
582 * @param $boxWidth Integer Width of the thumbnail box.
583 * @param $boxHeight Integer Height of the thumbnail box.
584 * @param $maxHeight Integer Maximum height expected for the thumbnail.
587 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
588 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
589 $roundedUp = ceil( $idealWidth );
590 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
591 return floor( $idealWidth );
598 * Shown in file history box on image description page.
601 * @return String Dimensions
603 function getDimensionsString( $file ) {
608 * Modify the parser object post-transform.
610 * This is often used to do $parser->addOutputHook(),
611 * in order to add some javascript to render a viewer.
612 * See TimedMediaHandler or OggHandler for an example.
614 * @param Parser $parser
617 function parserTransformHook( $parser, $file ) {
621 * File validation hook called on upload.
623 * If the file at the given local path is not valid, or its MIME type does not
624 * match the handler class, a Status object should be returned containing
627 * @param string $fileName The local path to the file.
628 * @return Status object
630 function verifyUpload( $fileName ) {
631 return Status
::newGood();
635 * Check for zero-sized thumbnails. These can be generated when
636 * no disk space is available or some other error occurs
638 * @param string $dstPath The location of the suspect file
639 * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
640 * @return bool True if removed, false otherwise
642 function removeBadFile( $dstPath, $retval = 0 ) {
643 if ( file_exists( $dstPath ) ) {
644 $thumbstat = stat( $dstPath );
645 if ( $thumbstat['size'] == 0 ||
$retval != 0 ) {
646 $result = unlink( $dstPath );
649 wfDebugLog( 'thumbnail',
650 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
651 $thumbstat['size'], $dstPath ) );
653 wfDebugLog( 'thumbnail',
654 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
655 $thumbstat['size'], $dstPath ) );
666 * Remove files from the purge list.
668 * This is used by some video handlers to prevent ?action=purge
669 * from removing a transcoded video, which is expensive to
672 * @see LocalFile::purgeThumbnails
674 * @param array $files
675 * @param array $options Purge options. Currently will always be
676 * an array with a single key 'forThumbRefresh' set to true.
678 public function filterThumbnailPurgeList( &$files, $options ) {
683 * True if the handler can rotate the media
687 public static function canRotate() {
692 * On supporting image formats, try to read out the low-level orientation
693 * of the file and return the angle that the file needs to be rotated to
696 * This information is only useful when manipulating the original file;
697 * the width and height we normally work with is logical, and will match
698 * any produced output views.
700 * For files we don't know, we return 0.
703 * @return int 0, 90, 180 or 270
705 public function getRotation( $file ) {