thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / media / MediaHandler.php
blobfd576e02825cd466e86cb94d0f1a82149bb45475
1 <?php
2 /**
3 * Media-handling base classes and generic functionality.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Media
24 /**
25 * Base media handler class
27 * @ingroup Media
29 abstract class MediaHandler {
30 const TRANSFORM_LATER = 1;
31 const METADATA_GOOD = true;
32 const METADATA_BAD = false;
33 const METADATA_COMPATIBLE = 2; // for old but backwards compatible.
34 /**
35 * Instance cache
37 static $handlers = array();
39 /**
40 * Get a MediaHandler for a given MIME type from the instance cache
42 * @param $type string
44 * @return MediaHandler
46 static function getHandler( $type ) {
47 global $wgMediaHandlers;
48 if ( !isset( $wgMediaHandlers[$type] ) ) {
49 wfDebug( __METHOD__ . ": no handler found for $type.\n" );
50 return false;
52 $class = $wgMediaHandlers[$type];
53 if ( !isset( self::$handlers[$class] ) ) {
54 self::$handlers[$class] = new $class;
55 if ( !self::$handlers[$class]->isEnabled() ) {
56 self::$handlers[$class] = false;
59 return self::$handlers[$class];
62 /**
63 * Get an associative array mapping magic word IDs to parameter names.
64 * Will be used by the parser to identify parameters.
66 abstract function getParamMap();
68 /**
69 * Validate a thumbnail parameter at parse time.
70 * Return true to accept the parameter, and false to reject it.
71 * If you return false, the parser will do something quiet and forgiving.
73 * @param $name
74 * @param $value
76 abstract function validateParam( $name, $value );
78 /**
79 * Merge a parameter array into a string appropriate for inclusion in filenames
81 * @param $params array
83 abstract function makeParamString( $params );
85 /**
86 * Parse a param string made with makeParamString back into an array
88 * @param $str string
90 abstract function parseParamString( $str );
92 /**
93 * Changes the parameter array as necessary, ready for transformation.
94 * Should be idempotent.
95 * Returns false if the parameters are unacceptable and the transform should fail
96 * @param $image
97 * @param $params
99 abstract function normaliseParams( $image, &$params );
102 * Get an image size array like that returned by getimagesize(), or false if it
103 * can't be determined.
105 * @param $image File: the image object, or false if there isn't one
106 * @param string $path the filename
107 * @return Array Follow the format of PHP getimagesize() internal function. See http://www.php.net/getimagesize
109 abstract function getImageSize( $image, $path );
112 * Get handler-specific metadata which will be saved in the img_metadata field.
114 * @param $image File: the image object, or false if there isn't one.
115 * Warning, FSFile::getPropsFromPath might pass an (object)array() instead (!)
116 * @param string $path the filename
117 * @return String
119 function getMetadata( $image, $path ) {
120 return '';
124 * Get metadata version.
126 * This is not used for validating metadata, this is used for the api when returning
127 * metadata, since api content formats should stay the same over time, and so things
128 * using ForiegnApiRepo can keep backwards compatibility
130 * All core media handlers share a common version number, and extensions can
131 * use the GetMetadataVersion hook to append to the array (they should append a unique
132 * string so not to get confusing). If there was a media handler named 'foo' with metadata
133 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
134 * version is 2, the end version string would look like '2;foo=3'.
136 * @return string version string
138 static function getMetadataVersion() {
139 $version = Array( '2' ); // core metadata version
140 wfRunHooks( 'GetMetadataVersion', Array( &$version ) );
141 return implode( ';', $version );
145 * Convert metadata version.
147 * By default just returns $metadata, but can be used to allow
148 * media handlers to convert between metadata versions.
150 * @param $metadata Mixed String or Array metadata array (serialized if string)
151 * @param $version Integer target version
152 * @return Array serialized metadata in specified version, or $metadata on fail.
154 function convertMetadataVersion( $metadata, $version = 1 ) {
155 if ( !is_array( $metadata ) ) {
157 //unserialize to keep return parameter consistent.
158 wfSuppressWarnings();
159 $ret = unserialize( $metadata );
160 wfRestoreWarnings();
161 return $ret;
163 return $metadata;
167 * Get a string describing the type of metadata, for display purposes.
169 * @return string
171 function getMetadataType( $image ) {
172 return false;
176 * Check if the metadata string is valid for this handler.
177 * If it returns MediaHandler::METADATA_BAD (or false), Image
178 * will reload the metadata from the file and update the database.
179 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
180 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
181 * compatible (which may or may not trigger a metadata reload).
182 * @return bool
184 function isMetadataValid( $image, $metadata ) {
185 return self::METADATA_GOOD;
189 * Get a MediaTransformOutput object representing an alternate of the transformed
190 * output which will call an intermediary thumbnail assist script.
192 * Used when the repository has a thumbnailScriptUrl option configured.
194 * Return false to fall back to the regular getTransform().
195 * @return bool
197 function getScriptedTransform( $image, $script, $params ) {
198 return false;
202 * Get a MediaTransformOutput object representing the transformed output. Does not
203 * actually do the transform.
205 * @param $image File: the image object
206 * @param string $dstPath filesystem destination path
207 * @param string $dstUrl Destination URL to use in output HTML
208 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
209 * @return MediaTransformOutput
211 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
212 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
216 * Get a MediaTransformOutput object representing the transformed output. Does the
217 * transform unless $flags contains self::TRANSFORM_LATER.
219 * @param $image File: the image object
220 * @param string $dstPath filesystem destination path
221 * @param string $dstUrl destination URL to use in output HTML
222 * @param array $params arbitrary set of parameters validated by $this->validateParam()
223 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
225 * @return MediaTransformOutput
227 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
230 * Get the thumbnail extension and MIME type for a given source MIME type
232 * @param String $ext Extension of original file
233 * @param String $mime Mime type of original file
234 * @param Array $params Handler specific rendering parameters
235 * @return array thumbnail extension and MIME type
237 function getThumbType( $ext, $mime, $params = null ) {
238 $magic = MimeMagic::singleton();
239 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
240 // The extension is not valid for this mime type and we do
241 // recognize the mime type
242 $extensions = $magic->getExtensionsForType( $mime );
243 if ( $extensions ) {
244 return array( strtok( $extensions, ' ' ), $mime );
248 // The extension is correct (true) or the mime type is unknown to
249 // MediaWiki (null)
250 return array( $ext, $mime );
254 * Get useful response headers for GET/HEAD requests for a file with the given metadata
255 * @param $metadata mixed Result of the getMetadata() function of this handler for a file
256 * @return Array
258 public function getStreamHeaders( $metadata ) {
259 return array();
263 * True if the handled types can be transformed
264 * @return bool
266 function canRender( $file ) {
267 return true;
271 * True if handled types cannot be displayed directly in a browser
272 * but can be rendered
273 * @return bool
275 function mustRender( $file ) {
276 return false;
280 * True if the type has multi-page capabilities
281 * @return bool
283 function isMultiPage( $file ) {
284 return false;
288 * Page count for a multi-page document, false if unsupported or unknown
289 * @return bool
291 function pageCount( $file ) {
292 return false;
296 * The material is vectorized and thus scaling is lossless
297 * @return bool
299 function isVectorized( $file ) {
300 return false;
304 * The material is an image, and is animated.
305 * In particular, video material need not return true.
306 * @note Before 1.20, this was a method of ImageHandler only
307 * @return bool
309 function isAnimatedImage( $file ) {
310 return false;
314 * If the material is animated, we can animate the thumbnail
315 * @since 1.20
316 * @return bool If material is not animated, handler may return any value.
318 function canAnimateThumbnail( $file ) {
319 return true;
323 * False if the handler is disabled for all files
324 * @return bool
326 function isEnabled() {
327 return true;
331 * Get an associative array of page dimensions
332 * Currently "width" and "height" are understood, but this might be
333 * expanded in the future.
334 * Returns false if unknown or if the document is not multi-page.
336 * @param $image File
337 * @param $page Unused, left for backcompatibility?
338 * @return array
340 function getPageDimensions( $image, $page ) {
341 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
342 return array(
343 'width' => $gis[0],
344 'height' => $gis[1]
349 * Generic getter for text layer.
350 * Currently overloaded by PDF and DjVu handlers
351 * @return bool
353 function getPageText( $image, $page ) {
354 return false;
358 * Get an array structure that looks like this:
360 * array(
361 * 'visible' => array(
362 * 'Human-readable name' => 'Human readable value',
363 * ...
364 * ),
365 * 'collapsed' => array(
366 * 'Human-readable name' => 'Human readable value',
367 * ...
370 * The UI will format this into a table where the visible fields are always
371 * visible, and the collapsed fields are optionally visible.
373 * The function should return false if there is no metadata to display.
377 * @todo FIXME: I don't really like this interface, it's not very flexible
378 * I think the media handler should generate HTML instead. It can do
379 * all the formatting according to some standard. That makes it possible
380 * to do things like visual indication of grouped and chained streams
381 * in ogg container files.
382 * @return bool
384 function formatMetadata( $image ) {
385 return false;
388 /** sorts the visible/invisible field.
389 * Split off from ImageHandler::formatMetadata, as used by more than
390 * one type of handler.
392 * This is used by the media handlers that use the FormatMetadata class
394 * @param array $metadataArray metadata array
395 * @return array for use displaying metadata.
397 function formatMetadataHelper( $metadataArray ) {
398 $result = array(
399 'visible' => array(),
400 'collapsed' => array()
403 $formatted = FormatMetadata::getFormattedData( $metadataArray );
404 // Sort fields into visible and collapsed
405 $visibleFields = $this->visibleMetadataFields();
406 foreach ( $formatted as $name => $value ) {
407 $tag = strtolower( $name );
408 self::addMeta( $result,
409 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
410 'exif',
411 $tag,
412 $value
415 return $result;
419 * Get a list of metadata items which should be displayed when
420 * the metadata table is collapsed.
422 * @return array of strings
423 * @access protected
425 function visibleMetadataFields() {
426 $fields = array();
427 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
428 foreach ( $lines as $line ) {
429 $matches = array();
430 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
431 $fields[] = $matches[1];
434 $fields = array_map( 'strtolower', $fields );
435 return $fields;
439 * This is used to generate an array element for each metadata value
440 * That array is then used to generate the table of metadata values
441 * on the image page
443 * @param &$array Array An array containing elements for each type of visibility
444 * and each of those elements being an array of metadata items. This function adds
445 * a value to that array.
446 * @param string $visibility ('visible' or 'collapsed') if this value is hidden
447 * by default.
448 * @param string $type type of metadata tag (currently always 'exif')
449 * @param string $id the name of the metadata tag (like 'artist' for example).
450 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
451 * @param string $value thingy goes into a wikitext table; it used to be escaped but
452 * that was incompatible with previous practise of customized display
453 * with wikitext formatting via messages such as 'exif-model-value'.
454 * So the escaping is taken back out, but generally this seems a confusing
455 * interface.
456 * @param string $param value to pass to the message for the name of the field
457 * as $1. Currently this parameter doesn't seem to ever be used.
459 * Note, everything here is passed through the parser later on (!)
461 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
462 $msg = wfMessage( "$type-$id", $param );
463 if ( $msg->exists() ) {
464 $name = $msg->text();
465 } else {
466 // This is for future compatibility when using instant commons.
467 // So as to not display as ugly a name if a new metadata
468 // property is defined that we don't know about
469 // (not a major issue since such a property would be collapsed
470 // by default).
471 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
472 $name = wfEscapeWikiText( $id );
474 $array[$visibility][] = array(
475 'id' => "$type-$id",
476 'name' => $name,
477 'value' => $value
482 * @param $file File
483 * @return string
485 function getShortDesc( $file ) {
486 global $wgLang;
487 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
491 * @param $file File
492 * @return string
494 function getLongDesc( $file ) {
495 global $wgLang;
496 return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
497 $file->getMimeType() )->parse();
501 * @param $file File
502 * @return string
504 static function getGeneralShortDesc( $file ) {
505 global $wgLang;
506 return $wgLang->formatSize( $file->getSize() );
510 * @param $file File
511 * @return string
513 static function getGeneralLongDesc( $file ) {
514 global $wgLang;
515 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
516 $file->getMimeType() )->parse();
520 * Calculate the largest thumbnail width for a given original file size
521 * such that the thumbnail's height is at most $maxHeight.
522 * @param $boxWidth Integer Width of the thumbnail box.
523 * @param $boxHeight Integer Height of the thumbnail box.
524 * @param $maxHeight Integer Maximum height expected for the thumbnail.
525 * @return Integer.
527 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
528 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
529 $roundedUp = ceil( $idealWidth );
530 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
531 return floor( $idealWidth );
532 } else {
533 return $roundedUp;
537 function getDimensionsString( $file ) {
538 return '';
542 * Modify the parser object post-transform
544 function parserTransformHook( $parser, $file ) {}
547 * File validation hook called on upload.
549 * If the file at the given local path is not valid, or its MIME type does not
550 * match the handler class, a Status object should be returned containing
551 * relevant errors.
553 * @param string $fileName The local path to the file.
554 * @return Status object
556 function verifyUpload( $fileName ) {
557 return Status::newGood();
561 * Check for zero-sized thumbnails. These can be generated when
562 * no disk space is available or some other error occurs
564 * @param string $dstPath The location of the suspect file
565 * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
566 * @return bool True if removed, false otherwise
568 function removeBadFile( $dstPath, $retval = 0 ) {
569 if ( file_exists( $dstPath ) ) {
570 $thumbstat = stat( $dstPath );
571 if ( $thumbstat['size'] == 0 || $retval != 0 ) {
572 $result = unlink( $dstPath );
574 if ( $result ) {
575 wfDebugLog( 'thumbnail',
576 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
577 $thumbstat['size'], $dstPath ) );
578 } else {
579 wfDebugLog( 'thumbnail',
580 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
581 $thumbstat['size'], $dstPath ) );
583 return true;
586 return false;
590 * Remove files from the purge list
592 * @param array $files
593 * @param array $options
595 public function filterThumbnailPurgeList( &$files, $options ) {
596 // Do nothing
600 * True if the handler can rotate the media
601 * @since 1.21
602 * @return bool
604 public static function canRotate() {
605 return false;