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