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