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
27 * @return MediaHandler
29 static function getHandler( $type ) {
30 global $wgMediaHandlers;
31 if ( !isset( $wgMediaHandlers[$type] ) ) {
32 wfDebug( __METHOD__
. ": no handler found for $type.\n");
35 $class = $wgMediaHandlers[$type];
36 if ( !isset( self
::$handlers[$class] ) ) {
37 self
::$handlers[$class] = new $class;
38 if ( !self
::$handlers[$class]->isEnabled() ) {
39 self
::$handlers[$class] = false;
42 return self
::$handlers[$class];
46 * Get an associative array mapping magic word IDs to parameter names.
47 * Will be used by the parser to identify parameters.
49 abstract function getParamMap();
52 * Validate a thumbnail parameter at parse time.
53 * Return true to accept the parameter, and false to reject it.
54 * If you return false, the parser will do something quiet and forgiving.
56 abstract function validateParam( $name, $value );
59 * Merge a parameter array into a string appropriate for inclusion in filenames
61 abstract function makeParamString( $params );
64 * Parse a param string made with makeParamString back into an array
66 abstract function parseParamString( $str );
69 * Changes the parameter array as necessary, ready for transformation.
70 * Should be idempotent.
71 * Returns false if the parameters are unacceptable and the transform should fail
73 abstract function normaliseParams( $image, &$params );
76 * Get an image size array like that returned by getimagesize(), or false if it
77 * can't be determined.
79 * @param $image File: the image object, or false if there isn't one
80 * @param $path String: the filename
83 abstract function getImageSize( $image, $path );
86 * Get handler-specific metadata which will be saved in the img_metadata field.
88 * @param $image File: the image object, or false if there isn't one.
89 * Warning, File::getPropsFromPath might pass an (object)array() instead (!)
90 * @param $path String: the filename
93 function getMetadata( $image, $path ) { return ''; }
96 * Get metadata version.
98 * This is not used for validating metadata, this is used for the api when returning
99 * metadata, since api content formats should stay the same over time, and so things
100 * using ForiegnApiRepo can keep backwards compatibility
102 * All core media handlers share a common version number, and extensions can
103 * use the GetMetadataVersion hook to append to the array (they should append a unique
104 * string so not to get confusing). If there was a media handler named 'foo' with metadata
105 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
106 * version is 2, the end version string would look like '2;foo=3'.
108 * @return string version string
110 static function getMetadataVersion () {
111 $version = Array( '2' ); // core metadata version
112 wfRunHooks('GetMetadataVersion', Array(&$version));
113 return implode( ';', $version);
117 * Convert metadata version.
119 * By default just returns $metadata, but can be used to allow
120 * media handlers to convert between metadata versions.
122 * @param $metadata Mixed String or Array metadata array (serialized if string)
123 * @param $version Integer target version
124 * @return Array serialized metadata in specified version, or $metadata on fail.
126 function convertMetadataVersion( $metadata, $version = 1 ) {
127 if ( !is_array( $metadata ) ) {
129 //unserialize to keep return parameter consistent.
130 wfSuppressWarnings();
131 $ret = unserialize( $metadata );
139 * Get a string describing the type of metadata, for display purposes.
141 function getMetadataType( $image ) { return false; }
144 * Check if the metadata string is valid for this handler.
145 * If it returns MediaHandler::METADATA_BAD (or false), Image
146 * will reload the metadata from the file and update the database.
147 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
148 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
149 * compatible (which may or may not trigger a metadata reload).
151 function isMetadataValid( $image, $metadata ) {
152 return self
::METADATA_GOOD
;
157 * Get a MediaTransformOutput object representing an alternate of the transformed
158 * output which will call an intermediary thumbnail assist script.
160 * Used when the repository has a thumbnailScriptUrl option configured.
162 * Return false to fall back to the regular getTransform().
164 function getScriptedTransform( $image, $script, $params ) {
169 * Get a MediaTransformOutput object representing the transformed output. Does not
170 * actually do the transform.
172 * @param $image File: the image object
173 * @param $dstPath String: filesystem destination path
174 * @param $dstUrl String: Destination URL to use in output HTML
175 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
177 function getTransform( $image, $dstPath, $dstUrl, $params ) {
178 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
182 * Get a MediaTransformOutput object representing the transformed output. Does the
183 * transform unless $flags contains self::TRANSFORM_LATER.
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()
189 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
191 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
194 * Get the thumbnail extension and MIME type for a given source MIME type
195 * @return array thumbnail extension and MIME type
197 function getThumbType( $ext, $mime, $params = null ) {
198 $magic = MimeMagic
::singleton();
199 if ( !$ext ||
$magic->isMatchingExtension( $ext, $mime ) === false ) {
200 // The extension is not valid for this mime type and we do
201 // recognize the mime type
202 $extensions = $magic->getExtensionsForType( $mime );
204 return array( strtok( $extensions, ' ' ), $mime );
208 // The extension is correct (true) or the mime type is unknown to
210 return array( $ext, $mime );
214 * True if the handled types can be transformed
216 function canRender( $file ) { return true; }
218 * True if handled types cannot be displayed directly in a browser
219 * but can be rendered
221 function mustRender( $file ) { return false; }
223 * True if the type has multi-page capabilities
225 function isMultiPage( $file ) { return false; }
227 * Page count for a multi-page document, false if unsupported or unknown
229 function pageCount( $file ) { return false; }
231 * The material is vectorized and thus scaling is lossless
233 function isVectorized( $file ) { return false; }
235 * False if the handler is disabled for all files
237 function isEnabled() { return true; }
240 * Get an associative array of page dimensions
241 * Currently "width" and "height" are understood, but this might be
242 * expanded in the future.
243 * Returns false if unknown or if the document is not multi-page.
247 function getPageDimensions( $image, $page ) {
248 $gis = $this->getImageSize( $image, $image->getPath() );
256 * Generic getter for text layer.
257 * Currently overloaded by PDF and DjVu handlers
259 function getPageText( $image, $page ) {
264 * Get an array structure that looks like this:
267 * 'visible' => array(
268 * 'Human-readable name' => 'Human readable value',
271 * 'collapsed' => array(
272 * 'Human-readable name' => 'Human readable value',
276 * The UI will format this into a table where the visible fields are always
277 * visible, and the collapsed fields are optionally visible.
279 * The function should return false if there is no metadata to display.
283 * FIXME: I don't really like this interface, it's not very flexible
284 * I think the media handler should generate HTML instead. It can do
285 * all the formatting according to some standard. That makes it possible
286 * to do things like visual indication of grouped and chained streams
287 * in ogg container files.
289 function formatMetadata( $image ) {
293 /** sorts the visible/invisible field.
294 * Split off from ImageHandler::formatMetadata, as used by more than
295 * one type of handler.
297 * This is used by the media handlers that use the FormatMetadata class
299 * @param $metadataArray Array metadata array
300 * @return array for use displaying metadata.
302 function formatMetadataHelper( $metadataArray ) {
304 'visible' => array(),
305 'collapsed' => array()
308 $formatted = FormatMetadata
::getFormattedData( $metadataArray );
309 // Sort fields into visible and collapsed
310 $visibleFields = $this->visibleMetadataFields();
311 foreach ( $formatted as $name => $value ) {
312 $tag = strtolower( $name );
313 self
::addMeta( $result,
314 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
324 * Get a list of metadata items which should be displayed when
325 * the metadata table is collapsed.
327 * @return array of strings
330 function visibleMetadataFields() {
332 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
333 foreach( $lines as $line ) {
335 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
336 $fields[] = $matches[1];
339 $fields = array_map( 'strtolower', $fields );
345 * This is used to generate an array element for each metadata value
346 * That array is then used to generate the table of metadata values
349 * @param &$array Array An array containing elements for each type of visibility
350 * and each of those elements being an array of metadata items. This function adds
351 * a value to that array.
352 * @param $visibility String ('visible' or 'collapsed') if this value is hidden
354 * @param $type String type of metadata tag (currently always 'exif')
355 * @param $id String the name of the metadata tag (like 'artist' for example).
356 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
357 * @param $value String thingy goes into a wikitext table; it used to be escaped but
358 * that was incompatible with previous practise of customized display
359 * with wikitext formatting via messages such as 'exif-model-value'.
360 * So the escaping is taken back out, but generally this seems a confusing
362 * @param $param String value to pass to the message for the name of the field
363 * as $1. Currently this parameter doesn't seem to ever be used.
365 * @return Array $array but with the new metadata field added.
367 * Note, everything here is passed through the parser later on (!)
369 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
370 $msgName = "$type-$id";
371 if ( wfEmptyMsg( $msgName ) ) {
372 // This is for future compatibility when using instant commons.
373 // So as to not display as ugly a name if a new metadata
374 // property is defined that we don't know about
375 // (not a major issue since such a property would be collapsed
377 wfDebug( __METHOD__
. ' Unknown metadata name: ' . $id . "\n" );
378 $name = wfEscapeWikiText( $id );
380 $name = wfMsg( $msgName, $param );
382 $array[$visibility][] = array(
393 function getShortDesc( $file ) {
395 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
396 $wgLang->formatNum( $file->getSize() ) );
404 function getLongDesc( $file ) {
406 $sk = $wgUser->getSkin();
407 return wfMsgExt( 'file-info', 'parseinline',
408 $sk->formatSize( $file->getSize() ),
409 $file->getMimeType() );
416 static function getGeneralShortDesc( $file ) {
418 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
419 $wgLang->formatNum( $file->getSize() ) );
427 static function getGeneralLongDesc( $file ) {
429 $sk = $wgUser->getSkin();
430 return wfMsgExt( 'file-info', 'parseinline',
431 $sk->formatSize( $file->getSize() ),
432 $file->getMimeType() );
435 function getDimensionsString( $file ) {
440 * Modify the parser object post-transform
442 function parserTransformHook( $parser, $file ) {}
445 * File validation hook called on upload.
447 * If the file at the given local path is not valid, or its MIME type does not
448 * match the handler class, a Status object should be returned containing
451 * @param $fileName The local path to the file.
452 * @return Status object
454 function verifyUpload( $fileName ) {
455 return Status
::newGood();
459 * Check for zero-sized thumbnails. These can be generated when
460 * no disk space is available or some other error occurs
462 * @param $dstPath The location of the suspect file
463 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
464 * @return true if removed, false otherwise
466 function removeBadFile( $dstPath, $retval = 0 ) {
467 if( file_exists( $dstPath ) ) {
468 $thumbstat = stat( $dstPath );
469 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
470 wfDebugLog( 'thumbnail',
471 sprintf( 'Removing bad %d-byte thumbnail "%s"',
472 $thumbstat['size'], $dstPath ) );
482 * Media handler abstract base class for images
486 abstract class ImageHandler
extends MediaHandler
{
492 function canRender( $file ) {
493 return ( $file->getWidth() && $file->getHeight() );
496 function getParamMap() {
497 return array( 'img_width' => 'width' );
500 function validateParam( $name, $value ) {
501 if ( in_array( $name, array( 'width', 'height' ) ) ) {
512 function makeParamString( $params ) {
513 if ( isset( $params['physicalWidth'] ) ) {
514 $width = $params['physicalWidth'];
515 } elseif ( isset( $params['width'] ) ) {
516 $width = $params['width'];
518 throw new MWException( 'No width specified to '.__METHOD__
);
520 # Removed for ProofreadPage
521 #$width = intval( $width );
525 function parseParamString( $str ) {
527 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
528 return array( 'width' => $m[1] );
534 function getScriptParams( $params ) {
535 return array( 'width' => $params['width'] );
543 function normaliseParams( $image, &$params ) {
544 $mimeType = $image->getMimeType();
546 if ( !isset( $params['width'] ) ) {
550 if ( !isset( $params['page'] ) ) {
553 if ( $params['page'] > $image->pageCount() ) {
554 $params['page'] = $image->pageCount();
557 if ( $params['page'] < 1 ) {
562 $srcWidth = $image->getWidth( $params['page'] );
563 $srcHeight = $image->getHeight( $params['page'] );
564 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
565 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
566 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
569 $params['height'] = File
::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
570 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
577 * Get a transform output object without actually doing the transform
579 function getTransform( $image, $dstPath, $dstUrl, $params ) {
580 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
584 * Validate thumbnail parameters and fill in the correct height
586 * @param $width Integer: specified width (input/output)
587 * @param $height Integer: height (output only)
588 * @param $srcWidth Integer: width of the source image
589 * @param $srcHeight Integer: height of the source image
590 * @param $mimeType Unused
591 * @return false to indicate that an error should be returned to the user.
593 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
594 $width = intval( $width );
596 # Sanity check $width
598 wfDebug( __METHOD__
.": Invalid destination width: $width\n" );
601 if ( $srcWidth <= 0 ) {
602 wfDebug( __METHOD__
.": Invalid source width: $srcWidth\n" );
606 $height = File
::scaleHeight( $srcWidth, $srcHeight, $width );
614 * @return bool|ThumbnailImage
616 function getScriptedTransform( $image, $script, $params ) {
617 if ( !$this->normaliseParams( $image, $params ) ) {
620 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
621 $page = isset( $params['page'] ) ?
$params['page'] : false;
623 if( $image->mustRender() ||
$params['width'] < $image->getWidth() ) {
624 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
628 function getImageSize( $image, $path ) {
629 wfSuppressWarnings();
630 $gis = getimagesize( $path );
635 function isAnimatedImage( $image ) {
643 function getShortDesc( $file ) {
645 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
646 $wgLang->formatNum( $file->getSize() ) );
647 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
649 return "$widthheight ($nbytes)";
656 function getLongDesc( $file ) {
658 return wfMsgExt('file-info-size', 'parseinline',
659 $wgLang->formatNum( $file->getWidth() ),
660 $wgLang->formatNum( $file->getHeight() ),
661 $wgLang->formatSize( $file->getSize() ),
662 $file->getMimeType() );
669 function getDimensionsString( $file ) {
671 $pages = $file->pageCount();
672 $width = $wgLang->formatNum( $file->getWidth() );
673 $height = $wgLang->formatNum( $file->getHeight() );
674 $pagesFmt = $wgLang->formatNum( $pages );
677 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
679 return wfMsg( 'widthheight', $width, $height );