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