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