(bug 35565) Special:Log/patrol doesn't indicate whether patrolling was automatic
[mediawiki.git] / includes / media / Generic.php
blobc6833f3cfacb0092b241d20f822e020ba94f2172
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;
16 const METADATA_GOOD = true;
17 const METADATA_BAD = false;
18 const METADATA_COMPATIBLE = 2; // for old but backwards compatible.
19 /**
20 * Instance cache
22 static $handlers = array();
24 /**
25 * Get a MediaHandler for a given MIME type from the instance cache
27 * @param $type string
29 * @return MediaHandler
31 static function getHandler( $type ) {
32 global $wgMediaHandlers;
33 if ( !isset( $wgMediaHandlers[$type] ) ) {
34 wfDebug( __METHOD__ . ": no handler found for $type.\n");
35 return false;
37 $class = $wgMediaHandlers[$type];
38 if ( !isset( self::$handlers[$class] ) ) {
39 self::$handlers[$class] = new $class;
40 if ( !self::$handlers[$class]->isEnabled() ) {
41 self::$handlers[$class] = false;
44 return self::$handlers[$class];
47 /**
48 * Get an associative array mapping magic word IDs to parameter names.
49 * Will be used by the parser to identify parameters.
51 abstract function getParamMap();
53 /**
54 * Validate a thumbnail parameter at parse time.
55 * Return true to accept the parameter, and false to reject it.
56 * If you return false, the parser will do something quiet and forgiving.
58 * @param $name
59 * @param $value
61 abstract function validateParam( $name, $value );
63 /**
64 * Merge a parameter array into a string appropriate for inclusion in filenames
66 * @param $params array
68 abstract function makeParamString( $params );
70 /**
71 * Parse a param string made with makeParamString back into an array
73 * @param $str string
75 abstract function parseParamString( $str );
77 /**
78 * Changes the parameter array as necessary, ready for transformation.
79 * Should be idempotent.
80 * Returns false if the parameters are unacceptable and the transform should fail
81 * @param $image
82 * @param $params
84 abstract function normaliseParams( $image, &$params );
86 /**
87 * Get an image size array like that returned by getimagesize(), or false if it
88 * can't be determined.
90 * @param $image File: the image object, or false if there isn't one
91 * @param $path String: the filename
92 * @return Array Follow the format of PHP getimagesize() internal function. See http://www.php.net/getimagesize
94 abstract function getImageSize( $image, $path );
96 /**
97 * Get handler-specific metadata which will be saved in the img_metadata field.
99 * @param $image File: the image object, or false if there isn't one.
100 * Warning, FSFile::getPropsFromPath might pass an (object)array() instead (!)
101 * @param $path String: the filename
102 * @return String
104 function getMetadata( $image, $path ) { return ''; }
107 * Get metadata version.
109 * This is not used for validating metadata, this is used for the api when returning
110 * metadata, since api content formats should stay the same over time, and so things
111 * using ForiegnApiRepo can keep backwards compatibility
113 * All core media handlers share a common version number, and extensions can
114 * use the GetMetadataVersion hook to append to the array (they should append a unique
115 * string so not to get confusing). If there was a media handler named 'foo' with metadata
116 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
117 * version is 2, the end version string would look like '2;foo=3'.
119 * @return string version string
121 static function getMetadataVersion () {
122 $version = Array( '2' ); // core metadata version
123 wfRunHooks('GetMetadataVersion', Array(&$version));
124 return implode( ';', $version);
128 * Convert metadata version.
130 * By default just returns $metadata, but can be used to allow
131 * media handlers to convert between metadata versions.
133 * @param $metadata Mixed String or Array metadata array (serialized if string)
134 * @param $version Integer target version
135 * @return Array serialized metadata in specified version, or $metadata on fail.
137 function convertMetadataVersion( $metadata, $version = 1 ) {
138 if ( !is_array( $metadata ) ) {
140 //unserialize to keep return parameter consistent.
141 wfSuppressWarnings();
142 $ret = unserialize( $metadata );
143 wfRestoreWarnings();
144 return $ret;
146 return $metadata;
150 * Get a string describing the type of metadata, for display purposes.
152 * @return string
154 function getMetadataType( $image ) { return false; }
157 * Check if the metadata string is valid for this handler.
158 * If it returns MediaHandler::METADATA_BAD (or false), Image
159 * will reload the metadata from the file and update the database.
160 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
161 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
162 * compatible (which may or may not trigger a metadata reload).
163 * @return bool
165 function isMetadataValid( $image, $metadata ) {
166 return self::METADATA_GOOD;
171 * Get a MediaTransformOutput object representing an alternate of the transformed
172 * output which will call an intermediary thumbnail assist script.
174 * Used when the repository has a thumbnailScriptUrl option configured.
176 * Return false to fall back to the regular getTransform().
177 * @return bool
179 function getScriptedTransform( $image, $script, $params ) {
180 return false;
184 * Get a MediaTransformOutput object representing the transformed output. Does not
185 * actually do the transform.
187 * @param $image File: the image object
188 * @param $dstPath String: filesystem destination path
189 * @param $dstUrl String: Destination URL to use in output HTML
190 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
191 * @return MediaTransformOutput
193 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
194 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
198 * Get a MediaTransformOutput object representing the transformed output. Does the
199 * transform unless $flags contains self::TRANSFORM_LATER.
201 * @param $image File: the image object
202 * @param $dstPath String: filesystem destination path
203 * @param $dstUrl String: destination URL to use in output HTML
204 * @param $params Array: arbitrary set of parameters validated by $this->validateParam()
205 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
207 * @return MediaTransformOutput
209 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
212 * Get the thumbnail extension and MIME type for a given source MIME type
213 * @return array thumbnail extension and MIME type
215 function getThumbType( $ext, $mime, $params = null ) {
216 $magic = MimeMagic::singleton();
217 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
218 // The extension is not valid for this mime type and we do
219 // recognize the mime type
220 $extensions = $magic->getExtensionsForType( $mime );
221 if ( $extensions ) {
222 return array( strtok( $extensions, ' ' ), $mime );
226 // The extension is correct (true) or the mime type is unknown to
227 // MediaWiki (null)
228 return array( $ext, $mime );
232 * True if the handled types can be transformed
233 * @return bool
235 function canRender( $file ) { return true; }
237 * True if handled types cannot be displayed directly in a browser
238 * but can be rendered
239 * @return bool
241 function mustRender( $file ) { return false; }
243 * True if the type has multi-page capabilities
244 * @return bool
246 function isMultiPage( $file ) { return false; }
248 * Page count for a multi-page document, false if unsupported or unknown
249 * @return bool
251 function pageCount( $file ) { return false; }
253 * The material is vectorized and thus scaling is lossless
254 * @return bool
256 function isVectorized( $file ) { return false; }
258 * False if the handler is disabled for all files
259 * @return bool
261 function isEnabled() { return true; }
264 * Get an associative array of page dimensions
265 * Currently "width" and "height" are understood, but this might be
266 * expanded in the future.
267 * Returns false if unknown or if the document is not multi-page.
269 * @param $image File
270 * @return array
272 function getPageDimensions( $image, $page ) {
273 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
274 return array(
275 'width' => $gis[0],
276 'height' => $gis[1]
281 * Generic getter for text layer.
282 * Currently overloaded by PDF and DjVu handlers
283 * @return bool
285 function getPageText( $image, $page ) {
286 return false;
290 * Get an array structure that looks like this:
292 * array(
293 * 'visible' => array(
294 * 'Human-readable name' => 'Human readable value',
295 * ...
296 * ),
297 * 'collapsed' => array(
298 * 'Human-readable name' => 'Human readable value',
299 * ...
302 * The UI will format this into a table where the visible fields are always
303 * visible, and the collapsed fields are optionally visible.
305 * The function should return false if there is no metadata to display.
309 * @todo FIXME: I don't really like this interface, it's not very flexible
310 * I think the media handler should generate HTML instead. It can do
311 * all the formatting according to some standard. That makes it possible
312 * to do things like visual indication of grouped and chained streams
313 * in ogg container files.
314 * @return bool
316 function formatMetadata( $image ) {
317 return false;
320 /** sorts the visible/invisible field.
321 * Split off from ImageHandler::formatMetadata, as used by more than
322 * one type of handler.
324 * This is used by the media handlers that use the FormatMetadata class
326 * @param $metadataArray Array metadata array
327 * @return array for use displaying metadata.
329 function formatMetadataHelper( $metadataArray ) {
330 $result = array(
331 'visible' => array(),
332 'collapsed' => array()
335 $formatted = FormatMetadata::getFormattedData( $metadataArray );
336 // Sort fields into visible and collapsed
337 $visibleFields = $this->visibleMetadataFields();
338 foreach ( $formatted as $name => $value ) {
339 $tag = strtolower( $name );
340 self::addMeta( $result,
341 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
342 'exif',
343 $tag,
344 $value
347 return $result;
351 * Get a list of metadata items which should be displayed when
352 * the metadata table is collapsed.
354 * @return array of strings
355 * @access protected
357 function visibleMetadataFields() {
358 $fields = array();
359 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
360 foreach( $lines as $line ) {
361 $matches = array();
362 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
363 $fields[] = $matches[1];
366 $fields = array_map( 'strtolower', $fields );
367 return $fields;
372 * This is used to generate an array element for each metadata value
373 * That array is then used to generate the table of metadata values
374 * on the image page
376 * @param &$array Array An array containing elements for each type of visibility
377 * and each of those elements being an array of metadata items. This function adds
378 * a value to that array.
379 * @param $visibility string ('visible' or 'collapsed') if this value is hidden
380 * by default.
381 * @param $type String type of metadata tag (currently always 'exif')
382 * @param $id String the name of the metadata tag (like 'artist' for example).
383 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
384 * @param $value String thingy goes into a wikitext table; it used to be escaped but
385 * that was incompatible with previous practise of customized display
386 * with wikitext formatting via messages such as 'exif-model-value'.
387 * So the escaping is taken back out, but generally this seems a confusing
388 * interface.
389 * @param $param String value to pass to the message for the name of the field
390 * as $1. Currently this parameter doesn't seem to ever be used.
392 * Note, everything here is passed through the parser later on (!)
394 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
395 $msg = wfMessage( "$type-$id", $param );
396 if ( $msg->exists() ) {
397 $name = $msg->text();
398 } else {
399 // This is for future compatibility when using instant commons.
400 // So as to not display as ugly a name if a new metadata
401 // property is defined that we don't know about
402 // (not a major issue since such a property would be collapsed
403 // by default).
404 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
405 $name = wfEscapeWikiText( $id );
407 $array[$visibility][] = array(
408 'id' => "$type-$id",
409 'name' => $name,
410 'value' => $value
415 * @param $file File
416 * @return string
418 function getShortDesc( $file ) {
419 global $wgLang;
420 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
424 * @param $file File
425 * @return string
427 function getLongDesc( $file ) {
428 global $wgLang;
429 return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
430 $file->getMimeType() )->parse();
434 * @param $file File
435 * @return string
437 static function getGeneralShortDesc( $file ) {
438 global $wgLang;
439 return $wgLang->formatSize( $file->getSize() );
443 * @param $file File
444 * @return string
446 static function getGeneralLongDesc( $file ) {
447 global $wgLang;
448 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
449 $file->getMimeType() )->parse();
453 * Calculate the largest thumbnail width for a given original file size
454 * such that the thumbnail's height is at most $maxHeight.
455 * @param $boxWidth Integer Width of the thumbnail box.
456 * @param $boxHeight Integer Height of the thumbnail box.
457 * @param $maxHeight Integer Maximum height expected for the thumbnail.
458 * @return Integer.
460 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
461 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
462 $roundedUp = ceil( $idealWidth );
463 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
464 return floor( $idealWidth );
465 } else {
466 return $roundedUp;
470 function getDimensionsString( $file ) {
471 return '';
475 * Modify the parser object post-transform
477 function parserTransformHook( $parser, $file ) {}
480 * File validation hook called on upload.
482 * If the file at the given local path is not valid, or its MIME type does not
483 * match the handler class, a Status object should be returned containing
484 * relevant errors.
486 * @param $fileName string The local path to the file.
487 * @return Status object
489 function verifyUpload( $fileName ) {
490 return Status::newGood();
494 * Check for zero-sized thumbnails. These can be generated when
495 * no disk space is available or some other error occurs
497 * @param $dstPath string The location of the suspect file
498 * @param $retval int Return value of some shell process, file will be deleted if this is non-zero
499 * @return bool True if removed, false otherwise
501 function removeBadFile( $dstPath, $retval = 0 ) {
502 if( file_exists( $dstPath ) ) {
503 $thumbstat = stat( $dstPath );
504 if( $thumbstat['size'] == 0 || $retval != 0 ) {
505 $result = unlink( $dstPath );
507 if ( $result ) {
508 wfDebugLog( 'thumbnail',
509 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
510 $thumbstat['size'], $dstPath ) );
511 } else {
512 wfDebugLog( 'thumbnail',
513 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
514 $thumbstat['size'], $dstPath ) );
516 return true;
519 return false;
523 * Remove files from the purge list
525 * @param array $files
526 * @param array $options
528 public function filterThumbnailPurgeList( &$files, $options ) {
529 // Do nothing
534 * Media handler abstract base class for images
536 * @ingroup Media
538 abstract class ImageHandler extends MediaHandler {
541 * @param $file File
542 * @return bool
544 function canRender( $file ) {
545 return ( $file->getWidth() && $file->getHeight() );
548 function getParamMap() {
549 return array( 'img_width' => 'width' );
552 function validateParam( $name, $value ) {
553 if ( in_array( $name, array( 'width', 'height' ) ) ) {
554 if ( $value <= 0 ) {
555 return false;
556 } else {
557 return true;
559 } else {
560 return false;
564 function makeParamString( $params ) {
565 if ( isset( $params['physicalWidth'] ) ) {
566 $width = $params['physicalWidth'];
567 } elseif ( isset( $params['width'] ) ) {
568 $width = $params['width'];
569 } else {
570 throw new MWException( 'No width specified to '.__METHOD__ );
572 # Removed for ProofreadPage
573 #$width = intval( $width );
574 return "{$width}px";
577 function parseParamString( $str ) {
578 $m = false;
579 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
580 return array( 'width' => $m[1] );
581 } else {
582 return false;
586 function getScriptParams( $params ) {
587 return array( 'width' => $params['width'] );
591 * @param $image File
592 * @param $params
593 * @return bool
595 function normaliseParams( $image, &$params ) {
596 $mimeType = $image->getMimeType();
598 if ( !isset( $params['width'] ) ) {
599 return false;
602 if ( !isset( $params['page'] ) ) {
603 $params['page'] = 1;
604 } else {
605 if ( $params['page'] > $image->pageCount() ) {
606 $params['page'] = $image->pageCount();
609 if ( $params['page'] < 1 ) {
610 $params['page'] = 1;
614 $srcWidth = $image->getWidth( $params['page'] );
615 $srcHeight = $image->getHeight( $params['page'] );
617 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
618 # Height & width were both set
619 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
620 # Height is the relative smaller dimension, so scale width accordingly
621 $params['width'] = self::fitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
623 if ( $params['width'] == 0 ) {
624 # Very small image, so we need to rely on client side scaling :(
625 $params['width'] = 1;
628 $params['physicalWidth'] = $params['width'];
629 } else {
630 # Height was crap, unset it so that it will be calculated later
631 unset( $params['height'] );
635 if ( !isset( $params['physicalWidth'] ) ) {
636 # Passed all validations, so set the physicalWidth
637 $params['physicalWidth'] = $params['width'];
640 # Because thumbs are only referred to by width, the height always needs
641 # to be scaled by the width to keep the thumbnail sizes consistent,
642 # even if it was set inside the if block above
643 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight,
644 $params['physicalWidth'] );
646 # Set the height if it was not validated in the if block higher up
647 if ( !isset( $params['height'] ) || $params['height'] == -1 ) {
648 $params['height'] = $params['physicalHeight'];
652 if ( !$this->validateThumbParams( $params['physicalWidth'],
653 $params['physicalHeight'], $srcWidth, $srcHeight, $mimeType ) ) {
654 return false;
656 return true;
660 * Validate thumbnail parameters and fill in the correct height
662 * @param $width Integer: specified width (input/output)
663 * @param $height Integer: height (output only)
664 * @param $srcWidth Integer: width of the source image
665 * @param $srcHeight Integer: height of the source image
666 * @param $mimeType
667 * @return bool False to indicate that an error should be returned to the user.
669 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
670 $width = intval( $width );
672 # Sanity check $width
673 if( $width <= 0) {
674 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
675 return false;
677 if ( $srcWidth <= 0 ) {
678 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
679 return false;
682 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
683 if ( $height == 0 ) {
684 # Force height to be at least 1 pixel
685 $height = 1;
687 return true;
691 * @param $image File
692 * @param $script
693 * @param $params
694 * @return bool|ThumbnailImage
696 function getScriptedTransform( $image, $script, $params ) {
697 if ( !$this->normaliseParams( $image, $params ) ) {
698 return false;
700 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
701 $page = isset( $params['page'] ) ? $params['page'] : false;
703 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
704 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
708 function getImageSize( $image, $path ) {
709 wfSuppressWarnings();
710 $gis = getimagesize( $path );
711 wfRestoreWarnings();
712 return $gis;
715 function isAnimatedImage( $image ) {
716 return false;
720 * @param $file File
721 * @return string
723 function getShortDesc( $file ) {
724 global $wgLang;
725 $nbytes = htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
726 $widthheight = wfMessage( 'widthheight' )->numParams( $file->getWidth(), $file->getHeight() )->escaped();
728 return "$widthheight ($nbytes)";
732 * @param $file File
733 * @return string
735 function getLongDesc( $file ) {
736 global $wgLang;
737 $pages = $file->pageCount();
738 $size = htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
739 if ( $pages === false || $pages <= 1 ) {
740 $msg = wfMessage( 'file-info-size' )->numParams( $file->getWidth(),
741 $file->getHeight() )->params( $size,
742 $file->getMimeType() )->parse();
743 } else {
744 $msg = wfMessage( 'file-info-size-pages' )->numParams( $file->getWidth(),
745 $file->getHeight() )->params( $size,
746 $file->getMimeType() )->numParams( $pages )->parse();
748 return $msg;
752 * @param $file File
753 * @return string
755 function getDimensionsString( $file ) {
756 $pages = $file->pageCount();
757 if ( $pages > 1 ) {
758 return wfMessage( 'widthheightpage' )->numParams( $file->getWidth(), $file->getHeight(), $pages )->text();
759 } else {
760 return wfMessage( 'widthheight' )->numParams( $file->getWidth(), $file->getHeight() )->text();