Fixing some of the "@return true" or "@return false", need to be "@return bool" and...
[lhc/web/wiklou.git] / includes / media / Generic.php
1 <?php
2 /**
3 * Media-handling base classes and generic functionality
4 *
5 * @file
6 * @ingroup Media
7 */
8
9 /**
10 * Base media handler class
11 *
12 * @ingroup Media
13 */
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
21 */
22 static $handlers = array();
23
24 /**
25 * Get a MediaHandler for a given MIME type from the instance cache
26 *
27 * @param $type string
28 *
29 * @return MediaHandler
30 */
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;
36 }
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;
42 }
43 }
44 return self::$handlers[$class];
45 }
46
47 /**
48 * Get an associative array mapping magic word IDs to parameter names.
49 * Will be used by the parser to identify parameters.
50 */
51 abstract function getParamMap();
52
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.
57 *
58 * @param $name
59 * @param $value
60 */
61 abstract function validateParam( $name, $value );
62
63 /**
64 * Merge a parameter array into a string appropriate for inclusion in filenames
65 *
66 * @param $params array
67 */
68 abstract function makeParamString( $params );
69
70 /**
71 * Parse a param string made with makeParamString back into an array
72 *
73 * @param $str string
74 */
75 abstract function parseParamString( $str );
76
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
83 */
84 abstract function normaliseParams( $image, &$params );
85
86 /**
87 * Get an image size array like that returned by getimagesize(), or false if it
88 * can't be determined.
89 *
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
93 */
94 abstract function getImageSize( $image, $path );
95
96 /**
97 * Get handler-specific metadata which will be saved in the img_metadata field.
98 *
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
103 */
104 function getMetadata( $image, $path ) { return ''; }
105
106 /**
107 * Get metadata version.
108 *
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
112 *
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'.
118 *
119 * @return string version string
120 */
121 static function getMetadataVersion () {
122 $version = Array( '2' ); // core metadata version
123 wfRunHooks('GetMetadataVersion', Array(&$version));
124 return implode( ';', $version);
125 }
126
127 /**
128 * Convert metadata version.
129 *
130 * By default just returns $metadata, but can be used to allow
131 * media handlers to convert between metadata versions.
132 *
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.
136 */
137 function convertMetadataVersion( $metadata, $version = 1 ) {
138 if ( !is_array( $metadata ) ) {
139
140 //unserialize to keep return parameter consistent.
141 wfSuppressWarnings();
142 $ret = unserialize( $metadata );
143 wfRestoreWarnings();
144 return $ret;
145 }
146 return $metadata;
147 }
148
149 /**
150 * Get a string describing the type of metadata, for display purposes.
151 *
152 * @return string
153 */
154 function getMetadataType( $image ) { return false; }
155
156 /**
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 */
164 function isMetadataValid( $image, $metadata ) {
165 return self::METADATA_GOOD;
166 }
167
168
169 /**
170 * Get a MediaTransformOutput object representing an alternate of the transformed
171 * output which will call an intermediary thumbnail assist script.
172 *
173 * Used when the repository has a thumbnailScriptUrl option configured.
174 *
175 * Return false to fall back to the regular getTransform().
176 */
177 function getScriptedTransform( $image, $script, $params ) {
178 return false;
179 }
180
181 /**
182 * Get a MediaTransformOutput object representing the transformed output. Does not
183 * actually do the transform.
184 *
185 * @param $image File: the image object
186 * @param $dstPath String: filesystem destination path
187 * @param $dstUrl String: Destination URL to use in output HTML
188 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
189 */
190 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
191 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
192 }
193
194 /**
195 * Get a MediaTransformOutput object representing the transformed output. Does the
196 * transform unless $flags contains self::TRANSFORM_LATER.
197 *
198 * @param $image File: the image object
199 * @param $dstPath String: filesystem destination path
200 * @param $dstUrl String: destination URL to use in output HTML
201 * @param $params Array: arbitrary set of parameters validated by $this->validateParam()
202 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
203 *
204 * @return MediaTransformOutput
205 */
206 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
207
208 /**
209 * Get the thumbnail extension and MIME type for a given source MIME type
210 * @return array thumbnail extension and MIME type
211 */
212 function getThumbType( $ext, $mime, $params = null ) {
213 $magic = MimeMagic::singleton();
214 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
215 // The extension is not valid for this mime type and we do
216 // recognize the mime type
217 $extensions = $magic->getExtensionsForType( $mime );
218 if ( $extensions ) {
219 return array( strtok( $extensions, ' ' ), $mime );
220 }
221 }
222
223 // The extension is correct (true) or the mime type is unknown to
224 // MediaWiki (null)
225 return array( $ext, $mime );
226 }
227
228 /**
229 * True if the handled types can be transformed
230 */
231 function canRender( $file ) { return true; }
232 /**
233 * True if handled types cannot be displayed directly in a browser
234 * but can be rendered
235 */
236 function mustRender( $file ) { return false; }
237 /**
238 * True if the type has multi-page capabilities
239 */
240 function isMultiPage( $file ) { return false; }
241 /**
242 * Page count for a multi-page document, false if unsupported or unknown
243 */
244 function pageCount( $file ) { return false; }
245 /**
246 * The material is vectorized and thus scaling is lossless
247 */
248 function isVectorized( $file ) { return false; }
249 /**
250 * False if the handler is disabled for all files
251 */
252 function isEnabled() { return true; }
253
254 /**
255 * Get an associative array of page dimensions
256 * Currently "width" and "height" are understood, but this might be
257 * expanded in the future.
258 * Returns false if unknown or if the document is not multi-page.
259 *
260 * @param $image File
261 */
262 function getPageDimensions( $image, $page ) {
263 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
264 return array(
265 'width' => $gis[0],
266 'height' => $gis[1]
267 );
268 }
269
270 /**
271 * Generic getter for text layer.
272 * Currently overloaded by PDF and DjVu handlers
273 */
274 function getPageText( $image, $page ) {
275 return false;
276 }
277
278 /**
279 * Get an array structure that looks like this:
280 *
281 * array(
282 * 'visible' => array(
283 * 'Human-readable name' => 'Human readable value',
284 * ...
285 * ),
286 * 'collapsed' => array(
287 * 'Human-readable name' => 'Human readable value',
288 * ...
289 * )
290 * )
291 * The UI will format this into a table where the visible fields are always
292 * visible, and the collapsed fields are optionally visible.
293 *
294 * The function should return false if there is no metadata to display.
295 */
296
297 /**
298 * @todo FIXME: I don't really like this interface, it's not very flexible
299 * I think the media handler should generate HTML instead. It can do
300 * all the formatting according to some standard. That makes it possible
301 * to do things like visual indication of grouped and chained streams
302 * in ogg container files.
303 */
304 function formatMetadata( $image ) {
305 return false;
306 }
307
308 /** sorts the visible/invisible field.
309 * Split off from ImageHandler::formatMetadata, as used by more than
310 * one type of handler.
311 *
312 * This is used by the media handlers that use the FormatMetadata class
313 *
314 * @param $metadataArray Array metadata array
315 * @return array for use displaying metadata.
316 */
317 function formatMetadataHelper( $metadataArray ) {
318 $result = array(
319 'visible' => array(),
320 'collapsed' => array()
321 );
322
323 $formatted = FormatMetadata::getFormattedData( $metadataArray );
324 // Sort fields into visible and collapsed
325 $visibleFields = $this->visibleMetadataFields();
326 foreach ( $formatted as $name => $value ) {
327 $tag = strtolower( $name );
328 self::addMeta( $result,
329 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
330 'exif',
331 $tag,
332 $value
333 );
334 }
335 return $result;
336 }
337
338 /**
339 * Get a list of metadata items which should be displayed when
340 * the metadata table is collapsed.
341 *
342 * @return array of strings
343 * @access protected
344 */
345 function visibleMetadataFields() {
346 $fields = array();
347 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
348 foreach( $lines as $line ) {
349 $matches = array();
350 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
351 $fields[] = $matches[1];
352 }
353 }
354 $fields = array_map( 'strtolower', $fields );
355 return $fields;
356 }
357
358
359 /**
360 * This is used to generate an array element for each metadata value
361 * That array is then used to generate the table of metadata values
362 * on the image page
363 *
364 * @param &$array Array An array containing elements for each type of visibility
365 * and each of those elements being an array of metadata items. This function adds
366 * a value to that array.
367 * @param $visibility string ('visible' or 'collapsed') if this value is hidden
368 * by default.
369 * @param $type String type of metadata tag (currently always 'exif')
370 * @param $id String the name of the metadata tag (like 'artist' for example).
371 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
372 * @param $value String thingy goes into a wikitext table; it used to be escaped but
373 * that was incompatible with previous practise of customized display
374 * with wikitext formatting via messages such as 'exif-model-value'.
375 * So the escaping is taken back out, but generally this seems a confusing
376 * interface.
377 * @param $param String value to pass to the message for the name of the field
378 * as $1. Currently this parameter doesn't seem to ever be used.
379 *
380 * Note, everything here is passed through the parser later on (!)
381 */
382 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
383 $msg = wfMessage( "$type-$id", $param );
384 if ( $msg->exists() ) {
385 $name = $msg->text();
386 } else {
387 // This is for future compatibility when using instant commons.
388 // So as to not display as ugly a name if a new metadata
389 // property is defined that we don't know about
390 // (not a major issue since such a property would be collapsed
391 // by default).
392 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
393 $name = wfEscapeWikiText( $id );
394 }
395 $array[$visibility][] = array(
396 'id' => "$type-$id",
397 'name' => $name,
398 'value' => $value
399 );
400 }
401
402 /**
403 * @param $file File
404 * @return string
405 */
406 function getShortDesc( $file ) {
407 global $wgLang;
408 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
409 }
410
411 /**
412 * @param $file File
413 * @return string
414 */
415 function getLongDesc( $file ) {
416 global $wgLang;
417 return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
418 $file->getMimeType() )->parse();
419 }
420
421 /**
422 * @param $file File
423 * @return string
424 */
425 static function getGeneralShortDesc( $file ) {
426 global $wgLang;
427 return $wgLang->formatSize( $file->getSize() );
428 }
429
430 /**
431 * @param $file File
432 * @return string
433 */
434 static function getGeneralLongDesc( $file ) {
435 global $wgLang;
436 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
437 $file->getMimeType() )->parse();
438 }
439
440 /**
441 * Calculate the largest thumbnail width for a given original file size
442 * such that the thumbnail's height is at most $maxHeight.
443 * @param $boxWidth Integer Width of the thumbnail box.
444 * @param $boxHeight Integer Height of the thumbnail box.
445 * @param $maxHeight Integer Maximum height expected for the thumbnail.
446 * @return Integer.
447 */
448 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
449 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
450 $roundedUp = ceil( $idealWidth );
451 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
452 return floor( $idealWidth );
453 } else {
454 return $roundedUp;
455 }
456 }
457
458 function getDimensionsString( $file ) {
459 return '';
460 }
461
462 /**
463 * Modify the parser object post-transform
464 */
465 function parserTransformHook( $parser, $file ) {}
466
467 /**
468 * File validation hook called on upload.
469 *
470 * If the file at the given local path is not valid, or its MIME type does not
471 * match the handler class, a Status object should be returned containing
472 * relevant errors.
473 *
474 * @param $fileName The local path to the file.
475 * @return Status object
476 */
477 function verifyUpload( $fileName ) {
478 return Status::newGood();
479 }
480
481 /**
482 * Check for zero-sized thumbnails. These can be generated when
483 * no disk space is available or some other error occurs
484 *
485 * @param $dstPath string The location of the suspect file
486 * @param $retval int Return value of some shell process, file will be deleted if this is non-zero
487 * @return bool if removed, false otherwise
488 */
489 function removeBadFile( $dstPath, $retval = 0 ) {
490 if( file_exists( $dstPath ) ) {
491 $thumbstat = stat( $dstPath );
492 if( $thumbstat['size'] == 0 || $retval != 0 ) {
493 $result = unlink( $dstPath );
494
495 if ( $result ) {
496 wfDebugLog( 'thumbnail',
497 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
498 $thumbstat['size'], $dstPath ) );
499 } else {
500 wfDebugLog( 'thumbnail',
501 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
502 $thumbstat['size'], $dstPath ) );
503 }
504 return true;
505 }
506 }
507 return false;
508 }
509
510 /**
511 * Remove files from the purge list
512 *
513 * @param array $files
514 * @param array $options
515 */
516 public function filterThumbnailPurgeList( &$files, $options ) {
517 // Do nothing
518 }
519 }
520
521 /**
522 * Media handler abstract base class for images
523 *
524 * @ingroup Media
525 */
526 abstract class ImageHandler extends MediaHandler {
527
528 /**
529 * @param $file File
530 * @return bool
531 */
532 function canRender( $file ) {
533 return ( $file->getWidth() && $file->getHeight() );
534 }
535
536 function getParamMap() {
537 return array( 'img_width' => 'width' );
538 }
539
540 function validateParam( $name, $value ) {
541 if ( in_array( $name, array( 'width', 'height' ) ) ) {
542 if ( $value <= 0 ) {
543 return false;
544 } else {
545 return true;
546 }
547 } else {
548 return false;
549 }
550 }
551
552 function makeParamString( $params ) {
553 if ( isset( $params['physicalWidth'] ) ) {
554 $width = $params['physicalWidth'];
555 } elseif ( isset( $params['width'] ) ) {
556 $width = $params['width'];
557 } else {
558 throw new MWException( 'No width specified to '.__METHOD__ );
559 }
560 # Removed for ProofreadPage
561 #$width = intval( $width );
562 return "{$width}px";
563 }
564
565 function parseParamString( $str ) {
566 $m = false;
567 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
568 return array( 'width' => $m[1] );
569 } else {
570 return false;
571 }
572 }
573
574 function getScriptParams( $params ) {
575 return array( 'width' => $params['width'] );
576 }
577
578 /**
579 * @param $image File
580 * @param $params
581 * @return bool
582 */
583 function normaliseParams( $image, &$params ) {
584 $mimeType = $image->getMimeType();
585
586 if ( !isset( $params['width'] ) ) {
587 return false;
588 }
589
590 if ( !isset( $params['page'] ) ) {
591 $params['page'] = 1;
592 } else {
593 if ( $params['page'] > $image->pageCount() ) {
594 $params['page'] = $image->pageCount();
595 }
596
597 if ( $params['page'] < 1 ) {
598 $params['page'] = 1;
599 }
600 }
601
602 $srcWidth = $image->getWidth( $params['page'] );
603 $srcHeight = $image->getHeight( $params['page'] );
604
605 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
606 # Height & width were both set
607 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
608 # Height is the relative smaller dimension, so scale width accordingly
609 $params['width'] = self::fitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
610
611 if ( $params['width'] == 0 ) {
612 # Very small image, so we need to rely on client side scaling :(
613 $params['width'] = 1;
614 }
615
616 $params['physicalWidth'] = $params['width'];
617 } else {
618 # Height was crap, unset it so that it will be calculated later
619 unset( $params['height'] );
620 }
621 }
622
623 if ( !isset( $params['physicalWidth'] ) ) {
624 # Passed all validations, so set the physicalWidth
625 $params['physicalWidth'] = $params['width'];
626 }
627
628 # Because thumbs are only referred to by width, the height always needs
629 # to be scaled by the width to keep the thumbnail sizes consistent,
630 # even if it was set inside the if block above
631 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight,
632 $params['physicalWidth'] );
633
634 # Set the height if it was not validated in the if block higher up
635 if ( !isset( $params['height'] ) || $params['height'] == -1 ) {
636 $params['height'] = $params['physicalHeight'];
637 }
638
639
640 if ( !$this->validateThumbParams( $params['physicalWidth'],
641 $params['physicalHeight'], $srcWidth, $srcHeight, $mimeType ) ) {
642 return false;
643 }
644 return true;
645 }
646
647 /**
648 * Validate thumbnail parameters and fill in the correct height
649 *
650 * @param $width Integer: specified width (input/output)
651 * @param $height Integer: height (output only)
652 * @param $srcWidth Integer: width of the source image
653 * @param $srcHeight Integer: height of the source image
654 * @param $mimeType Unused
655 * @return bool to indicate that an error should be returned to the user.
656 */
657 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
658 $width = intval( $width );
659
660 # Sanity check $width
661 if( $width <= 0) {
662 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
663 return false;
664 }
665 if ( $srcWidth <= 0 ) {
666 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
667 return false;
668 }
669
670 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
671 if ( $height == 0 ) {
672 # Force height to be at least 1 pixel
673 $height = 1;
674 }
675 return true;
676 }
677
678 /**
679 * @param $image File
680 * @param $script
681 * @param $params
682 * @return bool|ThumbnailImage
683 */
684 function getScriptedTransform( $image, $script, $params ) {
685 if ( !$this->normaliseParams( $image, $params ) ) {
686 return false;
687 }
688 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
689 $page = isset( $params['page'] ) ? $params['page'] : false;
690
691 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
692 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
693 }
694 }
695
696 function getImageSize( $image, $path ) {
697 wfSuppressWarnings();
698 $gis = getimagesize( $path );
699 wfRestoreWarnings();
700 return $gis;
701 }
702
703 function isAnimatedImage( $image ) {
704 return false;
705 }
706
707 /**
708 * @param $file File
709 * @return string
710 */
711 function getShortDesc( $file ) {
712 global $wgLang;
713 $nbytes = htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
714 $widthheight = wfMessage( 'widthheight' )->numParams( $file->getWidth(), $file->getHeight() )->escaped();
715
716 return "$widthheight ($nbytes)";
717 }
718
719 /**
720 * @param $file File
721 * @return string
722 */
723 function getLongDesc( $file ) {
724 global $wgLang;
725 $pages = $file->pageCount();
726 $size = htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
727 if ( $pages === false || $pages <= 1 ) {
728 $msg = wfMessage( 'file-info-size' )->numParams( $file->getWidth(),
729 $file->getHeight() )->params( $size,
730 $file->getMimeType() )->parse();
731 } else {
732 $msg = wfMessage( 'file-info-size-pages' )->numParams( $file->getWidth(),
733 $file->getHeight() )->params( $size,
734 $file->getMimeType() )->numParams( $pages )->parse();
735 }
736 return $msg;
737 }
738
739 /**
740 * @param $file File
741 * @return string
742 */
743 function getDimensionsString( $file ) {
744 $pages = $file->pageCount();
745 if ( $pages > 1 ) {
746 return wfMessage( 'widthheightpage' )->numParams( $file->getWidth(), $file->getHeight(), $pages )->text();
747 } else {
748 return wfMessage( 'widthheight' )->numParams( $file->getWidth(), $file->getHeight() )->text();
749 }
750 }
751 }