Merge "(bug 17602) fix Monobook action tabs not quite touching the page body"
[lhc/web/wiklou.git] / includes / media / MediaHandler.php
1 <?php
2 /**
3 * Media-handling base classes and generic functionality.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 /**
25 * Base media handler class
26 *
27 * @ingroup Media
28 */
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
36 */
37 static $handlers = array();
38
39 /**
40 * Get a MediaHandler for a given MIME type from the instance cache
41 *
42 * @param $type string
43 *
44 * @return MediaHandler
45 */
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;
51 }
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;
57 }
58 }
59 return self::$handlers[$class];
60 }
61
62 /**
63 * Get an associative array mapping magic word IDs to parameter names.
64 * Will be used by the parser to identify parameters.
65 */
66 abstract function getParamMap();
67
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.
72 *
73 * @param $name
74 * @param $value
75 */
76 abstract function validateParam( $name, $value );
77
78 /**
79 * Merge a parameter array into a string appropriate for inclusion in filenames
80 *
81 * @param $params array
82 */
83 abstract function makeParamString( $params );
84
85 /**
86 * Parse a param string made with makeParamString back into an array
87 *
88 * @param $str string
89 */
90 abstract function parseParamString( $str );
91
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
98 */
99 abstract function normaliseParams( $image, &$params );
100
101 /**
102 * Get an image size array like that returned by getimagesize(), or false if it
103 * can't be determined.
104 *
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
108 */
109 abstract function getImageSize( $image, $path );
110
111 /**
112 * Get handler-specific metadata which will be saved in the img_metadata field.
113 *
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
118 */
119 function getMetadata( $image, $path ) {
120 return '';
121 }
122
123 /**
124 * Get metadata version.
125 *
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
129 *
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'.
135 *
136 * @return string version string
137 */
138 static function getMetadataVersion() {
139 $version = Array( '2' ); // core metadata version
140 wfRunHooks( 'GetMetadataVersion', Array( &$version ) );
141 return implode( ';', $version );
142 }
143
144 /**
145 * Convert metadata version.
146 *
147 * By default just returns $metadata, but can be used to allow
148 * media handlers to convert between metadata versions.
149 *
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.
153 */
154 function convertMetadataVersion( $metadata, $version = 1 ) {
155 if ( !is_array( $metadata ) ) {
156
157 //unserialize to keep return parameter consistent.
158 wfSuppressWarnings();
159 $ret = unserialize( $metadata );
160 wfRestoreWarnings();
161 return $ret;
162 }
163 return $metadata;
164 }
165
166 /**
167 * Get a string describing the type of metadata, for display purposes.
168 *
169 * @return string
170 */
171 function getMetadataType( $image ) {
172 return false;
173 }
174
175 /**
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
183 */
184 function isMetadataValid( $image, $metadata ) {
185 return self::METADATA_GOOD;
186 }
187
188 /**
189 * Get a MediaTransformOutput object representing an alternate of the transformed
190 * output which will call an intermediary thumbnail assist script.
191 *
192 * Used when the repository has a thumbnailScriptUrl option configured.
193 *
194 * Return false to fall back to the regular getTransform().
195 * @return bool
196 */
197 function getScriptedTransform( $image, $script, $params ) {
198 return false;
199 }
200
201 /**
202 * Get a MediaTransformOutput object representing the transformed output. Does not
203 * actually do the transform.
204 *
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
210 */
211 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
212 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
213 }
214
215 /**
216 * Get a MediaTransformOutput object representing the transformed output. Does the
217 * transform unless $flags contains self::TRANSFORM_LATER.
218 *
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
224 *
225 * @return MediaTransformOutput
226 */
227 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
228
229 /**
230 * Get the thumbnail extension and MIME type for a given source MIME type
231 * @return array thumbnail extension and MIME type
232 */
233 function getThumbType( $ext, $mime, $params = null ) {
234 $magic = MimeMagic::singleton();
235 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
236 // The extension is not valid for this mime type and we do
237 // recognize the mime type
238 $extensions = $magic->getExtensionsForType( $mime );
239 if ( $extensions ) {
240 return array( strtok( $extensions, ' ' ), $mime );
241 }
242 }
243
244 // The extension is correct (true) or the mime type is unknown to
245 // MediaWiki (null)
246 return array( $ext, $mime );
247 }
248
249 /**
250 * Get useful response headers for GET/HEAD requests for a file with the given metadata
251 * @param $metadata mixed Result of the getMetadata() function of this handler for a file
252 * @return Array
253 */
254 public function getStreamHeaders( $metadata ) {
255 return array();
256 }
257
258 /**
259 * True if the handled types can be transformed
260 * @return bool
261 */
262 function canRender( $file ) {
263 return true;
264 }
265
266 /**
267 * True if handled types cannot be displayed directly in a browser
268 * but can be rendered
269 * @return bool
270 */
271 function mustRender( $file ) {
272 return false;
273 }
274
275 /**
276 * True if the type has multi-page capabilities
277 * @return bool
278 */
279 function isMultiPage( $file ) {
280 return false;
281 }
282
283 /**
284 * Page count for a multi-page document, false if unsupported or unknown
285 * @return bool
286 */
287 function pageCount( $file ) {
288 return false;
289 }
290
291 /**
292 * The material is vectorized and thus scaling is lossless
293 * @return bool
294 */
295 function isVectorized( $file ) {
296 return false;
297 }
298
299 /**
300 * The material is an image, and is animated.
301 * In particular, video material need not return true.
302 * @note Before 1.20, this was a method of ImageHandler only
303 * @return bool
304 */
305 function isAnimatedImage( $file ) {
306 return false;
307 }
308
309 /**
310 * If the material is animated, we can animate the thumbnail
311 * @since 1.20
312 * @return bool If material is not animated, handler may return any value.
313 */
314 function canAnimateThumbnail( $file ) {
315 return true;
316 }
317
318 /**
319 * False if the handler is disabled for all files
320 * @return bool
321 */
322 function isEnabled() {
323 return true;
324 }
325
326 /**
327 * Get an associative array of page dimensions
328 * Currently "width" and "height" are understood, but this might be
329 * expanded in the future.
330 * Returns false if unknown or if the document is not multi-page.
331 *
332 * @param $image File
333 * @param $page Unused, left for backcompatibility?
334 * @return array
335 */
336 function getPageDimensions( $image, $page ) {
337 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
338 return array(
339 'width' => $gis[0],
340 'height' => $gis[1]
341 );
342 }
343
344 /**
345 * Generic getter for text layer.
346 * Currently overloaded by PDF and DjVu handlers
347 * @return bool
348 */
349 function getPageText( $image, $page ) {
350 return false;
351 }
352
353 /**
354 * Get an array structure that looks like this:
355 *
356 * array(
357 * 'visible' => array(
358 * 'Human-readable name' => 'Human readable value',
359 * ...
360 * ),
361 * 'collapsed' => array(
362 * 'Human-readable name' => 'Human readable value',
363 * ...
364 * )
365 * )
366 * The UI will format this into a table where the visible fields are always
367 * visible, and the collapsed fields are optionally visible.
368 *
369 * The function should return false if there is no metadata to display.
370 */
371
372 /**
373 * @todo FIXME: I don't really like this interface, it's not very flexible
374 * I think the media handler should generate HTML instead. It can do
375 * all the formatting according to some standard. That makes it possible
376 * to do things like visual indication of grouped and chained streams
377 * in ogg container files.
378 * @return bool
379 */
380 function formatMetadata( $image ) {
381 return false;
382 }
383
384 /** sorts the visible/invisible field.
385 * Split off from ImageHandler::formatMetadata, as used by more than
386 * one type of handler.
387 *
388 * This is used by the media handlers that use the FormatMetadata class
389 *
390 * @param array $metadataArray metadata array
391 * @return array for use displaying metadata.
392 */
393 function formatMetadataHelper( $metadataArray ) {
394 $result = array(
395 'visible' => array(),
396 'collapsed' => array()
397 );
398
399 $formatted = FormatMetadata::getFormattedData( $metadataArray );
400 // Sort fields into visible and collapsed
401 $visibleFields = $this->visibleMetadataFields();
402 foreach ( $formatted as $name => $value ) {
403 $tag = strtolower( $name );
404 self::addMeta( $result,
405 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
406 'exif',
407 $tag,
408 $value
409 );
410 }
411 return $result;
412 }
413
414 /**
415 * Get a list of metadata items which should be displayed when
416 * the metadata table is collapsed.
417 *
418 * @return array of strings
419 * @access protected
420 */
421 function visibleMetadataFields() {
422 $fields = array();
423 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
424 foreach ( $lines as $line ) {
425 $matches = array();
426 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
427 $fields[] = $matches[1];
428 }
429 }
430 $fields = array_map( 'strtolower', $fields );
431 return $fields;
432 }
433
434 /**
435 * This is used to generate an array element for each metadata value
436 * That array is then used to generate the table of metadata values
437 * on the image page
438 *
439 * @param &$array Array An array containing elements for each type of visibility
440 * and each of those elements being an array of metadata items. This function adds
441 * a value to that array.
442 * @param string $visibility ('visible' or 'collapsed') if this value is hidden
443 * by default.
444 * @param string $type type of metadata tag (currently always 'exif')
445 * @param string $id the name of the metadata tag (like 'artist' for example).
446 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
447 * @param string $value thingy goes into a wikitext table; it used to be escaped but
448 * that was incompatible with previous practise of customized display
449 * with wikitext formatting via messages such as 'exif-model-value'.
450 * So the escaping is taken back out, but generally this seems a confusing
451 * interface.
452 * @param string $param value to pass to the message for the name of the field
453 * as $1. Currently this parameter doesn't seem to ever be used.
454 *
455 * Note, everything here is passed through the parser later on (!)
456 */
457 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
458 $msg = wfMessage( "$type-$id", $param );
459 if ( $msg->exists() ) {
460 $name = $msg->text();
461 } else {
462 // This is for future compatibility when using instant commons.
463 // So as to not display as ugly a name if a new metadata
464 // property is defined that we don't know about
465 // (not a major issue since such a property would be collapsed
466 // by default).
467 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
468 $name = wfEscapeWikiText( $id );
469 }
470 $array[$visibility][] = array(
471 'id' => "$type-$id",
472 'name' => $name,
473 'value' => $value
474 );
475 }
476
477 /**
478 * @param $file File
479 * @return string
480 */
481 function getShortDesc( $file ) {
482 global $wgLang;
483 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
484 }
485
486 /**
487 * @param $file File
488 * @return string
489 */
490 function getLongDesc( $file ) {
491 global $wgLang;
492 return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
493 $file->getMimeType() )->parse();
494 }
495
496 /**
497 * @param $file File
498 * @return string
499 */
500 static function getGeneralShortDesc( $file ) {
501 global $wgLang;
502 return $wgLang->formatSize( $file->getSize() );
503 }
504
505 /**
506 * @param $file File
507 * @return string
508 */
509 static function getGeneralLongDesc( $file ) {
510 global $wgLang;
511 return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
512 $file->getMimeType() )->parse();
513 }
514
515 /**
516 * Calculate the largest thumbnail width for a given original file size
517 * such that the thumbnail's height is at most $maxHeight.
518 * @param $boxWidth Integer Width of the thumbnail box.
519 * @param $boxHeight Integer Height of the thumbnail box.
520 * @param $maxHeight Integer Maximum height expected for the thumbnail.
521 * @return Integer.
522 */
523 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
524 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
525 $roundedUp = ceil( $idealWidth );
526 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
527 return floor( $idealWidth );
528 } else {
529 return $roundedUp;
530 }
531 }
532
533 function getDimensionsString( $file ) {
534 return '';
535 }
536
537 /**
538 * Modify the parser object post-transform
539 */
540 function parserTransformHook( $parser, $file ) {}
541
542 /**
543 * File validation hook called on upload.
544 *
545 * If the file at the given local path is not valid, or its MIME type does not
546 * match the handler class, a Status object should be returned containing
547 * relevant errors.
548 *
549 * @param string $fileName The local path to the file.
550 * @return Status object
551 */
552 function verifyUpload( $fileName ) {
553 return Status::newGood();
554 }
555
556 /**
557 * Check for zero-sized thumbnails. These can be generated when
558 * no disk space is available or some other error occurs
559 *
560 * @param string $dstPath The location of the suspect file
561 * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
562 * @return bool True if removed, false otherwise
563 */
564 function removeBadFile( $dstPath, $retval = 0 ) {
565 if ( file_exists( $dstPath ) ) {
566 $thumbstat = stat( $dstPath );
567 if ( $thumbstat['size'] == 0 || $retval != 0 ) {
568 $result = unlink( $dstPath );
569
570 if ( $result ) {
571 wfDebugLog( 'thumbnail',
572 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
573 $thumbstat['size'], $dstPath ) );
574 } else {
575 wfDebugLog( 'thumbnail',
576 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
577 $thumbstat['size'], $dstPath ) );
578 }
579 return true;
580 }
581 }
582 return false;
583 }
584
585 /**
586 * Remove files from the purge list
587 *
588 * @param array $files
589 * @param array $options
590 */
591 public function filterThumbnailPurgeList( &$files, $options ) {
592 // Do nothing
593 }
594
595 /*
596 * True if the handler can rotate the media
597 * @since 1.21
598 * @return bool
599 */
600 public static function canRotate() {
601 return false;
602 }
603 }