* (bug 11065) Fix regression in handling of wiki-formatted EXIF metadata
[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 * Get a MediaTransformOutput object representing the transformed output. Does not
101 * actually do the transform.
102 *
103 * @param Image $image The image object
104 * @param string $dstPath Filesystem destination path
105 * @param string $dstUrl Destination URL to use in output HTML
106 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
107 */
108 function getTransform( $image, $dstPath, $dstUrl, $params ) {
109 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
110 }
111
112 /**
113 * Get a MediaTransformOutput object representing the transformed output. Does the
114 * transform unless $flags contains self::TRANSFORM_LATER.
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 * @param integer $flags A bitfield, may contain self::TRANSFORM_LATER
121 */
122 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
123
124 /**
125 * Get the thumbnail extension and MIME type for a given source MIME type
126 * @return array thumbnail extension and MIME type
127 */
128 function getThumbType( $ext, $mime ) {
129 return array( $ext, $mime );
130 }
131
132 /**
133 * True if the handled types can be transformed
134 */
135 function canRender( $file ) { return true; }
136 /**
137 * True if handled types cannot be displayed directly in a browser
138 * but can be rendered
139 */
140 function mustRender( $file ) { return false; }
141 /**
142 * True if the type has multi-page capabilities
143 */
144 function isMultiPage( $file ) { return false; }
145 /**
146 * Page count for a multi-page document, false if unsupported or unknown
147 */
148 function pageCount( $file ) { return false; }
149 /**
150 * False if the handler is disabled for all files
151 */
152 function isEnabled() { return true; }
153
154 /**
155 * Get an associative array of page dimensions
156 * Currently "width" and "height" are understood, but this might be
157 * expanded in the future.
158 * Returns false if unknown or if the document is not multi-page.
159 */
160 function getPageDimensions( $image, $page ) {
161 $gis = $this->getImageSize( $image, $image->getPath() );
162 return array(
163 'width' => $gis[0],
164 'height' => $gis[1]
165 );
166 }
167
168 /**
169 * Get an array structure that looks like this:
170 *
171 * array(
172 * 'visible' => array(
173 * 'Human-readable name' => 'Human readable value',
174 * ...
175 * ),
176 * 'collapsed' => array(
177 * 'Human-readable name' => 'Human readable value',
178 * ...
179 * )
180 * )
181 * The UI will format this into a table where the visible fields are always
182 * visible, and the collapsed fields are optionally visible.
183 *
184 * The function should return false if there is no metadata to display.
185 */
186
187 /**
188 * FIXME: I don't really like this interface, it's not very flexible
189 * I think the media handler should generate HTML instead. It can do
190 * all the formatting according to some standard. That makes it possible
191 * to do things like visual indication of grouped and chained streams
192 * in ogg container files.
193 */
194 function formatMetadata( $image, $metadata ) {
195 return false;
196 }
197
198 /**
199 * @fixme document this!
200 * 'value' thingy goes into a wikitext table; it used to be escaped but
201 * that was incompatible with previous practice of customized display
202 * with wikitext formatting via messages such as 'exif-model-value'.
203 * So the escaping is taken back out, but generally this seems a confusing
204 * interface.
205 */
206 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
207 $array[$visibility][] = array(
208 'id' => "$type-$id",
209 'name' => wfMsg( "$type-$id", $param ),
210 'value' => $value
211 );
212 }
213
214 function getShortDesc( $file ) {
215 global $wgLang;
216 $nbytes = '(' . wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
217 $wgLang->formatNum( $file->getSize() ) ) . ')';
218 return "$nbytes";
219 }
220
221 function getLongDesc( $file ) {
222 global $wgUser;
223 $sk = $wgUser->getSkin();
224 return wfMsg( 'file-info', $sk->formatSize( $file->getSize() ), $file->getMimeType() );
225 }
226
227 function getDimensionsString() {
228 return '';
229 }
230
231 /**
232 * Modify the parser object post-transform
233 */
234 function parserTransformHook( $parser, $file ) {}
235 }
236
237 /**
238 * Media handler abstract base class for images
239 *
240 * @addtogroup Media
241 */
242 abstract class ImageHandler extends MediaHandler {
243 function canRender( $file ) {
244 if ( $file->getWidth() && $file->getHeight() ) {
245 return true;
246 } else {
247 return false;
248 }
249 }
250
251 function getParamMap() {
252 return array( 'img_width' => 'width' );
253 }
254
255 function validateParam( $name, $value ) {
256 if ( in_array( $name, array( 'width', 'height' ) ) ) {
257 if ( $value <= 0 ) {
258 return false;
259 } else {
260 return true;
261 }
262 } else {
263 return false;
264 }
265 }
266
267 function makeParamString( $params ) {
268 if ( isset( $params['physicalWidth'] ) ) {
269 $width = $params['physicalWidth'];
270 } elseif ( isset( $params['width'] ) ) {
271 $width = $params['width'];
272 } else {
273 throw new MWException( 'No width specified to '.__METHOD__ );
274 }
275 # Removed for ProofreadPage
276 #$width = intval( $width );
277 return "{$width}px";
278 }
279
280 function parseParamString( $str ) {
281 $m = false;
282 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
283 return array( 'width' => $m[1] );
284 } else {
285 return false;
286 }
287 }
288
289 function getScriptParams( $params ) {
290 return array( 'width' => $params['width'] );
291 }
292
293 function normaliseParams( $image, &$params ) {
294 $mimeType = $image->getMimeType();
295
296 if ( !isset( $params['width'] ) ) {
297 return false;
298 }
299 if ( !isset( $params['page'] ) ) {
300 $params['page'] = 1;
301 }
302 $srcWidth = $image->getWidth( $params['page'] );
303 $srcHeight = $image->getHeight( $params['page'] );
304 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
305 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
306 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
307 }
308 }
309 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
310 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
311 return false;
312 }
313 return true;
314 }
315
316 /**
317 * Get a transform output object without actually doing the transform
318 */
319 function getTransform( $image, $dstPath, $dstUrl, $params ) {
320 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
321 }
322
323 /**
324 * Validate thumbnail parameters and fill in the correct height
325 *
326 * @param integer &$width Specified width (input/output)
327 * @param integer &$height Height (output only)
328 * @return false to indicate that an error should be returned to the user.
329 */
330 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
331 $width = intval( $width );
332
333 # Sanity check $width
334 if( $width <= 0) {
335 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
336 return false;
337 }
338 if ( $srcWidth <= 0 ) {
339 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
340 return false;
341 }
342
343 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
344 return true;
345 }
346
347 function getScriptedTransform( $image, $script, $params ) {
348 if ( !$this->normaliseParams( $image, $params ) ) {
349 return false;
350 }
351 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
352 return new ThumbnailImage( $url, $params['width'], $params['height'] );
353 }
354
355 /**
356 * Check for zero-sized thumbnails. These can be generated when
357 * no disk space is available or some other error occurs
358 *
359 * @param $dstPath The location of the suspect file
360 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
361 * @return true if removed, false otherwise
362 */
363 function removeBadFile( $dstPath, $retval = 0 ) {
364 if( file_exists( $dstPath ) ) {
365 $thumbstat = stat( $dstPath );
366 if( $thumbstat['size'] == 0 || $retval != 0 ) {
367 wfDebugLog( 'thumbnail',
368 sprintf( 'Removing bad %d-byte thumbnail "%s"',
369 $thumbstat['size'], $dstPath ) );
370 unlink( $dstPath );
371 return true;
372 }
373 }
374 return false;
375 }
376
377 function getImageSize( $image, $path ) {
378 wfSuppressWarnings();
379 $gis = getimagesize( $path );
380 wfRestoreWarnings();
381 return $gis;
382 }
383
384 function getShortDesc( $file ) {
385 global $wgLang;
386 $nbytes = '(' . wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
387 $wgLang->formatNum( $file->getSize() ) ) . ')';
388 $widthheight = wfMsgHtml( 'widthheight', $file->getWidth(), $file->getHeight() );
389
390 return "$widthheight ($nbytes)";
391 }
392
393 function getLongDesc( $file ) {
394 global $wgLang;
395 return wfMsgHtml('file-info-size', $file->getWidth(), $file->getHeight(),
396 $wgLang->formatSize( $file->getSize() ), $file->getMimeType() );
397 }
398
399 function getDimensionsString( $file ) {
400 $pages = $file->pageCount();
401 if ( $pages > 1 ) {
402 return wfMsg( 'widthheightpage', $file->getWidth(), $file->getHeight(), $pages );
403 } else {
404 return wfMsg( 'widthheight', $file->getWidth(), $file->getHeight() );
405 }
406 }
407 }
408
409
410