* Reduced some pointless regex capture overhead
[mediawiki.git] / includes / media / Generic.php
blob92f03045c30929747697641cea5b018c596255d0
1 <?php
2 /**
3 * Media-handling base classes and generic functionality
5 * @file
6 * @ingroup Media
7 */
9 /**
10 * Base media handler class
12 * @ingroup Media
14 abstract class MediaHandler {
15 const TRANSFORM_LATER = 1;
17 /**
18 * Instance cache
20 static $handlers = array();
22 /**
23 * Get a MediaHandler for a given MIME type from the instance cache
25 static function getHandler( $type ) {
26 global $wgMediaHandlers;
27 if ( !isset( $wgMediaHandlers[$type] ) ) {
28 wfDebug( __METHOD__ . ": no handler found for $type.\n");
29 return false;
31 $class = $wgMediaHandlers[$type];
32 if ( !isset( self::$handlers[$class] ) ) {
33 self::$handlers[$class] = new $class;
34 if ( !self::$handlers[$class]->isEnabled() ) {
35 self::$handlers[$class] = false;
38 return self::$handlers[$class];
41 /**
42 * Get an associative array mapping magic word IDs to parameter names.
43 * Will be used by the parser to identify parameters.
45 abstract function getParamMap();
48 * Validate a thumbnail parameter at parse time.
49 * Return true to accept the parameter, and false to reject it.
50 * If you return false, the parser will do something quiet and forgiving.
52 abstract function validateParam( $name, $value );
54 /**
55 * Merge a parameter array into a string appropriate for inclusion in filenames
57 abstract function makeParamString( $params );
59 /**
60 * Parse a param string made with makeParamString back into an array
62 abstract function parseParamString( $str );
64 /**
65 * Changes the parameter array as necessary, ready for transformation.
66 * Should be idempotent.
67 * Returns false if the parameters are unacceptable and the transform should fail
69 abstract function normaliseParams( $image, &$params );
71 /**
72 * Get an image size array like that returned by getimagesize(), or false if it
73 * can't be determined.
75 * @param $image File: the image object, or false if there isn't one
76 * @param $path String: the filename
77 * @return Array
79 abstract function getImageSize( $image, $path );
81 /**
82 * Get handler-specific metadata which will be saved in the img_metadata field.
84 * @param $image File: the image object, or false if there isn't one
85 * @param $path String: the filename
86 * @return String
88 function getMetadata( $image, $path ) { return ''; }
90 /**
91 * Get a string describing the type of metadata, for display purposes.
93 function getMetadataType( $image ) { return false; }
95 /**
96 * Check if the metadata string is valid for this handler.
97 * If it returns false, Image will reload the metadata from the file and update the database
99 function isMetadataValid( $image, $metadata ) { return true; }
103 * Get a MediaTransformOutput object representing an alternate of the transformed
104 * output which will call an intermediary thumbnail assist script.
106 * Used when the repository has a thumbnailScriptUrl option configured.
108 * Return false to fall back to the regular getTransform().
110 function getScriptedTransform( $image, $script, $params ) {
111 return false;
115 * Get a MediaTransformOutput object representing the transformed output. Does not
116 * actually do the transform.
118 * @param $image File: the image object
119 * @param $dstPath String: filesystem destination path
120 * @param $dstUrl String: Destination URL to use in output HTML
121 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
123 function getTransform( $image, $dstPath, $dstUrl, $params ) {
124 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
128 * Get a MediaTransformOutput object representing the transformed output. Does the
129 * transform unless $flags contains self::TRANSFORM_LATER.
131 * @param $image File: the image object
132 * @param $dstPath String: filesystem destination path
133 * @param $dstUrl String: destination URL to use in output HTML
134 * @param $params Array: arbitrary set of parameters validated by $this->validateParam()
135 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
137 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
140 * Get the thumbnail extension and MIME type for a given source MIME type
141 * @return array thumbnail extension and MIME type
143 function getThumbType( $ext, $mime, $params = null ) {
144 return array( $ext, $mime );
148 * True if the handled types can be transformed
150 function canRender( $file ) { return true; }
152 * True if handled types cannot be displayed directly in a browser
153 * but can be rendered
155 function mustRender( $file ) { return false; }
157 * True if the type has multi-page capabilities
159 function isMultiPage( $file ) { return false; }
161 * Page count for a multi-page document, false if unsupported or unknown
163 function pageCount( $file ) { return false; }
165 * The material is vectorized and thus scaling is lossless
167 function isVectorized( $file ) { return false; }
169 * False if the handler is disabled for all files
171 function isEnabled() { return true; }
174 * Get an associative array of page dimensions
175 * Currently "width" and "height" are understood, but this might be
176 * expanded in the future.
177 * Returns false if unknown or if the document is not multi-page.
179 function getPageDimensions( $image, $page ) {
180 $gis = $this->getImageSize( $image, $image->getPath() );
181 return array(
182 'width' => $gis[0],
183 'height' => $gis[1]
188 * Generic getter for text layer.
189 * Currently overloaded by PDF and DjVu handlers
191 function getPageText( $image, $page ) {
192 return false;
196 * Get an array structure that looks like this:
198 * array(
199 * 'visible' => array(
200 * 'Human-readable name' => 'Human readable value',
201 * ...
202 * ),
203 * 'collapsed' => array(
204 * 'Human-readable name' => 'Human readable value',
205 * ...
208 * The UI will format this into a table where the visible fields are always
209 * visible, and the collapsed fields are optionally visible.
211 * The function should return false if there is no metadata to display.
215 * FIXME: I don't really like this interface, it's not very flexible
216 * I think the media handler should generate HTML instead. It can do
217 * all the formatting according to some standard. That makes it possible
218 * to do things like visual indication of grouped and chained streams
219 * in ogg container files.
221 function formatMetadata( $image ) {
222 return false;
226 * @todo Fixme: document this!
227 * 'value' thingy goes into a wikitext table; it used to be escaped but
228 * that was incompatible with previous practice of customized display
229 * with wikitext formatting via messages such as 'exif-model-value'.
230 * So the escaping is taken back out, but generally this seems a confusing
231 * interface.
233 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
234 $array[$visibility][] = array(
235 'id' => "$type-$id",
236 'name' => wfMsg( "$type-$id", $param ),
237 'value' => $value
241 function getShortDesc( $file ) {
242 global $wgLang;
243 $nbytes = '(' . wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
244 $wgLang->formatNum( $file->getSize() ) ) . ')';
245 return "$nbytes";
248 function getLongDesc( $file ) {
249 global $wgUser;
250 $sk = $wgUser->getSkin();
251 return wfMsgExt( 'file-info', 'parseinline',
252 $sk->formatSize( $file->getSize() ),
253 $file->getMimeType() );
256 static function getGeneralShortDesc( $file ) {
257 global $wgLang;
258 $nbytes = '(' . wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
259 $wgLang->formatNum( $file->getSize() ) ) . ')';
260 return "$nbytes";
263 static function getGeneralLongDesc( $file ) {
264 global $wgUser;
265 $sk = $wgUser->getSkin();
266 return wfMsgExt( 'file-info', 'parseinline',
267 $sk->formatSize( $file->getSize() ),
268 $file->getMimeType() );
271 function getDimensionsString( $file ) {
272 return '';
276 * Modify the parser object post-transform
278 function parserTransformHook( $parser, $file ) {}
281 * File validation hook called on upload.
283 * If the file at the given local path is not valid, or its MIME type does not
284 * match the handler class, a Status object should be returned containing
285 * relevant errors.
287 * @param $fileName The local path to the file.
288 * @return Status object
290 function verifyUpload( $fileName ) {
291 return Status::newGood();
295 * Check for zero-sized thumbnails. These can be generated when
296 * no disk space is available or some other error occurs
298 * @param $dstPath The location of the suspect file
299 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
300 * @return true if removed, false otherwise
302 function removeBadFile( $dstPath, $retval = 0 ) {
303 if( file_exists( $dstPath ) ) {
304 $thumbstat = stat( $dstPath );
305 if( $thumbstat['size'] == 0 || $retval != 0 ) {
306 wfDebugLog( 'thumbnail',
307 sprintf( 'Removing bad %d-byte thumbnail "%s"',
308 $thumbstat['size'], $dstPath ) );
309 unlink( $dstPath );
310 return true;
313 return false;
318 * Media handler abstract base class for images
320 * @ingroup Media
322 abstract class ImageHandler extends MediaHandler {
323 function canRender( $file ) {
324 if ( $file->getWidth() && $file->getHeight() ) {
325 return true;
326 } else {
327 return false;
331 function getParamMap() {
332 return array( 'img_width' => 'width' );
335 function validateParam( $name, $value ) {
336 if ( in_array( $name, array( 'width', 'height' ) ) ) {
337 if ( $value <= 0 ) {
338 return false;
339 } else {
340 return true;
342 } else {
343 return false;
347 function makeParamString( $params ) {
348 if ( isset( $params['physicalWidth'] ) ) {
349 $width = $params['physicalWidth'];
350 } elseif ( isset( $params['width'] ) ) {
351 $width = $params['width'];
352 } else {
353 throw new MWException( 'No width specified to '.__METHOD__ );
355 # Removed for ProofreadPage
356 #$width = intval( $width );
357 return "{$width}px";
360 function parseParamString( $str ) {
361 $m = false;
362 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
363 return array( 'width' => $m[1] );
364 } else {
365 return false;
369 function getScriptParams( $params ) {
370 return array( 'width' => $params['width'] );
373 function normaliseParams( $image, &$params ) {
374 $mimeType = $image->getMimeType();
376 if ( !isset( $params['width'] ) ) {
377 return false;
380 if ( !isset( $params['page'] ) ) {
381 $params['page'] = 1;
382 } else {
383 if ( $params['page'] > $image->pageCount() ) {
384 $params['page'] = $image->pageCount();
387 if ( $params['page'] < 1 ) {
388 $params['page'] = 1;
392 $srcWidth = $image->getWidth( $params['page'] );
393 $srcHeight = $image->getHeight( $params['page'] );
394 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
395 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
396 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
399 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
400 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
401 return false;
403 return true;
407 * Get a transform output object without actually doing the transform
409 function getTransform( $image, $dstPath, $dstUrl, $params ) {
410 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
414 * Validate thumbnail parameters and fill in the correct height
416 * @param $width Integer: specified width (input/output)
417 * @param $height Integer: height (output only)
418 * @param $srcWidth Integer: width of the source image
419 * @param $srcHeight Integer: height of the source image
420 * @param $mimeType Unused
421 * @return false to indicate that an error should be returned to the user.
423 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
424 $width = intval( $width );
426 # Sanity check $width
427 if( $width <= 0) {
428 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
429 return false;
431 if ( $srcWidth <= 0 ) {
432 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
433 return false;
436 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
437 return true;
440 function getScriptedTransform( $image, $script, $params ) {
441 if ( !$this->normaliseParams( $image, $params ) ) {
442 return false;
444 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
445 $page = isset( $params['page'] ) ? $params['page'] : false;
447 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
448 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
452 function getImageSize( $image, $path ) {
453 wfSuppressWarnings();
454 $gis = getimagesize( $path );
455 wfRestoreWarnings();
456 return $gis;
459 function isAnimatedImage( $image ) {
460 return false;
463 function getShortDesc( $file ) {
464 global $wgLang;
465 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
466 $wgLang->formatNum( $file->getSize() ) );
467 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
469 return "$widthheight ($nbytes)";
472 function getLongDesc( $file ) {
473 global $wgLang;
474 return wfMsgExt('file-info-size', 'parseinline',
475 $wgLang->formatNum( $file->getWidth() ),
476 $wgLang->formatNum( $file->getHeight() ),
477 $wgLang->formatSize( $file->getSize() ),
478 $file->getMimeType() );
481 function getDimensionsString( $file ) {
482 global $wgLang;
483 $pages = $file->pageCount();
484 $width = $wgLang->formatNum( $file->getWidth() );
485 $height = $wgLang->formatNum( $file->getHeight() );
486 $pagesFmt = $wgLang->formatNum( $pages );
488 if ( $pages > 1 ) {
489 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
490 } else {
491 return wfMsg( 'widthheight', $width, $height );