Remove unreachable line in DifferenceEngine
[mediawiki.git] / includes / media / Generic.php
blob1f6dec039d077f284e94660b4b9e07fd82b9641e
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 $magic = MimeMagic::singleton();
145 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
146 // The extension is not valid for this mime type and we do
147 // recognize the mime type
148 $extensions = $magic->getExtensionsForType( $mime );
149 if ( $extensions ) {
150 return array( strtok( $extensions, ' ' ), $mime );
154 // The extension is correct (true) or the mime type is unknown to
155 // MediaWiki (null)
156 return array( $ext, $mime );
160 * True if the handled types can be transformed
162 function canRender( $file ) { return true; }
164 * True if handled types cannot be displayed directly in a browser
165 * but can be rendered
167 function mustRender( $file ) { return false; }
169 * True if the type has multi-page capabilities
171 function isMultiPage( $file ) { return false; }
173 * Page count for a multi-page document, false if unsupported or unknown
175 function pageCount( $file ) { return false; }
177 * The material is vectorized and thus scaling is lossless
179 function isVectorized( $file ) { return false; }
181 * False if the handler is disabled for all files
183 function isEnabled() { return true; }
186 * Get an associative array of page dimensions
187 * Currently "width" and "height" are understood, but this might be
188 * expanded in the future.
189 * Returns false if unknown or if the document is not multi-page.
191 function getPageDimensions( $image, $page ) {
192 $gis = $this->getImageSize( $image, $image->getPath() );
193 return array(
194 'width' => $gis[0],
195 'height' => $gis[1]
200 * Generic getter for text layer.
201 * Currently overloaded by PDF and DjVu handlers
203 function getPageText( $image, $page ) {
204 return false;
208 * Get an array structure that looks like this:
210 * array(
211 * 'visible' => array(
212 * 'Human-readable name' => 'Human readable value',
213 * ...
214 * ),
215 * 'collapsed' => array(
216 * 'Human-readable name' => 'Human readable value',
217 * ...
220 * The UI will format this into a table where the visible fields are always
221 * visible, and the collapsed fields are optionally visible.
223 * The function should return false if there is no metadata to display.
227 * FIXME: I don't really like this interface, it's not very flexible
228 * I think the media handler should generate HTML instead. It can do
229 * all the formatting according to some standard. That makes it possible
230 * to do things like visual indication of grouped and chained streams
231 * in ogg container files.
233 function formatMetadata( $image ) {
234 return false;
238 * @todo Fixme: document this!
239 * 'value' thingy goes into a wikitext table; it used to be escaped but
240 * that was incompatible with previous practice of customized display
241 * with wikitext formatting via messages such as 'exif-model-value'.
242 * So the escaping is taken back out, but generally this seems a confusing
243 * interface.
245 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
246 $array[$visibility][] = array(
247 'id' => "$type-$id",
248 'name' => wfMsg( "$type-$id", $param ),
249 'value' => $value
253 function getShortDesc( $file ) {
254 global $wgLang;
255 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
256 $wgLang->formatNum( $file->getSize() ) );
257 return "$nbytes";
260 function getLongDesc( $file ) {
261 global $wgUser;
262 $sk = $wgUser->getSkin();
263 return wfMsgExt( 'file-info', 'parseinline',
264 $sk->formatSize( $file->getSize() ),
265 $file->getMimeType() );
268 static function getGeneralShortDesc( $file ) {
269 global $wgLang;
270 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
271 $wgLang->formatNum( $file->getSize() ) );
272 return "$nbytes";
275 static function getGeneralLongDesc( $file ) {
276 global $wgUser;
277 $sk = $wgUser->getSkin();
278 return wfMsgExt( 'file-info', 'parseinline',
279 $sk->formatSize( $file->getSize() ),
280 $file->getMimeType() );
283 function getDimensionsString( $file ) {
284 return '';
288 * Modify the parser object post-transform
290 function parserTransformHook( $parser, $file ) {}
293 * File validation hook called on upload.
295 * If the file at the given local path is not valid, or its MIME type does not
296 * match the handler class, a Status object should be returned containing
297 * relevant errors.
299 * @param $fileName The local path to the file.
300 * @return Status object
302 function verifyUpload( $fileName ) {
303 return Status::newGood();
307 * Check for zero-sized thumbnails. These can be generated when
308 * no disk space is available or some other error occurs
310 * @param $dstPath The location of the suspect file
311 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
312 * @return true if removed, false otherwise
314 function removeBadFile( $dstPath, $retval = 0 ) {
315 if( file_exists( $dstPath ) ) {
316 $thumbstat = stat( $dstPath );
317 if( $thumbstat['size'] == 0 || $retval != 0 ) {
318 wfDebugLog( 'thumbnail',
319 sprintf( 'Removing bad %d-byte thumbnail "%s"',
320 $thumbstat['size'], $dstPath ) );
321 unlink( $dstPath );
322 return true;
325 return false;
330 * Media handler abstract base class for images
332 * @ingroup Media
334 abstract class ImageHandler extends MediaHandler {
335 function canRender( $file ) {
336 if ( $file->getWidth() && $file->getHeight() ) {
337 return true;
338 } else {
339 return false;
343 function getParamMap() {
344 return array( 'img_width' => 'width' );
347 function validateParam( $name, $value ) {
348 if ( in_array( $name, array( 'width', 'height' ) ) ) {
349 if ( $value <= 0 ) {
350 return false;
351 } else {
352 return true;
354 } else {
355 return false;
359 function makeParamString( $params ) {
360 if ( isset( $params['physicalWidth'] ) ) {
361 $width = $params['physicalWidth'];
362 } elseif ( isset( $params['width'] ) ) {
363 $width = $params['width'];
364 } else {
365 throw new MWException( 'No width specified to '.__METHOD__ );
367 # Removed for ProofreadPage
368 #$width = intval( $width );
369 return "{$width}px";
372 function parseParamString( $str ) {
373 $m = false;
374 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
375 return array( 'width' => $m[1] );
376 } else {
377 return false;
381 function getScriptParams( $params ) {
382 return array( 'width' => $params['width'] );
385 function normaliseParams( $image, &$params ) {
386 $mimeType = $image->getMimeType();
388 if ( !isset( $params['width'] ) ) {
389 return false;
392 if ( !isset( $params['page'] ) ) {
393 $params['page'] = 1;
394 } else {
395 if ( $params['page'] > $image->pageCount() ) {
396 $params['page'] = $image->pageCount();
399 if ( $params['page'] < 1 ) {
400 $params['page'] = 1;
404 $srcWidth = $image->getWidth( $params['page'] );
405 $srcHeight = $image->getHeight( $params['page'] );
406 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
407 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
408 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
411 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
412 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
413 return false;
415 return true;
419 * Get a transform output object without actually doing the transform
421 function getTransform( $image, $dstPath, $dstUrl, $params ) {
422 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
426 * Validate thumbnail parameters and fill in the correct height
428 * @param $width Integer: specified width (input/output)
429 * @param $height Integer: height (output only)
430 * @param $srcWidth Integer: width of the source image
431 * @param $srcHeight Integer: height of the source image
432 * @param $mimeType Unused
433 * @return false to indicate that an error should be returned to the user.
435 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
436 $width = intval( $width );
438 # Sanity check $width
439 if( $width <= 0) {
440 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
441 return false;
443 if ( $srcWidth <= 0 ) {
444 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
445 return false;
448 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
449 return true;
452 function getScriptedTransform( $image, $script, $params ) {
453 if ( !$this->normaliseParams( $image, $params ) ) {
454 return false;
456 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
457 $page = isset( $params['page'] ) ? $params['page'] : false;
459 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
460 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
464 function getImageSize( $image, $path ) {
465 wfSuppressWarnings();
466 $gis = getimagesize( $path );
467 wfRestoreWarnings();
468 return $gis;
471 function isAnimatedImage( $image ) {
472 return false;
475 function getShortDesc( $file ) {
476 global $wgLang;
477 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
478 $wgLang->formatNum( $file->getSize() ) );
479 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
481 return "$widthheight ($nbytes)";
484 function getLongDesc( $file ) {
485 global $wgLang;
486 return wfMsgExt('file-info-size', 'parseinline',
487 $wgLang->formatNum( $file->getWidth() ),
488 $wgLang->formatNum( $file->getHeight() ),
489 $wgLang->formatSize( $file->getSize() ),
490 $file->getMimeType() );
493 function getDimensionsString( $file ) {
494 global $wgLang;
495 $pages = $file->pageCount();
496 $width = $wgLang->formatNum( $file->getWidth() );
497 $height = $wgLang->formatNum( $file->getHeight() );
498 $pagesFmt = $wgLang->formatNum( $pages );
500 if ( $pages > 1 ) {
501 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
502 } else {
503 return wfMsg( 'widthheight', $width, $height );