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