Merge "mediawiki.page.gallery.resize: Remove weird mw.hook call"
[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 ImageHandler {
30 /**
31 * @param File $image
32 * @param array $params Transform parameters. Entries with the keys 'width'
33 * and 'height' are the respective screen width and height, while the keys
34 * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
35 * @return bool
36 */
37 function normaliseParams( $image, &$params ) {
38 if ( !parent::normaliseParams( $image, $params ) ) {
39 return false;
40 }
41
42 # Obtain the source, pre-rotation dimensions
43 $srcWidth = $image->getWidth( $params['page'] );
44 $srcHeight = $image->getHeight( $params['page'] );
45
46 # Don't make an image bigger than the source
47 if ( $params['physicalWidth'] >= $srcWidth ) {
48 $params['physicalWidth'] = $srcWidth;
49 $params['physicalHeight'] = $srcHeight;
50
51 # Skip scaling limit checks if no scaling is required
52 # due to requested size being bigger than source.
53 if ( !$image->mustRender() ) {
54 return true;
55 }
56 }
57
58 # Check if the file is smaller than the maximum image area for thumbnailing
59 $checkImageAreaHookResult = null;
60 wfRunHooks(
61 'BitmapHandlerCheckImageArea',
62 array( $image, &$params, &$checkImageAreaHookResult )
63 );
64
65 if ( is_null( $checkImageAreaHookResult ) ) {
66 global $wgMaxImageArea;
67
68 if ( $srcWidth * $srcHeight > $wgMaxImageArea
69 && !( $image->getMimeType() == 'image/jpeg'
70 && self::getScalerType( false, false ) == 'im' )
71 ) {
72 # Only ImageMagick can efficiently downsize jpg images without loading
73 # the entire file in memory
74 return false;
75 }
76 } else {
77 return $checkImageAreaHookResult;
78 }
79
80 return true;
81 }
82
83 /**
84 * Extracts the width/height if the image will be scaled before rotating
85 *
86 * This will match the physical size/aspect ratio of the original image
87 * prior to application of the rotation -- so for a portrait image that's
88 * stored as raw landscape with 90-degress rotation, the resulting size
89 * will be wider than it is tall.
90 *
91 * @param array $params Parameters as returned by normaliseParams
92 * @param int $rotation The rotation angle that will be applied
93 * @return array ($width, $height) array
94 */
95 public function extractPreRotationDimensions( $params, $rotation ) {
96 if ( $rotation == 90 || $rotation == 270 ) {
97 # We'll resize before rotation, so swap the dimensions again
98 $width = $params['physicalHeight'];
99 $height = $params['physicalWidth'];
100 } else {
101 $width = $params['physicalWidth'];
102 $height = $params['physicalHeight'];
103 }
104
105 return array( $width, $height );
106 }
107
108 /**
109 * @param File $image
110 * @param string $dstPath
111 * @param string $dstUrl
112 * @param array $params
113 * @param int $flags
114 * @return MediaTransformError|ThumbnailImage|TransformParameterError
115 */
116 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
117 if ( !$this->normaliseParams( $image, $params ) ) {
118 return new TransformParameterError( $params );
119 }
120 # Create a parameter array to pass to the scaler
121 $scalerParams = array(
122 # The size to which the image will be resized
123 'physicalWidth' => $params['physicalWidth'],
124 'physicalHeight' => $params['physicalHeight'],
125 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
126 # The size of the image on the page
127 'clientWidth' => $params['width'],
128 'clientHeight' => $params['height'],
129 # Comment as will be added to the Exif of the thumbnail
130 'comment' => isset( $params['descriptionUrl'] )
131 ? "File source: {$params['descriptionUrl']}"
132 : '',
133 # Properties of the original image
134 'srcWidth' => $image->getWidth(),
135 'srcHeight' => $image->getHeight(),
136 'mimeType' => $image->getMimeType(),
137 'dstPath' => $dstPath,
138 'dstUrl' => $dstUrl,
139 );
140
141 if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
142 $scalerParams['quality'] = 30;
143 }
144
145 # Determine scaler type
146 $scaler = self::getScalerType( $dstPath );
147
148 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} " .
149 "thumbnail at $dstPath using scaler $scaler\n" );
150
151 if ( !$image->mustRender() &&
152 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
153 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
154 && !isset( $scalerParams['quality'] )
155 ) {
156
157 # normaliseParams (or the user) wants us to return the unscaled image
158 wfDebug( __METHOD__ . ": returning unscaled image\n" );
159
160 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
161 }
162
163 if ( $scaler == 'client' ) {
164 # Client-side image scaling, use the source URL
165 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
166 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
167 }
168
169 if ( $flags & self::TRANSFORM_LATER ) {
170 wfDebug( __METHOD__ . ": Transforming later per flags.\n" );
171 $newParams = array(
172 'width' => $scalerParams['clientWidth'],
173 'height' => $scalerParams['clientHeight']
174 );
175 if ( isset( $params['quality'] ) ) {
176 $newParams['quality'] = $params['quality'];
177 }
178 return new ThumbnailImage( $image, $dstUrl, false, $newParams );
179 }
180
181 # Try to make a target path for the thumbnail
182 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
183 wfDebug( __METHOD__ . ": Unable to create thumbnail destination " .
184 "directory, falling back to client scaling\n" );
185
186 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
187 }
188
189 # Transform functions and binaries need a FS source file
190 $scalerParams['srcPath'] = $image->getLocalRefPath();
191 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
192 wfDebugLog( 'thumbnail',
193 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
194 wfHostname(), $image->getName() ) );
195
196 return new MediaTransformError( 'thumbnail_error',
197 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
198 wfMessage( 'filemissing' )->text()
199 );
200 }
201
202 # Try a hook
203 $mto = null;
204 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
205 if ( !is_null( $mto ) ) {
206 wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto\n" );
207 $scaler = 'hookaborted';
208 }
209
210 switch ( $scaler ) {
211 case 'hookaborted':
212 # Handled by the hook above
213 /** @var MediaTransformOutput $mto */
214 $err = $mto->isError() ? $mto : false;
215 break;
216 case 'im':
217 $err = $this->transformImageMagick( $image, $scalerParams );
218 break;
219 case 'custom':
220 $err = $this->transformCustom( $image, $scalerParams );
221 break;
222 case 'imext':
223 $err = $this->transformImageMagickExt( $image, $scalerParams );
224 break;
225 case 'gd':
226 default:
227 $err = $this->transformGd( $image, $scalerParams );
228 break;
229 }
230
231 # Remove the file if a zero-byte thumbnail was created, or if there was an error
232 $removed = $this->removeBadFile( $dstPath, (bool)$err );
233 if ( $err ) {
234 # transform returned MediaTransforError
235 return $err;
236 } elseif ( $removed ) {
237 # Thumbnail was zero-byte and had to be removed
238 return new MediaTransformError( 'thumbnail_error',
239 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
240 wfMessage( 'unknown-error' )->text()
241 );
242 } elseif ( $mto ) {
243 return $mto;
244 } else {
245 $newParams = array(
246 'width' => $scalerParams['clientWidth'],
247 'height' => $scalerParams['clientHeight']
248 );
249 if ( isset( $params['quality'] ) ) {
250 $newParams['quality'] = $params['quality'];
251 }
252 return new ThumbnailImage( $image, $dstUrl, $dstPath, $newParams );
253 }
254 }
255
256 /**
257 * Returns which scaler type should be used. Creates parent directories
258 * for $dstPath and returns 'client' on error
259 *
260 * @param string $dstPath
261 * @param bool $checkDstPath
262 * @return string One of client, im, custom, gd, imext
263 */
264 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
265 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
266
267 if ( !$dstPath && $checkDstPath ) {
268 # No output path available, client side scaling only
269 $scaler = 'client';
270 } elseif ( !$wgUseImageResize ) {
271 $scaler = 'client';
272 } elseif ( $wgUseImageMagick ) {
273 $scaler = 'im';
274 } elseif ( $wgCustomConvertCommand ) {
275 $scaler = 'custom';
276 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
277 $scaler = 'gd';
278 } elseif ( class_exists( 'Imagick' ) ) {
279 $scaler = 'imext';
280 } else {
281 $scaler = 'client';
282 }
283
284 return $scaler;
285 }
286
287 /**
288 * Get a ThumbnailImage that respresents an image that will be scaled
289 * client side
290 *
291 * @param File $image File associated with this thumbnail
292 * @param array $scalerParams Array with scaler params
293 * @return ThumbnailImage
294 *
295 * @todo FIXME: No rotation support
296 */
297 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
298 $params = array(
299 'width' => $scalerParams['clientWidth'],
300 'height' => $scalerParams['clientHeight']
301 );
302
303 return new ThumbnailImage( $image, $image->getURL(), null, $params );
304 }
305
306 /**
307 * Transform an image using ImageMagick
308 *
309 * @param File $image File associated with this thumbnail
310 * @param array $params Array with scaler params
311 *
312 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
313 */
314 protected function transformImageMagick( $image, $params ) {
315 # use ImageMagick
316 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
317 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
318
319 $quality = array();
320 $sharpen = array();
321 $scene = false;
322 $animation_pre = array();
323 $animation_post = array();
324 $decoderHint = array();
325 if ( $params['mimeType'] == 'image/jpeg' ) {
326 $qualityVal = isset( $params['quality'] ) ? (string) $params['quality'] : null;
327 $quality = array( '-quality', $qualityVal ?: '80' ); // 80%
328 # Sharpening, see bug 6193
329 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
330 / ( $params['srcWidth'] + $params['srcHeight'] )
331 < $wgSharpenReductionThreshold
332 ) {
333 $sharpen = array( '-sharpen', $wgSharpenParameter );
334 }
335 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
336 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
337 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
338 }
339 } elseif ( $params['mimeType'] == 'image/png' ) {
340 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
341
342 } elseif ( $params['mimeType'] == 'image/gif' ) {
343 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
344 // Extract initial frame only; we're so big it'll
345 // be a total drag. :P
346 $scene = 0;
347 } elseif ( $this->isAnimatedImage( $image ) ) {
348 // Coalesce is needed to scale animated GIFs properly (bug 1017).
349 $animation_pre = array( '-coalesce' );
350 // We optimize the output, but -optimize is broken,
351 // use optimizeTransparency instead (bug 11822)
352 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
353 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
354 }
355 }
356 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
357 // Before merging layers, we need to set the background
358 // to be transparent to preserve alpha, as -layers merge
359 // merges all layers on to a canvas filled with the
360 // background colour. After merging we reset the background
361 // to be white for the default background colour setting
362 // in the PNG image (which is used in old IE)
363 $animation_post = array(
364 '-background', 'transparent',
365 '-layers', 'merge',
366 '-background', 'white',
367 );
368 wfSuppressWarnings();
369 $xcfMeta = unserialize( $image->getMetadata() );
370 wfRestoreWarnings();
371 if ( $xcfMeta
372 && isset( $xcfMeta['colorType'] )
373 && $xcfMeta['colorType'] === 'greyscale-alpha'
374 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
375 ) {
376 // bug 66323 - Greyscale images not rendered properly.
377 // So only take the "red" channel.
378 $channelOnly = array( '-channel', 'R', '-separate' );
379 $animation_post = array_merge( $animation_post, $channelOnly );
380 }
381 }
382
383 // Use one thread only, to avoid deadlock bugs on OOM
384 $env = array( 'OMP_NUM_THREADS' => 1 );
385 if ( strval( $wgImageMagickTempDir ) !== '' ) {
386 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
387 }
388
389 $rotation = $this->getRotation( $image );
390 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
391
392 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
393 array( $wgImageMagickConvertCommand ),
394 $quality,
395 // Specify white background color, will be used for transparent images
396 // in Internet Explorer/Windows instead of default black.
397 array( '-background', 'white' ),
398 $decoderHint,
399 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
400 $animation_pre,
401 // For the -thumbnail option a "!" is needed to force exact size,
402 // or ImageMagick may decide your ratio is wrong and slice off
403 // a pixel.
404 array( '-thumbnail', "{$width}x{$height}!" ),
405 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
406 ( $params['comment'] !== ''
407 ? array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
408 : array() ),
409 array( '-depth', 8 ),
410 $sharpen,
411 array( '-rotate', "-$rotation" ),
412 $animation_post,
413 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
414
415 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
416 wfProfileIn( 'convert' );
417 $retval = 0;
418 $err = wfShellExecWithStderr( $cmd, $retval, $env );
419 wfProfileOut( 'convert' );
420
421 if ( $retval !== 0 ) {
422 $this->logErrorForExternalProcess( $retval, $err, $cmd );
423
424 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
425 }
426
427 return false; # No error
428 }
429
430 /**
431 * Transform an image using the Imagick PHP extension
432 *
433 * @param File $image File associated with this thumbnail
434 * @param array $params Array with scaler params
435 *
436 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
437 */
438 protected function transformImageMagickExt( $image, $params ) {
439 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
440
441 try {
442 $im = new Imagick();
443 $im->readImage( $params['srcPath'] );
444
445 if ( $params['mimeType'] == 'image/jpeg' ) {
446 // Sharpening, see bug 6193
447 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
448 / ( $params['srcWidth'] + $params['srcHeight'] )
449 < $wgSharpenReductionThreshold
450 ) {
451 // Hack, since $wgSharpenParamater is written specifically for the command line convert
452 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
453 $im->sharpenImage( $radius, $sigma );
454 }
455 $qualityVal = isset( $params['quality'] ) ? (string) $params['quality'] : null;
456 $im->setCompressionQuality( $qualityVal ?: 80 );
457 } elseif ( $params['mimeType'] == 'image/png' ) {
458 $im->setCompressionQuality( 95 );
459 } elseif ( $params['mimeType'] == 'image/gif' ) {
460 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
461 // Extract initial frame only; we're so big it'll
462 // be a total drag. :P
463 $im->setImageScene( 0 );
464 } elseif ( $this->isAnimatedImage( $image ) ) {
465 // Coalesce is needed to scale animated GIFs properly (bug 1017).
466 $im = $im->coalesceImages();
467 }
468 }
469
470 $rotation = $this->getRotation( $image );
471 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
472
473 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
474
475 // Call Imagick::thumbnailImage on each frame
476 foreach ( $im as $i => $frame ) {
477 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
478 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
479 }
480 }
481 $im->setImageDepth( 8 );
482
483 if ( $rotation ) {
484 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
485 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
486 }
487 }
488
489 if ( $this->isAnimatedImage( $image ) ) {
490 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
491 // This is broken somehow... can't find out how to fix it
492 $result = $im->writeImages( $params['dstPath'], true );
493 } else {
494 $result = $im->writeImage( $params['dstPath'] );
495 }
496 if ( !$result ) {
497 return $this->getMediaTransformError( $params,
498 "Unable to write thumbnail to {$params['dstPath']}" );
499 }
500 } catch ( ImagickException $e ) {
501 return $this->getMediaTransformError( $params, $e->getMessage() );
502 }
503
504 return false;
505 }
506
507 /**
508 * Transform an image using a custom command
509 *
510 * @param File $image File associated with this thumbnail
511 * @param array $params Array with scaler params
512 *
513 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
514 */
515 protected function transformCustom( $image, $params ) {
516 # Use a custom convert command
517 global $wgCustomConvertCommand;
518
519 # Variables: %s %d %w %h
520 $src = wfEscapeShellArg( $params['srcPath'] );
521 $dst = wfEscapeShellArg( $params['dstPath'] );
522 $cmd = $wgCustomConvertCommand;
523 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
524 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
525 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
526 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
527 wfProfileIn( 'convert' );
528 $retval = 0;
529 $err = wfShellExecWithStderr( $cmd, $retval );
530 wfProfileOut( 'convert' );
531
532 if ( $retval !== 0 ) {
533 $this->logErrorForExternalProcess( $retval, $err, $cmd );
534
535 return $this->getMediaTransformError( $params, $err );
536 }
537
538 return false; # No error
539 }
540
541 /**
542 * Get a MediaTransformError with error 'thumbnail_error'
543 *
544 * @param array $params Parameter array as passed to the transform* functions
545 * @param string $errMsg Error message
546 * @return MediaTransformError
547 */
548 public function getMediaTransformError( $params, $errMsg ) {
549 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
550 $params['clientHeight'], $errMsg );
551 }
552
553 /**
554 * Transform an image using the built in GD library
555 *
556 * @param File $image File associated with this thumbnail
557 * @param array $params Array with scaler params
558 *
559 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
560 */
561 protected function transformGd( $image, $params ) {
562 # Use PHP's builtin GD library functions.
563 #
564 # First find out what kind of file this is, and select the correct
565 # input routine for this.
566
567 $typemap = array(
568 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
569 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
570 array( __CLASS__, 'imageJpegWrapper' ) ),
571 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
572 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
573 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
574 );
575
576 if ( !isset( $typemap[$params['mimeType']] ) ) {
577 $err = 'Image type not supported';
578 wfDebug( "$err\n" );
579 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
580
581 return $this->getMediaTransformError( $params, $errMsg );
582 }
583 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
584
585 if ( !function_exists( $loader ) ) {
586 $err = "Incomplete GD library configuration: missing function $loader";
587 wfDebug( "$err\n" );
588 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
589
590 return $this->getMediaTransformError( $params, $errMsg );
591 }
592
593 if ( !file_exists( $params['srcPath'] ) ) {
594 $err = "File seems to be missing: {$params['srcPath']}";
595 wfDebug( "$err\n" );
596 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
597
598 return $this->getMediaTransformError( $params, $errMsg );
599 }
600
601 $src_image = call_user_func( $loader, $params['srcPath'] );
602
603 $rotation = function_exists( 'imagerotate' ) ? $this->getRotation( $image ) : 0;
604 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
605 $dst_image = imagecreatetruecolor( $width, $height );
606
607 // Initialise the destination image to transparent instead of
608 // the default solid black, to support PNG and GIF transparency nicely
609 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
610 imagecolortransparent( $dst_image, $background );
611 imagealphablending( $dst_image, false );
612
613 if ( $colorStyle == 'palette' ) {
614 // Don't resample for paletted GIF images.
615 // It may just uglify them, and completely breaks transparency.
616 imagecopyresized( $dst_image, $src_image,
617 0, 0, 0, 0,
618 $width, $height,
619 imagesx( $src_image ), imagesy( $src_image ) );
620 } else {
621 imagecopyresampled( $dst_image, $src_image,
622 0, 0, 0, 0,
623 $width, $height,
624 imagesx( $src_image ), imagesy( $src_image ) );
625 }
626
627 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
628 $rot_image = imagerotate( $dst_image, $rotation, 0 );
629 imagedestroy( $dst_image );
630 $dst_image = $rot_image;
631 }
632
633 imagesavealpha( $dst_image, true );
634
635 $funcParams = array( $dst_image, $params['dstPath'] );
636 if ( $useQuality && isset( $params['quality'] ) ) {
637 $funcParams[] = $params['quality'];
638 }
639 call_user_func_array( $saveType, $funcParams );
640
641 imagedestroy( $dst_image );
642 imagedestroy( $src_image );
643
644 return false; # No error
645 }
646
647 /**
648 * Escape a string for ImageMagick's property input (e.g. -set -comment)
649 * See InterpretImageProperties() in magick/property.c
650 * @param string $s
651 * @return string
652 */
653 function escapeMagickProperty( $s ) {
654 // Double the backslashes
655 $s = str_replace( '\\', '\\\\', $s );
656 // Double the percents
657 $s = str_replace( '%', '%%', $s );
658 // Escape initial - or @
659 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
660 $s = '\\' . $s;
661 }
662
663 return $s;
664 }
665
666 /**
667 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
668 * and GetPathComponent() in magick/utility.c.
669 *
670 * This won't work with an initial ~ or @, so input files should be prefixed
671 * with the directory name.
672 *
673 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
674 * it's broken in a way that doesn't involve trying to convert every file
675 * in a directory, so we're better off escaping and waiting for the bugfix
676 * to filter down to users.
677 *
678 * @param string $path The file path
679 * @param bool|string $scene The scene specification, or false if there is none
680 * @throws MWException
681 * @return string
682 */
683 function escapeMagickInput( $path, $scene = false ) {
684 # Die on initial metacharacters (caller should prepend path)
685 $firstChar = substr( $path, 0, 1 );
686 if ( $firstChar === '~' || $firstChar === '@' ) {
687 throw new MWException( __METHOD__ . ': cannot escape this path name' );
688 }
689
690 # Escape glob chars
691 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
692
693 return $this->escapeMagickPath( $path, $scene );
694 }
695
696 /**
697 * Escape a string for ImageMagick's output filename. See
698 * InterpretImageFilename() in magick/image.c.
699 * @param string $path The file path
700 * @param bool|string $scene The scene specification, or false if there is none
701 * @return string
702 */
703 function escapeMagickOutput( $path, $scene = false ) {
704 $path = str_replace( '%', '%%', $path );
705
706 return $this->escapeMagickPath( $path, $scene );
707 }
708
709 /**
710 * Armour a string against ImageMagick's GetPathComponent(). This is a
711 * helper function for escapeMagickInput() and escapeMagickOutput().
712 *
713 * @param string $path The file path
714 * @param bool|string $scene The scene specification, or false if there is none
715 * @throws MWException
716 * @return string
717 */
718 protected function escapeMagickPath( $path, $scene = false ) {
719 # Die on format specifiers (other than drive letters). The regex is
720 # meant to match all the formats you get from "convert -list format"
721 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
722 if ( wfIsWindows() && is_dir( $m[0] ) ) {
723 // OK, it's a drive letter
724 // ImageMagick has a similar exception, see IsMagickConflict()
725 } else {
726 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
727 }
728 }
729
730 # If there are square brackets, add a do-nothing scene specification
731 # to force a literal interpretation
732 if ( $scene === false ) {
733 if ( strpos( $path, '[' ) !== false ) {
734 $path .= '[0--1]';
735 }
736 } else {
737 $path .= "[$scene]";
738 }
739
740 return $path;
741 }
742
743 /**
744 * Retrieve the version of the installed ImageMagick
745 * You can use PHPs version_compare() to use this value
746 * Value is cached for one hour.
747 * @return string Representing the IM version.
748 */
749 protected function getMagickVersion() {
750 global $wgMemc;
751
752 $cache = $wgMemc->get( "imagemagick-version" );
753 if ( !$cache ) {
754 global $wgImageMagickConvertCommand;
755 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
756 wfDebug( __METHOD__ . ": Running convert -version\n" );
757 $retval = '';
758 $return = wfShellExec( $cmd, $retval );
759 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
760 if ( $x != 1 ) {
761 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
762
763 return null;
764 }
765 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
766
767 return $matches[1];
768 }
769
770 return $cache;
771 }
772
773 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
774 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
775 imageinterlace( $dst_image );
776 imagejpeg( $dst_image, $thumbPath, $quality );
777 }
778
779 /**
780 * Returns whether the current scaler supports rotation (im and gd do)
781 *
782 * @return bool
783 */
784 public static function canRotate() {
785 $scaler = self::getScalerType( null, false );
786 switch ( $scaler ) {
787 case 'im':
788 # ImageMagick supports autorotation
789 return true;
790 case 'imext':
791 # Imagick::rotateImage
792 return true;
793 case 'gd':
794 # GD's imagerotate function is used to rotate images, but not
795 # all precompiled PHP versions have that function
796 return function_exists( 'imagerotate' );
797 default:
798 # Other scalers don't support rotation
799 return false;
800 }
801 }
802
803 /**
804 * @see $wgEnableAutoRotation
805 * @return bool Whether auto rotation is enabled
806 */
807 public static function autoRotateEnabled() {
808 global $wgEnableAutoRotation;
809
810 if ( $wgEnableAutoRotation === null ) {
811 // Only enable auto-rotation when the bitmap handler can rotate
812 $wgEnableAutoRotation = BitmapHandler::canRotate();
813 }
814
815 return $wgEnableAutoRotation;
816 }
817
818 /**
819 * @param File $file
820 * @param array $params Rotate parameters.
821 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
822 * @since 1.21
823 * @return bool
824 */
825 public function rotate( $file, $params ) {
826 global $wgImageMagickConvertCommand;
827
828 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
829 $scene = false;
830
831 $scaler = self::getScalerType( null, false );
832 switch ( $scaler ) {
833 case 'im':
834 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
835 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
836 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
837 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
838 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
839 wfProfileIn( 'convert' );
840 $retval = 0;
841 $err = wfShellExecWithStderr( $cmd, $retval );
842 wfProfileOut( 'convert' );
843 if ( $retval !== 0 ) {
844 $this->logErrorForExternalProcess( $retval, $err, $cmd );
845
846 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
847 }
848
849 return false;
850 case 'imext':
851 $im = new Imagick();
852 $im->readImage( $params['srcPath'] );
853 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
854 return new MediaTransformError( 'thumbnail_error', 0, 0,
855 "Error rotating $rotation degrees" );
856 }
857 $result = $im->writeImage( $params['dstPath'] );
858 if ( !$result ) {
859 return new MediaTransformError( 'thumbnail_error', 0, 0,
860 "Unable to write image to {$params['dstPath']}" );
861 }
862
863 return false;
864 default:
865 return new MediaTransformError( 'thumbnail_error', 0, 0,
866 "$scaler rotation not implemented" );
867 }
868 }
869
870 /**
871 * Rerurns whether the file needs to be rendered. Returns true if the
872 * file requires rotation and we are able to rotate it.
873 *
874 * @param File $file
875 * @return bool
876 */
877 public function mustRender( $file ) {
878 return self::canRotate() && $this->getRotation( $file ) != 0;
879 }
880 }