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