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