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