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