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