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