3 * Media-handling base classes and generic functionality
10 * Base media handler class
14 abstract class MediaHandler
{
15 const TRANSFORM_LATER
= 1;
16 const METADATA_GOOD
= true;
17 const METADATA_BAD
= false;
18 const METADATA_COMPATIBLE
= 2; // for old but backwards compatible.
22 static $handlers = array();
25 * Get a MediaHandler for a given MIME type from the instance cache
29 * @return MediaHandler
31 static function getHandler( $type ) {
32 global $wgMediaHandlers;
33 if ( !isset( $wgMediaHandlers[$type] ) ) {
34 wfDebug( __METHOD__
. ": no handler found for $type.\n");
37 $class = $wgMediaHandlers[$type];
38 if ( !isset( self
::$handlers[$class] ) ) {
39 self
::$handlers[$class] = new $class;
40 if ( !self
::$handlers[$class]->isEnabled() ) {
41 self
::$handlers[$class] = false;
44 return self
::$handlers[$class];
48 * Get an associative array mapping magic word IDs to parameter names.
49 * Will be used by the parser to identify parameters.
51 abstract function getParamMap();
54 * Validate a thumbnail parameter at parse time.
55 * Return true to accept the parameter, and false to reject it.
56 * If you return false, the parser will do something quiet and forgiving.
61 abstract function validateParam( $name, $value );
64 * Merge a parameter array into a string appropriate for inclusion in filenames
66 * @param $params array
68 abstract function makeParamString( $params );
71 * Parse a param string made with makeParamString back into an array
75 abstract function parseParamString( $str );
78 * Changes the parameter array as necessary, ready for transformation.
79 * Should be idempotent.
80 * Returns false if the parameters are unacceptable and the transform should fail
84 abstract function normaliseParams( $image, &$params );
87 * Get an image size array like that returned by getimagesize(), or false if it
88 * can't be determined.
90 * @param $image File: the image object, or false if there isn't one
91 * @param $path String: the filename
94 abstract function getImageSize( $image, $path );
97 * Get handler-specific metadata which will be saved in the img_metadata field.
99 * @param $image File: the image object, or false if there isn't one.
100 * Warning, File::getPropsFromPath might pass an (object)array() instead (!)
101 * @param $path String: the filename
104 function getMetadata( $image, $path ) { return ''; }
107 * Get metadata version.
109 * This is not used for validating metadata, this is used for the api when returning
110 * metadata, since api content formats should stay the same over time, and so things
111 * using ForiegnApiRepo can keep backwards compatibility
113 * All core media handlers share a common version number, and extensions can
114 * use the GetMetadataVersion hook to append to the array (they should append a unique
115 * string so not to get confusing). If there was a media handler named 'foo' with metadata
116 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
117 * version is 2, the end version string would look like '2;foo=3'.
119 * @return string version string
121 static function getMetadataVersion () {
122 $version = Array( '2' ); // core metadata version
123 wfRunHooks('GetMetadataVersion', Array(&$version));
124 return implode( ';', $version);
128 * Convert metadata version.
130 * By default just returns $metadata, but can be used to allow
131 * media handlers to convert between metadata versions.
133 * @param $metadata Mixed String or Array metadata array (serialized if string)
134 * @param $version Integer target version
135 * @return Array serialized metadata in specified version, or $metadata on fail.
137 function convertMetadataVersion( $metadata, $version = 1 ) {
138 if ( !is_array( $metadata ) ) {
140 //unserialize to keep return parameter consistent.
141 wfSuppressWarnings();
142 $ret = unserialize( $metadata );
150 * Get a string describing the type of metadata, for display purposes.
154 function getMetadataType( $image ) { return false; }
157 * Check if the metadata string is valid for this handler.
158 * If it returns MediaHandler::METADATA_BAD (or false), Image
159 * will reload the metadata from the file and update the database.
160 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
161 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
162 * compatible (which may or may not trigger a metadata reload).
164 function isMetadataValid( $image, $metadata ) {
165 return self
::METADATA_GOOD
;
170 * Get a MediaTransformOutput object representing an alternate of the transformed
171 * output which will call an intermediary thumbnail assist script.
173 * Used when the repository has a thumbnailScriptUrl option configured.
175 * Return false to fall back to the regular getTransform().
177 function getScriptedTransform( $image, $script, $params ) {
182 * Get a MediaTransformOutput object representing the transformed output. Does not
183 * actually do the transform.
185 * @param $image File: the image object
186 * @param $dstPath String: filesystem destination path
187 * @param $dstUrl String: Destination URL to use in output HTML
188 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
190 function getTransform( $image, $dstPath, $dstUrl, $params ) {
191 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
195 * Get a MediaTransformOutput object representing the transformed output. Does the
196 * transform unless $flags contains self::TRANSFORM_LATER.
198 * @param $image File: the image object
199 * @param $dstPath String: filesystem destination path
200 * @param $dstUrl String: destination URL to use in output HTML
201 * @param $params Array: arbitrary set of parameters validated by $this->validateParam()
202 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
204 * @return MediaTransformOutput
206 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
209 * Get the thumbnail extension and MIME type for a given source MIME type
210 * @return array thumbnail extension and MIME type
212 function getThumbType( $ext, $mime, $params = null ) {
213 $magic = MimeMagic
::singleton();
214 if ( !$ext ||
$magic->isMatchingExtension( $ext, $mime ) === false ) {
215 // The extension is not valid for this mime type and we do
216 // recognize the mime type
217 $extensions = $magic->getExtensionsForType( $mime );
219 return array( strtok( $extensions, ' ' ), $mime );
223 // The extension is correct (true) or the mime type is unknown to
225 return array( $ext, $mime );
229 * True if the handled types can be transformed
231 function canRender( $file ) { return true; }
233 * True if handled types cannot be displayed directly in a browser
234 * but can be rendered
236 function mustRender( $file ) { return false; }
238 * True if the type has multi-page capabilities
240 function isMultiPage( $file ) { return false; }
242 * Page count for a multi-page document, false if unsupported or unknown
244 function pageCount( $file ) { return false; }
246 * The material is vectorized and thus scaling is lossless
248 function isVectorized( $file ) { return false; }
250 * False if the handler is disabled for all files
252 function isEnabled() { return true; }
255 * Get an associative array of page dimensions
256 * Currently "width" and "height" are understood, but this might be
257 * expanded in the future.
258 * Returns false if unknown or if the document is not multi-page.
262 function getPageDimensions( $image, $page ) {
263 $gis = $this->getImageSize( $image, $image->getPath() );
271 * Generic getter for text layer.
272 * Currently overloaded by PDF and DjVu handlers
274 function getPageText( $image, $page ) {
279 * Get an array structure that looks like this:
282 * 'visible' => array(
283 * 'Human-readable name' => 'Human readable value',
286 * 'collapsed' => array(
287 * 'Human-readable name' => 'Human readable value',
291 * The UI will format this into a table where the visible fields are always
292 * visible, and the collapsed fields are optionally visible.
294 * The function should return false if there is no metadata to display.
298 * @todo FIXME: I don't really like this interface, it's not very flexible
299 * I think the media handler should generate HTML instead. It can do
300 * all the formatting according to some standard. That makes it possible
301 * to do things like visual indication of grouped and chained streams
302 * in ogg container files.
304 function formatMetadata( $image ) {
308 /** sorts the visible/invisible field.
309 * Split off from ImageHandler::formatMetadata, as used by more than
310 * one type of handler.
312 * This is used by the media handlers that use the FormatMetadata class
314 * @param $metadataArray Array metadata array
315 * @return array for use displaying metadata.
317 function formatMetadataHelper( $metadataArray ) {
319 'visible' => array(),
320 'collapsed' => array()
323 $formatted = FormatMetadata
::getFormattedData( $metadataArray );
324 // Sort fields into visible and collapsed
325 $visibleFields = $this->visibleMetadataFields();
326 foreach ( $formatted as $name => $value ) {
327 $tag = strtolower( $name );
328 self
::addMeta( $result,
329 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
339 * Get a list of metadata items which should be displayed when
340 * the metadata table is collapsed.
342 * @return array of strings
345 function visibleMetadataFields() {
347 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
348 foreach( $lines as $line ) {
350 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
351 $fields[] = $matches[1];
354 $fields = array_map( 'strtolower', $fields );
360 * This is used to generate an array element for each metadata value
361 * That array is then used to generate the table of metadata values
364 * @param &$array Array An array containing elements for each type of visibility
365 * and each of those elements being an array of metadata items. This function adds
366 * a value to that array.
367 * @param $visbility string ('visible' or 'collapsed') if this value is hidden
369 * @param $type String type of metadata tag (currently always 'exif')
370 * @param $id String the name of the metadata tag (like 'artist' for example).
371 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
372 * @param $value String thingy goes into a wikitext table; it used to be escaped but
373 * that was incompatible with previous practise of customized display
374 * with wikitext formatting via messages such as 'exif-model-value'.
375 * So the escaping is taken back out, but generally this seems a confusing
377 * @param $param String value to pass to the message for the name of the field
378 * as $1. Currently this parameter doesn't seem to ever be used.
380 * Note, everything here is passed through the parser later on (!)
382 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
383 $msg = wfMessage( "$type-$id", $param );
384 if ( $msg->exists() ) {
385 $name = $msg->text();
387 // This is for future compatibility when using instant commons.
388 // So as to not display as ugly a name if a new metadata
389 // property is defined that we don't know about
390 // (not a major issue since such a property would be collapsed
392 wfDebug( __METHOD__
. ' Unknown metadata name: ' . $id . "\n" );
393 $name = wfEscapeWikiText( $id );
395 $array[$visibility][] = array(
406 function getShortDesc( $file ) {
407 return wfMessage( 'nbytes' )->numParams( $file->getSize() )->escaped();
414 function getLongDesc( $file ) {
416 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
417 $file->getMimeType() )->parse();
424 static function getGeneralShortDesc( $file ) {
425 return wfMessage( 'nbytes' )->numParams( $file->getSize() )->escaped();
432 static function getGeneralLongDesc( $file ) {
434 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
435 $file->getMimeType() )->parse();
439 * Calculate the largest thumbnail width for a given original file size
440 * such that the thumbnail's height is at most $maxHeight.
441 * @param $boxWidth Integer Width of the thumbnail box.
442 * @param $boxHeight Integer Height of the thumbnail box.
443 * @param $maxHeight Integer Maximum height expected for the thumbnail.
446 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
447 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
448 $roundedUp = ceil( $idealWidth );
449 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
450 return floor( $idealWidth );
456 function getDimensionsString( $file ) {
461 * Modify the parser object post-transform
463 function parserTransformHook( $parser, $file ) {}
466 * File validation hook called on upload.
468 * If the file at the given local path is not valid, or its MIME type does not
469 * match the handler class, a Status object should be returned containing
472 * @param $fileName The local path to the file.
473 * @return Status object
475 function verifyUpload( $fileName ) {
476 return Status
::newGood();
480 * Check for zero-sized thumbnails. These can be generated when
481 * no disk space is available or some other error occurs
483 * @param $dstPath The location of the suspect file
484 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
485 * @return true if removed, false otherwise
487 function removeBadFile( $dstPath, $retval = 0 ) {
488 if( file_exists( $dstPath ) ) {
489 $thumbstat = stat( $dstPath );
490 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
491 $result = unlink( $dstPath );
494 wfDebugLog( 'thumbnail',
495 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
496 $thumbstat['size'], $dstPath ) );
498 wfDebugLog( 'thumbnail',
499 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
500 $thumbstat['size'], $dstPath ) );
509 * Remove files from the purge list
511 * @param array $files
512 * @param array $options
514 public function filterThumbnailPurgeList( &$files, $options ) {
520 * Media handler abstract base class for images
524 abstract class ImageHandler
extends MediaHandler
{
530 function canRender( $file ) {
531 return ( $file->getWidth() && $file->getHeight() );
534 function getParamMap() {
535 return array( 'img_width' => 'width' );
538 function validateParam( $name, $value ) {
539 if ( in_array( $name, array( 'width', 'height' ) ) ) {
550 function makeParamString( $params ) {
551 if ( isset( $params['physicalWidth'] ) ) {
552 $width = $params['physicalWidth'];
553 } elseif ( isset( $params['width'] ) ) {
554 $width = $params['width'];
556 throw new MWException( 'No width specified to '.__METHOD__
);
558 # Removed for ProofreadPage
559 #$width = intval( $width );
563 function parseParamString( $str ) {
565 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
566 return array( 'width' => $m[1] );
572 function getScriptParams( $params ) {
573 return array( 'width' => $params['width'] );
581 function normaliseParams( $image, &$params ) {
582 $mimeType = $image->getMimeType();
584 if ( !isset( $params['width'] ) ) {
588 if ( !isset( $params['page'] ) ) {
591 if ( $params['page'] > $image->pageCount() ) {
592 $params['page'] = $image->pageCount();
595 if ( $params['page'] < 1 ) {
600 $srcWidth = $image->getWidth( $params['page'] );
601 $srcHeight = $image->getHeight( $params['page'] );
603 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
604 # Height & width were both set
605 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
606 # Height is the relative smaller dimension, so scale width accordingly
607 $params['width'] = self
::fitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
609 if ( $params['width'] == 0 ) {
610 # Very small image, so we need to rely on client side scaling :(
611 $params['width'] = 1;
614 $params['physicalWidth'] = $params['width'];
616 # Height was crap, unset it so that it will be calculated later
617 unset( $params['height'] );
621 if ( !isset( $params['physicalWidth'] ) ) {
622 # Passed all validations, so set the physicalWidth
623 $params['physicalWidth'] = $params['width'];
626 # Because thumbs are only referred to by width, the height always needs
627 # to be scaled by the width to keep the thumbnail sizes consistent,
628 # even if it was set inside the if block above
629 $params['physicalHeight'] = File
::scaleHeight( $srcWidth, $srcHeight,
630 $params['physicalWidth'] );
632 # Set the height if it was not validated in the if block higher up
633 if ( !isset( $params['height'] ) ||
$params['height'] == -1 ) {
634 $params['height'] = $params['physicalHeight'];
638 if ( !$this->validateThumbParams( $params['physicalWidth'],
639 $params['physicalHeight'], $srcWidth, $srcHeight, $mimeType ) ) {
646 * Get a transform output object without actually doing the transform
648 function getTransform( $image, $dstPath, $dstUrl, $params ) {
649 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
653 * Validate thumbnail parameters and fill in the correct height
655 * @param $width Integer: specified width (input/output)
656 * @param $height Integer: height (output only)
657 * @param $srcWidth Integer: width of the source image
658 * @param $srcHeight Integer: height of the source image
659 * @param $mimeType Unused
660 * @return false to indicate that an error should be returned to the user.
662 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
663 $width = intval( $width );
665 # Sanity check $width
667 wfDebug( __METHOD__
.": Invalid destination width: $width\n" );
670 if ( $srcWidth <= 0 ) {
671 wfDebug( __METHOD__
.": Invalid source width: $srcWidth\n" );
675 $height = File
::scaleHeight( $srcWidth, $srcHeight, $width );
676 if ( $height == 0 ) {
677 # Force height to be at least 1 pixel
687 * @return bool|ThumbnailImage
689 function getScriptedTransform( $image, $script, $params ) {
690 if ( !$this->normaliseParams( $image, $params ) ) {
693 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
694 $page = isset( $params['page'] ) ?
$params['page'] : false;
696 if( $image->mustRender() ||
$params['width'] < $image->getWidth() ) {
697 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
701 function getImageSize( $image, $path ) {
702 wfSuppressWarnings();
703 $gis = getimagesize( $path );
708 function isAnimatedImage( $image ) {
716 function getShortDesc( $file ) {
717 $nbytes = wfMessage( 'nbytes' )->numParams( $file->getSize() )->escaped();
718 $widthheight = wfMessage( 'widthheight' )->numParams( $file->getWidth(), $file->getHeight() )->escaped();
720 return "$widthheight ($nbytes)";
727 function getLongDesc( $file ) {
729 $pages = $file->pageCount();
730 if ( $pages === false ||
$pages <= 1 ) {
731 $msg = wfMessage( 'file-info-size' )->numParams( $file->getWidth(),
732 $file->getHeight() )->params( $wgLang->formatSize( $file->getSize() ),
733 $file->getMimeType() )->parse();
735 $msg = wfMessage( 'file-info-size-pages' )->numParams( $file->getWidth(),
736 $file->getHeight() )->params( $wgLang->formatSize( $file->getSize() ),
737 $file->getMimeType() )->numParams( $pages )->parse();
746 function getDimensionsString( $file ) {
747 $pages = $file->pageCount();
749 return wfMessage( 'widthheightpage' )->numParams( $file->getWidth(), $file->getHeight(), $pages )->text();
751 return wfMessage( 'widthheight' )->numParams( $file->getWidth(), $file->getHeight() )->text();