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