Move the () surrounding description strings of files, out of the description and...
[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 * The material is vectorized and thus scaling is lossless
166 */
167 function isVectorized( $file ) { return false; }
168 /**
169 * False if the handler is disabled for all files
170 */
171 function isEnabled() { return true; }
172
173 /**
174 * Get an associative array of page dimensions
175 * Currently "width" and "height" are understood, but this might be
176 * expanded in the future.
177 * Returns false if unknown or if the document is not multi-page.
178 */
179 function getPageDimensions( $image, $page ) {
180 $gis = $this->getImageSize( $image, $image->getPath() );
181 return array(
182 'width' => $gis[0],
183 'height' => $gis[1]
184 );
185 }
186
187 /**
188 * Generic getter for text layer.
189 * Currently overloaded by PDF and DjVu handlers
190 */
191 function getPageText( $image, $page ) {
192 return false;
193 }
194
195 /**
196 * Get an array structure that looks like this:
197 *
198 * array(
199 * 'visible' => array(
200 * 'Human-readable name' => 'Human readable value',
201 * ...
202 * ),
203 * 'collapsed' => array(
204 * 'Human-readable name' => 'Human readable value',
205 * ...
206 * )
207 * )
208 * The UI will format this into a table where the visible fields are always
209 * visible, and the collapsed fields are optionally visible.
210 *
211 * The function should return false if there is no metadata to display.
212 */
213
214 /**
215 * FIXME: I don't really like this interface, it's not very flexible
216 * I think the media handler should generate HTML instead. It can do
217 * all the formatting according to some standard. That makes it possible
218 * to do things like visual indication of grouped and chained streams
219 * in ogg container files.
220 */
221 function formatMetadata( $image ) {
222 return false;
223 }
224
225 /**
226 * @todo Fixme: document this!
227 * 'value' thingy goes into a wikitext table; it used to be escaped but
228 * that was incompatible with previous practice of customized display
229 * with wikitext formatting via messages such as 'exif-model-value'.
230 * So the escaping is taken back out, but generally this seems a confusing
231 * interface.
232 */
233 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
234 $array[$visibility][] = array(
235 'id' => "$type-$id",
236 'name' => wfMsg( "$type-$id", $param ),
237 'value' => $value
238 );
239 }
240
241 function getShortDesc( $file ) {
242 global $wgLang;
243 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
244 $wgLang->formatNum( $file->getSize() ) );
245 return "$nbytes";
246 }
247
248 function getLongDesc( $file ) {
249 global $wgUser;
250 $sk = $wgUser->getSkin();
251 return wfMsgExt( 'file-info', 'parseinline',
252 $sk->formatSize( $file->getSize() ),
253 $file->getMimeType() );
254 }
255
256 static function getGeneralShortDesc( $file ) {
257 global $wgLang;
258 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
259 $wgLang->formatNum( $file->getSize() ) );
260 return "$nbytes";
261 }
262
263 static function getGeneralLongDesc( $file ) {
264 global $wgUser;
265 $sk = $wgUser->getSkin();
266 return wfMsgExt( 'file-info', 'parseinline',
267 $sk->formatSize( $file->getSize() ),
268 $file->getMimeType() );
269 }
270
271 function getDimensionsString( $file ) {
272 return '';
273 }
274
275 /**
276 * Modify the parser object post-transform
277 */
278 function parserTransformHook( $parser, $file ) {}
279
280 /**
281 * File validation hook called on upload.
282 *
283 * If the file at the given local path is not valid, or its MIME type does not
284 * match the handler class, a Status object should be returned containing
285 * relevant errors.
286 *
287 * @param $fileName The local path to the file.
288 * @return Status object
289 */
290 function verifyUpload( $fileName ) {
291 return Status::newGood();
292 }
293
294 /**
295 * Check for zero-sized thumbnails. These can be generated when
296 * no disk space is available or some other error occurs
297 *
298 * @param $dstPath The location of the suspect file
299 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
300 * @return true if removed, false otherwise
301 */
302 function removeBadFile( $dstPath, $retval = 0 ) {
303 if( file_exists( $dstPath ) ) {
304 $thumbstat = stat( $dstPath );
305 if( $thumbstat['size'] == 0 || $retval != 0 ) {
306 wfDebugLog( 'thumbnail',
307 sprintf( 'Removing bad %d-byte thumbnail "%s"',
308 $thumbstat['size'], $dstPath ) );
309 unlink( $dstPath );
310 return true;
311 }
312 }
313 return false;
314 }
315 }
316
317 /**
318 * Media handler abstract base class for images
319 *
320 * @ingroup Media
321 */
322 abstract class ImageHandler extends MediaHandler {
323 function canRender( $file ) {
324 if ( $file->getWidth() && $file->getHeight() ) {
325 return true;
326 } else {
327 return false;
328 }
329 }
330
331 function getParamMap() {
332 return array( 'img_width' => 'width' );
333 }
334
335 function validateParam( $name, $value ) {
336 if ( in_array( $name, array( 'width', 'height' ) ) ) {
337 if ( $value <= 0 ) {
338 return false;
339 } else {
340 return true;
341 }
342 } else {
343 return false;
344 }
345 }
346
347 function makeParamString( $params ) {
348 if ( isset( $params['physicalWidth'] ) ) {
349 $width = $params['physicalWidth'];
350 } elseif ( isset( $params['width'] ) ) {
351 $width = $params['width'];
352 } else {
353 throw new MWException( 'No width specified to '.__METHOD__ );
354 }
355 # Removed for ProofreadPage
356 #$width = intval( $width );
357 return "{$width}px";
358 }
359
360 function parseParamString( $str ) {
361 $m = false;
362 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
363 return array( 'width' => $m[1] );
364 } else {
365 return false;
366 }
367 }
368
369 function getScriptParams( $params ) {
370 return array( 'width' => $params['width'] );
371 }
372
373 function normaliseParams( $image, &$params ) {
374 $mimeType = $image->getMimeType();
375
376 if ( !isset( $params['width'] ) ) {
377 return false;
378 }
379
380 if ( !isset( $params['page'] ) ) {
381 $params['page'] = 1;
382 } else {
383 if ( $params['page'] > $image->pageCount() ) {
384 $params['page'] = $image->pageCount();
385 }
386
387 if ( $params['page'] < 1 ) {
388 $params['page'] = 1;
389 }
390 }
391
392 $srcWidth = $image->getWidth( $params['page'] );
393 $srcHeight = $image->getHeight( $params['page'] );
394 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
395 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
396 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
397 }
398 }
399 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
400 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
401 return false;
402 }
403 return true;
404 }
405
406 /**
407 * Get a transform output object without actually doing the transform
408 */
409 function getTransform( $image, $dstPath, $dstUrl, $params ) {
410 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
411 }
412
413 /**
414 * Validate thumbnail parameters and fill in the correct height
415 *
416 * @param $width Integer: specified width (input/output)
417 * @param $height Integer: height (output only)
418 * @param $srcWidth Integer: width of the source image
419 * @param $srcHeight Integer: height of the source image
420 * @param $mimeType Unused
421 * @return false to indicate that an error should be returned to the user.
422 */
423 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
424 $width = intval( $width );
425
426 # Sanity check $width
427 if( $width <= 0) {
428 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
429 return false;
430 }
431 if ( $srcWidth <= 0 ) {
432 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
433 return false;
434 }
435
436 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
437 return true;
438 }
439
440 function getScriptedTransform( $image, $script, $params ) {
441 if ( !$this->normaliseParams( $image, $params ) ) {
442 return false;
443 }
444 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
445 $page = isset( $params['page'] ) ? $params['page'] : false;
446
447 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
448 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
449 }
450 }
451
452 function getImageSize( $image, $path ) {
453 wfSuppressWarnings();
454 $gis = getimagesize( $path );
455 wfRestoreWarnings();
456 return $gis;
457 }
458
459 function isAnimatedImage( $image ) {
460 return false;
461 }
462
463 function getShortDesc( $file ) {
464 global $wgLang;
465 $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
466 $wgLang->formatNum( $file->getSize() ) );
467 $widthheight = wfMsgHtml( 'widthheight', $wgLang->formatNum( $file->getWidth() ) ,$wgLang->formatNum( $file->getHeight() ) );
468
469 return "$widthheight ($nbytes)";
470 }
471
472 function getLongDesc( $file ) {
473 global $wgLang;
474 return wfMsgExt('file-info-size', 'parseinline',
475 $wgLang->formatNum( $file->getWidth() ),
476 $wgLang->formatNum( $file->getHeight() ),
477 $wgLang->formatSize( $file->getSize() ),
478 $file->getMimeType() );
479 }
480
481 function getDimensionsString( $file ) {
482 global $wgLang;
483 $pages = $file->pageCount();
484 $width = $wgLang->formatNum( $file->getWidth() );
485 $height = $wgLang->formatNum( $file->getHeight() );
486 $pagesFmt = $wgLang->formatNum( $pages );
487
488 if ( $pages > 1 ) {
489 return wfMsgExt( 'widthheightpage', 'parsemag', $width, $height, $pagesFmt );
490 } else {
491 return wfMsg( 'widthheight', $width, $height );
492 }
493 }
494 }