* Confirmation is now required when deleting old versions of files
[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 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
199 $array[$visibility][] = array(
200 'id' => "$type-$id",
201 'name' => wfMsg( "$type-$id", $param ),
202 'value' => wfEscapeWikiText( $value )
203 );
204 }
205
206 function getShortDesc( $file ) {
207 global $wgLang;
208 $nbytes = '(' . wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
209 $wgLang->formatNum( $file->getSize() ) ) . ')';
210 }
211
212 function getLongDesc( $file ) {
213 global $wgUser;
214 $sk = $wgUser->getSkin();
215 return wfMsg( 'file-info', $sk->formatSize( $file->getSize() ), $file->getMimeType() );
216 }
217
218 function getDimensionsString() {
219 return '';
220 }
221
222 /**
223 * Modify the parser object post-transform
224 */
225 function parserTransformHook( $parser, $file ) {}
226 }
227
228 /**
229 * Media handler abstract base class for images
230 *
231 * @addtogroup Media
232 */
233 abstract class ImageHandler extends MediaHandler {
234 function canRender( $file ) {
235 if ( $file->getWidth() && $file->getHeight() ) {
236 return true;
237 } else {
238 return false;
239 }
240 }
241
242 function getParamMap() {
243 return array( 'img_width' => 'width' );
244 }
245
246 function validateParam( $name, $value ) {
247 if ( in_array( $name, array( 'width', 'height' ) ) ) {
248 if ( $value <= 0 ) {
249 return false;
250 } else {
251 return true;
252 }
253 } else {
254 return false;
255 }
256 }
257
258 function makeParamString( $params ) {
259 if ( isset( $params['physicalWidth'] ) ) {
260 $width = $params['physicalWidth'];
261 } elseif ( isset( $params['width'] ) ) {
262 $width = $params['width'];
263 } else {
264 throw new MWException( 'No width specified to '.__METHOD__ );
265 }
266 # Removed for ProofreadPage
267 #$width = intval( $width );
268 return "{$width}px";
269 }
270
271 function parseParamString( $str ) {
272 $m = false;
273 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
274 return array( 'width' => $m[1] );
275 } else {
276 return false;
277 }
278 }
279
280 function getScriptParams( $params ) {
281 return array( 'width' => $params['width'] );
282 }
283
284 function normaliseParams( $image, &$params ) {
285 $mimeType = $image->getMimeType();
286
287 if ( !isset( $params['width'] ) ) {
288 return false;
289 }
290 if ( !isset( $params['page'] ) ) {
291 $params['page'] = 1;
292 }
293 $srcWidth = $image->getWidth( $params['page'] );
294 $srcHeight = $image->getHeight( $params['page'] );
295 if ( isset( $params['height'] ) && $params['height'] != -1 ) {
296 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
297 $params['width'] = wfFitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
298 }
299 }
300 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
301 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
302 return false;
303 }
304 return true;
305 }
306
307 /**
308 * Get a transform output object without actually doing the transform
309 */
310 function getTransform( $image, $dstPath, $dstUrl, $params ) {
311 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
312 }
313
314 /**
315 * Validate thumbnail parameters and fill in the correct height
316 *
317 * @param integer &$width Specified width (input/output)
318 * @param integer &$height Height (output only)
319 * @return false to indicate that an error should be returned to the user.
320 */
321 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
322 $width = intval( $width );
323
324 # Sanity check $width
325 if( $width <= 0) {
326 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
327 return false;
328 }
329 if ( $srcWidth <= 0 ) {
330 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
331 return false;
332 }
333
334 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
335 return true;
336 }
337
338 function getScriptedTransform( $image, $script, $params ) {
339 if ( !$this->normaliseParams( $image, $params ) ) {
340 return false;
341 }
342 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
343 return new ThumbnailImage( $url, $params['width'], $params['height'] );
344 }
345
346 /**
347 * Check for zero-sized thumbnails. These can be generated when
348 * no disk space is available or some other error occurs
349 *
350 * @param $dstPath The location of the suspect file
351 * @param $retval Return value of some shell process, file will be deleted if this is non-zero
352 * @return true if removed, false otherwise
353 */
354 function removeBadFile( $dstPath, $retval = 0 ) {
355 if( file_exists( $dstPath ) ) {
356 $thumbstat = stat( $dstPath );
357 if( $thumbstat['size'] == 0 || $retval != 0 ) {
358 wfDebugLog( 'thumbnail',
359 sprintf( 'Removing bad %d-byte thumbnail "%s"',
360 $thumbstat['size'], $dstPath ) );
361 unlink( $dstPath );
362 return true;
363 }
364 }
365 return false;
366 }
367
368 function getImageSize( $image, $path ) {
369 wfSuppressWarnings();
370 $gis = getimagesize( $path );
371 wfRestoreWarnings();
372 return $gis;
373 }
374
375 function getShortDesc( $file ) {
376 global $wgLang;
377 $nbytes = '(' . wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
378 $wgLang->formatNum( $file->getSize() ) ) . ')';
379 $widthheight = wfMsgHtml( 'widthheight', $file->getWidth(), $file->getHeight() );
380
381 return "$widthheight ($nbytes)";
382 }
383
384 function getLongDesc( $file ) {
385 global $wgLang;
386 return wfMsgHtml('file-info-size', $file->getWidth(), $file->getHeight(),
387 $wgLang->formatSize( $file->getSize() ), $file->getMimeType() );
388 }
389
390 function getDimensionsString( $file ) {
391 $pages = $file->pageCount();
392 if ( $pages > 1 ) {
393 return wfMsg( 'widthheightpage', $file->getWidth(), $file->getHeight(), $pages );
394 } else {
395 return wfMsg( 'widthheight', $file->getWidth(), $file->getHeight() );
396 }
397 }
398 }
399
400
401