Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / media / MediaHandler.php
blobf6717cdb05e50d4d5b50a0ad1d2529424b076dd4
1 <?php
2 /**
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
20 * @file
21 * @ingroup Media
24 /**
25 * Base media handler class
27 * @ingroup Media
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.
34 /**
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();
42 /**
43 * Get a MediaHandler for a given MIME type from the instance cache
45 * @param string $type
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" );
53 return false;
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];
66 /**
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();
72 /**
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.
77 * @param string $name
78 * @param mixed $value
80 abstract function validateParam( $name, $value );
82 /**
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.
86 * @return string
88 abstract function makeParamString( $params );
90 /**
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 );
98 /**
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
102 * @param File $image
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 * This function is used for determining the width, height and bitdepth directly
112 * from an image. The results are stored in the database in the img_width,
113 * img_height, img_bits fields.
115 * @note If this is a multipage file, return the width and height of the
116 * first page.
118 * @param File $image The image object, or false if there isn't one
119 * @param string $path the filename
120 * @return array Follow the format of PHP getimagesize() internal function.
121 * See http://www.php.net/getimagesize. MediaWiki will only ever use the
122 * first two array keys (the width and height), and the 'bits' associative
123 * key. All other array keys are ignored. Returning a 'bits' key is optional
124 * as not all formats have a notion of "bitdepth".
126 abstract function getImageSize( $image, $path );
129 * Get handler-specific metadata which will be saved in the img_metadata field.
131 * @param File $image The image object, or false if there isn't one.
132 * Warning, FSFile::getPropsFromPath might pass an (object)array() instead (!)
133 * @param string $path The filename
134 * @return string A string of metadata in php serialized form (Run through serialize())
136 function getMetadata( $image, $path ) {
137 return '';
141 * Get metadata version.
143 * This is not used for validating metadata, this is used for the api when returning
144 * metadata, since api content formats should stay the same over time, and so things
145 * using ForeignApiRepo can keep backwards compatibility
147 * All core media handlers share a common version number, and extensions can
148 * use the GetMetadataVersion hook to append to the array (they should append a unique
149 * string so not to get confusing). If there was a media handler named 'foo' with metadata
150 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
151 * version is 2, the end version string would look like '2;foo=3'.
153 * @return string Version string
155 static function getMetadataVersion() {
156 $version = array( '2' ); // core metadata version
157 wfRunHooks( 'GetMetadataVersion', array( &$version ) );
159 return implode( ';', $version );
163 * Convert metadata version.
165 * By default just returns $metadata, but can be used to allow
166 * media handlers to convert between metadata versions.
168 * @param string|array $metadata Metadata array (serialized if string)
169 * @param int $version Target version
170 * @return array Serialized metadata in specified version, or $metadata on fail.
172 function convertMetadataVersion( $metadata, $version = 1 ) {
173 if ( !is_array( $metadata ) ) {
175 //unserialize to keep return parameter consistent.
176 wfSuppressWarnings();
177 $ret = unserialize( $metadata );
178 wfRestoreWarnings();
180 return $ret;
183 return $metadata;
187 * Get a string describing the type of metadata, for display purposes.
189 * @note This method is currently unused.
190 * @param File $image
191 * @return string
193 function getMetadataType( $image ) {
194 return false;
198 * Check if the metadata string is valid for this handler.
199 * If it returns MediaHandler::METADATA_BAD (or false), Image
200 * will reload the metadata from the file and update the database.
201 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
202 * MediaHandler::METADATA_COMPATIBLE if metadata is old but backwards
203 * compatible (which may or may not trigger a metadata reload).
205 * @note Returning self::METADATA_BAD will trigger a metadata reload from
206 * file on page view. Always returning this from a broken file, or suddenly
207 * triggering as bad metadata for a large number of files can cause
208 * performance problems.
209 * @param File $image
210 * @param string $metadata The metadata in serialized form
211 * @return bool
213 function isMetadataValid( $image, $metadata ) {
214 return self::METADATA_GOOD;
218 * Get an array of standard (FormatMetadata type) metadata values.
220 * The returned data is largely the same as that from getMetadata(),
221 * but formatted in a standard, stable, handler-independent way.
222 * The idea being that some values like ImageDescription or Artist
223 * are universal and should be retrievable in a handler generic way.
225 * The specific properties are the type of properties that can be
226 * handled by the FormatMetadata class. These values are exposed to the
227 * user via the filemetadata parser function.
229 * Details of the response format of this function can be found at
230 * https://www.mediawiki.org/wiki/Manual:File_metadata_handling
231 * tl/dr: the response is an associative array of
232 * properties keyed by name, but the value can be complex. You probably
233 * want to call one of the FormatMetadata::flatten* functions on the
234 * property values before using them, or call
235 * FormatMetadata::getFormattedData() on the full response array, which
236 * transforms all values into prettified, human-readable text.
238 * Subclasses overriding this function must return a value which is a
239 * valid API response fragment (all associative array keys are valid
240 * XML tagnames).
242 * Note, if the file simply has no metadata, but the handler supports
243 * this interface, it should return an empty array, not false.
245 * @param File $file
246 * @return array|bool False if interface not supported
247 * @since 1.23
249 public function getCommonMetaArray( File $file ) {
250 return false;
254 * Get a MediaTransformOutput object representing an alternate of the transformed
255 * output which will call an intermediary thumbnail assist script.
257 * Used when the repository has a thumbnailScriptUrl option configured.
259 * Return false to fall back to the regular getTransform().
260 * @param File $image
261 * @param string $script
262 * @param array $params
263 * @return bool|ThumbnailImage
265 function getScriptedTransform( $image, $script, $params ) {
266 return false;
270 * Get a MediaTransformOutput object representing the transformed output. Does not
271 * actually do the transform.
273 * @param File $image The image object
274 * @param string $dstPath Filesystem destination path
275 * @param string $dstUrl Destination URL to use in output HTML
276 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
277 * @return MediaTransformOutput
279 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
280 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
284 * Get a MediaTransformOutput object representing the transformed output. Does the
285 * transform unless $flags contains self::TRANSFORM_LATER.
287 * @param File $image The image object
288 * @param string $dstPath Filesystem destination path
289 * @param string $dstUrl Destination URL to use in output HTML
290 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
291 * Note: These parameters have *not* gone through $this->normaliseParams()
292 * @param int $flags A bitfield, may contain self::TRANSFORM_LATER
293 * @return MediaTransformOutput
295 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
298 * Get the thumbnail extension and MIME type for a given source MIME type
300 * @param string $ext Extension of original file
301 * @param string $mime MIME type of original file
302 * @param array $params Handler specific rendering parameters
303 * @return array thumbnail extension and MIME type
305 function getThumbType( $ext, $mime, $params = null ) {
306 $magic = MimeMagic::singleton();
307 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
308 // The extension is not valid for this mime type and we do
309 // recognize the mime type
310 $extensions = $magic->getExtensionsForType( $mime );
311 if ( $extensions ) {
312 return array( strtok( $extensions, ' ' ), $mime );
316 // The extension is correct (true) or the mime type is unknown to
317 // MediaWiki (null)
318 return array( $ext, $mime );
322 * Get useful response headers for GET/HEAD requests for a file with the given metadata
324 * @param mixed $metadata Result of the getMetadata() function of this handler for a file
325 * @return array
327 public function getStreamHeaders( $metadata ) {
328 return array();
332 * True if the handled types can be transformed
334 * @param File $file
335 * @return bool
337 function canRender( $file ) {
338 return true;
342 * True if handled types cannot be displayed directly in a browser
343 * but can be rendered
345 * @param File $file
346 * @return bool
348 function mustRender( $file ) {
349 return false;
353 * True if the type has multi-page capabilities
355 * @param File $file
356 * @return bool
358 function isMultiPage( $file ) {
359 return false;
363 * Page count for a multi-page document, false if unsupported or unknown
365 * @param File $file
366 * @return bool
368 function pageCount( $file ) {
369 return false;
373 * The material is vectorized and thus scaling is lossless
375 * @param File $file
376 * @return bool
378 function isVectorized( $file ) {
379 return false;
383 * The material is an image, and is animated.
384 * In particular, video material need not return true.
385 * @note Before 1.20, this was a method of ImageHandler only
387 * @param File $file
388 * @return bool
390 function isAnimatedImage( $file ) {
391 return false;
395 * If the material is animated, we can animate the thumbnail
396 * @since 1.20
398 * @param File $file
399 * @return bool If material is not animated, handler may return any value.
401 function canAnimateThumbnail( $file ) {
402 return true;
406 * False if the handler is disabled for all files
407 * @return bool
409 function isEnabled() {
410 return true;
414 * Get an associative array of page dimensions
415 * Currently "width" and "height" are understood, but this might be
416 * expanded in the future.
417 * Returns false if unknown.
419 * It is expected that handlers for paged media (e.g. DjVuHandler)
420 * will override this method so that it gives the correct results
421 * for each specific page of the file, using the $page argument.
423 * @note For non-paged media, use getImageSize.
425 * @param File $image
426 * @param int $page What page to get dimensions of
427 * @return array|bool
429 function getPageDimensions( $image, $page ) {
430 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
431 if ( $gis ) {
432 return array(
433 'width' => $gis[0],
434 'height' => $gis[1]
436 } else {
437 return false;
442 * Generic getter for text layer.
443 * Currently overloaded by PDF and DjVu handlers
444 * @param File $image
445 * @param int $page Page number to get information for
446 * @return bool|string Page text or false when no text found or if
447 * unsupported.
449 function getPageText( $image, $page ) {
450 return false;
454 * Get the text of the entire document.
455 * @param File $file
456 * @return bool|string The text of the document or false if unsupported.
458 public function getEntireText( File $file ) {
459 $numPages = $file->pageCount();
460 if ( !$numPages ) {
461 // Not a multipage document
462 return $this->getPageText( $file, 1 );
464 $document = '';
465 for ( $i = 1; $i <= $numPages; $i++ ) {
466 $curPage = $this->getPageText( $file, $i );
467 if ( is_string( $curPage ) ) {
468 $document .= $curPage . "\n";
471 if ( $document !== '' ) {
472 return $document;
474 return false;
478 * Get an array structure that looks like this:
480 * array(
481 * 'visible' => array(
482 * 'Human-readable name' => 'Human readable value',
483 * ...
484 * ),
485 * 'collapsed' => array(
486 * 'Human-readable name' => 'Human readable value',
487 * ...
490 * The UI will format this into a table where the visible fields are always
491 * visible, and the collapsed fields are optionally visible.
493 * The function should return false if there is no metadata to display.
497 * @todo FIXME: This interface is not very flexible. The media handler
498 * should generate HTML instead. It can do all the formatting according
499 * to some standard. That makes it possible to do things like visual
500 * indication of grouped and chained streams in ogg container files.
501 * @param File $image
502 * @return array|bool
504 function formatMetadata( $image ) {
505 return false;
508 /** sorts the visible/invisible field.
509 * Split off from ImageHandler::formatMetadata, as used by more than
510 * one type of handler.
512 * This is used by the media handlers that use the FormatMetadata class
514 * @param array $metadataArray Metadata array
515 * @return array Array for use displaying metadata.
517 function formatMetadataHelper( $metadataArray ) {
518 $result = array(
519 'visible' => array(),
520 'collapsed' => array()
523 $formatted = FormatMetadata::getFormattedData( $metadataArray );
524 // Sort fields into visible and collapsed
525 $visibleFields = $this->visibleMetadataFields();
526 foreach ( $formatted as $name => $value ) {
527 $tag = strtolower( $name );
528 self::addMeta( $result,
529 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
530 'exif',
531 $tag,
532 $value
536 return $result;
540 * Get a list of metadata items which should be displayed when
541 * the metadata table is collapsed.
543 * @return array Array of strings
545 protected function visibleMetadataFields() {
546 return FormatMetadata::getVisibleFields();
550 * This is used to generate an array element for each metadata value
551 * That array is then used to generate the table of metadata values
552 * on the image page
554 * @param array &$array An array containing elements for each type of visibility
555 * and each of those elements being an array of metadata items. This function adds
556 * a value to that array.
557 * @param string $visibility ('visible' or 'collapsed') if this value is hidden
558 * by default.
559 * @param string $type Type of metadata tag (currently always 'exif')
560 * @param string $id The name of the metadata tag (like 'artist' for example).
561 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
562 * @param string $value Thingy goes into a wikitext table; it used to be escaped but
563 * that was incompatible with previous practise of customized display
564 * with wikitext formatting via messages such as 'exif-model-value'.
565 * So the escaping is taken back out, but generally this seems a confusing
566 * interface.
567 * @param bool|string $param Value to pass to the message for the name of the field
568 * as $1. Currently this parameter doesn't seem to ever be used.
570 * Note, everything here is passed through the parser later on (!)
572 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
573 $msg = wfMessage( "$type-$id", $param );
574 if ( $msg->exists() ) {
575 $name = $msg->text();
576 } else {
577 // This is for future compatibility when using instant commons.
578 // So as to not display as ugly a name if a new metadata
579 // property is defined that we don't know about
580 // (not a major issue since such a property would be collapsed
581 // by default).
582 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
583 $name = wfEscapeWikiText( $id );
585 $array[$visibility][] = array(
586 'id' => "$type-$id",
587 'name' => $name,
588 'value' => $value
593 * Short description. Shown on Special:Search results.
595 * @param File $file
596 * @return string
598 function getShortDesc( $file ) {
599 return self::getGeneralShortDesc( $file );
603 * Long description. Shown under image on image description page surounded by ().
605 * @param File $file
606 * @return string
608 function getLongDesc( $file ) {
609 return self::getGeneralLongDesc( $file );
613 * Used instead of getShortDesc if there is no handler registered for file.
615 * @param File $file
616 * @return string
618 static function getGeneralShortDesc( $file ) {
619 global $wgLang;
621 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
625 * Used instead of getLongDesc if there is no handler registered for file.
627 * @param File $file
628 * @return string
630 static function getGeneralLongDesc( $file ) {
631 return wfMessage( 'file-info' )->sizeParams( $file->getSize() )
632 ->params( $file->getMimeType() )->parse();
636 * Calculate the largest thumbnail width for a given original file size
637 * such that the thumbnail's height is at most $maxHeight.
638 * @param int $boxWidth Width of the thumbnail box.
639 * @param int $boxHeight Height of the thumbnail box.
640 * @param int $maxHeight Maximum height expected for the thumbnail.
641 * @return int
643 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
644 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
645 $roundedUp = ceil( $idealWidth );
646 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
647 return floor( $idealWidth );
648 } else {
649 return $roundedUp;
654 * Shown in file history box on image description page.
656 * @param File $file
657 * @return string Dimensions
659 function getDimensionsString( $file ) {
660 return '';
664 * Modify the parser object post-transform.
666 * This is often used to do $parser->addOutputHook(),
667 * in order to add some javascript to render a viewer.
668 * See TimedMediaHandler or OggHandler for an example.
670 * @param Parser $parser
671 * @param File $file
673 function parserTransformHook( $parser, $file ) {
677 * File validation hook called on upload.
679 * If the file at the given local path is not valid, or its MIME type does not
680 * match the handler class, a Status object should be returned containing
681 * relevant errors.
683 * @param string $fileName The local path to the file.
684 * @return Status object
686 function verifyUpload( $fileName ) {
687 return Status::newGood();
691 * Check for zero-sized thumbnails. These can be generated when
692 * no disk space is available or some other error occurs
694 * @param string $dstPath The location of the suspect file
695 * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
696 * @return bool True if removed, false otherwise
698 function removeBadFile( $dstPath, $retval = 0 ) {
699 if ( file_exists( $dstPath ) ) {
700 $thumbstat = stat( $dstPath );
701 if ( $thumbstat['size'] == 0 || $retval != 0 ) {
702 $result = unlink( $dstPath );
704 if ( $result ) {
705 wfDebugLog( 'thumbnail',
706 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
707 $thumbstat['size'], $dstPath ) );
708 } else {
709 wfDebugLog( 'thumbnail',
710 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
711 $thumbstat['size'], $dstPath ) );
714 return true;
718 return false;
722 * Remove files from the purge list.
724 * This is used by some video handlers to prevent ?action=purge
725 * from removing a transcoded video, which is expensive to
726 * regenerate.
728 * @see LocalFile::purgeThumbnails
730 * @param array $files
731 * @param array $options Purge options. Currently will always be
732 * an array with a single key 'forThumbRefresh' set to true.
734 public function filterThumbnailPurgeList( &$files, $options ) {
735 // Do nothing
739 * True if the handler can rotate the media
740 * @since 1.21
741 * @return bool
743 public static function canRotate() {
744 return false;
748 * On supporting image formats, try to read out the low-level orientation
749 * of the file and return the angle that the file needs to be rotated to
750 * be viewed.
752 * This information is only useful when manipulating the original file;
753 * the width and height we normally work with is logical, and will match
754 * any produced output views.
756 * For files we don't know, we return 0.
758 * @param File $file
759 * @return int 0, 90, 180 or 270
761 public function getRotation( $file ) {
762 return 0;
766 * Log an error that occurred in an external process
768 * Moved from BitmapHandler to MediaHandler with MediaWiki 1.23
770 * @since 1.23
771 * @param int $retval
772 * @param string $err Error reported by command. Anything longer than
773 * MediaHandler::MAX_ERR_LOG_SIZE is stripped off.
774 * @param string $cmd
776 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
777 # Keep error output limited (bug 57985)
778 $errMessage = trim( substr( $err, 0, self::MAX_ERR_LOG_SIZE ) );
780 wfDebugLog( 'thumbnail',
781 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
782 wfHostname(), $retval, $errMessage, $cmd ) );
786 * Get list of languages file can be viewed in.
788 * @param File $file
789 * @return string[] Array of language codes, or empty array if unsupported.
790 * @since 1.23
792 public function getAvailableLanguages( File $file ) {
793 return array();
797 * On file types that support renderings in multiple languages,
798 * which language is used by default if unspecified.
800 * If getAvailableLanguages returns a non-empty array, this must return
801 * a valid language code. Otherwise can return null if files of this
802 * type do not support alternative language renderings.
804 * @param File $file
805 * @return string|null Language code or null if multi-language not supported for filetype.
806 * @since 1.23
808 public function getDefaultRenderLanguage( File $file ) {
809 return null;
813 * If its an audio file, return the length of the file. Otherwise 0.
815 * File::getLength() existed for a long time, but was calling a method
816 * that only existed in some subclasses of this class (The TMH ones).
818 * @param File $file
819 * @return float Length in seconds
820 * @since 1.23
822 public function getLength( $file ) {
823 return 0.0;
827 * True if creating thumbnails from the file is large or otherwise resource-intensive.
828 * @param File $file
829 * @return bool
831 public function isExpensiveToThumbnail( $file ) {
832 return false;