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 * Max length of error logged by logErrorForExternalProcess()
37 const MAX_ERR_LOG_SIZE
= 65535;
39 /** @var MediaHandler[] Instance cache with array of MediaHandler */
40 protected static $handlers = array();
43 * Get a MediaHandler for a given MIME type from the instance cache
46 * @return MediaHandler
48 static function getHandler( $type ) {
49 global $wgMediaHandlers;
50 if ( !isset( $wgMediaHandlers[$type] ) ) {
51 wfDebug( __METHOD__
. ": no handler found for $type.\n" );
55 $class = $wgMediaHandlers[$type];
56 if ( !isset( self
::$handlers[$class] ) ) {
57 self
::$handlers[$class] = new $class;
58 if ( !self
::$handlers[$class]->isEnabled() ) {
59 self
::$handlers[$class] = false;
63 return self
::$handlers[$class];
67 * Get an associative array mapping magic word IDs to parameter names.
68 * Will be used by the parser to identify parameters.
70 abstract function getParamMap();
73 * Validate a thumbnail parameter at parse time.
74 * Return true to accept the parameter, and false to reject it.
75 * If you return false, the parser will do something quiet and forgiving.
80 abstract function validateParam( $name, $value );
83 * Merge a parameter array into a string appropriate for inclusion in filenames
85 * @param array $params Array of parameters that have been through normaliseParams.
88 abstract function makeParamString( $params );
91 * Parse a param string made with makeParamString back into an array
93 * @param string $str The parameter string without file name (e.g. 122px)
94 * @return array|bool Array of parameters or false on failure.
96 abstract function parseParamString( $str );
99 * Changes the parameter array as necessary, ready for transformation.
100 * Should be idempotent.
101 * Returns false if the parameters are unacceptable and the transform should fail
103 * @param array $params
105 abstract function normaliseParams( $image, &$params );
108 * Get an image size array like that returned by getimagesize(), or false if it
109 * can't be determined.
111 * @param File $image The image object, or false if there isn't one
112 * @param string $path the filename
113 * @return array Follow the format of PHP getimagesize() internal function.
114 * See http://www.php.net/getimagesize
116 abstract function getImageSize( $image, $path );
119 * Get handler-specific metadata which will be saved in the img_metadata field.
121 * @param File $image The image object, or false if there isn't one.
122 * Warning, FSFile::getPropsFromPath might pass an (object)array() instead (!)
123 * @param string $path The filename
126 function getMetadata( $image, $path ) {
131 * Get metadata version.
133 * This is not used for validating metadata, this is used for the api when returning
134 * metadata, since api content formats should stay the same over time, and so things
135 * using ForiegnApiRepo can keep backwards compatibility
137 * All core media handlers share a common version number, and extensions can
138 * use the GetMetadataVersion hook to append to the array (they should append a unique
139 * string so not to get confusing). If there was a media handler named 'foo' with metadata
140 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
141 * version is 2, the end version string would look like '2;foo=3'.
143 * @return string Version string
145 static function getMetadataVersion() {
146 $version = array( '2' ); // core metadata version
147 wfRunHooks( 'GetMetadataVersion', array( &$version ) );
149 return implode( ';', $version );
153 * Convert metadata version.
155 * By default just returns $metadata, but can be used to allow
156 * media handlers to convert between metadata versions.
158 * @param string|array $metadata Metadata array (serialized if string)
159 * @param int $version Target version
160 * @return array Serialized metadata in specified version, or $metadata on fail.
162 function convertMetadataVersion( $metadata, $version = 1 ) {
163 if ( !is_array( $metadata ) ) {
165 //unserialize to keep return parameter consistent.
166 wfSuppressWarnings();
167 $ret = unserialize( $metadata );
177 * Get a string describing the type of metadata, for display purposes.
181 function getMetadataType( $image ) {
186 * Check if the metadata string is valid for this handler.
187 * If it returns MediaHandler::METADATA_BAD (or false), Image
188 * will reload the metadata from the file and update the database.
189 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
190 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
191 * compatible (which may or may not trigger a metadata reload).
193 * @param array $metadata
196 function isMetadataValid( $image, $metadata ) {
197 return self
::METADATA_GOOD
;
201 * Get an array of standard (FormatMetadata type) metadata values.
203 * The returned data is largely the same as that from getMetadata(),
204 * but formatted in a standard, stable, handler-independent way.
205 * The idea being that some values like ImageDescription or Artist
206 * are universal and should be retrievable in a handler generic way.
208 * The specific properties are the type of properties that can be
209 * handled by the FormatMetadata class. These values are exposed to the
210 * user via the filemetadata parser function.
212 * Details of the response format of this function can be found at
213 * https://www.mediawiki.org/wiki/Manual:File_metadata_handling
214 * tl/dr: the response is an associative array of
215 * properties keyed by name, but the value can be complex. You probably
216 * want to call one of the FormatMetadata::flatten* functions on the
217 * property values before using them, or call
218 * FormatMetadata::getFormattedData() on the full response array, which
219 * transforms all values into prettified, human-readable text.
221 * Subclasses overriding this function must return a value which is a
222 * valid API response fragment (all associative array keys are valid
225 * Note, if the file simply has no metadata, but the handler supports
226 * this interface, it should return an empty array, not false.
229 * @return array|bool False if interface not supported
232 public function getCommonMetaArray( File
$file ) {
237 * Get a MediaTransformOutput object representing an alternate of the transformed
238 * output which will call an intermediary thumbnail assist script.
240 * Used when the repository has a thumbnailScriptUrl option configured.
242 * Return false to fall back to the regular getTransform().
244 * @param string $script
245 * @param array $params
246 * @return bool|ThumbnailImage
248 function getScriptedTransform( $image, $script, $params ) {
253 * Get a MediaTransformOutput object representing the transformed output. Does not
254 * actually do the transform.
256 * @param File $image The image object
257 * @param string $dstPath Filesystem destination path
258 * @param string $dstUrl Destination URL to use in output HTML
259 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
260 * @return MediaTransformOutput
262 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
263 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
267 * Get a MediaTransformOutput object representing the transformed output. Does the
268 * transform unless $flags contains self::TRANSFORM_LATER.
270 * @param File $image The image object
271 * @param string $dstPath Filesystem destination path
272 * @param string $dstUrl Destination URL to use in output HTML
273 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
274 * Note: These parameters have *not* gone through $this->normaliseParams()
275 * @param int $flags A bitfield, may contain self::TRANSFORM_LATER
276 * @return MediaTransformOutput
278 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
281 * Get the thumbnail extension and MIME type for a given source MIME type
283 * @param string $ext Extension of original file
284 * @param string $mime MIME type of original file
285 * @param array $params Handler specific rendering parameters
286 * @return array thumbnail extension and MIME type
288 function getThumbType( $ext, $mime, $params = null ) {
289 $magic = MimeMagic
::singleton();
290 if ( !$ext ||
$magic->isMatchingExtension( $ext, $mime ) === false ) {
291 // The extension is not valid for this mime type and we do
292 // recognize the mime type
293 $extensions = $magic->getExtensionsForType( $mime );
295 return array( strtok( $extensions, ' ' ), $mime );
299 // The extension is correct (true) or the mime type is unknown to
301 return array( $ext, $mime );
305 * Get useful response headers for GET/HEAD requests for a file with the given metadata
307 * @param mixed $metadata Result of the getMetadata() function of this handler for a file
310 public function getStreamHeaders( $metadata ) {
315 * True if the handled types can be transformed
320 function canRender( $file ) {
325 * True if handled types cannot be displayed directly in a browser
326 * but can be rendered
331 function mustRender( $file ) {
336 * True if the type has multi-page capabilities
341 function isMultiPage( $file ) {
346 * Page count for a multi-page document, false if unsupported or unknown
351 function pageCount( $file ) {
356 * The material is vectorized and thus scaling is lossless
361 function isVectorized( $file ) {
366 * The material is an image, and is animated.
367 * In particular, video material need not return true.
368 * @note Before 1.20, this was a method of ImageHandler only
373 function isAnimatedImage( $file ) {
378 * If the material is animated, we can animate the thumbnail
382 * @return bool If material is not animated, handler may return any value.
384 function canAnimateThumbnail( $file ) {
389 * False if the handler is disabled for all files
392 function isEnabled() {
397 * Get an associative array of page dimensions
398 * Currently "width" and "height" are understood, but this might be
399 * expanded in the future.
400 * Returns false if unknown.
402 * It is expected that handlers for paged media (e.g. DjVuHandler)
403 * will override this method so that it gives the correct results
404 * for each specific page of the file, using the $page argument.
406 * @note For non-paged media, use getImageSize.
409 * @param int $page What page to get dimensions of
412 function getPageDimensions( $image, $page ) {
413 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
425 * Generic getter for text layer.
426 * Currently overloaded by PDF and DjVu handlers
428 * @param int $page Page number to get information for
429 * @return bool|string Page text or false when no text found or if
432 function getPageText( $image, $page ) {
437 * Get the text of the entire document.
439 * @return bool|string The text of the document or false if unsupported.
441 public function getEntireText( File
$file ) {
442 $numPages = $file->pageCount();
444 // Not a multipage document
445 return $this->getPageText( $file, 1 );
448 for ( $i = 1; $i <= $numPages; $i++
) {
449 $curPage = $this->getPageText( $file, $i );
450 if ( is_string( $curPage ) ) {
451 $document .= $curPage . "\n";
454 if ( $document !== '' ) {
461 * Get an array structure that looks like this:
464 * 'visible' => array(
465 * 'Human-readable name' => 'Human readable value',
468 * 'collapsed' => array(
469 * 'Human-readable name' => 'Human readable value',
473 * The UI will format this into a table where the visible fields are always
474 * visible, and the collapsed fields are optionally visible.
476 * The function should return false if there is no metadata to display.
480 * @todo FIXME: This interface is not very flexible. The media handler
481 * should generate HTML instead. It can do all the formatting according
482 * to some standard. That makes it possible to do things like visual
483 * indication of grouped and chained streams in ogg container files.
487 function formatMetadata( $image ) {
491 /** sorts the visible/invisible field.
492 * Split off from ImageHandler::formatMetadata, as used by more than
493 * one type of handler.
495 * This is used by the media handlers that use the FormatMetadata class
497 * @param array $metadataArray Metadata array
498 * @return array Array for use displaying metadata.
500 function formatMetadataHelper( $metadataArray ) {
502 'visible' => array(),
503 'collapsed' => array()
506 $formatted = FormatMetadata
::getFormattedData( $metadataArray );
507 // Sort fields into visible and collapsed
508 $visibleFields = $this->visibleMetadataFields();
509 foreach ( $formatted as $name => $value ) {
510 $tag = strtolower( $name );
511 self
::addMeta( $result,
512 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
523 * Get a list of metadata items which should be displayed when
524 * the metadata table is collapsed.
526 * @return array Array of strings
528 protected function visibleMetadataFields() {
529 return FormatMetadata
::getVisibleFields();
533 * This is used to generate an array element for each metadata value
534 * That array is then used to generate the table of metadata values
537 * @param array &$array An array containing elements for each type of visibility
538 * and each of those elements being an array of metadata items. This function adds
539 * a value to that array.
540 * @param string $visibility ('visible' or 'collapsed') if this value is hidden
542 * @param string $type Type of metadata tag (currently always 'exif')
543 * @param string $id The name of the metadata tag (like 'artist' for example).
544 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
545 * @param string $value Thingy goes into a wikitext table; it used to be escaped but
546 * that was incompatible with previous practise of customized display
547 * with wikitext formatting via messages such as 'exif-model-value'.
548 * So the escaping is taken back out, but generally this seems a confusing
550 * @param bool|string $param Value to pass to the message for the name of the field
551 * as $1. Currently this parameter doesn't seem to ever be used.
553 * Note, everything here is passed through the parser later on (!)
555 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
556 $msg = wfMessage( "$type-$id", $param );
557 if ( $msg->exists() ) {
558 $name = $msg->text();
560 // This is for future compatibility when using instant commons.
561 // So as to not display as ugly a name if a new metadata
562 // property is defined that we don't know about
563 // (not a major issue since such a property would be collapsed
565 wfDebug( __METHOD__
. ' Unknown metadata name: ' . $id . "\n" );
566 $name = wfEscapeWikiText( $id );
568 $array[$visibility][] = array(
576 * Used instead of getLongDesc if there is no handler registered for file.
581 function getShortDesc( $file ) {
584 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
588 * Short description. Shown on Special:Search results.
593 function getLongDesc( $file ) {
596 return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
597 $file->getMimeType() )->parse();
601 * Long description. Shown under image on image description page surounded by ().
606 static function getGeneralShortDesc( $file ) {
609 return $wgLang->formatSize( $file->getSize() );
613 * Used instead of getShortDesc if there is no handler registered for file.
618 static function getGeneralLongDesc( $file ) {
621 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
622 $file->getMimeType() )->parse();
626 * Calculate the largest thumbnail width for a given original file size
627 * such that the thumbnail's height is at most $maxHeight.
628 * @param int $boxWidth Width of the thumbnail box.
629 * @param int $boxHeight Height of the thumbnail box.
630 * @param int $maxHeight Maximum height expected for the thumbnail.
633 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
634 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
635 $roundedUp = ceil( $idealWidth );
636 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
637 return floor( $idealWidth );
644 * Shown in file history box on image description page.
647 * @return string Dimensions
649 function getDimensionsString( $file ) {
654 * Modify the parser object post-transform.
656 * This is often used to do $parser->addOutputHook(),
657 * in order to add some javascript to render a viewer.
658 * See TimedMediaHandler or OggHandler for an example.
660 * @param Parser $parser
663 function parserTransformHook( $parser, $file ) {
667 * File validation hook called on upload.
669 * If the file at the given local path is not valid, or its MIME type does not
670 * match the handler class, a Status object should be returned containing
673 * @param string $fileName The local path to the file.
674 * @return Status object
676 function verifyUpload( $fileName ) {
677 return Status
::newGood();
681 * Check for zero-sized thumbnails. These can be generated when
682 * no disk space is available or some other error occurs
684 * @param string $dstPath The location of the suspect file
685 * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
686 * @return bool True if removed, false otherwise
688 function removeBadFile( $dstPath, $retval = 0 ) {
689 if ( file_exists( $dstPath ) ) {
690 $thumbstat = stat( $dstPath );
691 if ( $thumbstat['size'] == 0 ||
$retval != 0 ) {
692 $result = unlink( $dstPath );
695 wfDebugLog( 'thumbnail',
696 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
697 $thumbstat['size'], $dstPath ) );
699 wfDebugLog( 'thumbnail',
700 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
701 $thumbstat['size'], $dstPath ) );
712 * Remove files from the purge list.
714 * This is used by some video handlers to prevent ?action=purge
715 * from removing a transcoded video, which is expensive to
718 * @see LocalFile::purgeThumbnails
720 * @param array $files
721 * @param array $options Purge options. Currently will always be
722 * an array with a single key 'forThumbRefresh' set to true.
724 public function filterThumbnailPurgeList( &$files, $options ) {
729 * True if the handler can rotate the media
733 public static function canRotate() {
738 * On supporting image formats, try to read out the low-level orientation
739 * of the file and return the angle that the file needs to be rotated to
742 * This information is only useful when manipulating the original file;
743 * the width and height we normally work with is logical, and will match
744 * any produced output views.
746 * For files we don't know, we return 0.
749 * @return int 0, 90, 180 or 270
751 public function getRotation( $file ) {
756 * Log an error that occurred in an external process
758 * Moved from BitmapHandler to MediaHandler with MediaWiki 1.23
762 * @param string $err Error reported by command. Anything longer than
763 * MediaHandler::MAX_ERR_LOG_SIZE is stripped off.
766 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
767 # Keep error output limited (bug 57985)
768 $errMessage = trim( substr( $err, 0, self
::MAX_ERR_LOG_SIZE
) );
770 wfDebugLog( 'thumbnail',
771 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
772 wfHostname(), $retval, $errMessage, $cmd ) );
776 * Get list of languages file can be viewed in.
779 * @return string[] Array of language codes, or empty array if unsupported.
782 public function getAvailableLanguages( File
$file ) {
787 * On file types that support renderings in multiple languages,
788 * which language is used by default if unspecified.
790 * If getAvailableLanguages returns a non-empty array, this must return
791 * a valid language code. Otherwise can return null if files of this
792 * type do not support alternative language renderings.
795 * @return string|null Language code or null if multi-language not supported for filetype.
798 public function getDefaultRenderLanguage( File
$file ) {
803 * If its an audio file, return the length of the file. Otherwise 0.
805 * File::getLength() existed for a long time, but was calling a method
806 * that only existed in some subclasses of this class (The TMH ones).
809 * @return float Length in seconds
812 public function getLength( $file ) {