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