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