Merge "API: Use ApiBase::PARAM_HELP_MSG_PER_VALUE for 'prop' in query+watchlist"
[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' || $params['mimeType'] == 'image/webp' ) {
97 $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' );
110 }
111 }
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',
123 );
124 MediaWiki\suppressWarnings();
125 $xcfMeta = unserialize( $image->getMetadata() );
126 MediaWiki\restoreWarnings();
127 if ( $xcfMeta
128 && isset( $xcfMeta['colorType'] )
129 && $xcfMeta['colorType'] === 'greyscale-alpha'
130 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
131 ) {
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 );
136 }
137 }
138
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;
143 }
144
145 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
146 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
147
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'] ) ) ) );
170
171 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
172 $retval = 0;
173 $err = wfShellExecWithStderr( $cmd, $retval, $env );
174
175 if ( $retval !== 0 ) {
176 $this->logErrorForExternalProcess( $retval, $err, $cmd );
177
178 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
179 }
180
181 return false; # No error
182 }
183
184 /**
185 * Transform an image using the Imagick PHP extension
186 *
187 * @param File $image File associated with this thumbnail
188 * @param array $params Array with scaler params
189 *
190 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
191 */
192 protected function transformImageMagickExt( $image, $params ) {
193 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
194
195 try {
196 $im = new Imagick();
197 $im->readImage( $params['srcPath'] );
198
199 if ( $params['mimeType'] == 'image/jpeg' ) {
200 // Sharpening, see bug 6193
201 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
202 / ( $params['srcWidth'] + $params['srcHeight'] )
203 < $wgSharpenReductionThreshold
204 ) {
205 // Hack, since $wgSharpenParameter is written specifically for the command line convert
206 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
207 $im->sharpenImage( $radius, $sigma );
208 }
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();
221 }
222 }
223
224 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
225 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
226
227 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
228
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" );
233 }
234 }
235 $im->setImageDepth( 8 );
236
237 if ( $rotation ) {
238 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
239 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
240 }
241 }
242
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'] );
249 }
250 if ( !$result ) {
251 return $this->getMediaTransformError( $params,
252 "Unable to write thumbnail to {$params['dstPath']}" );
253 }
254 } catch ( ImagickException $e ) {
255 return $this->getMediaTransformError( $params, $e->getMessage() );
256 }
257
258 return false;
259 }
260
261 /**
262 * Transform an image using a custom command
263 *
264 * @param File $image File associated with this thumbnail
265 * @param array $params Array with scaler params
266 *
267 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
268 */
269 protected function transformCustom( $image, $params ) {
270 # Use a custom convert command
271 global $wgCustomConvertCommand;
272
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 );
283
284 if ( $retval !== 0 ) {
285 $this->logErrorForExternalProcess( $retval, $err, $cmd );
286
287 return $this->getMediaTransformError( $params, $err );
288 }
289
290 return false; # No error
291 }
292
293 /**
294 * Transform an image using the built in GD library
295 *
296 * @param File $image File associated with this thumbnail
297 * @param array $params Array with scaler params
298 *
299 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
300 */
301 protected function transformGd( $image, $params ) {
302 # Use PHP's builtin GD library functions.
303 #
304 # First find out what kind of file this is, and select the correct
305 # input routine for this.
306
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' ),
314 );
315
316 if ( !isset( $typemap[$params['mimeType']] ) ) {
317 $err = 'Image type not supported';
318 wfDebug( "$err\n" );
319 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
320
321 return $this->getMediaTransformError( $params, $errMsg );
322 }
323 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
324
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();
329
330 return $this->getMediaTransformError( $params, $errMsg );
331 }
332
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();
337
338 return $this->getMediaTransformError( $params, $errMsg );
339 }
340
341 $src_image = call_user_func( $loader, $params['srcPath'] );
342
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 );
346
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 );
352
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 ) );
365 }
366
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;
371 }
372
373 imagesavealpha( $dst_image, true );
374
375 $funcParams = array( $dst_image, $params['dstPath'] );
376 if ( $useQuality && isset( $params['quality'] ) ) {
377 $funcParams[] = $params['quality'];
378 }
379 call_user_func_array( $saveType, $funcParams );
380
381 imagedestroy( $dst_image );
382 imagedestroy( $src_image );
383
384 return false; # No error
385 }
386
387 /**
388 * Callback for transformGd when transforming jpeg images.
389 */
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 );
394 }
395
396 /**
397 * Returns whether the current scaler supports rotation (im and gd do)
398 *
399 * @return bool
400 */
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;
417 }
418 }
419
420 /**
421 * @see $wgEnableAutoRotation
422 * @return bool Whether auto rotation is enabled
423 */
424 public function autoRotateEnabled() {
425 global $wgEnableAutoRotation;
426
427 if ( $wgEnableAutoRotation === null ) {
428 // Only enable auto-rotation when we actually can
429 return $this->canRotate();
430 }
431
432 return $wgEnableAutoRotation;
433 }
434
435 /**
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
441 */
442 public function rotate( $file, $params ) {
443 global $wgImageMagickConvertCommand;
444
445 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
446 $scene = false;
447
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 );
460
461 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
462 }
463
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" );
471 }
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']}" );
476 }
477
478 return false;
479 default:
480 return new MediaTransformError( 'thumbnail_error', 0, 0,
481 "$scaler rotation not implemented" );
482 }
483 }
484 }