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