9dbd7e30dbea97b97abc1716af8d0be4f7870d40
[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 * Check for zero-sized thumbnails. These can be generated when
278 * no disk space is available or some other error occurs
279 *
280 * @param $dstPath The location of the suspect file
281 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
282 * @return true if removed, false otherwise
283 */
284 function removeBadFile( $dstPath, $retval = 0 ) {
285 if( file_exists( $dstPath ) ) {
286 $thumbstat = stat( $dstPath );
287 if( $thumbstat['size'] == 0 || $retval != 0 ) {
288 wfDebugLog( 'thumbnail',
289 sprintf( 'Removing bad %d-byte thumbnail "%s"',
290 $thumbstat['size'], $dstPath ) );
291 unlink( $dstPath );
292 return true;
293 }
294 }
295 return false;
296 }
297 }
298
299 /**
300 * Media handler abstract base class for images
301 *
302 * @ingroup Media
303 */
304 abstract class ImageHandler extends MediaHandler {
305 function canRender( $file ) {
306 if ( $file->getWidth() && $file->getHeight() ) {
307 return true;
308 } else {
309 return false;
310 }
311 }
312
313 function getParamMap() {
314 return array( 'img_width' => 'width' );
315 }
316
317 function validateParam( $name, $value ) {
318 if ( in_array( $name, array( 'width', 'height' ) ) ) {
319 if ( $value <= 0 ) {
320 return false;
321 } else {
322 return true;
323 }
324 } else {
325 return false;
326 }
327 }
328
329 function makeParamString( $params ) {
330 if ( isset( $params['physicalWidth'] ) ) {
331 $width = $params['physicalWidth'];
332 } elseif ( isset( $params['width'] ) ) {
333 $width = $params['width'];
334 } else {
335 throw new MWException( 'No width specified to '.__METHOD__ );
336 }
337 # Removed for ProofreadPage
338 #$width = intval( $width );
339 return "{$width}px";
340 }
341
342 function parseParamString( $str ) {
343 $m = false;
344 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
345 return array( 'width' => $m[1] );
346 } else {
347 return false;
348 }
349 }
350
351 function getScriptParams( $params ) {
352 return array( 'width' => $params['width'] );
353 }
354
355 function normaliseParams( $image, &$params ) {
356 $mimeType = $image->getMimeType();
357
358 if ( !isset( $params['width'] ) ) {
359 return false;
360 }
361
362 if ( !isset( $params['page'] ) ) {
363 $params['page'] = 1;
364 } else {
365 if ( $params['page'] > $image->pageCount() ) {
366 $params['page'] = $image->pageCount();
367 }
368
369 if ( $params['page'] < 1 ) {
370 $params['page'] = 1;
371 }
372 }
373
374 $srcWidth = $image->getWidth( $params['page'] );
375 $srcHeight = $image->getHeight( $params['page'] );
376 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
377 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
378 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
379 }
380 }
381 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
382 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
383 return false;
384 }
385 return true;
386 }
387
388 /**
389 * Get a transform output object without actually doing the transform
390 */
391 function getTransform( $image, $dstPath, $dstUrl, $params ) {
392 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
393 }
394
395 /**
396 * Validate thumbnail parameters and fill in the correct height
397 *
398 * @param $width Integer: specified width (input/output)
399 * @param $height Integer: height (output only)
400 * @param $srcWidth Integer: width of the source image
401 * @param $srcHeight Integer: height of the source image
402 * @param $mimeType Unused
403 * @return false to indicate that an error should be returned to the user.
404 */
405 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
406 $width = intval( $width );
407
408 # Sanity check $width
409 if( $width <= 0) {
410 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
411 return false;
412 }
413 if ( $srcWidth <= 0 ) {
414 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
415 return false;
416 }
417
418 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
419 return true;
420 }
421
422 function getScriptedTransform( $image, $script, $params ) {
423 if ( !$this->normaliseParams( $image, $params ) ) {
424 return false;
425 }
426 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
427 $page = isset( $params['page'] ) ? $params['page'] : false;
428
429 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
430 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
431 }
432 }
433
434 function getImageSize( $image, $path ) {
435 wfSuppressWarnings();
436 $gis = getimagesize( $path );
437 wfRestoreWarnings();
438 return $gis;
439 }
440
441 function isAnimatedImage( $image ) {
442 return false;
443 }
444
445 function getShortDesc( $file ) {
446 global $wgLang;
447 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
448 $wgLang->formatNum( $file->getSize() ) );
449 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
450
451 return "$widthheight ($nbytes)";
452 }
453
454 function getLongDesc( $file ) {
455 global $wgLang;
456 return wfMsgExt('file-info-size', 'parseinline',
457 $wgLang->formatNum( $file->getWidth() ),
458 $wgLang->formatNum( $file->getHeight() ),
459 $wgLang->formatSize( $file->getSize() ),
460 $file->getMimeType() );
461 }
462
463 function getDimensionsString( $file ) {
464 global $wgLang;
465 $pages = $file->pageCount();
466 $width = $wgLang->formatNum( $file->getWidth() );
467 $height = $wgLang->formatNum( $file->getHeight() );
468 $pagesFmt = $wgLang->formatNum( $pages );
469
470 if ( $pages > 1 ) {
471 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
472 } else {
473 return wfMsg( 'widthheight', $width, $height );
474 }
475 }
476 }