Merge "Add .sass-cache to .gitignore"
[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
172 # Try a hook
173 $mto = null;
174 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
175 if ( !is_null( $mto ) ) {
176 wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto\n" );
177 $scaler = 'hookaborted';
178 }
179
180 switch ( $scaler ) {
181 case 'hookaborted':
182 # Handled by the hook above
183 $err = $mto->isError() ? $mto : false;
184 break;
185 case 'im':
186 $err = $this->transformImageMagick( $image, $scalerParams );
187 break;
188 case 'custom':
189 $err = $this->transformCustom( $image, $scalerParams );
190 break;
191 case 'imext':
192 $err = $this->transformImageMagickExt( $image, $scalerParams );
193 break;
194 case 'gd':
195 default:
196 $err = $this->transformGd( $image, $scalerParams );
197 break;
198 }
199
200 # Remove the file if a zero-byte thumbnail was created, or if there was an error
201 $removed = $this->removeBadFile( $dstPath, (bool)$err );
202 if ( $err ) {
203 # transform returned MediaTransforError
204 return $err;
205 } elseif ( $removed ) {
206 # Thumbnail was zero-byte and had to be removed
207 return new MediaTransformError( 'thumbnail_error',
208 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
209 } elseif ( $mto ) {
210 return $mto;
211 } else {
212 $params = array(
213 'width' => $scalerParams['clientWidth'],
214 'height' => $scalerParams['clientHeight']
215 );
216 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
217 }
218 }
219
220 /**
221 * Returns which scaler type should be used. Creates parent directories
222 * for $dstPath and returns 'client' on error
223 *
224 * @return string client,im,custom,gd
225 */
226 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
227 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
228
229 if ( !$dstPath && $checkDstPath ) {
230 # No output path available, client side scaling only
231 $scaler = 'client';
232 } elseif ( !$wgUseImageResize ) {
233 $scaler = 'client';
234 } elseif ( $wgUseImageMagick ) {
235 $scaler = 'im';
236 } elseif ( $wgCustomConvertCommand ) {
237 $scaler = 'custom';
238 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
239 $scaler = 'gd';
240 } elseif ( class_exists( 'Imagick' ) ) {
241 $scaler = 'imext';
242 } else {
243 $scaler = 'client';
244 }
245 return $scaler;
246 }
247
248 /**
249 * Get a ThumbnailImage that respresents an image that will be scaled
250 * client side
251 *
252 * @param $image File File associated with this thumbnail
253 * @param array $scalerParams Array with scaler params
254 * @return ThumbnailImage
255 *
256 * @todo fixme: no rotation support
257 */
258 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
259 $params = array(
260 'width' => $scalerParams['clientWidth'],
261 'height' => $scalerParams['clientHeight']
262 );
263 return new ThumbnailImage( $image, $image->getURL(), null, $params );
264 }
265
266 /**
267 * Transform an image using ImageMagick
268 *
269 * @param $image File File associated with this thumbnail
270 * @param array $params Array with scaler params
271 *
272 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
273 */
274 protected function transformImageMagick( $image, $params ) {
275 # use ImageMagick
276 global $wgSharpenReductionThreshold, $wgSharpenParameter,
277 $wgMaxAnimatedGifArea,
278 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
279
280 $quality = '';
281 $sharpen = '';
282 $scene = false;
283 $animation_pre = '';
284 $animation_post = '';
285 $decoderHint = '';
286 if ( $params['mimeType'] == 'image/jpeg' ) {
287 $quality = "-quality 80"; // 80%
288 # Sharpening, see bug 6193
289 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
290 / ( $params['srcWidth'] + $params['srcHeight'] )
291 < $wgSharpenReductionThreshold ) {
292 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
293 }
294 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
295 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
296 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
297 }
298
299 } elseif ( $params['mimeType'] == 'image/png' ) {
300 $quality = "-quality 95"; // zlib 9, adaptive filtering
301
302 } elseif ( $params['mimeType'] == 'image/gif' ) {
303 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
304 // Extract initial frame only; we're so big it'll
305 // be a total drag. :P
306 $scene = 0;
307
308 } elseif ( $this->isAnimatedImage( $image ) ) {
309 // Coalesce is needed to scale animated GIFs properly (bug 1017).
310 $animation_pre = '-coalesce';
311 // We optimize the output, but -optimize is broken,
312 // use optimizeTransparency instead (bug 11822)
313 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
314 $animation_post = '-fuzz 5% -layers optimizeTransparency';
315 }
316 }
317 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
318 $animation_post = '-layers merge';
319 }
320
321 // Use one thread only, to avoid deadlock bugs on OOM
322 $env = array( 'OMP_NUM_THREADS' => 1 );
323 if ( strval( $wgImageMagickTempDir ) !== '' ) {
324 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
325 }
326
327 $rotation = $this->getRotation( $image );
328 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
329
330 $cmd =
331 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
332 // Specify white background color, will be used for transparent images
333 // in Internet Explorer/Windows instead of default black.
334 " {$quality} -background white" .
335 " {$decoderHint} " .
336 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
337 " {$animation_pre}" .
338 // For the -thumbnail option a "!" is needed to force exact size,
339 // or ImageMagick may decide your ratio is wrong and slice off
340 // a pixel.
341 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
342 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
343 ( $params['comment'] !== ''
344 ? " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
345 : '' ) .
346 " -depth 8 $sharpen " .
347 " -rotate -$rotation " .
348 " {$animation_post} " .
349 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
350
351 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
352 wfProfileIn( 'convert' );
353 $retval = 0;
354 $err = wfShellExecWithStderr( $cmd, $retval, $env );
355 wfProfileOut( 'convert' );
356
357 if ( $retval !== 0 ) {
358 $this->logErrorForExternalProcess( $retval, $err, $cmd );
359 return $this->getMediaTransformError( $params, $err );
360 }
361
362 return false; # No error
363 }
364
365 /**
366 * Transform an image using the Imagick PHP extension
367 *
368 * @param $image File File associated with this thumbnail
369 * @param array $params Array with scaler params
370 *
371 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
372 */
373 protected function transformImageMagickExt( $image, $params ) {
374 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
375
376 try {
377 $im = new Imagick();
378 $im->readImage( $params['srcPath'] );
379
380 if ( $params['mimeType'] == 'image/jpeg' ) {
381 // Sharpening, see bug 6193
382 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
383 / ( $params['srcWidth'] + $params['srcHeight'] )
384 < $wgSharpenReductionThreshold ) {
385 // Hack, since $wgSharpenParamater is written specifically for the command line convert
386 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
387 $im->sharpenImage( $radius, $sigma );
388 }
389 $im->setCompressionQuality( 80 );
390 } elseif ( $params['mimeType'] == 'image/png' ) {
391 $im->setCompressionQuality( 95 );
392 } elseif ( $params['mimeType'] == 'image/gif' ) {
393 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
394 // Extract initial frame only; we're so big it'll
395 // be a total drag. :P
396 $im->setImageScene( 0 );
397 } elseif ( $this->isAnimatedImage( $image ) ) {
398 // Coalesce is needed to scale animated GIFs properly (bug 1017).
399 $im = $im->coalesceImages();
400 }
401 }
402
403 $rotation = $this->getRotation( $image );
404 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
405
406 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
407
408 // Call Imagick::thumbnailImage on each frame
409 foreach ( $im as $i => $frame ) {
410 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
411 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
412 }
413 }
414 $im->setImageDepth( 8 );
415
416 if ( $rotation ) {
417 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
418 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
419 }
420 }
421
422 if ( $this->isAnimatedImage( $image ) ) {
423 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
424 // This is broken somehow... can't find out how to fix it
425 $result = $im->writeImages( $params['dstPath'], true );
426 } else {
427 $result = $im->writeImage( $params['dstPath'] );
428 }
429 if ( !$result ) {
430 return $this->getMediaTransformError( $params,
431 "Unable to write thumbnail to {$params['dstPath']}" );
432 }
433
434 } catch ( ImagickException $e ) {
435 return $this->getMediaTransformError( $params, $e->getMessage() );
436 }
437
438 return false;
439
440 }
441
442 /**
443 * Transform an image using a custom command
444 *
445 * @param $image File File associated with this thumbnail
446 * @param array $params Array with scaler params
447 *
448 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
449 */
450 protected function transformCustom( $image, $params ) {
451 # Use a custom convert command
452 global $wgCustomConvertCommand;
453
454 # Variables: %s %d %w %h
455 $src = wfEscapeShellArg( $params['srcPath'] );
456 $dst = wfEscapeShellArg( $params['dstPath'] );
457 $cmd = $wgCustomConvertCommand;
458 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
459 $cmd = str_replace( '%h', $params['physicalHeight'],
460 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
461 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
462 wfProfileIn( 'convert' );
463 $retval = 0;
464 $err = wfShellExecWithStderr( $cmd, $retval );
465 wfProfileOut( 'convert' );
466
467 if ( $retval !== 0 ) {
468 $this->logErrorForExternalProcess( $retval, $err, $cmd );
469 return $this->getMediaTransformError( $params, $err );
470 }
471 return false; # No error
472 }
473
474 /**
475 * Log an error that occurred in an external process
476 *
477 * @param $retval int
478 * @param $err int
479 * @param $cmd string
480 */
481 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
482 wfDebugLog( 'thumbnail',
483 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
484 wfHostname(), $retval, trim( $err ), $cmd ) );
485 }
486 /**
487 * Get a MediaTransformError with error 'thumbnail_error'
488 *
489 * @param array $params Parameter array as passed to the transform* functions
490 * @param string $errMsg Error message
491 * @return MediaTransformError
492 */
493 public function getMediaTransformError( $params, $errMsg ) {
494 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
495 $params['clientHeight'], $errMsg );
496 }
497
498 /**
499 * Transform an image using the built in GD library
500 *
501 * @param $image File File associated with this thumbnail
502 * @param array $params Array with scaler params
503 *
504 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
505 */
506 protected function transformGd( $image, $params ) {
507 # Use PHP's builtin GD library functions.
508 #
509 # First find out what kind of file this is, and select the correct
510 # input routine for this.
511
512 $typemap = array(
513 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
514 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
515 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
516 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
517 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
518 );
519 if ( !isset( $typemap[$params['mimeType']] ) ) {
520 $err = 'Image type not supported';
521 wfDebug( "$err\n" );
522 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
523 return $this->getMediaTransformError( $params, $errMsg );
524 }
525 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
526
527 if ( !function_exists( $loader ) ) {
528 $err = "Incomplete GD library configuration: missing function $loader";
529 wfDebug( "$err\n" );
530 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
531 return $this->getMediaTransformError( $params, $errMsg );
532 }
533
534 if ( !file_exists( $params['srcPath'] ) ) {
535 $err = "File seems to be missing: {$params['srcPath']}";
536 wfDebug( "$err\n" );
537 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
538 return $this->getMediaTransformError( $params, $errMsg );
539 }
540
541 $src_image = call_user_func( $loader, $params['srcPath'] );
542
543 $rotation = function_exists( 'imagerotate' ) ? $this->getRotation( $image ) : 0;
544 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
545 $dst_image = imagecreatetruecolor( $width, $height );
546
547 // Initialise the destination image to transparent instead of
548 // the default solid black, to support PNG and GIF transparency nicely
549 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
550 imagecolortransparent( $dst_image, $background );
551 imagealphablending( $dst_image, false );
552
553 if ( $colorStyle == 'palette' ) {
554 // Don't resample for paletted GIF images.
555 // It may just uglify them, and completely breaks transparency.
556 imagecopyresized( $dst_image, $src_image,
557 0, 0, 0, 0,
558 $width, $height,
559 imagesx( $src_image ), imagesy( $src_image ) );
560 } else {
561 imagecopyresampled( $dst_image, $src_image,
562 0, 0, 0, 0,
563 $width, $height,
564 imagesx( $src_image ), imagesy( $src_image ) );
565 }
566
567 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
568 $rot_image = imagerotate( $dst_image, $rotation, 0 );
569 imagedestroy( $dst_image );
570 $dst_image = $rot_image;
571 }
572
573 imagesavealpha( $dst_image, true );
574
575 call_user_func( $saveType, $dst_image, $params['dstPath'] );
576 imagedestroy( $dst_image );
577 imagedestroy( $src_image );
578
579 return false; # No error
580 }
581
582 /**
583 * Escape a string for ImageMagick's property input (e.g. -set -comment)
584 * See InterpretImageProperties() in magick/property.c
585 * @return mixed|string
586 */
587 function escapeMagickProperty( $s ) {
588 // Double the backslashes
589 $s = str_replace( '\\', '\\\\', $s );
590 // Double the percents
591 $s = str_replace( '%', '%%', $s );
592 // Escape initial - or @
593 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
594 $s = '\\' . $s;
595 }
596 return $s;
597 }
598
599 /**
600 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
601 * and GetPathComponent() in magick/utility.c.
602 *
603 * This won't work with an initial ~ or @, so input files should be prefixed
604 * with the directory name.
605 *
606 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
607 * it's broken in a way that doesn't involve trying to convert every file
608 * in a directory, so we're better off escaping and waiting for the bugfix
609 * to filter down to users.
610 *
611 * @param string $path The file path
612 * @param bool|string $scene The scene specification, or false if there is none
613 * @throws MWException
614 * @return string
615 */
616 function escapeMagickInput( $path, $scene = false ) {
617 # Die on initial metacharacters (caller should prepend path)
618 $firstChar = substr( $path, 0, 1 );
619 if ( $firstChar === '~' || $firstChar === '@' ) {
620 throw new MWException( __METHOD__ . ': cannot escape this path name' );
621 }
622
623 # Escape glob chars
624 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
625
626 return $this->escapeMagickPath( $path, $scene );
627 }
628
629 /**
630 * Escape a string for ImageMagick's output filename. See
631 * InterpretImageFilename() in magick/image.c.
632 * @return string
633 */
634 function escapeMagickOutput( $path, $scene = false ) {
635 $path = str_replace( '%', '%%', $path );
636 return $this->escapeMagickPath( $path, $scene );
637 }
638
639 /**
640 * Armour a string against ImageMagick's GetPathComponent(). This is a
641 * helper function for escapeMagickInput() and escapeMagickOutput().
642 *
643 * @param string $path The file path
644 * @param bool|string $scene The scene specification, or false if there is none
645 * @throws MWException
646 * @return string
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 /**
706 * Returns whether the current scaler supports rotation (im and gd do)
707 *
708 * @return bool
709 */
710 public static function canRotate() {
711 $scaler = self::getScalerType( null, false );
712 switch ( $scaler ) {
713 case 'im':
714 # ImageMagick supports autorotation
715 return true;
716 case 'imext':
717 # Imagick::rotateImage
718 return true;
719 case 'gd':
720 # GD's imagerotate function is used to rotate images, but not
721 # all precompiled PHP versions have that function
722 return function_exists( 'imagerotate' );
723 default:
724 # Other scalers don't support rotation
725 return false;
726 }
727 }
728
729 /**
730 * @param $file File
731 * @param array $params Rotate parameters.
732 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
733 * @since 1.21
734 * @return bool
735 */
736 public function rotate( $file, $params ) {
737 global $wgImageMagickConvertCommand;
738
739 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
740 $scene = false;
741
742 $scaler = self::getScalerType( null, false );
743 switch ( $scaler ) {
744 case 'im':
745 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
746 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
747 " -rotate -$rotation " .
748 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
749 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
750 wfProfileIn( 'convert' );
751 $retval = 0;
752 $err = wfShellExecWithStderr( $cmd, $retval, $env );
753 wfProfileOut( 'convert' );
754 if ( $retval !== 0 ) {
755 $this->logErrorForExternalProcess( $retval, $err, $cmd );
756 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
757 }
758 return false;
759 case 'imext':
760 $im = new Imagick();
761 $im->readImage( $params['srcPath'] );
762 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
763 return new MediaTransformError( 'thumbnail_error', 0, 0,
764 "Error rotating $rotation degrees" );
765 }
766 $result = $im->writeImage( $params['dstPath'] );
767 if ( !$result ) {
768 return new MediaTransformError( 'thumbnail_error', 0, 0,
769 "Unable to write image to {$params['dstPath']}" );
770 }
771 return false;
772 default:
773 return new MediaTransformError( 'thumbnail_error', 0, 0,
774 "$scaler rotation not implemented" );
775 }
776 }
777
778 /**
779 * Rerurns whether the file needs to be rendered. Returns true if the
780 * file requires rotation and we are able to rotate it.
781 *
782 * @param $file File
783 * @return bool
784 */
785 public function mustRender( $file ) {
786 return self::canRotate() && $this->getRotation( $file ) != 0;
787 }
788 }