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