Merge "(bug 47070) check content model namespace on import."
[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 = '';
311 $sharpen = '';
312 $scene = false;
313 $animation_pre = '';
314 $animation_post = '';
315 $decoderHint = '';
316 if ( $params['mimeType'] == 'image/jpeg' ) {
317 $quality = "-quality 80"; // 80%
318 # Sharpening, see bug 6193
319 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
320 / ( $params['srcWidth'] + $params['srcHeight'] )
321 < $wgSharpenReductionThreshold
322 ) {
323 $sharpen = "-sharpen " . wfEscapeShellArg( $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 = "-define jpeg:size={$params['physicalDimensions']}";
328 }
329 } elseif ( $params['mimeType'] == 'image/png' ) {
330 $quality = "-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 = '-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 = '-fuzz 5% -layers optimizeTransparency';
344 }
345 }
346 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
347 $animation_post = '-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 =
360 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
361 // Specify white background color, will be used for transparent images
362 // in Internet Explorer/Windows instead of default black.
363 " {$quality} -background white" .
364 " {$decoderHint} " .
365 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
366 " {$animation_pre}" .
367 // For the -thumbnail option a "!" is needed to force exact size,
368 // or ImageMagick may decide your ratio is wrong and slice off
369 // a pixel.
370 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
371 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
372 ( $params['comment'] !== ''
373 ? " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
374 : '' ) .
375 " -depth 8 $sharpen " .
376 " -rotate -$rotation " .
377 " {$animation_post} " .
378 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
379
380 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
381 wfProfileIn( 'convert' );
382 $retval = 0;
383 $err = wfShellExecWithStderr( $cmd, $retval, $env );
384 wfProfileOut( 'convert' );
385
386 if ( $retval !== 0 ) {
387 $this->logErrorForExternalProcess( $retval, $err, $cmd );
388
389 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
390 }
391
392 return false; # No error
393 }
394
395 /**
396 * Transform an image using the Imagick PHP extension
397 *
398 * @param File $image File associated with this thumbnail
399 * @param array $params Array with scaler params
400 *
401 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
402 */
403 protected function transformImageMagickExt( $image, $params ) {
404 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
405
406 try {
407 $im = new Imagick();
408 $im->readImage( $params['srcPath'] );
409
410 if ( $params['mimeType'] == 'image/jpeg' ) {
411 // Sharpening, see bug 6193
412 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
413 / ( $params['srcWidth'] + $params['srcHeight'] )
414 < $wgSharpenReductionThreshold
415 ) {
416 // Hack, since $wgSharpenParamater is written specifically for the command line convert
417 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
418 $im->sharpenImage( $radius, $sigma );
419 }
420 $im->setCompressionQuality( 80 );
421 } elseif ( $params['mimeType'] == 'image/png' ) {
422 $im->setCompressionQuality( 95 );
423 } elseif ( $params['mimeType'] == 'image/gif' ) {
424 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
425 // Extract initial frame only; we're so big it'll
426 // be a total drag. :P
427 $im->setImageScene( 0 );
428 } elseif ( $this->isAnimatedImage( $image ) ) {
429 // Coalesce is needed to scale animated GIFs properly (bug 1017).
430 $im = $im->coalesceImages();
431 }
432 }
433
434 $rotation = $this->getRotation( $image );
435 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
436
437 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
438
439 // Call Imagick::thumbnailImage on each frame
440 foreach ( $im as $i => $frame ) {
441 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
442 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
443 }
444 }
445 $im->setImageDepth( 8 );
446
447 if ( $rotation ) {
448 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
449 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
450 }
451 }
452
453 if ( $this->isAnimatedImage( $image ) ) {
454 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
455 // This is broken somehow... can't find out how to fix it
456 $result = $im->writeImages( $params['dstPath'], true );
457 } else {
458 $result = $im->writeImage( $params['dstPath'] );
459 }
460 if ( !$result ) {
461 return $this->getMediaTransformError( $params,
462 "Unable to write thumbnail to {$params['dstPath']}" );
463 }
464 } catch ( ImagickException $e ) {
465 return $this->getMediaTransformError( $params, $e->getMessage() );
466 }
467
468 return false;
469 }
470
471 /**
472 * Transform an image using a custom command
473 *
474 * @param File $image File associated with this thumbnail
475 * @param array $params Array with scaler params
476 *
477 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
478 */
479 protected function transformCustom( $image, $params ) {
480 # Use a custom convert command
481 global $wgCustomConvertCommand;
482
483 # Variables: %s %d %w %h
484 $src = wfEscapeShellArg( $params['srcPath'] );
485 $dst = wfEscapeShellArg( $params['dstPath'] );
486 $cmd = $wgCustomConvertCommand;
487 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
488 $cmd = str_replace( '%h', $params['physicalHeight'],
489 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
490 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
491 wfProfileIn( 'convert' );
492 $retval = 0;
493 $err = wfShellExecWithStderr( $cmd, $retval );
494 wfProfileOut( 'convert' );
495
496 if ( $retval !== 0 ) {
497 $this->logErrorForExternalProcess( $retval, $err, $cmd );
498
499 return $this->getMediaTransformError( $params, $err );
500 }
501
502 return false; # No error
503 }
504
505 /**
506 * Get a MediaTransformError with error 'thumbnail_error'
507 *
508 * @param array $params Parameter array as passed to the transform* functions
509 * @param string $errMsg Error message
510 * @return MediaTransformError
511 */
512 public function getMediaTransformError( $params, $errMsg ) {
513 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
514 $params['clientHeight'], $errMsg );
515 }
516
517 /**
518 * Transform an image using the built in GD library
519 *
520 * @param File $image File associated with this thumbnail
521 * @param array $params Array with scaler params
522 *
523 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
524 */
525 protected function transformGd( $image, $params ) {
526 # Use PHP's builtin GD library functions.
527 #
528 # First find out what kind of file this is, and select the correct
529 # input routine for this.
530
531 $typemap = array(
532 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
533 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor',
534 array( __CLASS__, 'imageJpegWrapper' ) ),
535 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
536 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
537 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
538 );
539 if ( !isset( $typemap[$params['mimeType']] ) ) {
540 $err = 'Image type not supported';
541 wfDebug( "$err\n" );
542 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
543
544 return $this->getMediaTransformError( $params, $errMsg );
545 }
546 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
547
548 if ( !function_exists( $loader ) ) {
549 $err = "Incomplete GD library configuration: missing function $loader";
550 wfDebug( "$err\n" );
551 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
552
553 return $this->getMediaTransformError( $params, $errMsg );
554 }
555
556 if ( !file_exists( $params['srcPath'] ) ) {
557 $err = "File seems to be missing: {$params['srcPath']}";
558 wfDebug( "$err\n" );
559 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
560
561 return $this->getMediaTransformError( $params, $errMsg );
562 }
563
564 $src_image = call_user_func( $loader, $params['srcPath'] );
565
566 $rotation = function_exists( 'imagerotate' ) ? $this->getRotation( $image ) : 0;
567 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
568 $dst_image = imagecreatetruecolor( $width, $height );
569
570 // Initialise the destination image to transparent instead of
571 // the default solid black, to support PNG and GIF transparency nicely
572 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
573 imagecolortransparent( $dst_image, $background );
574 imagealphablending( $dst_image, false );
575
576 if ( $colorStyle == 'palette' ) {
577 // Don't resample for paletted GIF images.
578 // It may just uglify them, and completely breaks transparency.
579 imagecopyresized( $dst_image, $src_image,
580 0, 0, 0, 0,
581 $width, $height,
582 imagesx( $src_image ), imagesy( $src_image ) );
583 } else {
584 imagecopyresampled( $dst_image, $src_image,
585 0, 0, 0, 0,
586 $width, $height,
587 imagesx( $src_image ), imagesy( $src_image ) );
588 }
589
590 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
591 $rot_image = imagerotate( $dst_image, $rotation, 0 );
592 imagedestroy( $dst_image );
593 $dst_image = $rot_image;
594 }
595
596 imagesavealpha( $dst_image, true );
597
598 call_user_func( $saveType, $dst_image, $params['dstPath'] );
599 imagedestroy( $dst_image );
600 imagedestroy( $src_image );
601
602 return false; # No error
603 }
604
605 /**
606 * Escape a string for ImageMagick's property input (e.g. -set -comment)
607 * See InterpretImageProperties() in magick/property.c
608 * @param string $s
609 * @return string
610 */
611 function escapeMagickProperty( $s ) {
612 // Double the backslashes
613 $s = str_replace( '\\', '\\\\', $s );
614 // Double the percents
615 $s = str_replace( '%', '%%', $s );
616 // Escape initial - or @
617 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
618 $s = '\\' . $s;
619 }
620
621 return $s;
622 }
623
624 /**
625 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
626 * and GetPathComponent() in magick/utility.c.
627 *
628 * This won't work with an initial ~ or @, so input files should be prefixed
629 * with the directory name.
630 *
631 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
632 * it's broken in a way that doesn't involve trying to convert every file
633 * in a directory, so we're better off escaping and waiting for the bugfix
634 * to filter down to users.
635 *
636 * @param string $path The file path
637 * @param bool|string $scene The scene specification, or false if there is none
638 * @throws MWException
639 * @return string
640 */
641 function escapeMagickInput( $path, $scene = false ) {
642 # Die on initial metacharacters (caller should prepend path)
643 $firstChar = substr( $path, 0, 1 );
644 if ( $firstChar === '~' || $firstChar === '@' ) {
645 throw new MWException( __METHOD__ . ': cannot escape this path name' );
646 }
647
648 # Escape glob chars
649 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
650
651 return $this->escapeMagickPath( $path, $scene );
652 }
653
654 /**
655 * Escape a string for ImageMagick's output filename. See
656 * InterpretImageFilename() in magick/image.c.
657 * @param string $path The file path
658 * @param bool|string $scene The scene specification, or false if there is none
659 * @return string
660 */
661 function escapeMagickOutput( $path, $scene = false ) {
662 $path = str_replace( '%', '%%', $path );
663
664 return $this->escapeMagickPath( $path, $scene );
665 }
666
667 /**
668 * Armour a string against ImageMagick's GetPathComponent(). This is a
669 * helper function for escapeMagickInput() and escapeMagickOutput().
670 *
671 * @param string $path The file path
672 * @param bool|string $scene The scene specification, or false if there is none
673 * @throws MWException
674 * @return string
675 */
676 protected function escapeMagickPath( $path, $scene = false ) {
677 # Die on format specifiers (other than drive letters). The regex is
678 # meant to match all the formats you get from "convert -list format"
679 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
680 if ( wfIsWindows() && is_dir( $m[0] ) ) {
681 // OK, it's a drive letter
682 // ImageMagick has a similar exception, see IsMagickConflict()
683 } else {
684 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
685 }
686 }
687
688 # If there are square brackets, add a do-nothing scene specification
689 # to force a literal interpretation
690 if ( $scene === false ) {
691 if ( strpos( $path, '[' ) !== false ) {
692 $path .= '[0--1]';
693 }
694 } else {
695 $path .= "[$scene]";
696 }
697
698 return $path;
699 }
700
701 /**
702 * Retrieve the version of the installed ImageMagick
703 * You can use PHPs version_compare() to use this value
704 * Value is cached for one hour.
705 * @return string Representing the IM version.
706 */
707 protected function getMagickVersion() {
708 global $wgMemc;
709
710 $cache = $wgMemc->get( "imagemagick-version" );
711 if ( !$cache ) {
712 global $wgImageMagickConvertCommand;
713 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
714 wfDebug( __METHOD__ . ": Running convert -version\n" );
715 $retval = '';
716 $return = wfShellExec( $cmd, $retval );
717 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
718 if ( $x != 1 ) {
719 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
720
721 return null;
722 }
723 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
724
725 return $matches[1];
726 }
727
728 return $cache;
729 }
730
731 static function imageJpegWrapper( $dst_image, $thumbPath ) {
732 imageinterlace( $dst_image );
733 imagejpeg( $dst_image, $thumbPath, 95 );
734 }
735
736 /**
737 * Returns whether the current scaler supports rotation (im and gd do)
738 *
739 * @return bool
740 */
741 public static function canRotate() {
742 $scaler = self::getScalerType( null, false );
743 switch ( $scaler ) {
744 case 'im':
745 # ImageMagick supports autorotation
746 return true;
747 case 'imext':
748 # Imagick::rotateImage
749 return true;
750 case 'gd':
751 # GD's imagerotate function is used to rotate images, but not
752 # all precompiled PHP versions have that function
753 return function_exists( 'imagerotate' );
754 default:
755 # Other scalers don't support rotation
756 return false;
757 }
758 }
759
760 /**
761 * @see $wgEnableAutoRotation
762 * @return bool Whether auto rotation is enabled
763 */
764 public static function autoRotateEnabled() {
765 global $wgEnableAutoRotation;
766
767 if ( $wgEnableAutoRotation === null ) {
768 // Only enable auto-rotation when the bitmap handler can rotate
769 $wgEnableAutoRotation = BitmapHandler::canRotate();
770 }
771
772 return $wgEnableAutoRotation;
773 }
774
775 /**
776 * @param File $file
777 * @param array $params Rotate parameters.
778 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
779 * @since 1.21
780 * @return bool
781 */
782 public function rotate( $file, $params ) {
783 global $wgImageMagickConvertCommand;
784
785 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
786 $scene = false;
787
788 $scaler = self::getScalerType( null, false );
789 switch ( $scaler ) {
790 case 'im':
791 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
792 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
793 " -rotate -$rotation " .
794 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
795 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
796 wfProfileIn( 'convert' );
797 $retval = 0;
798 // @todo FIXME: Undefined variable %env
799 $err = wfShellExecWithStderr( $cmd, $retval, $env );
800 wfProfileOut( 'convert' );
801 if ( $retval !== 0 ) {
802 $this->logErrorForExternalProcess( $retval, $err, $cmd );
803
804 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
805 }
806
807 return false;
808 case 'imext':
809 $im = new Imagick();
810 $im->readImage( $params['srcPath'] );
811 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
812 return new MediaTransformError( 'thumbnail_error', 0, 0,
813 "Error rotating $rotation degrees" );
814 }
815 $result = $im->writeImage( $params['dstPath'] );
816 if ( !$result ) {
817 return new MediaTransformError( 'thumbnail_error', 0, 0,
818 "Unable to write image to {$params['dstPath']}" );
819 }
820
821 return false;
822 default:
823 return new MediaTransformError( 'thumbnail_error', 0, 0,
824 "$scaler rotation not implemented" );
825 }
826 }
827
828 /**
829 * Rerurns whether the file needs to be rendered. Returns true if the
830 * file requires rotation and we are able to rotate it.
831 *
832 * @param File $file
833 * @return bool
834 */
835 public function mustRender( $file ) {
836 return self::canRotate() && $this->getRotation( $file ) != 0;
837 }
838 }