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