Merge "$wgUseGzip had no effect"
[lhc/web/wiklou.git] / includes / media / Bitmap.php
1 <?php
2 /**
3 * Generic handler for bitmap images.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 /**
25 * Generic handler for bitmap images
26 *
27 * @ingroup Media
28 */
29 class BitmapHandler extends TransformationalImageHandler {
30
31 /**
32 * Returns which scaler type should be used. Creates parent directories
33 * for $dstPath and returns 'client' on error
34 *
35 * @param string $dstPath
36 * @param bool $checkDstPath
37 * @return string|Callable One of client, im, custom, gd, imext or an array( object, method )
38 */
39 protected function getScalerType( $dstPath, $checkDstPath = true ) {
40 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
41
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';
57 }
58
59 return $scaler;
60 }
61
62 /**
63 * Transform an image using ImageMagick
64 *
65 * @param File $image File associated with this thumbnail
66 * @param array $params Array with scaler params
67 *
68 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
69 */
70 protected function transformImageMagick( $image, $params ) {
71 # use ImageMagick
72 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
73 $wgImageMagickTempDir, $wgImageMagickConvertCommand, $wgResourceBasePath,
74 $wgUseTinyRGBForJPGThumbnails;
75
76 $quality = array();
77 $sharpen = array();
78 $scene = false;
79 $animation_pre = array();
80 $animation_post = array();
81 $decoderHint = array();
82 if ( $params['mimeType'] == 'image/jpeg' ) {
83 $qualityVal = isset( $params['quality'] ) ? (string)$params['quality'] : null;
84 $quality = array( '-quality', $qualityVal ?: '80' ); // 80%
85 # Sharpening, see bug 6193
86 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
87 / ( $params['srcWidth'] + $params['srcHeight'] )
88 < $wgSharpenReductionThreshold
89 ) {
90 $sharpen = array( '-sharpen', $wgSharpenParameter );
91 }
92 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
93 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
94 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
95 }
96 } elseif ( $params['mimeType'] == 'image/png' ) {
97 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
98
99 } elseif ( $params['mimeType'] == 'image/gif' ) {
100 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
101 // Extract initial frame only; we're so big it'll
102 // be a total drag. :P
103 $scene = 0;
104 } elseif ( $this->isAnimatedImage( $image ) ) {
105 // Coalesce is needed to scale animated GIFs properly (bug 1017).
106 $animation_pre = array( '-coalesce' );
107 // We optimize the output, but -optimize is broken,
108 // use optimizeTransparency instead (bug 11822)
109 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
110 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
111 }
112 }
113 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
114 // Before merging layers, we need to set the background
115 // to be transparent to preserve alpha, as -layers merge
116 // merges all layers on to a canvas filled with the
117 // background colour. After merging we reset the background
118 // to be white for the default background colour setting
119 // in the PNG image (which is used in old IE)
120 $animation_pre = array(
121 '-background', 'transparent',
122 '-layers', 'merge',
123 '-background', 'white',
124 );
125 MediaWiki\suppressWarnings();
126 $xcfMeta = unserialize( $image->getMetadata() );
127 MediaWiki\restoreWarnings();
128 if ( $xcfMeta
129 && isset( $xcfMeta['colorType'] )
130 && $xcfMeta['colorType'] === 'greyscale-alpha'
131 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
132 ) {
133 // bug 66323 - Greyscale images not rendered properly.
134 // So only take the "red" channel.
135 $channelOnly = array( '-channel', 'R', '-separate' );
136 $animation_pre = array_merge( $animation_pre, $channelOnly );
137 }
138 }
139
140 // Use one thread only, to avoid deadlock bugs on OOM
141 $env = array( 'OMP_NUM_THREADS' => 1 );
142 if ( strval( $wgImageMagickTempDir ) !== '' ) {
143 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
144 }
145
146 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
147 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
148
149 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
150 array( $wgImageMagickConvertCommand ),
151 $quality,
152 // Specify white background color, will be used for transparent images
153 // in Internet Explorer/Windows instead of default black.
154 array( '-background', 'white' ),
155 $decoderHint,
156 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
157 $animation_pre,
158 // For the -thumbnail option a "!" is needed to force exact size,
159 // or ImageMagick may decide your ratio is wrong and slice off
160 // a pixel.
161 array( '-thumbnail', "{$width}x{$height}!" ),
162 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
163 ( $params['comment'] !== ''
164 ? array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
165 : array() ),
166 array( '-depth', 8 ),
167 $sharpen,
168 array( '-rotate', "-$rotation" ),
169 $animation_post,
170 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
171
172 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
173 $retval = 0;
174 $err = wfShellExecWithStderr( $cmd, $retval, $env );
175
176 if ( $retval !== 0 ) {
177 $this->logErrorForExternalProcess( $retval, $err, $cmd );
178
179 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
180 }
181
182 return false; # No error
183 }
184
185 /**
186 * Transform an image using the Imagick PHP extension
187 *
188 * @param File $image File associated with this thumbnail
189 * @param array $params Array with scaler params
190 *
191 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
192 */
193 protected function transformImageMagickExt( $image, $params ) {
194 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
195
196 try {
197 $im = new Imagick();
198 $im->readImage( $params['srcPath'] );
199
200 if ( $params['mimeType'] == 'image/jpeg' ) {
201 // Sharpening, see bug 6193
202 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
203 / ( $params['srcWidth'] + $params['srcHeight'] )
204 < $wgSharpenReductionThreshold
205 ) {
206 // Hack, since $wgSharpenParameter is written specifically for the command line convert
207 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
208 $im->sharpenImage( $radius, $sigma );
209 }
210 $qualityVal = isset( $params['quality'] ) ? (string)$params['quality'] : null;
211 $im->setCompressionQuality( $qualityVal ?: 80 );
212 } elseif ( $params['mimeType'] == 'image/png' ) {
213 $im->setCompressionQuality( 95 );
214 } elseif ( $params['mimeType'] == 'image/gif' ) {
215 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
216 // Extract initial frame only; we're so big it'll
217 // be a total drag. :P
218 $im->setImageScene( 0 );
219 } elseif ( $this->isAnimatedImage( $image ) ) {
220 // Coalesce is needed to scale animated GIFs properly (bug 1017).
221 $im = $im->coalesceImages();
222 }
223 }
224
225 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
226 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
227
228 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
229
230 // Call Imagick::thumbnailImage on each frame
231 foreach ( $im as $i => $frame ) {
232 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
233 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
234 }
235 }
236 $im->setImageDepth( 8 );
237
238 if ( $rotation ) {
239 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
240 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
241 }
242 }
243
244 if ( $this->isAnimatedImage( $image ) ) {
245 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
246 // This is broken somehow... can't find out how to fix it
247 $result = $im->writeImages( $params['dstPath'], true );
248 } else {
249 $result = $im->writeImage( $params['dstPath'] );
250 }
251 if ( !$result ) {
252 return $this->getMediaTransformError( $params,
253 "Unable to write thumbnail to {$params['dstPath']}" );
254 }
255 } catch ( ImagickException $e ) {
256 return $this->getMediaTransformError( $params, $e->getMessage() );
257 }
258
259 return false;
260 }
261
262 /**
263 * Transform an image using a custom command
264 *
265 * @param File $image File associated with this thumbnail
266 * @param array $params Array with scaler params
267 *
268 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
269 */
270 protected function transformCustom( $image, $params ) {
271 # Use a custom convert command
272 global $wgCustomConvertCommand;
273
274 # Variables: %s %d %w %h
275 $src = wfEscapeShellArg( $params['srcPath'] );
276 $dst = wfEscapeShellArg( $params['dstPath'] );
277 $cmd = $wgCustomConvertCommand;
278 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
279 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
280 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
281 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
282 $retval = 0;
283 $err = wfShellExecWithStderr( $cmd, $retval );
284
285 if ( $retval !== 0 ) {
286 $this->logErrorForExternalProcess( $retval, $err, $cmd );
287
288 return $this->getMediaTransformError( $params, $err );
289 }
290
291 return false; # No error
292 }
293
294 /**
295 * Transform an image using the built in GD library
296 *
297 * @param File $image File associated with this thumbnail
298 * @param array $params Array with scaler params
299 *
300 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
301 */
302 protected function transformGd( $image, $params ) {
303 # Use PHP's builtin GD library functions.
304 #
305 # First find out what kind of file this is, and select the correct
306 # input routine for this.
307
308 $typemap = array(
309 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
310 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
311 array( __CLASS__, 'imageJpegWrapper' ) ),
312 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
313 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
314 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
315 );
316
317 if ( !isset( $typemap[$params['mimeType']] ) ) {
318 $err = 'Image type not supported';
319 wfDebug( "$err\n" );
320 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
321
322 return $this->getMediaTransformError( $params, $errMsg );
323 }
324 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
325
326 if ( !function_exists( $loader ) ) {
327 $err = "Incomplete GD library configuration: missing function $loader";
328 wfDebug( "$err\n" );
329 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
330
331 return $this->getMediaTransformError( $params, $errMsg );
332 }
333
334 if ( !file_exists( $params['srcPath'] ) ) {
335 $err = "File seems to be missing: {$params['srcPath']}";
336 wfDebug( "$err\n" );
337 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
338
339 return $this->getMediaTransformError( $params, $errMsg );
340 }
341
342 $src_image = call_user_func( $loader, $params['srcPath'] );
343
344 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ? $this->getRotation( $image ) : 0;
345 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
346 $dst_image = imagecreatetruecolor( $width, $height );
347
348 // Initialise the destination image to transparent instead of
349 // the default solid black, to support PNG and GIF transparency nicely
350 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
351 imagecolortransparent( $dst_image, $background );
352 imagealphablending( $dst_image, false );
353
354 if ( $colorStyle == 'palette' ) {
355 // Don't resample for paletted GIF images.
356 // It may just uglify them, and completely breaks transparency.
357 imagecopyresized( $dst_image, $src_image,
358 0, 0, 0, 0,
359 $width, $height,
360 imagesx( $src_image ), imagesy( $src_image ) );
361 } else {
362 imagecopyresampled( $dst_image, $src_image,
363 0, 0, 0, 0,
364 $width, $height,
365 imagesx( $src_image ), imagesy( $src_image ) );
366 }
367
368 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
369 $rot_image = imagerotate( $dst_image, $rotation, 0 );
370 imagedestroy( $dst_image );
371 $dst_image = $rot_image;
372 }
373
374 imagesavealpha( $dst_image, true );
375
376 $funcParams = array( $dst_image, $params['dstPath'] );
377 if ( $useQuality && isset( $params['quality'] ) ) {
378 $funcParams[] = $params['quality'];
379 }
380 call_user_func_array( $saveType, $funcParams );
381
382 imagedestroy( $dst_image );
383 imagedestroy( $src_image );
384
385 return false; # No error
386 }
387
388 /**
389 * Callback for transformGd when transforming jpeg images.
390 */
391 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
392 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
393 imageinterlace( $dst_image );
394 imagejpeg( $dst_image, $thumbPath, $quality );
395 }
396
397 /**
398 * Returns whether the current scaler supports rotation (im and gd do)
399 *
400 * @return bool
401 */
402 public function canRotate() {
403 $scaler = $this->getScalerType( null, false );
404 switch ( $scaler ) {
405 case 'im':
406 # ImageMagick supports autorotation
407 return true;
408 case 'imext':
409 # Imagick::rotateImage
410 return true;
411 case 'gd':
412 # GD's imagerotate function is used to rotate images, but not
413 # all precompiled PHP versions have that function
414 return function_exists( 'imagerotate' );
415 default:
416 # Other scalers don't support rotation
417 return false;
418 }
419 }
420
421 /**
422 * @see $wgEnableAutoRotation
423 * @return bool Whether auto rotation is enabled
424 */
425 public function autoRotateEnabled() {
426 global $wgEnableAutoRotation;
427
428 if ( $wgEnableAutoRotation === null ) {
429 // Only enable auto-rotation when we actually can
430 return $this->canRotate();
431 }
432
433 return $wgEnableAutoRotation;
434 }
435
436 /**
437 * @param File $file
438 * @param array $params Rotate parameters.
439 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
440 * @since 1.21
441 * @return bool
442 */
443 public function rotate( $file, $params ) {
444 global $wgImageMagickConvertCommand;
445
446 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
447 $scene = false;
448
449 $scaler = $this->getScalerType( null, false );
450 switch ( $scaler ) {
451 case 'im':
452 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
453 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
454 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
455 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
456 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
457 $retval = 0;
458 $err = wfShellExecWithStderr( $cmd, $retval );
459 if ( $retval !== 0 ) {
460 $this->logErrorForExternalProcess( $retval, $err, $cmd );
461
462 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
463 }
464
465 return false;
466 case 'imext':
467 $im = new Imagick();
468 $im->readImage( $params['srcPath'] );
469 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
470 return new MediaTransformError( 'thumbnail_error', 0, 0,
471 "Error rotating $rotation degrees" );
472 }
473 $result = $im->writeImage( $params['dstPath'] );
474 if ( !$result ) {
475 return new MediaTransformError( 'thumbnail_error', 0, 0,
476 "Unable to write image to {$params['dstPath']}" );
477 }
478
479 return false;
480 default:
481 return new MediaTransformError( 'thumbnail_error', 0, 0,
482 "$scaler rotation not implemented" );
483 }
484 }
485 }