Fix function level comments that start with /* not /**
[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 * @return MediaHandler
28 */
29 static function getHandler( $type ) {
30 global $wgMediaHandlers;
31 if ( !isset( $wgMediaHandlers[$type] ) ) {
32 wfDebug( __METHOD__ . ": no handler found for $type.\n");
33 return false;
34 }
35 $class = $wgMediaHandlers[$type];
36 if ( !isset( self::$handlers[$class] ) ) {
37 self::$handlers[$class] = new $class;
38 if ( !self::$handlers[$class]->isEnabled() ) {
39 self::$handlers[$class] = false;
40 }
41 }
42 return self::$handlers[$class];
43 }
44
45 /**
46 * Get an associative array mapping magic word IDs to parameter names.
47 * Will be used by the parser to identify parameters.
48 */
49 abstract function getParamMap();
50
51 /**
52 * Validate a thumbnail parameter at parse time.
53 * Return true to accept the parameter, and false to reject it.
54 * If you return false, the parser will do something quiet and forgiving.
55 */
56 abstract function validateParam( $name, $value );
57
58 /**
59 * Merge a parameter array into a string appropriate for inclusion in filenames
60 */
61 abstract function makeParamString( $params );
62
63 /**
64 * Parse a param string made with makeParamString back into an array
65 */
66 abstract function parseParamString( $str );
67
68 /**
69 * Changes the parameter array as necessary, ready for transformation.
70 * Should be idempotent.
71 * Returns false if the parameters are unacceptable and the transform should fail
72 */
73 abstract function normaliseParams( $image, &$params );
74
75 /**
76 * Get an image size array like that returned by getimagesize(), or false if it
77 * can't be determined.
78 *
79 * @param $image File: the image object, or false if there isn't one
80 * @param $path String: the filename
81 * @return Array
82 */
83 abstract function getImageSize( $image, $path );
84
85 /**
86 * Get handler-specific metadata which will be saved in the img_metadata field.
87 *
88 * @param $image File: the image object, or false if there isn't one.
89 * Warning, File::getPropsFromPath might pass an (object)array() instead (!)
90 * @param $path String: the filename
91 * @return String
92 */
93 function getMetadata( $image, $path ) { return ''; }
94
95 /**
96 * Get metadata version.
97 *
98 * This is not used for validating metadata, this is used for the api when returning
99 * metadata, since api content formats should stay the same over time, and so things
100 * using ForiegnApiRepo can keep backwards compatibility
101 *
102 * All core media handlers share a common version number, and extensions can
103 * use the GetMetadataVersion hook to append to the array (they should append a unique
104 * string so not to get confusing). If there was a media handler named 'foo' with metadata
105 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
106 * version is 2, the end version string would look like '2;foo=3'.
107 *
108 * @return string version string
109 */
110 static function getMetadataVersion () {
111 $version = Array( '2' ); // core metadata version
112 wfRunHooks('GetMetadataVersion', Array(&$version));
113 return implode( ';', $version);
114 }
115
116 /**
117 * Convert metadata version.
118 *
119 * By default just returns $metadata, but can be used to allow
120 * media handlers to convert between metadata versions.
121 *
122 * @param $metadata Mixed String or Array metadata array (serialized if string)
123 * @param $version Integer target version
124 * @return Array serialized metadata in specified version, or $metadata on fail.
125 */
126 function convertMetadataVersion( $metadata, $version = 1 ) {
127 if ( !is_array( $metadata ) ) {
128
129 //unserialize to keep return parameter consistent.
130 wfSuppressWarnings();
131 $ret = unserialize( $metadata );
132 wfRestoreWarnings();
133 return $ret;
134 }
135 return $metadata;
136 }
137
138 /**
139 * Get a string describing the type of metadata, for display purposes.
140 */
141 function getMetadataType( $image ) { return false; }
142
143 /**
144 * Check if the metadata string is valid for this handler.
145 * If it returns MediaHandler::METADATA_BAD (or false), Image
146 * will reload the metadata from the file and update the database.
147 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
148 * MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
149 * compatible (which may or may not trigger a metadata reload).
150 */
151 function isMetadataValid( $image, $metadata ) {
152 return self::METADATA_GOOD;
153 }
154
155
156 /**
157 * Get a MediaTransformOutput object representing an alternate of the transformed
158 * output which will call an intermediary thumbnail assist script.
159 *
160 * Used when the repository has a thumbnailScriptUrl option configured.
161 *
162 * Return false to fall back to the regular getTransform().
163 */
164 function getScriptedTransform( $image, $script, $params ) {
165 return false;
166 }
167
168 /**
169 * Get a MediaTransformOutput object representing the transformed output. Does not
170 * actually do the transform.
171 *
172 * @param $image File: the image object
173 * @param $dstPath String: filesystem destination path
174 * @param $dstUrl String: Destination URL to use in output HTML
175 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
176 */
177 function getTransform( $image, $dstPath, $dstUrl, $params ) {
178 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
179 }
180
181 /**
182 * Get a MediaTransformOutput object representing the transformed output. Does the
183 * transform unless $flags contains self::TRANSFORM_LATER.
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 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
190 */
191 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
192
193 /**
194 * Get the thumbnail extension and MIME type for a given source MIME type
195 * @return array thumbnail extension and MIME type
196 */
197 function getThumbType( $ext, $mime, $params = null ) {
198 $magic = MimeMagic::singleton();
199 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
200 // The extension is not valid for this mime type and we do
201 // recognize the mime type
202 $extensions = $magic->getExtensionsForType( $mime );
203 if ( $extensions ) {
204 return array( strtok( $extensions, ' ' ), $mime );
205 }
206 }
207
208 // The extension is correct (true) or the mime type is unknown to
209 // MediaWiki (null)
210 return array( $ext, $mime );
211 }
212
213 /**
214 * True if the handled types can be transformed
215 */
216 function canRender( $file ) { return true; }
217 /**
218 * True if handled types cannot be displayed directly in a browser
219 * but can be rendered
220 */
221 function mustRender( $file ) { return false; }
222 /**
223 * True if the type has multi-page capabilities
224 */
225 function isMultiPage( $file ) { return false; }
226 /**
227 * Page count for a multi-page document, false if unsupported or unknown
228 */
229 function pageCount( $file ) { return false; }
230 /**
231 * The material is vectorized and thus scaling is lossless
232 */
233 function isVectorized( $file ) { return false; }
234 /**
235 * False if the handler is disabled for all files
236 */
237 function isEnabled() { return true; }
238
239 /**
240 * Get an associative array of page dimensions
241 * Currently "width" and "height" are understood, but this might be
242 * expanded in the future.
243 * Returns false if unknown or if the document is not multi-page.
244 *
245 * @param $image File
246 */
247 function getPageDimensions( $image, $page ) {
248 $gis = $this->getImageSize( $image, $image->getPath() );
249 return array(
250 'width' => $gis[0],
251 'height' => $gis[1]
252 );
253 }
254
255 /**
256 * Generic getter for text layer.
257 * Currently overloaded by PDF and DjVu handlers
258 */
259 function getPageText( $image, $page ) {
260 return false;
261 }
262
263 /**
264 * Get an array structure that looks like this:
265 *
266 * array(
267 * 'visible' => array(
268 * 'Human-readable name' => 'Human readable value',
269 * ...
270 * ),
271 * 'collapsed' => array(
272 * 'Human-readable name' => 'Human readable value',
273 * ...
274 * )
275 * )
276 * The UI will format this into a table where the visible fields are always
277 * visible, and the collapsed fields are optionally visible.
278 *
279 * The function should return false if there is no metadata to display.
280 */
281
282 /**
283 * @todo FIXME: I don't really like this interface, it's not very flexible
284 * I think the media handler should generate HTML instead. It can do
285 * all the formatting according to some standard. That makes it possible
286 * to do things like visual indication of grouped and chained streams
287 * in ogg container files.
288 */
289 function formatMetadata( $image ) {
290 return false;
291 }
292
293 /** sorts the visible/invisible field.
294 * Split off from ImageHandler::formatMetadata, as used by more than
295 * one type of handler.
296 *
297 * This is used by the media handlers that use the FormatMetadata class
298 *
299 * @param $metadataArray Array metadata array
300 * @return array for use displaying metadata.
301 */
302 function formatMetadataHelper( $metadataArray ) {
303 $result = array(
304 'visible' => array(),
305 'collapsed' => array()
306 );
307
308 $formatted = FormatMetadata::getFormattedData( $metadataArray );
309 // Sort fields into visible and collapsed
310 $visibleFields = $this->visibleMetadataFields();
311 foreach ( $formatted as $name => $value ) {
312 $tag = strtolower( $name );
313 self::addMeta( $result,
314 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
315 'exif',
316 $tag,
317 $value
318 );
319 }
320 return $result;
321 }
322
323 /**
324 * Get a list of metadata items which should be displayed when
325 * the metadata table is collapsed.
326 *
327 * @return array of strings
328 * @access protected
329 */
330 function visibleMetadataFields() {
331 $fields = array();
332 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
333 foreach( $lines as $line ) {
334 $matches = array();
335 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
336 $fields[] = $matches[1];
337 }
338 }
339 $fields = array_map( 'strtolower', $fields );
340 return $fields;
341 }
342
343
344 /**
345 * This is used to generate an array element for each metadata value
346 * That array is then used to generate the table of metadata values
347 * on the image page
348 *
349 * @param &$array Array An array containing elements for each type of visibility
350 * and each of those elements being an array of metadata items. This function adds
351 * a value to that array.
352 * @param $visibility string ('visible' or 'collapsed') if this value is hidden
353 * by default.
354 * @param $type String type of metadata tag (currently always 'exif')
355 * @param $id String the name of the metadata tag (like 'artist' for example).
356 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
357 * @param $value String thingy goes into a wikitext table; it used to be escaped but
358 * that was incompatible with previous practise of customized display
359 * with wikitext formatting via messages such as 'exif-model-value'.
360 * So the escaping is taken back out, but generally this seems a confusing
361 * interface.
362 * @param $param String value to pass to the message for the name of the field
363 * as $1. Currently this parameter doesn't seem to ever be used.
364 *
365 * Note, everything here is passed through the parser later on (!)
366 */
367 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
368 $msgName = "$type-$id";
369 if ( wfEmptyMsg( $msgName ) ) {
370 // This is for future compatibility when using instant commons.
371 // So as to not display as ugly a name if a new metadata
372 // property is defined that we don't know about
373 // (not a major issue since such a property would be collapsed
374 // by default).
375 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
376 $name = wfEscapeWikiText( $id );
377 } else {
378 $name = wfMsg( $msgName, $param );
379 }
380 $array[$visibility][] = array(
381 'id' => "$type-$id",
382 'name' => $name,
383 'value' => $value
384 );
385 }
386
387 /**
388 * @param $file File
389 * @return string
390 */
391 function getShortDesc( $file ) {
392 global $wgLang;
393 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
394 $wgLang->formatNum( $file->getSize() ) );
395 return "$nbytes";
396 }
397
398 /**
399 * @param $file File
400 * @return string
401 */
402 function getLongDesc( $file ) {
403 global $wgUser;
404 $sk = $wgUser->getSkin();
405 return wfMsgExt( 'file-info', 'parseinline',
406 $sk->formatSize( $file->getSize() ),
407 $file->getMimeType() );
408 }
409
410 /**
411 * @param $file File
412 * @return string
413 */
414 static function getGeneralShortDesc( $file ) {
415 global $wgLang;
416 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
417 $wgLang->formatNum( $file->getSize() ) );
418 return "$nbytes";
419 }
420
421 /**
422 * @param $file File
423 * @return string
424 */
425 static function getGeneralLongDesc( $file ) {
426 global $wgUser;
427 $sk = $wgUser->getSkin();
428 return wfMsgExt( 'file-info', 'parseinline',
429 $sk->formatSize( $file->getSize() ),
430 $file->getMimeType() );
431 }
432
433 function getDimensionsString( $file ) {
434 return '';
435 }
436
437 /**
438 * Modify the parser object post-transform
439 */
440 function parserTransformHook( $parser, $file ) {}
441
442 /**
443 * File validation hook called on upload.
444 *
445 * If the file at the given local path is not valid, or its MIME type does not
446 * match the handler class, a Status object should be returned containing
447 * relevant errors.
448 *
449 * @param $fileName The local path to the file.
450 * @return Status object
451 */
452 function verifyUpload( $fileName ) {
453 return Status::newGood();
454 }
455
456 /**
457 * Check for zero-sized thumbnails. These can be generated when
458 * no disk space is available or some other error occurs
459 *
460 * @param $dstPath The location of the suspect file
461 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
462 * @return true if removed, false otherwise
463 */
464 function removeBadFile( $dstPath, $retval = 0 ) {
465 if( file_exists( $dstPath ) ) {
466 $thumbstat = stat( $dstPath );
467 if( $thumbstat['size'] == 0 || $retval != 0 ) {
468 wfDebugLog( 'thumbnail',
469 sprintf( 'Removing bad %d-byte thumbnail "%s"',
470 $thumbstat['size'], $dstPath ) );
471 unlink( $dstPath );
472 return true;
473 }
474 }
475 return false;
476 }
477 }
478
479 /**
480 * Media handler abstract base class for images
481 *
482 * @ingroup Media
483 */
484 abstract class ImageHandler extends MediaHandler {
485
486 /**
487 * @param $file File
488 * @return bool
489 */
490 function canRender( $file ) {
491 return ( $file->getWidth() && $file->getHeight() );
492 }
493
494 function getParamMap() {
495 return array( 'img_width' => 'width' );
496 }
497
498 function validateParam( $name, $value ) {
499 if ( in_array( $name, array( 'width', 'height' ) ) ) {
500 if ( $value <= 0 ) {
501 return false;
502 } else {
503 return true;
504 }
505 } else {
506 return false;
507 }
508 }
509
510 function makeParamString( $params ) {
511 if ( isset( $params['physicalWidth'] ) ) {
512 $width = $params['physicalWidth'];
513 } elseif ( isset( $params['width'] ) ) {
514 $width = $params['width'];
515 } else {
516 throw new MWException( 'No width specified to '.__METHOD__ );
517 }
518 # Removed for ProofreadPage
519 #$width = intval( $width );
520 return "{$width}px";
521 }
522
523 function parseParamString( $str ) {
524 $m = false;
525 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
526 return array( 'width' => $m[1] );
527 } else {
528 return false;
529 }
530 }
531
532 function getScriptParams( $params ) {
533 return array( 'width' => $params['width'] );
534 }
535
536 /**
537 * @param $image File
538 * @param $params
539 * @return bool
540 */
541 function normaliseParams( $image, &$params ) {
542 $mimeType = $image->getMimeType();
543
544 if ( !isset( $params['width'] ) ) {
545 return false;
546 }
547
548 if ( !isset( $params['page'] ) ) {
549 $params['page'] = 1;
550 } else {
551 if ( $params['page'] > $image->pageCount() ) {
552 $params['page'] = $image->pageCount();
553 }
554
555 if ( $params['page'] < 1 ) {
556 $params['page'] = 1;
557 }
558 }
559
560 $srcWidth = $image->getWidth( $params['page'] );
561 $srcHeight = $image->getHeight( $params['page'] );
562 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
563 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
564 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
565 }
566 }
567 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
568 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
569 return false;
570 }
571 return true;
572 }
573
574 /**
575 * Get a transform output object without actually doing the transform
576 */
577 function getTransform( $image, $dstPath, $dstUrl, $params ) {
578 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
579 }
580
581 /**
582 * Validate thumbnail parameters and fill in the correct height
583 *
584 * @param $width Integer: specified width (input/output)
585 * @param $height Integer: height (output only)
586 * @param $srcWidth Integer: width of the source image
587 * @param $srcHeight Integer: height of the source image
588 * @param $mimeType Unused
589 * @return false to indicate that an error should be returned to the user.
590 */
591 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
592 $width = intval( $width );
593
594 # Sanity check $width
595 if( $width <= 0) {
596 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
597 return false;
598 }
599 if ( $srcWidth <= 0 ) {
600 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
601 return false;
602 }
603
604 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
605 return true;
606 }
607
608 /**
609 * @param $image File
610 * @param $script
611 * @param $params
612 * @return bool|ThumbnailImage
613 */
614 function getScriptedTransform( $image, $script, $params ) {
615 if ( !$this->normaliseParams( $image, $params ) ) {
616 return false;
617 }
618 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
619 $page = isset( $params['page'] ) ? $params['page'] : false;
620
621 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
622 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
623 }
624 }
625
626 function getImageSize( $image, $path ) {
627 wfSuppressWarnings();
628 $gis = getimagesize( $path );
629 wfRestoreWarnings();
630 return $gis;
631 }
632
633 function isAnimatedImage( $image ) {
634 return false;
635 }
636
637 /**
638 * @param $file File
639 * @return string
640 */
641 function getShortDesc( $file ) {
642 global $wgLang;
643 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
644 $wgLang->formatNum( $file->getSize() ) );
645 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
646
647 return "$widthheight ($nbytes)";
648 }
649
650 /**
651 * @param $file File
652 * @return string
653 */
654 function getLongDesc( $file ) {
655 global $wgLang;
656 $pages = $file->pageCount();
657 if ( $pages === false || $pages <= 1 ) {
658 $msg = wfMsgExt('file-info-size', 'parseinline',
659 $wgLang->formatNum( $file->getWidth() ),
660 $wgLang->formatNum( $file->getHeight() ),
661 $wgLang->formatSize( $file->getSize() ),
662 $file->getMimeType() );
663 } else {
664 $msg = wfMsgExt('file-info-size-pages', 'parseinline',
665 $wgLang->formatNum( $file->getWidth() ),
666 $wgLang->formatNum( $file->getHeight() ),
667 $wgLang->formatSize( $file->getSize() ),
668 $file->getMimeType(),
669 $wgLang->formatNum( $pages ) );
670 }
671 return $msg;
672 }
673
674 /**
675 * @param $file File
676 * @return string
677 */
678 function getDimensionsString( $file ) {
679 global $wgLang;
680 $pages = $file->pageCount();
681 $width = $wgLang->formatNum( $file->getWidth() );
682 $height = $wgLang->formatNum( $file->getHeight() );
683 $pagesFmt = $wgLang->formatNum( $pages );
684
685 if ( $pages > 1 ) {
686 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
687 } else {
688 return wfMsg( 'widthheight', $width, $height );
689 }
690 }
691 }