If the unknown element is empty, there won't be a matching END_ELEMENT. There's nothi...
[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
17 /**
18 * Instance cache
19 */
20 static $handlers = array();
21
22 /**
23 * Get a MediaHandler for a given MIME type from the instance cache
24 *
25 * @return MediaHandler
26 */
27 static function getHandler( $type ) {
28 global $wgMediaHandlers;
29 if ( !isset( $wgMediaHandlers[$type] ) ) {
30 wfDebug( __METHOD__ . ": no handler found for $type.\n");
31 return false;
32 }
33 $class = $wgMediaHandlers[$type];
34 if ( !isset( self::$handlers[$class] ) ) {
35 self::$handlers[$class] = new $class;
36 if ( !self::$handlers[$class]->isEnabled() ) {
37 self::$handlers[$class] = false;
38 }
39 }
40 return self::$handlers[$class];
41 }
42
43 /**
44 * Get an associative array mapping magic word IDs to parameter names.
45 * Will be used by the parser to identify parameters.
46 */
47 abstract function getParamMap();
48
49 /*
50 * Validate a thumbnail parameter at parse time.
51 * Return true to accept the parameter, and false to reject it.
52 * If you return false, the parser will do something quiet and forgiving.
53 */
54 abstract function validateParam( $name, $value );
55
56 /**
57 * Merge a parameter array into a string appropriate for inclusion in filenames
58 */
59 abstract function makeParamString( $params );
60
61 /**
62 * Parse a param string made with makeParamString back into an array
63 */
64 abstract function parseParamString( $str );
65
66 /**
67 * Changes the parameter array as necessary, ready for transformation.
68 * Should be idempotent.
69 * Returns false if the parameters are unacceptable and the transform should fail
70 */
71 abstract function normaliseParams( $image, &$params );
72
73 /**
74 * Get an image size array like that returned by getimagesize(), or false if it
75 * can't be determined.
76 *
77 * @param $image File: the image object, or false if there isn't one
78 * @param $path String: the filename
79 * @return Array
80 */
81 abstract function getImageSize( $image, $path );
82
83 /**
84 * Get handler-specific metadata which will be saved in the img_metadata field.
85 *
86 * @param $image File: the image object, or false if there isn't one
87 * @param $path String: the filename
88 * @return String
89 */
90 function getMetadata( $image, $path ) { return ''; }
91
92 /**
93 * Get a string describing the type of metadata, for display purposes.
94 */
95 function getMetadataType( $image ) { return false; }
96
97 /**
98 * Check if the metadata string is valid for this handler.
99 * If it returns false, Image will reload the metadata from the file and update the database
100 */
101 function isMetadataValid( $image, $metadata ) { return true; }
102
103
104 /**
105 * Get a MediaTransformOutput object representing an alternate of the transformed
106 * output which will call an intermediary thumbnail assist script.
107 *
108 * Used when the repository has a thumbnailScriptUrl option configured.
109 *
110 * Return false to fall back to the regular getTransform().
111 */
112 function getScriptedTransform( $image, $script, $params ) {
113 return false;
114 }
115
116 /**
117 * Get a MediaTransformOutput object representing the transformed output. Does not
118 * actually do the transform.
119 *
120 * @param $image File: the image object
121 * @param $dstPath String: filesystem destination path
122 * @param $dstUrl String: Destination URL to use in output HTML
123 * @param $params Array: Arbitrary set of parameters validated by $this->validateParam()
124 */
125 function getTransform( $image, $dstPath, $dstUrl, $params ) {
126 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
127 }
128
129 /**
130 * Get a MediaTransformOutput object representing the transformed output. Does the
131 * transform unless $flags contains self::TRANSFORM_LATER.
132 *
133 * @param $image File: the image object
134 * @param $dstPath String: filesystem destination path
135 * @param $dstUrl String: destination URL to use in output HTML
136 * @param $params Array: arbitrary set of parameters validated by $this->validateParam()
137 * @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
138 */
139 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
140
141 /**
142 * Get the thumbnail extension and MIME type for a given source MIME type
143 * @return array thumbnail extension and MIME type
144 */
145 function getThumbType( $ext, $mime, $params = null ) {
146 $magic = MimeMagic::singleton();
147 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
148 // The extension is not valid for this mime type and we do
149 // recognize the mime type
150 $extensions = $magic->getExtensionsForType( $mime );
151 if ( $extensions ) {
152 return array( strtok( $extensions, ' ' ), $mime );
153 }
154 }
155
156 // The extension is correct (true) or the mime type is unknown to
157 // MediaWiki (null)
158 return array( $ext, $mime );
159 }
160
161 /**
162 * True if the handled types can be transformed
163 */
164 function canRender( $file ) { return true; }
165 /**
166 * True if handled types cannot be displayed directly in a browser
167 * but can be rendered
168 */
169 function mustRender( $file ) { return false; }
170 /**
171 * True if the type has multi-page capabilities
172 */
173 function isMultiPage( $file ) { return false; }
174 /**
175 * Page count for a multi-page document, false if unsupported or unknown
176 */
177 function pageCount( $file ) { return false; }
178 /**
179 * The material is vectorized and thus scaling is lossless
180 */
181 function isVectorized( $file ) { return false; }
182 /**
183 * False if the handler is disabled for all files
184 */
185 function isEnabled() { return true; }
186
187 /**
188 * Get an associative array of page dimensions
189 * Currently "width" and "height" are understood, but this might be
190 * expanded in the future.
191 * Returns false if unknown or if the document is not multi-page.
192 *
193 * @param $image File
194 */
195 function getPageDimensions( $image, $page ) {
196 $gis = $this->getImageSize( $image, $image->getPath() );
197 return array(
198 'width' => $gis[0],
199 'height' => $gis[1]
200 );
201 }
202
203 /**
204 * Generic getter for text layer.
205 * Currently overloaded by PDF and DjVu handlers
206 */
207 function getPageText( $image, $page ) {
208 return false;
209 }
210
211 /**
212 * Get an array structure that looks like this:
213 *
214 * array(
215 * 'visible' => array(
216 * 'Human-readable name' => 'Human readable value',
217 * ...
218 * ),
219 * 'collapsed' => array(
220 * 'Human-readable name' => 'Human readable value',
221 * ...
222 * )
223 * )
224 * The UI will format this into a table where the visible fields are always
225 * visible, and the collapsed fields are optionally visible.
226 *
227 * The function should return false if there is no metadata to display.
228 */
229
230 /**
231 * FIXME: I don't really like this interface, it's not very flexible
232 * I think the media handler should generate HTML instead. It can do
233 * all the formatting according to some standard. That makes it possible
234 * to do things like visual indication of grouped and chained streams
235 * in ogg container files.
236 */
237 function formatMetadata( $image ) {
238 return false;
239 }
240
241 /**
242 * @todo Fixme: document this!
243 * 'value' thingy goes into a wikitext table; it used to be escaped but
244 * that was incompatible with previous practice of customized display
245 * with wikitext formatting via messages such as 'exif-model-value'.
246 * So the escaping is taken back out, but generally this seems a confusing
247 * interface.
248 */
249 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
250 $array[$visibility][] = array(
251 'id' => "$type-$id",
252 'name' => wfMsg( "$type-$id", $param ),
253 'value' => $value
254 );
255 }
256
257 /**
258 * @param $file File
259 * @return string
260 */
261 function getShortDesc( $file ) {
262 global $wgLang;
263 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
264 $wgLang->formatNum( $file->getSize() ) );
265 return "$nbytes";
266 }
267
268 /**
269 * @param $file File
270 * @return string
271 */
272 function getLongDesc( $file ) {
273 global $wgUser;
274 $sk = $wgUser->getSkin();
275 return wfMsgExt( 'file-info', 'parseinline',
276 $sk->formatSize( $file->getSize() ),
277 $file->getMimeType() );
278 }
279
280 /**
281 * @param $file File
282 * @return string
283 */
284 static function getGeneralShortDesc( $file ) {
285 global $wgLang;
286 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
287 $wgLang->formatNum( $file->getSize() ) );
288 return "$nbytes";
289 }
290
291 /**
292 * @param $file File
293 * @return string
294 */
295 static function getGeneralLongDesc( $file ) {
296 global $wgUser;
297 $sk = $wgUser->getSkin();
298 return wfMsgExt( 'file-info', 'parseinline',
299 $sk->formatSize( $file->getSize() ),
300 $file->getMimeType() );
301 }
302
303 function getDimensionsString( $file ) {
304 return '';
305 }
306
307 /**
308 * Modify the parser object post-transform
309 */
310 function parserTransformHook( $parser, $file ) {}
311
312 /**
313 * File validation hook called on upload.
314 *
315 * If the file at the given local path is not valid, or its MIME type does not
316 * match the handler class, a Status object should be returned containing
317 * relevant errors.
318 *
319 * @param $fileName The local path to the file.
320 * @return Status object
321 */
322 function verifyUpload( $fileName ) {
323 return Status::newGood();
324 }
325
326 /**
327 * Check for zero-sized thumbnails. These can be generated when
328 * no disk space is available or some other error occurs
329 *
330 * @param $dstPath The location of the suspect file
331 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
332 * @return true if removed, false otherwise
333 */
334 function removeBadFile( $dstPath, $retval = 0 ) {
335 if( file_exists( $dstPath ) ) {
336 $thumbstat = stat( $dstPath );
337 if( $thumbstat['size'] == 0 || $retval != 0 ) {
338 wfDebugLog( 'thumbnail',
339 sprintf( 'Removing bad %d-byte thumbnail "%s"',
340 $thumbstat['size'], $dstPath ) );
341 unlink( $dstPath );
342 return true;
343 }
344 }
345 return false;
346 }
347 }
348
349 /**
350 * Media handler abstract base class for images
351 *
352 * @ingroup Media
353 */
354 abstract class ImageHandler extends MediaHandler {
355
356 /**
357 * @param $file File
358 * @return bool
359 */
360 function canRender( $file ) {
361 return ( $file->getWidth() && $file->getHeight() );
362 }
363
364 function getParamMap() {
365 return array( 'img_width' => 'width' );
366 }
367
368 function validateParam( $name, $value ) {
369 if ( in_array( $name, array( 'width', 'height' ) ) ) {
370 if ( $value <= 0 ) {
371 return false;
372 } else {
373 return true;
374 }
375 } else {
376 return false;
377 }
378 }
379
380 function makeParamString( $params ) {
381 if ( isset( $params['physicalWidth'] ) ) {
382 $width = $params['physicalWidth'];
383 } elseif ( isset( $params['width'] ) ) {
384 $width = $params['width'];
385 } else {
386 throw new MWException( 'No width specified to '.__METHOD__ );
387 }
388 # Removed for ProofreadPage
389 #$width = intval( $width );
390 return "{$width}px";
391 }
392
393 function parseParamString( $str ) {
394 $m = false;
395 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
396 return array( 'width' => $m[1] );
397 } else {
398 return false;
399 }
400 }
401
402 function getScriptParams( $params ) {
403 return array( 'width' => $params['width'] );
404 }
405
406 /**
407 * @param $image File
408 * @param $params
409 * @return bool
410 */
411 function normaliseParams( $image, &$params ) {
412 $mimeType = $image->getMimeType();
413
414 if ( !isset( $params['width'] ) ) {
415 return false;
416 }
417
418 if ( !isset( $params['page'] ) ) {
419 $params['page'] = 1;
420 } else {
421 if ( $params['page'] > $image->pageCount() ) {
422 $params['page'] = $image->pageCount();
423 }
424
425 if ( $params['page'] < 1 ) {
426 $params['page'] = 1;
427 }
428 }
429
430 $srcWidth = $image->getWidth( $params['page'] );
431 $srcHeight = $image->getHeight( $params['page'] );
432 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
433 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
434 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
435 }
436 }
437 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
438 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
439 return false;
440 }
441 return true;
442 }
443
444 /**
445 * Get a transform output object without actually doing the transform
446 */
447 function getTransform( $image, $dstPath, $dstUrl, $params ) {
448 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
449 }
450
451 /**
452 * Validate thumbnail parameters and fill in the correct height
453 *
454 * @param $width Integer: specified width (input/output)
455 * @param $height Integer: height (output only)
456 * @param $srcWidth Integer: width of the source image
457 * @param $srcHeight Integer: height of the source image
458 * @param $mimeType Unused
459 * @return false to indicate that an error should be returned to the user.
460 */
461 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
462 $width = intval( $width );
463
464 # Sanity check $width
465 if( $width <= 0) {
466 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
467 return false;
468 }
469 if ( $srcWidth <= 0 ) {
470 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
471 return false;
472 }
473
474 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
475 return true;
476 }
477
478 /**
479 * @param $image File
480 * @param $script
481 * @param $params
482 * @return bool|ThumbnailImage
483 */
484 function getScriptedTransform( $image, $script, $params ) {
485 if ( !$this->normaliseParams( $image, $params ) ) {
486 return false;
487 }
488 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
489 $page = isset( $params['page'] ) ? $params['page'] : false;
490
491 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
492 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
493 }
494 }
495
496 function getImageSize( $image, $path ) {
497 wfSuppressWarnings();
498 $gis = getimagesize( $path );
499 wfRestoreWarnings();
500 return $gis;
501 }
502
503 function isAnimatedImage( $image ) {
504 return false;
505 }
506
507 /**
508 * @param $file File
509 * @return string
510 */
511 function getShortDesc( $file ) {
512 global $wgLang;
513 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
514 $wgLang->formatNum( $file->getSize() ) );
515 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
516
517 return "$widthheight ($nbytes)";
518 }
519
520 /**
521 * @param $file File
522 * @return string
523 */
524 function getLongDesc( $file ) {
525 global $wgLang;
526 return wfMsgExt('file-info-size', 'parseinline',
527 $wgLang->formatNum( $file->getWidth() ),
528 $wgLang->formatNum( $file->getHeight() ),
529 $wgLang->formatSize( $file->getSize() ),
530 $file->getMimeType() );
531 }
532
533 /**
534 * @param $file File
535 * @return string
536 */
537 function getDimensionsString( $file ) {
538 global $wgLang;
539 $pages = $file->pageCount();
540 $width = $wgLang->formatNum( $file->getWidth() );
541 $height = $wgLang->formatNum( $file->getHeight() );
542 $pagesFmt = $wgLang->formatNum( $pages );
543
544 if ( $pages > 1 ) {
545 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
546 } else {
547 return wfMsg( 'widthheight', $width, $height );
548 }
549 }
550 }