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.
35 /** @var MediaHandler[] Instance cache with array of MediaHandler */
36 protected static $handlers = array();
39 * Get a MediaHandler for a given MIME type from the instance cache
43 * @return MediaHandler
45 static function getHandler( $type ) {
46 global $wgMediaHandlers;
47 if ( !isset( $wgMediaHandlers[$type] ) ) {
48 wfDebug( __METHOD__
. ": no handler found for $type.\n" );
52 $class = $wgMediaHandlers[$type];
53 if ( !isset( self
::$handlers[$class] ) ) {
54 self
::$handlers[$class] = new $class;
55 if ( !self
::$handlers[$class]->isEnabled() ) {
56 self
::$handlers[$class] = false;
60 return self
::$handlers[$class];
64 * Get an associative array mapping magic word IDs to parameter names.
65 * Will be used by the parser to identify parameters.
67 abstract function getParamMap();
70 * Validate a thumbnail parameter at parse time.
71 * Return true to accept the parameter, and false to reject it.
72 * If you return false, the parser will do something quiet and forgiving.
77 abstract function validateParam( $name, $value );
80 * Merge a parameter array into a string appropriate for inclusion in filenames
82 * @param array $params Array of parameters that have been through normaliseParams.
85 abstract function makeParamString( $params );
88 * Parse a param string made with makeParamString back into an array
90 * @param string $str The parameter string without file name (e.g. 122px)
91 * @return array|bool Array of parameters or false on failure.
93 abstract function parseParamString( $str );
96 * Changes the parameter array as necessary, ready for transformation.
97 * Should be idempotent.
98 * Returns false if the parameters are unacceptable and the transform should fail
102 abstract function normaliseParams( $image, &$params );
105 * Get an image size array like that returned by getimagesize(), or false if it
106 * can't be determined.
108 * @param File $image The image object, or false if there isn't one
109 * @param string $path the filename
110 * @return array Follow the format of PHP getimagesize() internal function. See http://www.php.net/getimagesize
112 abstract function getImageSize( $image, $path );
115 * Get handler-specific metadata which will be saved in the img_metadata field.
117 * @param File $image The image object, or false if there isn't one.
118 * Warning, FSFile::getPropsFromPath might pass an (object)array() instead (!)
119 * @param string $path The filename
122 function getMetadata( $image, $path ) {
127 * Get metadata version.
129 * This is not used for validating metadata, this is used for the api when returning
130 * metadata, since api content formats should stay the same over time, and so things
131 * using ForiegnApiRepo can keep backwards compatibility
133 * All core media handlers share a common version number, and extensions can
134 * use the GetMetadataVersion hook to append to the array (they should append a unique
135 * string so not to get confusing). If there was a media handler named 'foo' with metadata
136 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
137 * version is 2, the end version string would look like '2;foo=3'.
139 * @return string Version string
141 static function getMetadataVersion() {
142 $version = array( '2' ); // core metadata version
143 wfRunHooks( 'GetMetadataVersion', array( &$version ) );
145 return implode( ';', $version );
149 * Convert metadata version.
151 * By default just returns $metadata, but can be used to allow
152 * media handlers to convert between metadata versions.
154 * @param mixed|string|array $metadata Metadata array (serialized if string)
155 * @param int $version Target version
156 * @return array Serialized metadata in specified version, or $metadata on fail.
158 function convertMetadataVersion( $metadata, $version = 1 ) {
159 if ( !is_array( $metadata ) ) {
161 //unserialize to keep return parameter consistent.
162 wfSuppressWarnings();
163 $ret = unserialize( $metadata );
173 * Get a string describing the type of metadata, for display purposes.
177 function getMetadataType( $image ) {
182 * Check if the metadata string is valid for this handler.
183 * If it returns MediaHandler::METADATA_BAD (or false), Image
184 * will reload the metadata from the file and update the database.
185 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
186 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
187 * compatible (which may or may not trigger a metadata reload).
190 function isMetadataValid( $image, $metadata ) {
191 return self
::METADATA_GOOD
;
195 * Get an array of standard (FormatMetadata type) metadata values.
197 * The returned data is largely the same as that from getMetadata(),
198 * but formatted in a standard, stable, handler-independent way.
199 * The idea being that some values like ImageDescription or Artist
200 * are universal and should be retrievable in a handler generic way.
202 * The specific properties are the type of properties that can be
203 * handled by the FormatMetadata class. These values are exposed to the
204 * user via the filemetadata parser function.
206 * Details of the response format of this function can be found at
207 * https://www.mediawiki.org/wiki/Manual:File_metadata_handling
208 * tl/dr: the response is an associative array of
209 * properties keyed by name, but the value can be complex. You probably
210 * want to call one of the FormatMetadata::flatten* functions on the
211 * property values before using them, or call
212 * FormatMetadata::getFormattedData() on the full response array, which
213 * transforms all values into prettified, human-readable text.
215 * Subclasses overriding this function must return a value which is a
216 * valid API response fragment (all associative array keys are valid
219 * Note, if the file simply has no metadata, but the handler supports
220 * this interface, it should return an empty array, not false.
224 * @return array|bool False if interface not supported
227 public function getCommonMetaArray( File
$file ) {
232 * Get a MediaTransformOutput object representing an alternate of the transformed
233 * output which will call an intermediary thumbnail assist script.
235 * Used when the repository has a thumbnailScriptUrl option configured.
237 * Return false to fall back to the regular getTransform().
240 function getScriptedTransform( $image, $script, $params ) {
245 * Get a MediaTransformOutput object representing the transformed output. Does not
246 * actually do the transform.
248 * @param File $image The image object
249 * @param string $dstPath filesystem destination path
250 * @param string $dstUrl Destination URL to use in output HTML
251 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
252 * @return MediaTransformOutput
254 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
255 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
259 * Get a MediaTransformOutput object representing the transformed output. Does the
260 * transform unless $flags contains self::TRANSFORM_LATER.
262 * @param File $image The image object
263 * @param string $dstPath filesystem destination path
264 * @param string $dstUrl destination URL to use in output HTML
265 * @param array $params arbitrary set of parameters validated by $this->validateParam()
266 * Note: These parameters have *not* gone through $this->normaliseParams()
267 * @param int $flags A bitfield, may contain self::TRANSFORM_LATER
269 * @return MediaTransformOutput
271 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
274 * Get the thumbnail extension and MIME type for a given source MIME type
276 * @param string $ext Extension of original file
277 * @param string $mime Mime type of original file
278 * @param array $params Handler specific rendering parameters
279 * @return array thumbnail extension and MIME type
281 function getThumbType( $ext, $mime, $params = null ) {
282 $magic = MimeMagic
::singleton();
283 if ( !$ext ||
$magic->isMatchingExtension( $ext, $mime ) === false ) {
284 // The extension is not valid for this mime type and we do
285 // recognize the mime type
286 $extensions = $magic->getExtensionsForType( $mime );
288 return array( strtok( $extensions, ' ' ), $mime );
292 // The extension is correct (true) or the mime type is unknown to
294 return array( $ext, $mime );
298 * Get useful response headers for GET/HEAD requests for a file with the given metadata
299 * @param mixed $metadata Result of the getMetadata() function of this handler for a file
302 public function getStreamHeaders( $metadata ) {
307 * True if the handled types can be transformed
310 function canRender( $file ) {
315 * True if handled types cannot be displayed directly in a browser
316 * but can be rendered
319 function mustRender( $file ) {
324 * True if the type has multi-page capabilities
327 function isMultiPage( $file ) {
332 * Page count for a multi-page document, false if unsupported or unknown
335 function pageCount( $file ) {
340 * The material is vectorized and thus scaling is lossless
343 function isVectorized( $file ) {
348 * The material is an image, and is animated.
349 * In particular, video material need not return true.
350 * @note Before 1.20, this was a method of ImageHandler only
353 function isAnimatedImage( $file ) {
358 * If the material is animated, we can animate the thumbnail
360 * @return bool If material is not animated, handler may return any value.
362 function canAnimateThumbnail( $file ) {
367 * False if the handler is disabled for all files
370 function isEnabled() {
375 * Get an associative array of page dimensions
376 * Currently "width" and "height" are understood, but this might be
377 * expanded in the future.
378 * Returns false if unknown.
380 * It is expected that handlers for paged media (e.g. DjVuHandler)
381 * will override this method so that it gives the correct results
382 * for each specific page of the file, using the $page argument.
384 * @note For non-paged media, use getImageSize.
387 * @param int $page What page to get dimensions of
390 function getPageDimensions( $image, $page ) {
391 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
403 * Generic getter for text layer.
404 * Currently overloaded by PDF and DjVu handlers
407 function getPageText( $image, $page ) {
412 * Get an array structure that looks like this:
415 * 'visible' => array(
416 * 'Human-readable name' => 'Human readable value',
419 * 'collapsed' => array(
420 * 'Human-readable name' => 'Human readable value',
424 * The UI will format this into a table where the visible fields are always
425 * visible, and the collapsed fields are optionally visible.
427 * The function should return false if there is no metadata to display.
431 * @todo FIXME: I don't really like this interface, it's not very flexible
432 * I think the media handler should generate HTML instead. It can do
433 * all the formatting according to some standard. That makes it possible
434 * to do things like visual indication of grouped and chained streams
435 * in ogg container files.
438 function formatMetadata( $image ) {
442 /** sorts the visible/invisible field.
443 * Split off from ImageHandler::formatMetadata, as used by more than
444 * one type of handler.
446 * This is used by the media handlers that use the FormatMetadata class
448 * @param array $metadataArray metadata array
449 * @return array for use displaying metadata.
451 function formatMetadataHelper( $metadataArray ) {
453 'visible' => array(),
454 'collapsed' => array()
457 $formatted = FormatMetadata
::getFormattedData( $metadataArray );
458 // Sort fields into visible and collapsed
459 $visibleFields = $this->visibleMetadataFields();
460 foreach ( $formatted as $name => $value ) {
461 $tag = strtolower( $name );
462 self
::addMeta( $result,
463 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
474 * Get a list of metadata items which should be displayed when
475 * the metadata table is collapsed.
477 * @return array of strings
480 function visibleMetadataFields() {
481 return FormatMetadata
::getVisibleFields();
485 * This is used to generate an array element for each metadata value
486 * That array is then used to generate the table of metadata values
489 * @param &$array Array An array containing elements for each type of visibility
490 * and each of those elements being an array of metadata items. This function adds
491 * a value to that array.
492 * @param string $visibility ('visible' or 'collapsed') if this value is hidden
494 * @param string $type type of metadata tag (currently always 'exif')
495 * @param string $id the name of the metadata tag (like 'artist' for example).
496 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
497 * @param string $value thingy goes into a wikitext table; it used to be escaped but
498 * that was incompatible with previous practise of customized display
499 * with wikitext formatting via messages such as 'exif-model-value'.
500 * So the escaping is taken back out, but generally this seems a confusing
502 * @param string $param value to pass to the message for the name of the field
503 * as $1. Currently this parameter doesn't seem to ever be used.
505 * Note, everything here is passed through the parser later on (!)
507 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
508 $msg = wfMessage( "$type-$id", $param );
509 if ( $msg->exists() ) {
510 $name = $msg->text();
512 // This is for future compatibility when using instant commons.
513 // So as to not display as ugly a name if a new metadata
514 // property is defined that we don't know about
515 // (not a major issue since such a property would be collapsed
517 wfDebug( __METHOD__
. ' Unknown metadata name: ' . $id . "\n" );
518 $name = wfEscapeWikiText( $id );
520 $array[$visibility][] = array(
528 * Used instead of getLongDesc if there is no handler registered for file.
533 function getShortDesc( $file ) {
536 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
540 * Short description. Shown on Special:Search results.
545 function getLongDesc( $file ) {
548 return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
549 $file->getMimeType() )->parse();
553 * Long description. Shown under image on image description page surounded by ().
558 static function getGeneralShortDesc( $file ) {
561 return $wgLang->formatSize( $file->getSize() );
565 * Used instead of getShortDesc if there is no handler registered for file.
570 static function getGeneralLongDesc( $file ) {
573 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
574 $file->getMimeType() )->parse();
578 * Calculate the largest thumbnail width for a given original file size
579 * such that the thumbnail's height is at most $maxHeight.
580 * @param $boxWidth Integer Width of the thumbnail box.
581 * @param $boxHeight Integer Height of the thumbnail box.
582 * @param $maxHeight Integer Maximum height expected for the thumbnail.
585 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
586 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
587 $roundedUp = ceil( $idealWidth );
588 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
589 return floor( $idealWidth );
596 * Shown in file history box on image description page.
599 * @return String Dimensions
601 function getDimensionsString( $file ) {
606 * Modify the parser object post-transform.
608 * This is often used to do $parser->addOutputHook(),
609 * in order to add some javascript to render a viewer.
610 * See TimedMediaHandler or OggHandler for an example.
612 * @param Parser $parser
615 function parserTransformHook( $parser, $file ) {
619 * File validation hook called on upload.
621 * If the file at the given local path is not valid, or its MIME type does not
622 * match the handler class, a Status object should be returned containing
625 * @param string $fileName The local path to the file.
626 * @return Status object
628 function verifyUpload( $fileName ) {
629 return Status
::newGood();
633 * Check for zero-sized thumbnails. These can be generated when
634 * no disk space is available or some other error occurs
636 * @param string $dstPath The location of the suspect file
637 * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
638 * @return bool True if removed, false otherwise
640 function removeBadFile( $dstPath, $retval = 0 ) {
641 if ( file_exists( $dstPath ) ) {
642 $thumbstat = stat( $dstPath );
643 if ( $thumbstat['size'] == 0 ||
$retval != 0 ) {
644 $result = unlink( $dstPath );
647 wfDebugLog( 'thumbnail',
648 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
649 $thumbstat['size'], $dstPath ) );
651 wfDebugLog( 'thumbnail',
652 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
653 $thumbstat['size'], $dstPath ) );
664 * Remove files from the purge list.
666 * This is used by some video handlers to prevent ?action=purge
667 * from removing a transcoded video, which is expensive to
670 * @see LocalFile::purgeThumbnails
672 * @param array $files
673 * @param array $options Purge options. Currently will always be
674 * an array with a single key 'forThumbRefresh' set to true.
676 public function filterThumbnailPurgeList( &$files, $options ) {
681 * True if the handler can rotate the media
685 public static function canRotate() {
690 * On supporting image formats, try to read out the low-level orientation
691 * of the file and return the angle that the file needs to be rotated to
694 * This information is only useful when manipulating the original file;
695 * the width and height we normally work with is logical, and will match
696 * any produced output views.
698 * For files we don't know, we return 0.
701 * @return int 0, 90, 180 or 270
703 public function getRotation( $file ) {