Apply timestampOrNull in the correct place, thanks to Brion for catching this.
[mediawiki.git] / includes / media / Generic.php
blob944f2789245654cb53dc14fe4908309342f52f4c
1 <?php
3 /**
4 * Media-handling base classes and generic functionality
5 */
7 /**
8 * Base media handler class
10 * @addtogroup Media
12 abstract class MediaHandler {
13 const TRANSFORM_LATER = 1;
15 /**
16 * Instance cache
18 static $handlers = array();
20 /**
21 * Get a MediaHandler for a given MIME type from the instance cache
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;
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;
36 return self::$handlers[$class];
39 /**
40 * Get an associative array mapping magic word IDs to parameter names.
41 * Will be used by the parser to identify parameters.
43 abstract function getParamMap();
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.
50 abstract function validateParam( $name, $value );
52 /**
53 * Merge a parameter array into a string appropriate for inclusion in filenames
55 abstract function makeParamString( $params );
57 /**
58 * Parse a param string made with makeParamString back into an array
60 abstract function parseParamString( $str );
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
67 abstract function normaliseParams( $image, &$params );
69 /**
70 * Get an image size array like that returned by getimagesize(), or false if it
71 * can't be determined.
73 * @param Image $image The image object, or false if there isn't one
74 * @param string $fileName The filename
75 * @return array
77 abstract function getImageSize( $image, $path );
79 /**
80 * Get handler-specific metadata which will be saved in the img_metadata field.
82 * @param Image $image The image object, or false if there isn't one
83 * @param string $fileName The filename
84 * @return string
86 function getMetadata( $image, $path ) { return ''; }
88 /**
89 * Get a string describing the type of metadata, for display purposes.
91 function getMetadataType( $image ) { return false; }
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
97 function isMetadataValid( $image, $metadata ) { return true; }
101 * Get a MediaTransformOutput object representing an alternate of the transformed
102 * output which will call an intermediary thumbnail assist script.
104 * Used when the repository has a thumbnailScriptUrl option configured.
106 * Return false to fall back to the regular getTransform().
108 function getScriptedTransform( $image, $script, $params ) {
109 return false;
113 * Get a MediaTransformOutput object representing the transformed output. Does not
114 * actually do the transform.
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()
121 function getTransform( $image, $dstPath, $dstUrl, $params ) {
122 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
126 * Get a MediaTransformOutput object representing the transformed output. Does the
127 * transform unless $flags contains self::TRANSFORM_LATER.
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
135 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
138 * Get the thumbnail extension and MIME type for a given source MIME type
139 * @return array thumbnail extension and MIME type
141 function getThumbType( $ext, $mime ) {
142 return array( $ext, $mime );
146 * True if the handled types can be transformed
148 function canRender( $file ) { return true; }
150 * True if handled types cannot be displayed directly in a browser
151 * but can be rendered
153 function mustRender( $file ) { return false; }
155 * True if the type has multi-page capabilities
157 function isMultiPage( $file ) { return false; }
159 * Page count for a multi-page document, false if unsupported or unknown
161 function pageCount( $file ) { return false; }
163 * False if the handler is disabled for all files
165 function isEnabled() { return true; }
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.
173 function getPageDimensions( $image, $page ) {
174 $gis = $this->getImageSize( $image, $image->getPath() );
175 return array(
176 'width' => $gis[0],
177 'height' => $gis[1]
182 * Get an array structure that looks like this:
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 * ...
194 * The UI will format this into a table where the visible fields are always
195 * visible, and the collapsed fields are optionally visible.
197 * The function should return false if there is no metadata to display.
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.
207 function formatMetadata( $image ) {
208 return false;
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.
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
227 function getShortDesc( $file ) {
228 global $wgLang;
229 $nbytes = '(' . wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
230 $wgLang->formatNum( $file->getSize() ) ) . ')';
231 return "$nbytes";
234 function getLongDesc( $file ) {
235 global $wgUser;
236 $sk = $wgUser->getSkin();
237 return wfMsg( 'file-info', $sk->formatSize( $file->getSize() ), $file->getMimeType() );
240 function getDimensionsString( $file ) {
241 return '';
245 * Modify the parser object post-transform
247 function parserTransformHook( $parser, $file ) {}
250 * Check for zero-sized thumbnails. These can be generated when
251 * no disk space is available or some other error occurs
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
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;
268 return false;
273 * Media handler abstract base class for images
275 * @addtogroup Media
277 abstract class ImageHandler extends MediaHandler {
278 function canRender( $file ) {
279 if ( $file->getWidth() && $file->getHeight() ) {
280 return true;
281 } else {
282 return false;
286 function getParamMap() {
287 return array( 'img_width' => 'width' );
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;
297 } else {
298 return false;
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__ );
310 # Removed for ProofreadPage
311 #$width = intval( $width );
312 return "{$width}px";
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;
324 function getScriptParams( $params ) {
325 return array( 'width' => $params['width'] );
328 function normaliseParams( $image, &$params ) {
329 $mimeType = $image->getMimeType();
331 if ( !isset( $params['width'] ) ) {
332 return false;
334 if ( !isset( $params['page'] ) ) {
335 $params['page'] = 1;
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'] );
344 $params['height'] = File::scaleHeight( $srcWidth, $srcHeight, $params['width'] );
345 if ( !$this->validateThumbParams( $params['width'], $params['height'], $srcWidth, $srcHeight, $mimeType ) ) {
346 return false;
348 return true;
352 * Get a transform output object without actually doing the transform
354 function getTransform( $image, $dstPath, $dstUrl, $params ) {
355 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
359 * Validate thumbnail parameters and fill in the correct height
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.
365 function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
366 $width = intval( $width );
368 # Sanity check $width
369 if( $width <= 0) {
370 wfDebug( __METHOD__.": Invalid destination width: $width\n" );
371 return false;
373 if ( $srcWidth <= 0 ) {
374 wfDebug( __METHOD__.": Invalid source width: $srcWidth\n" );
375 return false;
378 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
379 return true;
382 function getScriptedTransform( $image, $script, $params ) {
383 if ( !$this->normaliseParams( $image, $params ) ) {
384 return false;
386 $url = $script . '&' . wfArrayToCGI( $this->getScriptParams( $params ) );
387 $page = isset( $params['page'] ) ? $params['page'] : false;
389 if( $image->mustRender() || $params['width'] < $image->getWidth() ) {
390 return new ThumbnailImage( $image, $url, $params['width'], $params['height'], $page );
394 function getImageSize( $image, $path ) {
395 wfSuppressWarnings();
396 $gis = getimagesize( $path );
397 wfRestoreWarnings();
398 return $gis;
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() ) );
407 return "$widthheight ($nbytes)";
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() );
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() ) );