Merge "Make the URL input on Special:LinkSearch ltr by default"
[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 $animation_post = array( '-layers', 'merge' );
358 wfSuppressWarnings();
359 $xcfMeta = unserialize( $image->getMetadata() );
360 wfRestoreWarnings();
361 if ( $xcfMeta
362 && isset( $xcfMeta['colorType'] )
363 && $xcfMeta['colorType'] === 'greyscale-alpha'
364 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
365 ) {
366 // bug 66323 - Greyscale images not rendered properly.
367 // So only take the "red" channel.
368 $channelOnly = array( '-channel', 'R', '-separate' );
369 $animation_post = array_merge( $animation_post, $channelOnly );
370 }
371 }
372
373 // Use one thread only, to avoid deadlock bugs on OOM
374 $env = array( 'OMP_NUM_THREADS' => 1 );
375 if ( strval( $wgImageMagickTempDir ) !== '' ) {
376 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
377 }
378
379 $rotation = $this->getRotation( $image );
380 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
381
382 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
383 array( $wgImageMagickConvertCommand ),
384 $quality,
385 // Specify white background color, will be used for transparent images
386 // in Internet Explorer/Windows instead of default black.
387 array( '-background', 'white' ),
388 $decoderHint,
389 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
390 $animation_pre,
391 // For the -thumbnail option a "!" is needed to force exact size,
392 // or ImageMagick may decide your ratio is wrong and slice off
393 // a pixel.
394 array( '-thumbnail', "{$width}x{$height}!" ),
395 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
396 ( $params['comment'] !== ''
397 ? array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
398 : array() ),
399 array( '-depth', 8 ),
400 $sharpen,
401 array( '-rotate', "-$rotation" ),
402 $animation_post,
403 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
404
405 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
406 wfProfileIn( 'convert' );
407 $retval = 0;
408 $err = wfShellExecWithStderr( $cmd, $retval, $env );
409 wfProfileOut( 'convert' );
410
411 if ( $retval !== 0 ) {
412 $this->logErrorForExternalProcess( $retval, $err, $cmd );
413
414 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
415 }
416
417 return false; # No error
418 }
419
420 /**
421 * Transform an image using the Imagick PHP extension
422 *
423 * @param File $image File associated with this thumbnail
424 * @param array $params Array with scaler params
425 *
426 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
427 */
428 protected function transformImageMagickExt( $image, $params ) {
429 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
430
431 try {
432 $im = new Imagick();
433 $im->readImage( $params['srcPath'] );
434
435 if ( $params['mimeType'] == 'image/jpeg' ) {
436 // Sharpening, see bug 6193
437 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
438 / ( $params['srcWidth'] + $params['srcHeight'] )
439 < $wgSharpenReductionThreshold
440 ) {
441 // Hack, since $wgSharpenParamater is written specifically for the command line convert
442 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
443 $im->sharpenImage( $radius, $sigma );
444 }
445 $qualityVal = isset( $params['quality'] ) ? (string) $params['quality'] : null;
446 $im->setCompressionQuality( $qualityVal ?: 80 );
447 } elseif ( $params['mimeType'] == 'image/png' ) {
448 $im->setCompressionQuality( 95 );
449 } elseif ( $params['mimeType'] == 'image/gif' ) {
450 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
451 // Extract initial frame only; we're so big it'll
452 // be a total drag. :P
453 $im->setImageScene( 0 );
454 } elseif ( $this->isAnimatedImage( $image ) ) {
455 // Coalesce is needed to scale animated GIFs properly (bug 1017).
456 $im = $im->coalesceImages();
457 }
458 }
459
460 $rotation = $this->getRotation( $image );
461 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
462
463 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
464
465 // Call Imagick::thumbnailImage on each frame
466 foreach ( $im as $i => $frame ) {
467 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
468 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
469 }
470 }
471 $im->setImageDepth( 8 );
472
473 if ( $rotation ) {
474 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
475 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
476 }
477 }
478
479 if ( $this->isAnimatedImage( $image ) ) {
480 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
481 // This is broken somehow... can't find out how to fix it
482 $result = $im->writeImages( $params['dstPath'], true );
483 } else {
484 $result = $im->writeImage( $params['dstPath'] );
485 }
486 if ( !$result ) {
487 return $this->getMediaTransformError( $params,
488 "Unable to write thumbnail to {$params['dstPath']}" );
489 }
490 } catch ( ImagickException $e ) {
491 return $this->getMediaTransformError( $params, $e->getMessage() );
492 }
493
494 return false;
495 }
496
497 /**
498 * Transform an image using a custom command
499 *
500 * @param File $image File associated with this thumbnail
501 * @param array $params Array with scaler params
502 *
503 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
504 */
505 protected function transformCustom( $image, $params ) {
506 # Use a custom convert command
507 global $wgCustomConvertCommand;
508
509 # Variables: %s %d %w %h
510 $src = wfEscapeShellArg( $params['srcPath'] );
511 $dst = wfEscapeShellArg( $params['dstPath'] );
512 $cmd = $wgCustomConvertCommand;
513 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
514 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
515 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
516 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
517 wfProfileIn( 'convert' );
518 $retval = 0;
519 $err = wfShellExecWithStderr( $cmd, $retval );
520 wfProfileOut( 'convert' );
521
522 if ( $retval !== 0 ) {
523 $this->logErrorForExternalProcess( $retval, $err, $cmd );
524
525 return $this->getMediaTransformError( $params, $err );
526 }
527
528 return false; # No error
529 }
530
531 /**
532 * Get a MediaTransformError with error 'thumbnail_error'
533 *
534 * @param array $params Parameter array as passed to the transform* functions
535 * @param string $errMsg Error message
536 * @return MediaTransformError
537 */
538 public function getMediaTransformError( $params, $errMsg ) {
539 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
540 $params['clientHeight'], $errMsg );
541 }
542
543 /**
544 * Transform an image using the built in GD library
545 *
546 * @param File $image File associated with this thumbnail
547 * @param array $params Array with scaler params
548 *
549 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
550 */
551 protected function transformGd( $image, $params ) {
552 # Use PHP's builtin GD library functions.
553 #
554 # First find out what kind of file this is, and select the correct
555 # input routine for this.
556
557 $typemap = array(
558 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
559 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
560 array( __CLASS__, 'imageJpegWrapper' ) ),
561 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
562 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
563 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
564 );
565
566 if ( !isset( $typemap[$params['mimeType']] ) ) {
567 $err = 'Image type not supported';
568 wfDebug( "$err\n" );
569 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
570
571 return $this->getMediaTransformError( $params, $errMsg );
572 }
573 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
574
575 if ( !function_exists( $loader ) ) {
576 $err = "Incomplete GD library configuration: missing function $loader";
577 wfDebug( "$err\n" );
578 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
579
580 return $this->getMediaTransformError( $params, $errMsg );
581 }
582
583 if ( !file_exists( $params['srcPath'] ) ) {
584 $err = "File seems to be missing: {$params['srcPath']}";
585 wfDebug( "$err\n" );
586 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
587
588 return $this->getMediaTransformError( $params, $errMsg );
589 }
590
591 $src_image = call_user_func( $loader, $params['srcPath'] );
592
593 $rotation = function_exists( 'imagerotate' ) ? $this->getRotation( $image ) : 0;
594 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
595 $dst_image = imagecreatetruecolor( $width, $height );
596
597 // Initialise the destination image to transparent instead of
598 // the default solid black, to support PNG and GIF transparency nicely
599 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
600 imagecolortransparent( $dst_image, $background );
601 imagealphablending( $dst_image, false );
602
603 if ( $colorStyle == 'palette' ) {
604 // Don't resample for paletted GIF images.
605 // It may just uglify them, and completely breaks transparency.
606 imagecopyresized( $dst_image, $src_image,
607 0, 0, 0, 0,
608 $width, $height,
609 imagesx( $src_image ), imagesy( $src_image ) );
610 } else {
611 imagecopyresampled( $dst_image, $src_image,
612 0, 0, 0, 0,
613 $width, $height,
614 imagesx( $src_image ), imagesy( $src_image ) );
615 }
616
617 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
618 $rot_image = imagerotate( $dst_image, $rotation, 0 );
619 imagedestroy( $dst_image );
620 $dst_image = $rot_image;
621 }
622
623 imagesavealpha( $dst_image, true );
624
625 $funcParams = array( $dst_image, $params['dstPath'] );
626 if ( $useQuality && isset( $params['quality'] ) ) {
627 $funcParams[] = $params['quality'];
628 }
629 call_user_func_array( $saveType, $funcParams );
630
631 imagedestroy( $dst_image );
632 imagedestroy( $src_image );
633
634 return false; # No error
635 }
636
637 /**
638 * Escape a string for ImageMagick's property input (e.g. -set -comment)
639 * See InterpretImageProperties() in magick/property.c
640 * @param string $s
641 * @return string
642 */
643 function escapeMagickProperty( $s ) {
644 // Double the backslashes
645 $s = str_replace( '\\', '\\\\', $s );
646 // Double the percents
647 $s = str_replace( '%', '%%', $s );
648 // Escape initial - or @
649 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
650 $s = '\\' . $s;
651 }
652
653 return $s;
654 }
655
656 /**
657 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
658 * and GetPathComponent() in magick/utility.c.
659 *
660 * This won't work with an initial ~ or @, so input files should be prefixed
661 * with the directory name.
662 *
663 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
664 * it's broken in a way that doesn't involve trying to convert every file
665 * in a directory, so we're better off escaping and waiting for the bugfix
666 * to filter down to users.
667 *
668 * @param string $path The file path
669 * @param bool|string $scene The scene specification, or false if there is none
670 * @throws MWException
671 * @return string
672 */
673 function escapeMagickInput( $path, $scene = false ) {
674 # Die on initial metacharacters (caller should prepend path)
675 $firstChar = substr( $path, 0, 1 );
676 if ( $firstChar === '~' || $firstChar === '@' ) {
677 throw new MWException( __METHOD__ . ': cannot escape this path name' );
678 }
679
680 # Escape glob chars
681 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
682
683 return $this->escapeMagickPath( $path, $scene );
684 }
685
686 /**
687 * Escape a string for ImageMagick's output filename. See
688 * InterpretImageFilename() in magick/image.c.
689 * @param string $path The file path
690 * @param bool|string $scene The scene specification, or false if there is none
691 * @return string
692 */
693 function escapeMagickOutput( $path, $scene = false ) {
694 $path = str_replace( '%', '%%', $path );
695
696 return $this->escapeMagickPath( $path, $scene );
697 }
698
699 /**
700 * Armour a string against ImageMagick's GetPathComponent(). This is a
701 * helper function for escapeMagickInput() and escapeMagickOutput().
702 *
703 * @param string $path The file path
704 * @param bool|string $scene The scene specification, or false if there is none
705 * @throws MWException
706 * @return string
707 */
708 protected function escapeMagickPath( $path, $scene = false ) {
709 # Die on format specifiers (other than drive letters). The regex is
710 # meant to match all the formats you get from "convert -list format"
711 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
712 if ( wfIsWindows() && is_dir( $m[0] ) ) {
713 // OK, it's a drive letter
714 // ImageMagick has a similar exception, see IsMagickConflict()
715 } else {
716 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
717 }
718 }
719
720 # If there are square brackets, add a do-nothing scene specification
721 # to force a literal interpretation
722 if ( $scene === false ) {
723 if ( strpos( $path, '[' ) !== false ) {
724 $path .= '[0--1]';
725 }
726 } else {
727 $path .= "[$scene]";
728 }
729
730 return $path;
731 }
732
733 /**
734 * Retrieve the version of the installed ImageMagick
735 * You can use PHPs version_compare() to use this value
736 * Value is cached for one hour.
737 * @return string Representing the IM version.
738 */
739 protected function getMagickVersion() {
740 global $wgMemc;
741
742 $cache = $wgMemc->get( "imagemagick-version" );
743 if ( !$cache ) {
744 global $wgImageMagickConvertCommand;
745 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
746 wfDebug( __METHOD__ . ": Running convert -version\n" );
747 $retval = '';
748 $return = wfShellExec( $cmd, $retval );
749 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
750 if ( $x != 1 ) {
751 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
752
753 return null;
754 }
755 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
756
757 return $matches[1];
758 }
759
760 return $cache;
761 }
762
763 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
764 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
765 imageinterlace( $dst_image );
766 imagejpeg( $dst_image, $thumbPath, $quality );
767 }
768
769 /**
770 * Returns whether the current scaler supports rotation (im and gd do)
771 *
772 * @return bool
773 */
774 public static function canRotate() {
775 $scaler = self::getScalerType( null, false );
776 switch ( $scaler ) {
777 case 'im':
778 # ImageMagick supports autorotation
779 return true;
780 case 'imext':
781 # Imagick::rotateImage
782 return true;
783 case 'gd':
784 # GD's imagerotate function is used to rotate images, but not
785 # all precompiled PHP versions have that function
786 return function_exists( 'imagerotate' );
787 default:
788 # Other scalers don't support rotation
789 return false;
790 }
791 }
792
793 /**
794 * @see $wgEnableAutoRotation
795 * @return bool Whether auto rotation is enabled
796 */
797 public static function autoRotateEnabled() {
798 global $wgEnableAutoRotation;
799
800 if ( $wgEnableAutoRotation === null ) {
801 // Only enable auto-rotation when the bitmap handler can rotate
802 $wgEnableAutoRotation = BitmapHandler::canRotate();
803 }
804
805 return $wgEnableAutoRotation;
806 }
807
808 /**
809 * @param File $file
810 * @param array $params Rotate parameters.
811 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
812 * @since 1.21
813 * @return bool
814 */
815 public function rotate( $file, $params ) {
816 global $wgImageMagickConvertCommand;
817
818 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
819 $scene = false;
820
821 $scaler = self::getScalerType( null, false );
822 switch ( $scaler ) {
823 case 'im':
824 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
825 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
826 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
827 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
828 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
829 wfProfileIn( 'convert' );
830 $retval = 0;
831 $err = wfShellExecWithStderr( $cmd, $retval );
832 wfProfileOut( 'convert' );
833 if ( $retval !== 0 ) {
834 $this->logErrorForExternalProcess( $retval, $err, $cmd );
835
836 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
837 }
838
839 return false;
840 case 'imext':
841 $im = new Imagick();
842 $im->readImage( $params['srcPath'] );
843 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
844 return new MediaTransformError( 'thumbnail_error', 0, 0,
845 "Error rotating $rotation degrees" );
846 }
847 $result = $im->writeImage( $params['dstPath'] );
848 if ( !$result ) {
849 return new MediaTransformError( 'thumbnail_error', 0, 0,
850 "Unable to write image to {$params['dstPath']}" );
851 }
852
853 return false;
854 default:
855 return new MediaTransformError( 'thumbnail_error', 0, 0,
856 "$scaler rotation not implemented" );
857 }
858 }
859
860 /**
861 * Rerurns whether the file needs to be rendered. Returns true if the
862 * file requires rotation and we are able to rotate it.
863 *
864 * @param File $file
865 * @return bool
866 */
867 public function mustRender( $file ) {
868 return self::canRotate() && $this->getRotation( $file ) != 0;
869 }
870 }