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