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