Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / media / TransformationalImageHandler.php
blobfd8d81d24c2e9c1dacf6b30f1a73dda0de63c6c0
1 <?php
2 /**
3 * Base class for handlers which require transforming images in a
4 * similar way as BitmapHandler does.
6 * This was split from BitmapHandler on the basis that some extensions
7 * might want to work in a similar way to BitmapHandler, but for
8 * different formats.
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
25 * @file
26 * @ingroup Media
29 /**
30 * Handler for images that need to be transformed
32 * @since 1.24
33 * @ingroup Media
35 abstract class TransformationalImageHandler extends ImageHandler {
36 /**
37 * @param File $image
38 * @param array $params Transform parameters. Entries with the keys 'width'
39 * and 'height' are the respective screen width and height, while the keys
40 * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
41 * @return bool
43 function normaliseParams( $image, &$params ) {
44 if ( !parent::normaliseParams( $image, $params ) ) {
45 return false;
48 # Obtain the source, pre-rotation dimensions
49 $srcWidth = $image->getWidth( $params['page'] );
50 $srcHeight = $image->getHeight( $params['page'] );
52 # Don't make an image bigger than the source
53 if ( $params['physicalWidth'] >= $srcWidth ) {
54 $params['physicalWidth'] = $srcWidth;
55 $params['physicalHeight'] = $srcHeight;
57 # Skip scaling limit checks if no scaling is required
58 # due to requested size being bigger than source.
59 if ( !$image->mustRender() ) {
60 return true;
64 return true;
67 /**
68 * Extracts the width/height if the image will be scaled before rotating
70 * This will match the physical size/aspect ratio of the original image
71 * prior to application of the rotation -- so for a portrait image that's
72 * stored as raw landscape with 90-degress rotation, the resulting size
73 * will be wider than it is tall.
75 * @param array $params Parameters as returned by normaliseParams
76 * @param int $rotation The rotation angle that will be applied
77 * @return array ($width, $height) array
79 public function extractPreRotationDimensions( $params, $rotation ) {
80 if ( $rotation == 90 || $rotation == 270 ) {
81 # We'll resize before rotation, so swap the dimensions again
82 $width = $params['physicalHeight'];
83 $height = $params['physicalWidth'];
84 } else {
85 $width = $params['physicalWidth'];
86 $height = $params['physicalHeight'];
89 return array( $width, $height );
92 /**
93 * Create a thumbnail.
95 * This sets up various parameters, and then calls a helper method
96 * based on $this->getScalerType in order to scale the image.
98 * @param File $image
99 * @param string $dstPath
100 * @param string $dstUrl
101 * @param array $params
102 * @param int $flags
103 * @return MediaTransformError|ThumbnailImage|TransformParameterError
105 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
106 if ( !$this->normaliseParams( $image, $params ) ) {
107 return new TransformParameterError( $params );
110 # Create a parameter array to pass to the scaler
111 $scalerParams = array(
112 # The size to which the image will be resized
113 'physicalWidth' => $params['physicalWidth'],
114 'physicalHeight' => $params['physicalHeight'],
115 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
116 # The size of the image on the page
117 'clientWidth' => $params['width'],
118 'clientHeight' => $params['height'],
119 # Comment as will be added to the Exif of the thumbnail
120 'comment' => isset( $params['descriptionUrl'] )
121 ? "File source: {$params['descriptionUrl']}"
122 : '',
123 # Properties of the original image
124 'srcWidth' => $image->getWidth(),
125 'srcHeight' => $image->getHeight(),
126 'mimeType' => $image->getMimeType(),
127 'dstPath' => $dstPath,
128 'dstUrl' => $dstUrl,
131 if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
132 $scalerParams['quality'] = 30;
135 // For subclasses that might be paged.
136 if ( $image->isMultipage() && isset( $params['page'] ) ) {
137 $scalerParams['page'] = intval( $params['page'] );
140 # Determine scaler type
141 $scaler = $this->getScalerType( $dstPath );
143 if ( is_array( $scaler ) ) {
144 $scalerName = get_class( $scaler[0] );
145 } else {
146 $scalerName = $scaler;
149 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} " .
150 "thumbnail at $dstPath using scaler $scalerName\n" );
152 if ( !$image->mustRender() &&
153 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
154 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
155 && !isset( $scalerParams['quality'] )
158 # normaliseParams (or the user) wants us to return the unscaled image
159 wfDebug( __METHOD__ . ": returning unscaled image\n" );
161 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
164 if ( $scaler == 'client' ) {
165 # Client-side image scaling, use the source URL
166 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
167 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
170 if ( !$this->isImageAreaOkForThumbnaling( $image, $params ) ) {
171 global $wgMaxImageArea;
172 return new TransformTooBigImageAreaError( $params, $wgMaxImageArea );
175 if ( $flags & self::TRANSFORM_LATER ) {
176 wfDebug( __METHOD__ . ": Transforming later per flags.\n" );
177 $newParams = array(
178 'width' => $scalerParams['clientWidth'],
179 'height' => $scalerParams['clientHeight']
181 if ( isset( $params['quality'] ) ) {
182 $newParams['quality'] = $params['quality'];
184 if ( isset( $params['page'] ) && $params['page'] ) {
185 $newParams['page'] = $params['page'];
187 return new ThumbnailImage( $image, $dstUrl, false, $newParams );
190 # Try to make a target path for the thumbnail
191 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
192 wfDebug( __METHOD__ . ": Unable to create thumbnail destination " .
193 "directory, falling back to client scaling\n" );
195 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
198 # Transform functions and binaries need a FS source file
199 $thumbnailSource = $this->getThumbnailSource( $image, $params );
201 // If the source isn't the original, disable EXIF rotation because it's already been applied
202 if ( $scalerParams['srcWidth'] != $thumbnailSource['width']
203 || $scalerParams['srcHeight'] != $thumbnailSource['height'] ) {
204 $scalerParams['disableRotation'] = true;
207 $scalerParams['srcPath'] = $thumbnailSource['path'];
208 $scalerParams['srcWidth'] = $thumbnailSource['width'];
209 $scalerParams['srcHeight'] = $thumbnailSource['height'];
211 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
212 wfDebugLog( 'thumbnail',
213 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
214 wfHostname(), $image->getName() ) );
216 return new MediaTransformError( 'thumbnail_error',
217 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
218 wfMessage( 'filemissing' )->text()
222 # Try a hook. Called "Bitmap" for historical reasons.
223 /** @var $mto MediaTransformOutput */
224 $mto = null;
225 Hooks::run( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
226 if ( !is_null( $mto ) ) {
227 wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto\n" );
228 $scaler = 'hookaborted';
231 // $scaler will return a MediaTransformError on failure, or false on success.
232 // If the scaler is succesful, it will have created a thumbnail at the destination
233 // path.
234 if ( is_array( $scaler ) && is_callable( $scaler ) ) {
235 // Allow subclasses to specify their own rendering methods.
236 $err = call_user_func( $scaler, $image, $scalerParams );
237 } else {
238 switch ( $scaler ) {
239 case 'hookaborted':
240 # Handled by the hook above
241 $err = $mto->isError() ? $mto : false;
242 break;
243 case 'im':
244 $err = $this->transformImageMagick( $image, $scalerParams );
245 break;
246 case 'custom':
247 $err = $this->transformCustom( $image, $scalerParams );
248 break;
249 case 'imext':
250 $err = $this->transformImageMagickExt( $image, $scalerParams );
251 break;
252 case 'gd':
253 default:
254 $err = $this->transformGd( $image, $scalerParams );
255 break;
259 # Remove the file if a zero-byte thumbnail was created, or if there was an error
260 $removed = $this->removeBadFile( $dstPath, (bool)$err );
261 if ( $err ) {
262 # transform returned MediaTransforError
263 return $err;
264 } elseif ( $removed ) {
265 # Thumbnail was zero-byte and had to be removed
266 return new MediaTransformError( 'thumbnail_error',
267 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
268 wfMessage( 'unknown-error' )->text()
270 } elseif ( $mto ) {
271 return $mto;
272 } else {
273 $newParams = array(
274 'width' => $scalerParams['clientWidth'],
275 'height' => $scalerParams['clientHeight']
277 if ( isset( $params['quality'] ) ) {
278 $newParams['quality'] = $params['quality'];
280 if ( isset( $params['page'] ) && $params['page'] ) {
281 $newParams['page'] = $params['page'];
283 return new ThumbnailImage( $image, $dstUrl, $dstPath, $newParams );
288 * Get the source file for the transform
290 * @param $file File
291 * @param $params Array
292 * @return Array Array with keys width, height and path.
294 protected function getThumbnailSource( $file, $params ) {
295 return $file->getThumbnailSource( $params );
299 * Returns what sort of scaler type should be used.
301 * Values can be one of client, im, custom, gd, imext, or an array
302 * of object, method-name to call that specific method.
304 * If specifying a custom scaler command with array( Obj, method ),
305 * the method in question should take 2 parameters, a File object,
306 * and a $scalerParams array with various options (See doTransform
307 * for what is in $scalerParams). On error it should return a
308 * MediaTransformError object. On success it should return false,
309 * and simply make sure the thumbnail file is located at
310 * $scalerParams['dstPath'].
312 * If there is a problem with the output path, it returns "client"
313 * to do client side scaling.
315 * @param string $dstPath
316 * @param bool $checkDstPath Check that $dstPath is valid
317 * @return string|Callable One of client, im, custom, gd, imext, or a Callable array.
319 abstract protected function getScalerType( $dstPath, $checkDstPath = true );
322 * Get a ThumbnailImage that respresents an image that will be scaled
323 * client side
325 * @param File $image File associated with this thumbnail
326 * @param array $scalerParams Array with scaler params
327 * @return ThumbnailImage
329 * @todo FIXME: No rotation support
331 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
332 $params = array(
333 'width' => $scalerParams['clientWidth'],
334 'height' => $scalerParams['clientHeight']
337 return new ThumbnailImage( $image, $image->getURL(), null, $params );
341 * Transform an image using ImageMagick
343 * This is a stub method. The real method is in BitmapHander.
345 * @param File $image File associated with this thumbnail
346 * @param array $params Array with scaler params
348 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
350 protected function transformImageMagick( $image, $params ) {
351 return $this->getMediaTransformError( $params, "Unimplemented" );
355 * Transform an image using the Imagick PHP extension
357 * This is a stub method. The real method is in BitmapHander.
359 * @param File $image File associated with this thumbnail
360 * @param array $params Array with scaler params
362 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
364 protected function transformImageMagickExt( $image, $params ) {
365 return $this->getMediaTransformError( $params, "Unimplemented" );
369 * Transform an image using a custom command
371 * This is a stub method. The real method is in BitmapHander.
373 * @param File $image File associated with this thumbnail
374 * @param array $params Array with scaler params
376 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
378 protected function transformCustom( $image, $params ) {
379 return $this->getMediaTransformError( $params, "Unimplemented" );
383 * Get a MediaTransformError with error 'thumbnail_error'
385 * @param array $params Parameter array as passed to the transform* functions
386 * @param string $errMsg Error message
387 * @return MediaTransformError
389 public function getMediaTransformError( $params, $errMsg ) {
390 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
391 $params['clientHeight'], $errMsg );
395 * Transform an image using the built in GD library
397 * This is a stub method. The real method is in BitmapHander.
399 * @param File $image File associated with this thumbnail
400 * @param array $params Array with scaler params
402 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
404 protected function transformGd( $image, $params ) {
405 return $this->getMediaTransformError( $params, "Unimplemented" );
409 * Escape a string for ImageMagick's property input (e.g. -set -comment)
410 * See InterpretImageProperties() in magick/property.c
411 * @param string $s
412 * @return string
414 function escapeMagickProperty( $s ) {
415 // Double the backslashes
416 $s = str_replace( '\\', '\\\\', $s );
417 // Double the percents
418 $s = str_replace( '%', '%%', $s );
419 // Escape initial - or @
420 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
421 $s = '\\' . $s;
424 return $s;
428 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
429 * and GetPathComponent() in magick/utility.c.
431 * This won't work with an initial ~ or @, so input files should be prefixed
432 * with the directory name.
434 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
435 * it's broken in a way that doesn't involve trying to convert every file
436 * in a directory, so we're better off escaping and waiting for the bugfix
437 * to filter down to users.
439 * @param string $path The file path
440 * @param bool|string $scene The scene specification, or false if there is none
441 * @throws MWException
442 * @return string
444 function escapeMagickInput( $path, $scene = false ) {
445 # Die on initial metacharacters (caller should prepend path)
446 $firstChar = substr( $path, 0, 1 );
447 if ( $firstChar === '~' || $firstChar === '@' ) {
448 throw new MWException( __METHOD__ . ': cannot escape this path name' );
451 # Escape glob chars
452 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
454 return $this->escapeMagickPath( $path, $scene );
458 * Escape a string for ImageMagick's output filename. See
459 * InterpretImageFilename() in magick/image.c.
460 * @param string $path The file path
461 * @param bool|string $scene The scene specification, or false if there is none
462 * @return string
464 function escapeMagickOutput( $path, $scene = false ) {
465 $path = str_replace( '%', '%%', $path );
467 return $this->escapeMagickPath( $path, $scene );
471 * Armour a string against ImageMagick's GetPathComponent(). This is a
472 * helper function for escapeMagickInput() and escapeMagickOutput().
474 * @param string $path The file path
475 * @param bool|string $scene The scene specification, or false if there is none
476 * @throws MWException
477 * @return string
479 protected function escapeMagickPath( $path, $scene = false ) {
480 # Die on format specifiers (other than drive letters). The regex is
481 # meant to match all the formats you get from "convert -list format"
482 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
483 if ( wfIsWindows() && is_dir( $m[0] ) ) {
484 // OK, it's a drive letter
485 // ImageMagick has a similar exception, see IsMagickConflict()
486 } else {
487 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
491 # If there are square brackets, add a do-nothing scene specification
492 # to force a literal interpretation
493 if ( $scene === false ) {
494 if ( strpos( $path, '[' ) !== false ) {
495 $path .= '[0--1]';
497 } else {
498 $path .= "[$scene]";
501 return $path;
505 * Retrieve the version of the installed ImageMagick
506 * You can use PHPs version_compare() to use this value
507 * Value is cached for one hour.
508 * @return string Representing the IM version.
510 protected function getMagickVersion() {
511 global $wgMemc;
513 $cache = $wgMemc->get( "imagemagick-version" );
514 if ( !$cache ) {
515 global $wgImageMagickConvertCommand;
516 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
517 wfDebug( __METHOD__ . ": Running convert -version\n" );
518 $retval = '';
519 $return = wfShellExec( $cmd, $retval );
520 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
521 if ( $x != 1 ) {
522 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
524 return null;
526 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
528 return $matches[1];
531 return $cache;
535 * Returns whether the current scaler supports rotation.
537 * @since 1.24 No longer static
538 * @return bool
540 public function canRotate() {
541 return false;
545 * Should we automatically rotate an image based on exif
547 * @since 1.24 No longer static
548 * @see $wgEnableAutoRotation
549 * @return bool Whether auto rotation is enabled
551 public function autoRotateEnabled() {
552 return false;
556 * Rotate a thumbnail.
558 * This is a stub. See BitmapHandler::rotate.
560 * @param File $file
561 * @param array $params Rotate parameters.
562 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
563 * @since 1.24 Is non-static. From 1.21 it was static
564 * @return bool
566 public function rotate( $file, $params ) {
567 return new MediaTransformError( 'thumbnail_error', 0, 0,
568 get_class( $this ) . ' rotation not implemented' );
572 * Returns whether the file needs to be rendered. Returns true if the
573 * file requires rotation and we are able to rotate it.
575 * @param File $file
576 * @return bool
578 public function mustRender( $file ) {
579 return $this->canRotate() && $this->getRotation( $file ) != 0;
583 * Check if the file is smaller than the maximum image area for thumbnailing.
585 * Runs the 'BitmapHandlerCheckImageArea' hook.
587 * @param File $file
588 * @param array $params
589 * @return bool
590 * @since 1.25
592 public function isImageAreaOkForThumbnaling( $file, &$params ) {
593 global $wgMaxImageArea;
595 # For historical reasons, hook starts with BitmapHandler
596 $checkImageAreaHookResult = null;
597 Hooks::run(
598 'BitmapHandlerCheckImageArea',
599 array( $file, &$params, &$checkImageAreaHookResult )
602 if ( !is_null( $checkImageAreaHookResult ) ) {
603 // was set by hook, so return that value
604 return (bool)$checkImageAreaHookResult;
607 $srcWidth = $file->getWidth( $params['page'] );
608 $srcHeight = $file->getHeight( $params['page'] );
610 if ( $srcWidth * $srcHeight > $wgMaxImageArea
611 && !( $file->getMimeType() == 'image/jpeg'
612 && $this->getScalerType( false, false ) == 'im' )
614 # Only ImageMagick can efficiently downsize jpg images without loading
615 # the entire file in memory
616 return false;
618 return true;