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