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