In SpecialUploadStash:
[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->getLocalRefPath(),
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'], false );
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 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
306 $animation_post = '-layers merge';
307 }
308
309 // Use one thread only, to avoid deadlock bugs on OOM
310 $env = array( 'OMP_NUM_THREADS' => 1 );
311 if ( strval( $wgImageMagickTempDir ) !== '' ) {
312 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
313 }
314
315 $rotation = $this->getRotation( $image );
316 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
317
318 $cmd =
319 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
320 // Specify white background color, will be used for transparent images
321 // in Internet Explorer/Windows instead of default black.
322 " {$quality} -background white" .
323 " {$decoderHint} " .
324 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
325 " {$animation_pre}" .
326 // For the -thumbnail option a "!" is needed to force exact size,
327 // or ImageMagick may decide your ratio is wrong and slice off
328 // a pixel.
329 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
330 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
331 ( $params['comment'] !== ''
332 ? " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
333 : '' ) .
334 " -depth 8 $sharpen " .
335 " -rotate -$rotation " .
336 " {$animation_post} " .
337 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
338
339 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
340 wfProfileIn( 'convert' );
341 $retval = 0;
342 $err = wfShellExec( $cmd, $retval, $env );
343 wfProfileOut( 'convert' );
344
345 if ( $retval !== 0 ) {
346 $this->logErrorForExternalProcess( $retval, $err, $cmd );
347 return $this->getMediaTransformError( $params, $err );
348 }
349
350 return false; # No error
351 }
352
353 /**
354 * Transform an image using the Imagick PHP extension
355 *
356 * @param $image File File associated with this thumbnail
357 * @param $params array Array with scaler params
358 *
359 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
360 */
361 protected function transformImageMagickExt( $image, $params ) {
362 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
363
364 try {
365 $im = new Imagick();
366 $im->readImage( $params['srcPath'] );
367
368 if ( $params['mimeType'] == 'image/jpeg' ) {
369 // Sharpening, see bug 6193
370 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
371 / ( $params['srcWidth'] + $params['srcHeight'] )
372 < $wgSharpenReductionThreshold ) {
373 // Hack, since $wgSharpenParamater is written specifically for the command line convert
374 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
375 $im->sharpenImage( $radius, $sigma );
376 }
377 $im->setCompressionQuality( 80 );
378 } elseif( $params['mimeType'] == 'image/png' ) {
379 $im->setCompressionQuality( 95 );
380 } elseif ( $params['mimeType'] == 'image/gif' ) {
381 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
382 // Extract initial frame only; we're so big it'll
383 // be a total drag. :P
384 $im->setImageScene( 0 );
385 } elseif ( $this->isAnimatedImage( $image ) ) {
386 // Coalesce is needed to scale animated GIFs properly (bug 1017).
387 $im = $im->coalesceImages();
388 }
389 }
390
391 $rotation = $this->getRotation( $image );
392 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
393
394 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
395
396 // Call Imagick::thumbnailImage on each frame
397 foreach ( $im as $i => $frame ) {
398 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
399 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
400 }
401 }
402 $im->setImageDepth( 8 );
403
404 if ( $rotation ) {
405 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
406 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
407 }
408 }
409
410 if ( $this->isAnimatedImage( $image ) ) {
411 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
412 // This is broken somehow... can't find out how to fix it
413 $result = $im->writeImages( $params['dstPath'], true );
414 } else {
415 $result = $im->writeImage( $params['dstPath'] );
416 }
417 if ( !$result ) {
418 return $this->getMediaTransformError( $params,
419 "Unable to write thumbnail to {$params['dstPath']}" );
420 }
421
422 } catch ( ImagickException $e ) {
423 return $this->getMediaTransformError( $params, $e->getMessage() );
424 }
425
426 return false;
427
428 }
429
430 /**
431 * Transform an image using a custom command
432 *
433 * @param $image File File associated with this thumbnail
434 * @param $params array Array with scaler params
435 *
436 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
437 */
438 protected function transformCustom( $image, $params ) {
439 # Use a custom convert command
440 global $wgCustomConvertCommand;
441
442 # Variables: %s %d %w %h
443 $src = wfEscapeShellArg( $params['srcPath'] );
444 $dst = wfEscapeShellArg( $params['dstPath'] );
445 $cmd = $wgCustomConvertCommand;
446 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
447 $cmd = str_replace( '%h', $params['physicalHeight'],
448 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
449 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
450 wfProfileIn( 'convert' );
451 $retval = 0;
452 $err = wfShellExec( $cmd, $retval );
453 wfProfileOut( 'convert' );
454
455 if ( $retval !== 0 ) {
456 $this->logErrorForExternalProcess( $retval, $err, $cmd );
457 return $this->getMediaTransformError( $params, $err );
458 }
459 return false; # No error
460 }
461
462 /**
463 * Log an error that occured in an external process
464 *
465 * @param $retval int
466 * @param $err int
467 * @param $cmd string
468 */
469 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
470 wfDebugLog( 'thumbnail',
471 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
472 wfHostname(), $retval, trim( $err ), $cmd ) );
473 }
474 /**
475 * Get a MediaTransformError with error 'thumbnail_error'
476 *
477 * @param $params array Parameter array as passed to the transform* functions
478 * @param $errMsg string Error message
479 * @return MediaTransformError
480 */
481 public function getMediaTransformError( $params, $errMsg ) {
482 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
483 $params['clientHeight'], $errMsg );
484 }
485
486 /**
487 * Transform an image using the built in GD library
488 *
489 * @param $image File File associated with this thumbnail
490 * @param $params array Array with scaler params
491 *
492 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
493 */
494 protected function transformGd( $image, $params ) {
495 # Use PHP's builtin GD library functions.
496 #
497 # First find out what kind of file this is, and select the correct
498 # input routine for this.
499
500 $typemap = array(
501 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
502 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
503 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
504 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
505 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
506 );
507 if ( !isset( $typemap[$params['mimeType']] ) ) {
508 $err = 'Image type not supported';
509 wfDebug( "$err\n" );
510 $errMsg = wfMsg ( 'thumbnail_image-type' );
511 return $this->getMediaTransformError( $params, $errMsg );
512 }
513 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
514
515 if ( !function_exists( $loader ) ) {
516 $err = "Incomplete GD library configuration: missing function $loader";
517 wfDebug( "$err\n" );
518 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
519 return $this->getMediaTransformError( $params, $errMsg );
520 }
521
522 if ( !file_exists( $params['srcPath'] ) ) {
523 $err = "File seems to be missing: {$params['srcPath']}";
524 wfDebug( "$err\n" );
525 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
526 return $this->getMediaTransformError( $params, $errMsg );
527 }
528
529 $src_image = call_user_func( $loader, $params['srcPath'] );
530
531 $rotation = function_exists( 'imagerotate' ) ? $this->getRotation( $image ) : 0;
532 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
533 $dst_image = imagecreatetruecolor( $width, $height );
534
535 // Initialise the destination image to transparent instead of
536 // the default solid black, to support PNG and GIF transparency nicely
537 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
538 imagecolortransparent( $dst_image, $background );
539 imagealphablending( $dst_image, false );
540
541 if ( $colorStyle == 'palette' ) {
542 // Don't resample for paletted GIF images.
543 // It may just uglify them, and completely breaks transparency.
544 imagecopyresized( $dst_image, $src_image,
545 0, 0, 0, 0,
546 $width, $height,
547 imagesx( $src_image ), imagesy( $src_image ) );
548 } else {
549 imagecopyresampled( $dst_image, $src_image,
550 0, 0, 0, 0,
551 $width, $height,
552 imagesx( $src_image ), imagesy( $src_image ) );
553 }
554
555 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
556 $rot_image = imagerotate( $dst_image, $rotation, 0 );
557 imagedestroy( $dst_image );
558 $dst_image = $rot_image;
559 }
560
561 imagesavealpha( $dst_image, true );
562
563 call_user_func( $saveType, $dst_image, $params['dstPath'] );
564 imagedestroy( $dst_image );
565 imagedestroy( $src_image );
566
567 return false; # No error
568 }
569
570 /**
571 * Escape a string for ImageMagick's property input (e.g. -set -comment)
572 * See InterpretImageProperties() in magick/property.c
573 */
574 function escapeMagickProperty( $s ) {
575 // Double the backslashes
576 $s = str_replace( '\\', '\\\\', $s );
577 // Double the percents
578 $s = str_replace( '%', '%%', $s );
579 // Escape initial - or @
580 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
581 $s = '\\' . $s;
582 }
583 return $s;
584 }
585
586 /**
587 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
588 * and GetPathComponent() in magick/utility.c.
589 *
590 * This won't work with an initial ~ or @, so input files should be prefixed
591 * with the directory name.
592 *
593 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
594 * it's broken in a way that doesn't involve trying to convert every file
595 * in a directory, so we're better off escaping and waiting for the bugfix
596 * to filter down to users.
597 *
598 * @param $path string The file path
599 * @param $scene string The scene specification, or false if there is none
600 */
601 function escapeMagickInput( $path, $scene = false ) {
602 # Die on initial metacharacters (caller should prepend path)
603 $firstChar = substr( $path, 0, 1 );
604 if ( $firstChar === '~' || $firstChar === '@' ) {
605 throw new MWException( __METHOD__ . ': cannot escape this path name' );
606 }
607
608 # Escape glob chars
609 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
610
611 return $this->escapeMagickPath( $path, $scene );
612 }
613
614 /**
615 * Escape a string for ImageMagick's output filename. See
616 * InterpretImageFilename() in magick/image.c.
617 */
618 function escapeMagickOutput( $path, $scene = false ) {
619 $path = str_replace( '%', '%%', $path );
620 return $this->escapeMagickPath( $path, $scene );
621 }
622
623 /**
624 * Armour a string against ImageMagick's GetPathComponent(). This is a
625 * helper function for escapeMagickInput() and escapeMagickOutput().
626 *
627 * @param $path string The file path
628 * @param $scene string The scene specification, or false if there is none
629 */
630 protected function escapeMagickPath( $path, $scene = false ) {
631 # Die on format specifiers (other than drive letters). The regex is
632 # meant to match all the formats you get from "convert -list format"
633 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
634 if ( wfIsWindows() && is_dir( $m[0] ) ) {
635 // OK, it's a drive letter
636 // ImageMagick has a similar exception, see IsMagickConflict()
637 } else {
638 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
639 }
640 }
641
642 # If there are square brackets, add a do-nothing scene specification
643 # to force a literal interpretation
644 if ( $scene === false ) {
645 if ( strpos( $path, '[' ) !== false ) {
646 $path .= '[0--1]';
647 }
648 } else {
649 $path .= "[$scene]";
650 }
651 return $path;
652 }
653
654 /**
655 * Retrieve the version of the installed ImageMagick
656 * You can use PHPs version_compare() to use this value
657 * Value is cached for one hour.
658 * @return String representing the IM version.
659 */
660 protected function getMagickVersion() {
661 global $wgMemc;
662
663 $cache = $wgMemc->get( "imagemagick-version" );
664 if ( !$cache ) {
665 global $wgImageMagickConvertCommand;
666 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
667 wfDebug( __METHOD__ . ": Running convert -version\n" );
668 $retval = '';
669 $return = wfShellExec( $cmd, $retval );
670 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
671 if ( $x != 1 ) {
672 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
673 return null;
674 }
675 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
676 return $matches[1];
677 }
678 return $cache;
679 }
680
681 static function imageJpegWrapper( $dst_image, $thumbPath ) {
682 imageinterlace( $dst_image );
683 imagejpeg( $dst_image, $thumbPath, 95 );
684 }
685
686 /**
687 * On supporting image formats, try to read out the low-level orientation
688 * of the file and return the angle that the file needs to be rotated to
689 * be viewed.
690 *
691 * This information is only useful when manipulating the original file;
692 * the width and height we normally work with is logical, and will match
693 * any produced output views.
694 *
695 * The base BitmapHandler doesn't understand any metadata formats, so this
696 * is left up to child classes to implement.
697 *
698 * @param $file File
699 * @return int 0, 90, 180 or 270
700 */
701 public function getRotation( $file ) {
702 return 0;
703 }
704
705 /**
706 * Returns whether the current scaler supports rotation (im and gd do)
707 *
708 * @return bool
709 */
710 public static function canRotate() {
711 $scaler = self::getScalerType( null, false );
712 switch ( $scaler ) {
713 case 'im':
714 # ImageMagick supports autorotation
715 return true;
716 case 'imext':
717 # Imagick::rotateImage
718 return true;
719 case 'gd':
720 # GD's imagerotate function is used to rotate images, but not
721 # all precompiled PHP versions have that function
722 return function_exists( 'imagerotate' );
723 default:
724 # Other scalers don't support rotation
725 return false;
726 }
727 }
728
729 /**
730 * Rerurns whether the file needs to be rendered. Returns true if the
731 * file requires rotation and we are able to rotate it.
732 *
733 * @param $file File
734 * @return bool
735 */
736 public function mustRender( $file ) {
737 return self::canRotate() && $this->getRotation( $file ) != 0;
738 }
739 }