Merge "Define 'MW_UPDATER' when running update.php"
[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( 'BitmapHandlerCheckImageArea', array( $image, &$params, &$checkImageAreaHookResult ) );
61 if ( is_null( $checkImageAreaHookResult ) ) {
62 global $wgMaxImageArea;
63
64 if ( $srcWidth * $srcHeight > $wgMaxImageArea
65 && !( $image->getMimeType() == 'image/jpeg'
66 && self::getScalerType( false, false ) == 'im' )
67 ) {
68 # Only ImageMagick can efficiently downsize jpg images without loading
69 # the entire file in memory
70 return false;
71 }
72 } else {
73 return $checkImageAreaHookResult;
74 }
75
76 return true;
77 }
78
79 /**
80 * Extracts the width/height if the image will be scaled before rotating
81 *
82 * This will match the physical size/aspect ratio of the original image
83 * prior to application of the rotation -- so for a portrait image that's
84 * stored as raw landscape with 90-degress rotation, the resulting size
85 * will be wider than it is tall.
86 *
87 * @param array $params Parameters as returned by normaliseParams
88 * @param int $rotation The rotation angle that will be applied
89 * @return array ($width, $height) array
90 */
91 public function extractPreRotationDimensions( $params, $rotation ) {
92 if ( $rotation == 90 || $rotation == 270 ) {
93 # We'll resize before rotation, so swap the dimensions again
94 $width = $params['physicalHeight'];
95 $height = $params['physicalWidth'];
96 } else {
97 $width = $params['physicalWidth'];
98 $height = $params['physicalHeight'];
99 }
100
101 return array( $width, $height );
102 }
103
104 /**
105 * @param $image File
106 * @param $dstPath
107 * @param $dstUrl
108 * @param $params
109 * @param int $flags
110 * @return MediaTransformError|ThumbnailImage|TransformParameterError
111 */
112 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
113 if ( !$this->normaliseParams( $image, $params ) ) {
114 return new TransformParameterError( $params );
115 }
116 # Create a parameter array to pass to the scaler
117 $scalerParams = array(
118 # The size to which the image will be resized
119 'physicalWidth' => $params['physicalWidth'],
120 'physicalHeight' => $params['physicalHeight'],
121 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
122 # The size of the image on the page
123 'clientWidth' => $params['width'],
124 'clientHeight' => $params['height'],
125 # Comment as will be added to the Exif of the thumbnail
126 'comment' => isset( $params['descriptionUrl'] )
127 ? "File source: {$params['descriptionUrl']}"
128 : '',
129 # Properties of the original image
130 'srcWidth' => $image->getWidth(),
131 'srcHeight' => $image->getHeight(),
132 'mimeType' => $image->getMimeType(),
133 'dstPath' => $dstPath,
134 'dstUrl' => $dstUrl,
135 );
136
137 # Determine scaler type
138 $scaler = self::getScalerType( $dstPath );
139
140 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath using scaler $scaler\n" );
141
142 if ( !$image->mustRender() &&
143 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
144 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
145 ) {
146
147 # normaliseParams (or the user) wants us to return the unscaled image
148 wfDebug( __METHOD__ . ": returning unscaled image\n" );
149
150 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
151 }
152
153 if ( $scaler == 'client' ) {
154 # Client-side image scaling, use the source URL
155 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
156 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
157 }
158
159 if ( $flags & self::TRANSFORM_LATER ) {
160 wfDebug( __METHOD__ . ": Transforming later per flags.\n" );
161 $params = array(
162 'width' => $scalerParams['clientWidth'],
163 'height' => $scalerParams['clientHeight']
164 );
165
166 return new ThumbnailImage( $image, $dstUrl, false, $params );
167 }
168
169 # Try to make a target path for the thumbnail
170 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
171 wfDebug( __METHOD__ . ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
172
173 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
174 }
175
176 # Transform functions and binaries need a FS source file
177 $scalerParams['srcPath'] = $image->getLocalRefPath();
178 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
179 wfDebugLog( 'thumbnail',
180 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
181 wfHostname(), $image->getName() ) );
182
183 return new MediaTransformError( 'thumbnail_error',
184 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
185 }
186
187 # Try a hook
188 $mto = null;
189 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
190 if ( !is_null( $mto ) ) {
191 wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto\n" );
192 $scaler = 'hookaborted';
193 }
194
195 switch ( $scaler ) {
196 case 'hookaborted':
197 # Handled by the hook above
198 $err = $mto->isError() ? $mto : false;
199 break;
200 case 'im':
201 $err = $this->transformImageMagick( $image, $scalerParams );
202 break;
203 case 'custom':
204 $err = $this->transformCustom( $image, $scalerParams );
205 break;
206 case 'imext':
207 $err = $this->transformImageMagickExt( $image, $scalerParams );
208 break;
209 case 'gd':
210 default:
211 $err = $this->transformGd( $image, $scalerParams );
212 break;
213 }
214
215 # Remove the file if a zero-byte thumbnail was created, or if there was an error
216 $removed = $this->removeBadFile( $dstPath, (bool)$err );
217 if ( $err ) {
218 # transform returned MediaTransforError
219 return $err;
220 } elseif ( $removed ) {
221 # Thumbnail was zero-byte and had to be removed
222 return new MediaTransformError( 'thumbnail_error',
223 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
224 } elseif ( $mto ) {
225 return $mto;
226 } else {
227 $params = array(
228 'width' => $scalerParams['clientWidth'],
229 'height' => $scalerParams['clientHeight']
230 );
231
232 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
233 }
234 }
235
236 /**
237 * Returns which scaler type should be used. Creates parent directories
238 * for $dstPath and returns 'client' on error
239 *
240 * @return string client,im,custom,gd
241 */
242 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
243 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
244
245 if ( !$dstPath && $checkDstPath ) {
246 # No output path available, client side scaling only
247 $scaler = 'client';
248 } elseif ( !$wgUseImageResize ) {
249 $scaler = 'client';
250 } elseif ( $wgUseImageMagick ) {
251 $scaler = 'im';
252 } elseif ( $wgCustomConvertCommand ) {
253 $scaler = 'custom';
254 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
255 $scaler = 'gd';
256 } elseif ( class_exists( 'Imagick' ) ) {
257 $scaler = 'imext';
258 } else {
259 $scaler = 'client';
260 }
261
262 return $scaler;
263 }
264
265 /**
266 * Get a ThumbnailImage that respresents an image that will be scaled
267 * client side
268 *
269 * @param $image File File associated with this thumbnail
270 * @param array $scalerParams Array with scaler params
271 * @return ThumbnailImage
272 *
273 * @todo fixme: no rotation support
274 */
275 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
276 $params = array(
277 'width' => $scalerParams['clientWidth'],
278 'height' => $scalerParams['clientHeight']
279 );
280
281 return new ThumbnailImage( $image, $image->getURL(), null, $params );
282 }
283
284 /**
285 * Transform an image using ImageMagick
286 *
287 * @param $image File File associated with this thumbnail
288 * @param array $params Array with scaler params
289 *
290 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
291 */
292 protected function transformImageMagick( $image, $params ) {
293 # use ImageMagick
294 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
295 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
296
297 $quality = '';
298 $sharpen = '';
299 $scene = false;
300 $animation_pre = '';
301 $animation_post = '';
302 $decoderHint = '';
303 if ( $params['mimeType'] == 'image/jpeg' ) {
304 $quality = "-quality 80"; // 80%
305 # Sharpening, see bug 6193
306 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
307 / ( $params['srcWidth'] + $params['srcHeight'] )
308 < $wgSharpenReductionThreshold
309 ) {
310 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
311 }
312 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
313 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
314 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
315 }
316 } elseif ( $params['mimeType'] == 'image/png' ) {
317 $quality = "-quality 95"; // zlib 9, adaptive filtering
318
319 } elseif ( $params['mimeType'] == 'image/gif' ) {
320 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
321 // Extract initial frame only; we're so big it'll
322 // be a total drag. :P
323 $scene = 0;
324 } elseif ( $this->isAnimatedImage( $image ) ) {
325 // Coalesce is needed to scale animated GIFs properly (bug 1017).
326 $animation_pre = '-coalesce';
327 // We optimize the output, but -optimize is broken,
328 // use optimizeTransparency instead (bug 11822)
329 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
330 $animation_post = '-fuzz 5% -layers optimizeTransparency';
331 }
332 }
333 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
334 $animation_post = '-layers merge';
335 }
336
337 // Use one thread only, to avoid deadlock bugs on OOM
338 $env = array( 'OMP_NUM_THREADS' => 1 );
339 if ( strval( $wgImageMagickTempDir ) !== '' ) {
340 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
341 }
342
343 $rotation = $this->getRotation( $image );
344 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
345
346 $cmd =
347 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
348 // Specify white background color, will be used for transparent images
349 // in Internet Explorer/Windows instead of default black.
350 " {$quality} -background white" .
351 " {$decoderHint} " .
352 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
353 " {$animation_pre}" .
354 // For the -thumbnail option a "!" is needed to force exact size,
355 // or ImageMagick may decide your ratio is wrong and slice off
356 // a pixel.
357 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
358 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
359 ( $params['comment'] !== ''
360 ? " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
361 : '' ) .
362 " -depth 8 $sharpen " .
363 " -rotate -$rotation " .
364 " {$animation_post} " .
365 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
366
367 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
368 wfProfileIn( 'convert' );
369 $retval = 0;
370 $err = wfShellExecWithStderr( $cmd, $retval, $env );
371 wfProfileOut( 'convert' );
372
373 if ( $retval !== 0 ) {
374 $this->logErrorForExternalProcess( $retval, $err, $cmd );
375
376 return $this->getMediaTransformError( $params, $err );
377 }
378
379 return false; # No error
380 }
381
382 /**
383 * Transform an image using the Imagick PHP extension
384 *
385 * @param $image File File associated with this thumbnail
386 * @param array $params Array with scaler params
387 *
388 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
389 */
390 protected function transformImageMagickExt( $image, $params ) {
391 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
392
393 try {
394 $im = new Imagick();
395 $im->readImage( $params['srcPath'] );
396
397 if ( $params['mimeType'] == 'image/jpeg' ) {
398 // Sharpening, see bug 6193
399 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
400 / ( $params['srcWidth'] + $params['srcHeight'] )
401 < $wgSharpenReductionThreshold
402 ) {
403 // Hack, since $wgSharpenParamater is written specifically for the command line convert
404 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
405 $im->sharpenImage( $radius, $sigma );
406 }
407 $im->setCompressionQuality( 80 );
408 } elseif ( $params['mimeType'] == 'image/png' ) {
409 $im->setCompressionQuality( 95 );
410 } elseif ( $params['mimeType'] == 'image/gif' ) {
411 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
412 // Extract initial frame only; we're so big it'll
413 // be a total drag. :P
414 $im->setImageScene( 0 );
415 } elseif ( $this->isAnimatedImage( $image ) ) {
416 // Coalesce is needed to scale animated GIFs properly (bug 1017).
417 $im = $im->coalesceImages();
418 }
419 }
420
421 $rotation = $this->getRotation( $image );
422 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
423
424 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
425
426 // Call Imagick::thumbnailImage on each frame
427 foreach ( $im as $i => $frame ) {
428 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
429 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
430 }
431 }
432 $im->setImageDepth( 8 );
433
434 if ( $rotation ) {
435 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
436 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
437 }
438 }
439
440 if ( $this->isAnimatedImage( $image ) ) {
441 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
442 // This is broken somehow... can't find out how to fix it
443 $result = $im->writeImages( $params['dstPath'], true );
444 } else {
445 $result = $im->writeImage( $params['dstPath'] );
446 }
447 if ( !$result ) {
448 return $this->getMediaTransformError( $params,
449 "Unable to write thumbnail to {$params['dstPath']}" );
450 }
451 } catch ( ImagickException $e ) {
452 return $this->getMediaTransformError( $params, $e->getMessage() );
453 }
454
455 return false;
456 }
457
458 /**
459 * Transform an image using a custom command
460 *
461 * @param $image File File associated with this thumbnail
462 * @param array $params Array with scaler params
463 *
464 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
465 */
466 protected function transformCustom( $image, $params ) {
467 # Use a custom convert command
468 global $wgCustomConvertCommand;
469
470 # Variables: %s %d %w %h
471 $src = wfEscapeShellArg( $params['srcPath'] );
472 $dst = wfEscapeShellArg( $params['dstPath'] );
473 $cmd = $wgCustomConvertCommand;
474 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
475 $cmd = str_replace( '%h', $params['physicalHeight'],
476 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
477 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
478 wfProfileIn( 'convert' );
479 $retval = 0;
480 $err = wfShellExecWithStderr( $cmd, $retval );
481 wfProfileOut( 'convert' );
482
483 if ( $retval !== 0 ) {
484 $this->logErrorForExternalProcess( $retval, $err, $cmd );
485
486 return $this->getMediaTransformError( $params, $err );
487 }
488
489 return false; # No error
490 }
491
492 /**
493 * Log an error that occurred in an external process
494 *
495 * @param $retval int
496 * @param $err int
497 * @param $cmd string
498 */
499 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
500 wfDebugLog( 'thumbnail',
501 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
502 wfHostname(), $retval, trim( $err ), $cmd ) );
503 }
504
505 /**
506 * Get a MediaTransformError with error 'thumbnail_error'
507 *
508 * @param array $params Parameter array as passed to the transform* functions
509 * @param string $errMsg Error message
510 * @return MediaTransformError
511 */
512 public function getMediaTransformError( $params, $errMsg ) {
513 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
514 $params['clientHeight'], $errMsg );
515 }
516
517 /**
518 * Transform an image using the built in GD library
519 *
520 * @param $image File File associated with this thumbnail
521 * @param array $params Array with scaler params
522 *
523 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
524 */
525 protected function transformGd( $image, $params ) {
526 # Use PHP's builtin GD library functions.
527 #
528 # First find out what kind of file this is, and select the correct
529 # input routine for this.
530
531 $typemap = array(
532 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
533 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
534 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
535 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
536 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
537 );
538 if ( !isset( $typemap[$params['mimeType']] ) ) {
539 $err = 'Image type not supported';
540 wfDebug( "$err\n" );
541 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
542
543 return $this->getMediaTransformError( $params, $errMsg );
544 }
545 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
546
547 if ( !function_exists( $loader ) ) {
548 $err = "Incomplete GD library configuration: missing function $loader";
549 wfDebug( "$err\n" );
550 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
551
552 return $this->getMediaTransformError( $params, $errMsg );
553 }
554
555 if ( !file_exists( $params['srcPath'] ) ) {
556 $err = "File seems to be missing: {$params['srcPath']}";
557 wfDebug( "$err\n" );
558 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
559
560 return $this->getMediaTransformError( $params, $errMsg );
561 }
562
563 $src_image = call_user_func( $loader, $params['srcPath'] );
564
565 $rotation = function_exists( 'imagerotate' ) ? $this->getRotation( $image ) : 0;
566 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
567 $dst_image = imagecreatetruecolor( $width, $height );
568
569 // Initialise the destination image to transparent instead of
570 // the default solid black, to support PNG and GIF transparency nicely
571 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
572 imagecolortransparent( $dst_image, $background );
573 imagealphablending( $dst_image, false );
574
575 if ( $colorStyle == 'palette' ) {
576 // Don't resample for paletted GIF images.
577 // It may just uglify them, and completely breaks transparency.
578 imagecopyresized( $dst_image, $src_image,
579 0, 0, 0, 0,
580 $width, $height,
581 imagesx( $src_image ), imagesy( $src_image ) );
582 } else {
583 imagecopyresampled( $dst_image, $src_image,
584 0, 0, 0, 0,
585 $width, $height,
586 imagesx( $src_image ), imagesy( $src_image ) );
587 }
588
589 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
590 $rot_image = imagerotate( $dst_image, $rotation, 0 );
591 imagedestroy( $dst_image );
592 $dst_image = $rot_image;
593 }
594
595 imagesavealpha( $dst_image, true );
596
597 call_user_func( $saveType, $dst_image, $params['dstPath'] );
598 imagedestroy( $dst_image );
599 imagedestroy( $src_image );
600
601 return false; # No error
602 }
603
604 /**
605 * Escape a string for ImageMagick's property input (e.g. -set -comment)
606 * See InterpretImageProperties() in magick/property.c
607 * @return mixed|string
608 */
609 function escapeMagickProperty( $s ) {
610 // Double the backslashes
611 $s = str_replace( '\\', '\\\\', $s );
612 // Double the percents
613 $s = str_replace( '%', '%%', $s );
614 // Escape initial - or @
615 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
616 $s = '\\' . $s;
617 }
618
619 return $s;
620 }
621
622 /**
623 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
624 * and GetPathComponent() in magick/utility.c.
625 *
626 * This won't work with an initial ~ or @, so input files should be prefixed
627 * with the directory name.
628 *
629 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
630 * it's broken in a way that doesn't involve trying to convert every file
631 * in a directory, so we're better off escaping and waiting for the bugfix
632 * to filter down to users.
633 *
634 * @param string $path The file path
635 * @param bool|string $scene The scene specification, or false if there is none
636 * @throws MWException
637 * @return string
638 */
639 function escapeMagickInput( $path, $scene = false ) {
640 # Die on initial metacharacters (caller should prepend path)
641 $firstChar = substr( $path, 0, 1 );
642 if ( $firstChar === '~' || $firstChar === '@' ) {
643 throw new MWException( __METHOD__ . ': cannot escape this path name' );
644 }
645
646 # Escape glob chars
647 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
648
649 return $this->escapeMagickPath( $path, $scene );
650 }
651
652 /**
653 * Escape a string for ImageMagick's output filename. See
654 * InterpretImageFilename() in magick/image.c.
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 $err = wfShellExecWithStderr( $cmd, $retval, $env );
780 wfProfileOut( 'convert' );
781 if ( $retval !== 0 ) {
782 $this->logErrorForExternalProcess( $retval, $err, $cmd );
783
784 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
785 }
786
787 return false;
788 case 'imext':
789 $im = new Imagick();
790 $im->readImage( $params['srcPath'] );
791 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
792 return new MediaTransformError( 'thumbnail_error', 0, 0,
793 "Error rotating $rotation degrees" );
794 }
795 $result = $im->writeImage( $params['dstPath'] );
796 if ( !$result ) {
797 return new MediaTransformError( 'thumbnail_error', 0, 0,
798 "Unable to write image to {$params['dstPath']}" );
799 }
800
801 return false;
802 default:
803 return new MediaTransformError( 'thumbnail_error', 0, 0,
804 "$scaler rotation not implemented" );
805 }
806 }
807
808 /**
809 * Rerurns whether the file needs to be rendered. Returns true if the
810 * file requires rotation and we are able to rotate it.
811 *
812 * @param $file File
813 * @return bool
814 */
815 public function mustRender( $file ) {
816 return self::canRotate() && $this->getRotation( $file ) != 0;
817 }
818 }