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