SpecialLinkSearch: clean up munged query variable handling
[mediawiki.git] / includes / media / Bitmap.php
blobeadcf94ba88221e46e7a45301a0ddbd9f149d024
1 <?php
2 /**
3 * Generic handler for bitmap images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Media
24 /**
25 * Generic handler for bitmap images
27 * @ingroup Media
29 class BitmapHandler extends TransformationalImageHandler {
31 /**
32 * Returns which scaler type should be used. Creates parent directories
33 * for $dstPath and returns 'client' on error
35 * @param string $dstPath
36 * @param bool $checkDstPath
37 * @return string|Callable One of client, im, custom, gd, imext or an array( object, method )
39 protected function getScalerType( $dstPath, $checkDstPath = true ) {
40 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
42 if ( !$dstPath && $checkDstPath ) {
43 # No output path available, client side scaling only
44 $scaler = 'client';
45 } elseif ( !$wgUseImageResize ) {
46 $scaler = 'client';
47 } elseif ( $wgUseImageMagick ) {
48 $scaler = 'im';
49 } elseif ( $wgCustomConvertCommand ) {
50 $scaler = 'custom';
51 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
52 $scaler = 'gd';
53 } elseif ( class_exists( 'Imagick' ) ) {
54 $scaler = 'imext';
55 } else {
56 $scaler = 'client';
59 return $scaler;
62 /**
63 * Transform an image using ImageMagick
65 * @param File $image File associated with this thumbnail
66 * @param array $params Array with scaler params
68 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
70 protected function transformImageMagick( $image, $params ) {
71 # use ImageMagick
72 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
73 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
75 $quality = array();
76 $sharpen = array();
77 $scene = false;
78 $animation_pre = array();
79 $animation_post = array();
80 $decoderHint = array();
81 if ( $params['mimeType'] == 'image/jpeg' ) {
82 $qualityVal = isset( $params['quality'] ) ? (string)$params['quality'] : null;
83 $quality = array( '-quality', $qualityVal ?: '80' ); // 80%
84 # Sharpening, see bug 6193
85 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
86 / ( $params['srcWidth'] + $params['srcHeight'] )
87 < $wgSharpenReductionThreshold
88 ) {
89 $sharpen = array( '-sharpen', $wgSharpenParameter );
91 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
92 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
93 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
95 } elseif ( $params['mimeType'] == 'image/png' ) {
96 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
98 } elseif ( $params['mimeType'] == 'image/gif' ) {
99 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
100 // Extract initial frame only; we're so big it'll
101 // be a total drag. :P
102 $scene = 0;
103 } elseif ( $this->isAnimatedImage( $image ) ) {
104 // Coalesce is needed to scale animated GIFs properly (bug 1017).
105 $animation_pre = array( '-coalesce' );
106 // We optimize the output, but -optimize is broken,
107 // use optimizeTransparency instead (bug 11822)
108 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
109 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
112 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
113 // Before merging layers, we need to set the background
114 // to be transparent to preserve alpha, as -layers merge
115 // merges all layers on to a canvas filled with the
116 // background colour. After merging we reset the background
117 // to be white for the default background colour setting
118 // in the PNG image (which is used in old IE)
119 $animation_pre = array(
120 '-background', 'transparent',
121 '-layers', 'merge',
122 '-background', 'white',
124 wfSuppressWarnings();
125 $xcfMeta = unserialize( $image->getMetadata() );
126 wfRestoreWarnings();
127 if ( $xcfMeta
128 && isset( $xcfMeta['colorType'] )
129 && $xcfMeta['colorType'] === 'greyscale-alpha'
130 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
132 // bug 66323 - Greyscale images not rendered properly.
133 // So only take the "red" channel.
134 $channelOnly = array( '-channel', 'R', '-separate' );
135 $animation_pre = array_merge( $animation_pre, $channelOnly );
139 // Use one thread only, to avoid deadlock bugs on OOM
140 $env = array( 'OMP_NUM_THREADS' => 1 );
141 if ( strval( $wgImageMagickTempDir ) !== '' ) {
142 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
145 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
146 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
148 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
149 array( $wgImageMagickConvertCommand ),
150 $quality,
151 // Specify white background color, will be used for transparent images
152 // in Internet Explorer/Windows instead of default black.
153 array( '-background', 'white' ),
154 $decoderHint,
155 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
156 $animation_pre,
157 // For the -thumbnail option a "!" is needed to force exact size,
158 // or ImageMagick may decide your ratio is wrong and slice off
159 // a pixel.
160 array( '-thumbnail', "{$width}x{$height}!" ),
161 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
162 ( $params['comment'] !== ''
163 ? array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
164 : array() ),
165 array( '-depth', 8 ),
166 $sharpen,
167 array( '-rotate', "-$rotation" ),
168 $animation_post,
169 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
171 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
172 $retval = 0;
173 $err = wfShellExecWithStderr( $cmd, $retval, $env );
175 if ( $retval !== 0 ) {
176 $this->logErrorForExternalProcess( $retval, $err, $cmd );
178 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
181 return false; # No error
185 * Transform an image using the Imagick PHP extension
187 * @param File $image File associated with this thumbnail
188 * @param array $params Array with scaler params
190 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
192 protected function transformImageMagickExt( $image, $params ) {
193 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
195 try {
196 $im = new Imagick();
197 $im->readImage( $params['srcPath'] );
199 if ( $params['mimeType'] == 'image/jpeg' ) {
200 // Sharpening, see bug 6193
201 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
202 / ( $params['srcWidth'] + $params['srcHeight'] )
203 < $wgSharpenReductionThreshold
205 // Hack, since $wgSharpenParameter is written specifically for the command line convert
206 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
207 $im->sharpenImage( $radius, $sigma );
209 $qualityVal = isset( $params['quality'] ) ? (string)$params['quality'] : null;
210 $im->setCompressionQuality( $qualityVal ?: 80 );
211 } elseif ( $params['mimeType'] == 'image/png' ) {
212 $im->setCompressionQuality( 95 );
213 } elseif ( $params['mimeType'] == 'image/gif' ) {
214 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
215 // Extract initial frame only; we're so big it'll
216 // be a total drag. :P
217 $im->setImageScene( 0 );
218 } elseif ( $this->isAnimatedImage( $image ) ) {
219 // Coalesce is needed to scale animated GIFs properly (bug 1017).
220 $im = $im->coalesceImages();
224 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
225 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
227 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
229 // Call Imagick::thumbnailImage on each frame
230 foreach ( $im as $i => $frame ) {
231 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
232 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
235 $im->setImageDepth( 8 );
237 if ( $rotation ) {
238 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
239 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
243 if ( $this->isAnimatedImage( $image ) ) {
244 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
245 // This is broken somehow... can't find out how to fix it
246 $result = $im->writeImages( $params['dstPath'], true );
247 } else {
248 $result = $im->writeImage( $params['dstPath'] );
250 if ( !$result ) {
251 return $this->getMediaTransformError( $params,
252 "Unable to write thumbnail to {$params['dstPath']}" );
254 } catch ( ImagickException $e ) {
255 return $this->getMediaTransformError( $params, $e->getMessage() );
258 return false;
262 * Transform an image using a custom command
264 * @param File $image File associated with this thumbnail
265 * @param array $params Array with scaler params
267 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
269 protected function transformCustom( $image, $params ) {
270 # Use a custom convert command
271 global $wgCustomConvertCommand;
273 # Variables: %s %d %w %h
274 $src = wfEscapeShellArg( $params['srcPath'] );
275 $dst = wfEscapeShellArg( $params['dstPath'] );
276 $cmd = $wgCustomConvertCommand;
277 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
278 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
279 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
280 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
281 $retval = 0;
282 $err = wfShellExecWithStderr( $cmd, $retval );
284 if ( $retval !== 0 ) {
285 $this->logErrorForExternalProcess( $retval, $err, $cmd );
287 return $this->getMediaTransformError( $params, $err );
290 return false; # No error
294 * Transform an image using the built in GD library
296 * @param File $image File associated with this thumbnail
297 * @param array $params Array with scaler params
299 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
301 protected function transformGd( $image, $params ) {
302 # Use PHP's builtin GD library functions.
304 # First find out what kind of file this is, and select the correct
305 # input routine for this.
307 $typemap = array(
308 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
309 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
310 array( __CLASS__, 'imageJpegWrapper' ) ),
311 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
312 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
313 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
316 if ( !isset( $typemap[$params['mimeType']] ) ) {
317 $err = 'Image type not supported';
318 wfDebug( "$err\n" );
319 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
321 return $this->getMediaTransformError( $params, $errMsg );
323 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
325 if ( !function_exists( $loader ) ) {
326 $err = "Incomplete GD library configuration: missing function $loader";
327 wfDebug( "$err\n" );
328 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
330 return $this->getMediaTransformError( $params, $errMsg );
333 if ( !file_exists( $params['srcPath'] ) ) {
334 $err = "File seems to be missing: {$params['srcPath']}";
335 wfDebug( "$err\n" );
336 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
338 return $this->getMediaTransformError( $params, $errMsg );
341 $src_image = call_user_func( $loader, $params['srcPath'] );
343 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ? $this->getRotation( $image ) : 0;
344 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
345 $dst_image = imagecreatetruecolor( $width, $height );
347 // Initialise the destination image to transparent instead of
348 // the default solid black, to support PNG and GIF transparency nicely
349 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
350 imagecolortransparent( $dst_image, $background );
351 imagealphablending( $dst_image, false );
353 if ( $colorStyle == 'palette' ) {
354 // Don't resample for paletted GIF images.
355 // It may just uglify them, and completely breaks transparency.
356 imagecopyresized( $dst_image, $src_image,
357 0, 0, 0, 0,
358 $width, $height,
359 imagesx( $src_image ), imagesy( $src_image ) );
360 } else {
361 imagecopyresampled( $dst_image, $src_image,
362 0, 0, 0, 0,
363 $width, $height,
364 imagesx( $src_image ), imagesy( $src_image ) );
367 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
368 $rot_image = imagerotate( $dst_image, $rotation, 0 );
369 imagedestroy( $dst_image );
370 $dst_image = $rot_image;
373 imagesavealpha( $dst_image, true );
375 $funcParams = array( $dst_image, $params['dstPath'] );
376 if ( $useQuality && isset( $params['quality'] ) ) {
377 $funcParams[] = $params['quality'];
379 call_user_func_array( $saveType, $funcParams );
381 imagedestroy( $dst_image );
382 imagedestroy( $src_image );
384 return false; # No error
388 * Callback for transformGd when transforming jpeg images.
390 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
391 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
392 imageinterlace( $dst_image );
393 imagejpeg( $dst_image, $thumbPath, $quality );
397 * Returns whether the current scaler supports rotation (im and gd do)
399 * @return bool
401 public function canRotate() {
402 $scaler = $this->getScalerType( null, false );
403 switch ( $scaler ) {
404 case 'im':
405 # ImageMagick supports autorotation
406 return true;
407 case 'imext':
408 # Imagick::rotateImage
409 return true;
410 case 'gd':
411 # GD's imagerotate function is used to rotate images, but not
412 # all precompiled PHP versions have that function
413 return function_exists( 'imagerotate' );
414 default:
415 # Other scalers don't support rotation
416 return false;
421 * @see $wgEnableAutoRotation
422 * @return bool Whether auto rotation is enabled
424 public function autoRotateEnabled() {
425 global $wgEnableAutoRotation;
427 if ( $wgEnableAutoRotation === null ) {
428 // Only enable auto-rotation when we actually can
429 return $this->canRotate();
432 return $wgEnableAutoRotation;
436 * @param File $file
437 * @param array $params Rotate parameters.
438 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
439 * @since 1.21
440 * @return bool
442 public function rotate( $file, $params ) {
443 global $wgImageMagickConvertCommand;
445 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
446 $scene = false;
448 $scaler = $this->getScalerType( null, false );
449 switch ( $scaler ) {
450 case 'im':
451 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
452 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
453 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
454 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
455 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
456 $retval = 0;
457 $err = wfShellExecWithStderr( $cmd, $retval );
458 if ( $retval !== 0 ) {
459 $this->logErrorForExternalProcess( $retval, $err, $cmd );
461 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
464 return false;
465 case 'imext':
466 $im = new Imagick();
467 $im->readImage( $params['srcPath'] );
468 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
469 return new MediaTransformError( 'thumbnail_error', 0, 0,
470 "Error rotating $rotation degrees" );
472 $result = $im->writeImage( $params['dstPath'] );
473 if ( !$result ) {
474 return new MediaTransformError( 'thumbnail_error', 0, 0,
475 "Unable to write image to {$params['dstPath']}" );
478 return false;
479 default:
480 return new MediaTransformError( 'thumbnail_error', 0, 0,
481 "$scaler rotation not implemented" );