3 * Media-handling base classes and generic functionality
10 * Base media handler class
14 abstract class MediaHandler
{
15 const TRANSFORM_LATER
= 1;
20 static $handlers = array();
23 * Get a MediaHandler for a given MIME type from the instance cache
25 * @return MediaHandler
27 static function getHandler( $type ) {
28 global $wgMediaHandlers;
29 if ( !isset( $wgMediaHandlers[$type] ) ) {
30 wfDebug( __METHOD__
. ": no handler found for $type.\n");
33 $class = $wgMediaHandlers[$type];
34 if ( !isset( self
::$handlers[$class] ) ) {
35 self
::$handlers[$class] = new $class;
36 if ( !self
::$handlers[$class]->isEnabled() ) {
37 self
::$handlers[$class] = false;
40 return self
::$handlers[$class];
44 * Get an associative array mapping magic word IDs to parameter names.
45 * Will be used by the parser to identify parameters.
47 abstract function getParamMap();
50 * Validate a thumbnail parameter at parse time.
51 * Return true to accept the parameter, and false to reject it.
52 * If you return false, the parser will do something quiet and forgiving.
54 abstract function validateParam( $name, $value );
57 * Merge a parameter array into a string appropriate for inclusion in filenames
59 abstract function makeParamString( $params );
62 * Parse a param string made with makeParamString back into an array
64 abstract function parseParamString( $str );
67 * Changes the parameter array as necessary, ready for transformation.
68 * Should be idempotent.
69 * Returns false if the parameters are unacceptable and the transform should fail
71 abstract function normaliseParams( $image, &$params );
74 * Get an image size array like that returned by getimagesize(), or false if it
75 * can't be determined.
77 * @param $image File: the image object, or false if there isn't one
78 * @param $path String: the filename
81 abstract function getImageSize( $image, $path );
84 * Get handler-specific metadata which will be saved in the img_metadata field.
86 * @param $image File: the image object, or false if there isn't one
87 * @param $path String: the filename
90 function getMetadata( $image, $path ) { return ''; }
93 * Get a string describing the type of metadata, for display purposes.
95 function getMetadataType( $image ) { return false; }
98 * Check if the metadata string is valid for this handler.
99 * If it returns false, Image will reload the metadata from the file and update the database
101 function isMetadataValid( $image, $metadata ) { return true; }
105 * Get a MediaTransformOutput object representing an alternate of the transformed
106 * output which will call an intermediary thumbnail assist script.
108 * Used when the repository has a thumbnailScriptUrl option configured.
110 * Return false to fall back to the regular getTransform().
112 function getScriptedTransform( $image, $script, $params ) {
117 * Get a MediaTransformOutput object representing the transformed output. Does not
118 * actually do the transform.
120 * @param $image File: the image object
121 * @param $dstPath String: filesystem destination path
122 * @param $dstUrl String: Destination URL to use in output HTML
123 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
125 function getTransform( $image, $dstPath, $dstUrl, $params ) {
126 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
130 * Get a MediaTransformOutput object representing the transformed output. Does the
131 * transform unless $flags contains self::TRANSFORM_LATER.
133 * @param $image File: the image object
134 * @param $dstPath String: filesystem destination path
135 * @param $dstUrl String: destination URL to use in output HTML
136 * @param $params Array: arbitrary set of parameters validated by $this->validateParam()
137 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
139 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
142 * Get the thumbnail extension and MIME type for a given source MIME type
143 * @return array thumbnail extension and MIME type
145 function getThumbType( $ext, $mime, $params = null ) {
146 $magic = MimeMagic
::singleton();
147 if ( !$ext ||
$magic->isMatchingExtension( $ext, $mime ) === false ) {
148 // The extension is not valid for this mime type and we do
149 // recognize the mime type
150 $extensions = $magic->getExtensionsForType( $mime );
152 return array( strtok( $extensions, ' ' ), $mime );
156 // The extension is correct (true) or the mime type is unknown to
158 return array( $ext, $mime );
162 * True if the handled types can be transformed
164 function canRender( $file ) { return true; }
166 * True if handled types cannot be displayed directly in a browser
167 * but can be rendered
169 function mustRender( $file ) { return false; }
171 * True if the type has multi-page capabilities
173 function isMultiPage( $file ) { return false; }
175 * Page count for a multi-page document, false if unsupported or unknown
177 function pageCount( $file ) { return false; }
179 * The material is vectorized and thus scaling is lossless
181 function isVectorized( $file ) { return false; }
183 * False if the handler is disabled for all files
185 function isEnabled() { return true; }
188 * Get an associative array of page dimensions
189 * Currently "width" and "height" are understood, but this might be
190 * expanded in the future.
191 * Returns false if unknown or if the document is not multi-page.
195 function getPageDimensions( $image, $page ) {
196 $gis = $this->getImageSize( $image, $image->getPath() );
204 * Generic getter for text layer.
205 * Currently overloaded by PDF and DjVu handlers
207 function getPageText( $image, $page ) {
212 * Get an array structure that looks like this:
215 * 'visible' => array(
216 * 'Human-readable name' => 'Human readable value',
219 * 'collapsed' => array(
220 * 'Human-readable name' => 'Human readable value',
224 * The UI will format this into a table where the visible fields are always
225 * visible, and the collapsed fields are optionally visible.
227 * The function should return false if there is no metadata to display.
231 * FIXME: I don't really like this interface, it's not very flexible
232 * I think the media handler should generate HTML instead. It can do
233 * all the formatting according to some standard. That makes it possible
234 * to do things like visual indication of grouped and chained streams
235 * in ogg container files.
237 function formatMetadata( $image ) {
242 * @todo Fixme: document this!
243 * 'value' thingy goes into a wikitext table; it used to be escaped but
244 * that was incompatible with previous practice of customized display
245 * with wikitext formatting via messages such as 'exif-model-value'.
246 * So the escaping is taken back out, but generally this seems a confusing
249 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
250 $array[$visibility][] = array(
252 'name' => wfMsg( "$type-$id", $param ),
261 function getShortDesc( $file ) {
263 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
264 $wgLang->formatNum( $file->getSize() ) );
272 function getLongDesc( $file ) {
274 $sk = $wgUser->getSkin();
275 return wfMsgExt( 'file-info', 'parseinline',
276 $sk->formatSize( $file->getSize() ),
277 $file->getMimeType() );
284 static function getGeneralShortDesc( $file ) {
286 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
287 $wgLang->formatNum( $file->getSize() ) );
295 static function getGeneralLongDesc( $file ) {
297 $sk = $wgUser->getSkin();
298 return wfMsgExt( 'file-info', 'parseinline',
299 $sk->formatSize( $file->getSize() ),
300 $file->getMimeType() );
303 function getDimensionsString( $file ) {
308 * Modify the parser object post-transform
310 function parserTransformHook( $parser, $file ) {}
313 * File validation hook called on upload.
315 * If the file at the given local path is not valid, or its MIME type does not
316 * match the handler class, a Status object should be returned containing
319 * @param $fileName The local path to the file.
320 * @return Status object
322 function verifyUpload( $fileName ) {
323 return Status
::newGood();
327 * Check for zero-sized thumbnails. These can be generated when
328 * no disk space is available or some other error occurs
330 * @param $dstPath The location of the suspect file
331 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
332 * @return true if removed, false otherwise
334 function removeBadFile( $dstPath, $retval = 0 ) {
335 if( file_exists( $dstPath ) ) {
336 $thumbstat = stat( $dstPath );
337 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
338 wfDebugLog( 'thumbnail',
339 sprintf( 'Removing bad %d-byte thumbnail "%s"',
340 $thumbstat['size'], $dstPath ) );
350 * Media handler abstract base class for images
354 abstract class ImageHandler
extends MediaHandler
{
360 function canRender( $file ) {
361 return ( $file->getWidth() && $file->getHeight() );
364 function getParamMap() {
365 return array( 'img_width' => 'width' );
368 function validateParam( $name, $value ) {
369 if ( in_array( $name, array( 'width', 'height' ) ) ) {
380 function makeParamString( $params ) {
381 if ( isset( $params['physicalWidth'] ) ) {
382 $width = $params['physicalWidth'];
383 } elseif ( isset( $params['width'] ) ) {
384 $width = $params['width'];
386 throw new MWException( 'No width specified to '.__METHOD__
);
388 # Removed for ProofreadPage
389 #$width = intval( $width );
393 function parseParamString( $str ) {
395 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
396 return array( 'width' => $m[1] );
402 function getScriptParams( $params ) {
403 return array( 'width' => $params['width'] );
411 function normaliseParams( $image, &$params ) {
412 $mimeType = $image->getMimeType();
414 if ( !isset( $params['width'] ) ) {
418 if ( !isset( $params['page'] ) ) {
421 if ( $params['page'] > $image->pageCount() ) {
422 $params['page'] = $image->pageCount();
425 if ( $params['page'] < 1 ) {
430 $srcWidth = $image->getWidth( $params['page'] );
431 $srcHeight = $image->getHeight( $params['page'] );
432 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
433 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
434 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
437 $params['height'] = File
::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
438 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
445 * Get a transform output object without actually doing the transform
447 function getTransform( $image, $dstPath, $dstUrl, $params ) {
448 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self
::TRANSFORM_LATER
);
452 * Validate thumbnail parameters and fill in the correct height
454 * @param $width Integer: specified width (input/output)
455 * @param $height Integer: height (output only)
456 * @param $srcWidth Integer: width of the source image
457 * @param $srcHeight Integer: height of the source image
458 * @param $mimeType Unused
459 * @return false to indicate that an error should be returned to the user.
461 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
462 $width = intval( $width );
464 # Sanity check $width
466 wfDebug( __METHOD__
.": Invalid destination width: $width\n" );
469 if ( $srcWidth <= 0 ) {
470 wfDebug( __METHOD__
.": Invalid source width: $srcWidth\n" );
474 $height = File
::scaleHeight( $srcWidth, $srcHeight, $width );
482 * @return bool|ThumbnailImage
484 function getScriptedTransform( $image, $script, $params ) {
485 if ( !$this->normaliseParams( $image, $params ) ) {
488 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
489 $page = isset( $params['page'] ) ?
$params['page'] : false;
491 if( $image->mustRender() ||
$params['width'] < $image->getWidth() ) {
492 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
496 function getImageSize( $image, $path ) {
497 wfSuppressWarnings();
498 $gis = getimagesize( $path );
503 function isAnimatedImage( $image ) {
511 function getShortDesc( $file ) {
513 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
514 $wgLang->formatNum( $file->getSize() ) );
515 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
517 return "$widthheight ($nbytes)";
524 function getLongDesc( $file ) {
526 return wfMsgExt('file-info-size', 'parseinline',
527 $wgLang->formatNum( $file->getWidth() ),
528 $wgLang->formatNum( $file->getHeight() ),
529 $wgLang->formatSize( $file->getSize() ),
530 $file->getMimeType() );
537 function getDimensionsString( $file ) {
539 $pages = $file->pageCount();
540 $width = $wgLang->formatNum( $file->getWidth() );
541 $height = $wgLang->formatNum( $file->getHeight() );
542 $pagesFmt = $wgLang->formatNum( $pages );
545 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
547 return wfMsg( 'widthheight', $width, $height );