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