(bug 27809) Check for availability of imagerotate function before using it
[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 'gd':
147 default:
148 $err = $this->transformGd( $image, $scalerParams );
149 break;
150 }
151
152 # Remove the file if a zero-byte thumbnail was created, or if there was an error
153 $removed = $this->removeBadFile( $dstPath, (bool)$err );
154 if ( $err ) {
155 # transform returned MediaTransforError
156 return $err;
157 } elseif ( $removed ) {
158 # Thumbnail was zero-byte and had to be removed
159 return new MediaTransformError( 'thumbnail_error',
160 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
161 } else {
162 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
163 $scalerParams['clientHeight'], $dstPath );
164 }
165 }
166
167 /**
168 * Returns which scaler type should be used. Creates parent directories
169 * for $dstPath and returns 'client' on error
170 *
171 * @return string client,im,custom,gd
172 */
173 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
174 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
175
176 if ( !$dstPath && $checkDstPath ) {
177 # No output path available, client side scaling only
178 $scaler = 'client';
179 } elseif ( !$wgUseImageResize ) {
180 $scaler = 'client';
181 } elseif ( $wgUseImageMagick ) {
182 $scaler = 'im';
183 } elseif ( $wgCustomConvertCommand ) {
184 $scaler = 'custom';
185 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
186 $scaler = 'gd';
187 } else {
188 $scaler = 'client';
189 }
190
191 if ( $scaler != 'client' && $dstPath ) {
192 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
193 # Unable to create a path for the thumbnail
194 return 'client';
195 }
196 }
197 return $scaler;
198 }
199
200 /**
201 * Get a ThumbnailImage that respresents an image that will be scaled
202 * client side
203 *
204 * @param $image File File associated with this thumbnail
205 * @param $params array Array with scaler params
206 * @return ThumbnailImage
207 */
208 protected function getClientScalingThumbnailImage( $image, $params ) {
209 return new ThumbnailImage( $image, $image->getURL(),
210 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
211 }
212
213 /**
214 * Transform an image using ImageMagick
215 *
216 * @param $image File File associated with this thumbnail
217 * @param $params array Array with scaler params
218 *
219 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
220 */
221 protected function transformImageMagick( $image, $params ) {
222 # use ImageMagick
223 global $wgSharpenReductionThreshold, $wgSharpenParameter,
224 $wgMaxAnimatedGifArea,
225 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
226
227 $quality = '';
228 $sharpen = '';
229 $scene = false;
230 $animation_pre = '';
231 $animation_post = '';
232 $decoderHint = '';
233 if ( $params['mimeType'] == 'image/jpeg' ) {
234 $quality = "-quality 80"; // 80%
235 # Sharpening, see bug 6193
236 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
237 / ( $params['srcWidth'] + $params['srcHeight'] )
238 < $wgSharpenReductionThreshold ) {
239 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
240 }
241 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
242 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
243
244 } elseif ( $params['mimeType'] == 'image/png' ) {
245 $quality = "-quality 95"; // zlib 9, adaptive filtering
246
247 } elseif ( $params['mimeType'] == 'image/gif' ) {
248 if ( $this->getImageArea( $image, $params['srcWidth'],
249 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
250 // Extract initial frame only; we're so big it'll
251 // be a total drag. :P
252 $scene = 0;
253
254 } elseif ( $this->isAnimatedImage( $image ) ) {
255 // Coalesce is needed to scale animated GIFs properly (bug 1017).
256 $animation_pre = '-coalesce';
257 // We optimize the output, but -optimize is broken,
258 // use optimizeTransparency instead (bug 11822)
259 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
260 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
261 }
262 }
263 }
264
265 // Use one thread only, to avoid deadlock bugs on OOM
266 $env = array( 'OMP_NUM_THREADS' => 1 );
267 if ( strval( $wgImageMagickTempDir ) !== '' ) {
268 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
269 }
270
271 $cmd =
272 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
273 // Specify white background color, will be used for transparent images
274 // in Internet Explorer/Windows instead of default black.
275 " {$quality} -background white" .
276 " {$decoderHint} " .
277 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
278 " {$animation_pre}" .
279 // For the -thumbnail option a "!" is needed to force exact size,
280 // or ImageMagick may decide your ratio is wrong and slice off
281 // a pixel.
282 " -thumbnail " . wfEscapeShellArg( "{$params['physicalDimensions']}!" ) .
283 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
284 ( $params['comment'] !== ''
285 ? " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
286 : '' ) .
287 " -depth 8 $sharpen -auto-orient" .
288 " {$animation_post} " .
289 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
290
291 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
292 wfProfileIn( 'convert' );
293 $retval = 0;
294 $err = wfShellExec( $cmd, $retval, $env );
295 wfProfileOut( 'convert' );
296
297 if ( $retval !== 0 ) {
298 $this->logErrorForExternalProcess( $retval, $err, $cmd );
299 return $this->getMediaTransformError( $params, $err );
300 }
301
302 return false; # No error
303 }
304
305 /**
306 * Transform an image using a custom command
307 *
308 * @param $image File File associated with this thumbnail
309 * @param $params array Array with scaler params
310 *
311 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
312 */
313 protected function transformCustom( $image, $params ) {
314 # Use a custom convert command
315 global $wgCustomConvertCommand;
316
317 # Variables: %s %d %w %h
318 $src = wfEscapeShellArg( $params['srcPath'] );
319 $dst = wfEscapeShellArg( $params['dstPath'] );
320 $cmd = $wgCustomConvertCommand;
321 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
322 $cmd = str_replace( '%h', $params['physicalHeight'],
323 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
324 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
325 wfProfileIn( 'convert' );
326 $retval = 0;
327 $err = wfShellExec( $cmd, $retval );
328 wfProfileOut( 'convert' );
329
330 if ( $retval !== 0 ) {
331 $this->logErrorForExternalProcess( $retval, $err, $cmd );
332 return $this->getMediaTransformError( $params, $err );
333 }
334 return false; # No error
335 }
336
337 /**
338 * Log an error that occured in an external process
339 *
340 * @param $retval int
341 * @param $err int
342 * @param $cmd string
343 */
344 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
345 wfDebugLog( 'thumbnail',
346 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
347 wfHostname(), $retval, trim( $err ), $cmd ) );
348 }
349 /**
350 * Get a MediaTransformError with error 'thumbnail_error'
351 *
352 * @param $params array Parameter array as passed to the transform* functions
353 * @param $errMsg string Error message
354 * @return MediaTransformError
355 */
356 protected function getMediaTransformError( $params, $errMsg ) {
357 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
358 $params['clientHeight'], $errMsg );
359 }
360
361 /**
362 * Transform an image using the built in GD library
363 *
364 * @param $image File File associated with this thumbnail
365 * @param $params array Array with scaler params
366 *
367 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
368 */
369 protected function transformGd( $image, $params ) {
370 # Use PHP's builtin GD library functions.
371 #
372 # First find out what kind of file this is, and select the correct
373 # input routine for this.
374
375 $typemap = array(
376 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
377 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
378 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
379 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
380 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
381 );
382 if ( !isset( $typemap[$params['mimeType']] ) ) {
383 $err = 'Image type not supported';
384 wfDebug( "$err\n" );
385 $errMsg = wfMsg ( 'thumbnail_image-type' );
386 return $this->getMediaTransformError( $params, $errMsg );
387 }
388 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
389
390 if ( !function_exists( $loader ) ) {
391 $err = "Incomplete GD library configuration: missing function $loader";
392 wfDebug( "$err\n" );
393 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
394 return $this->getMediaTransformError( $params, $errMsg );
395 }
396
397 if ( !file_exists( $params['srcPath'] ) ) {
398 $err = "File seems to be missing: {$params['srcPath']}";
399 wfDebug( "$err\n" );
400 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
401 return $this->getMediaTransformError( $params, $errMsg );
402 }
403
404 $src_image = call_user_func( $loader, $params['srcPath'] );
405
406 $rotation = function_exists( 'imagerotate' ) ? $this->getRotation( $image ) : 0;
407 if ( $rotation == 90 || $rotation == 270 ) {
408 # We'll resize before rotation, so swap the dimensions again
409 $width = $params['physicalHeight'];
410 $height = $params['physicalWidth'];
411 } else {
412 $width = $params['physicalWidth'];
413 $height = $params['physicalHeight'];
414 }
415 $dst_image = imagecreatetruecolor( $width, $height );
416
417 // Initialise the destination image to transparent instead of
418 // the default solid black, to support PNG and GIF transparency nicely
419 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
420 imagecolortransparent( $dst_image, $background );
421 imagealphablending( $dst_image, false );
422
423 if ( $colorStyle == 'palette' ) {
424 // Don't resample for paletted GIF images.
425 // It may just uglify them, and completely breaks transparency.
426 imagecopyresized( $dst_image, $src_image,
427 0, 0, 0, 0,
428 $width, $height,
429 imagesx( $src_image ), imagesy( $src_image ) );
430 } else {
431 imagecopyresampled( $dst_image, $src_image,
432 0, 0, 0, 0,
433 $width, $height,
434 imagesx( $src_image ), imagesy( $src_image ) );
435 }
436
437 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
438 $rot_image = imagerotate( $dst_image, $rotation, 0 );
439 imagedestroy( $dst_image );
440 $dst_image = $rot_image;
441 }
442
443 imagesavealpha( $dst_image, true );
444
445 call_user_func( $saveType, $dst_image, $params['dstPath'] );
446 imagedestroy( $dst_image );
447 imagedestroy( $src_image );
448
449 return false; # No error
450 }
451
452 /**
453 * Escape a string for ImageMagick's property input (e.g. -set -comment)
454 * See InterpretImageProperties() in magick/property.c
455 */
456 function escapeMagickProperty( $s ) {
457 // Double the backslashes
458 $s = str_replace( '\\', '\\\\', $s );
459 // Double the percents
460 $s = str_replace( '%', '%%', $s );
461 // Escape initial - or @
462 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
463 $s = '\\' . $s;
464 }
465 return $s;
466 }
467
468 /**
469 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
470 * and GetPathComponent() in magick/utility.c.
471 *
472 * This won't work with an initial ~ or @, so input files should be prefixed
473 * with the directory name.
474 *
475 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
476 * it's broken in a way that doesn't involve trying to convert every file
477 * in a directory, so we're better off escaping and waiting for the bugfix
478 * to filter down to users.
479 *
480 * @param $path string The file path
481 * @param $scene string The scene specification, or false if there is none
482 */
483 function escapeMagickInput( $path, $scene = false ) {
484 # Die on initial metacharacters (caller should prepend path)
485 $firstChar = substr( $path, 0, 1 );
486 if ( $firstChar === '~' || $firstChar === '@' ) {
487 throw new MWException( __METHOD__ . ': cannot escape this path name' );
488 }
489
490 # Escape glob chars
491 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
492
493 return $this->escapeMagickPath( $path, $scene );
494 }
495
496 /**
497 * Escape a string for ImageMagick's output filename. See
498 * InterpretImageFilename() in magick/image.c.
499 */
500 function escapeMagickOutput( $path, $scene = false ) {
501 $path = str_replace( '%', '%%', $path );
502 return $this->escapeMagickPath( $path, $scene );
503 }
504
505 /**
506 * Armour a string against ImageMagick's GetPathComponent(). This is a
507 * helper function for escapeMagickInput() and escapeMagickOutput().
508 *
509 * @param $path string The file path
510 * @param $scene string The scene specification, or false if there is none
511 */
512 protected function escapeMagickPath( $path, $scene = false ) {
513 # Die on format specifiers (other than drive letters). The regex is
514 # meant to match all the formats you get from "convert -list format"
515 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
516 if ( wfIsWindows() && is_dir( $m[0] ) ) {
517 // OK, it's a drive letter
518 // ImageMagick has a similar exception, see IsMagickConflict()
519 } else {
520 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
521 }
522 }
523
524 # If there are square brackets, add a do-nothing scene specification
525 # to force a literal interpretation
526 if ( $scene === false ) {
527 if ( strpos( $path, '[' ) !== false ) {
528 $path .= '[0--1]';
529 }
530 } else {
531 $path .= "[$scene]";
532 }
533 return $path;
534 }
535
536 /**
537 * Retrieve the version of the installed ImageMagick
538 * You can use PHPs version_compare() to use this value
539 * Value is cached for one hour.
540 * @return String representing the IM version.
541 */
542 protected function getMagickVersion() {
543 global $wgMemc;
544
545 $cache = $wgMemc->get( "imagemagick-version" );
546 if ( !$cache ) {
547 global $wgImageMagickConvertCommand;
548 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
549 wfDebug( __METHOD__ . ": Running convert -version\n" );
550 $retval = '';
551 $return = wfShellExec( $cmd, $retval );
552 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
553 if ( $x != 1 ) {
554 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
555 return null;
556 }
557 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
558 return $matches[1];
559 }
560 return $cache;
561 }
562
563 static function imageJpegWrapper( $dst_image, $thumbPath ) {
564 imageinterlace( $dst_image );
565 imagejpeg( $dst_image, $thumbPath, 95 );
566 }
567
568
569 function getMetadata( $image, $filename ) {
570 global $wgShowEXIF;
571 if ( $wgShowEXIF && file_exists( $filename ) ) {
572 $exif = new Exif( $filename );
573 $data = $exif->getFilteredData();
574 if ( $data ) {
575 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
576 return serialize( $data );
577 } else {
578 return '0';
579 }
580 } else {
581 return '';
582 }
583 }
584
585 function getMetadataType( $image ) {
586 return 'exif';
587 }
588
589 function isMetadataValid( $image, $metadata ) {
590 global $wgShowEXIF;
591 if ( !$wgShowEXIF ) {
592 # Metadata disabled and so an empty field is expected
593 return true;
594 }
595 if ( $metadata === '0' ) {
596 # Special value indicating that there is no EXIF data in the file
597 return true;
598 }
599 wfSuppressWarnings();
600 $exif = unserialize( $metadata );
601 wfRestoreWarnings();
602 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
603 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
604 {
605 # Wrong version
606 wfDebug( __METHOD__ . ": wrong version\n" );
607 return false;
608 }
609 return true;
610 }
611
612 /**
613 * Get a list of EXIF metadata items which should be displayed when
614 * the metadata table is collapsed.
615 *
616 * @return array of strings
617 * @access private
618 */
619 function visibleMetadataFields() {
620 $fields = array();
621 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
622 foreach ( $lines as $line ) {
623 $matches = array();
624 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
625 $fields[] = $matches[1];
626 }
627 }
628 $fields = array_map( 'strtolower', $fields );
629 return $fields;
630 }
631
632 /**
633 * @param $image File
634 * @return array|bool
635 */
636 function formatMetadata( $image ) {
637 $result = array(
638 'visible' => array(),
639 'collapsed' => array()
640 );
641 $metadata = $image->getMetadata();
642 if ( !$metadata ) {
643 return false;
644 }
645 $exif = unserialize( $metadata );
646 if ( !$exif ) {
647 return false;
648 }
649 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
650 $format = new FormatExif( $exif );
651
652 $formatted = $format->getFormattedData();
653 // Sort fields into visible and collapsed
654 $visibleFields = $this->visibleMetadataFields();
655 foreach ( $formatted as $name => $value ) {
656 $tag = strtolower( $name );
657 self::addMeta( $result,
658 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
659 'exif',
660 $tag,
661 $value
662 );
663 }
664 return $result;
665 }
666
667 /**
668 * Try to read out the orientation of the file and return the angle that
669 * the file needs to be rotated to be viewed
670 *
671 * @param $file File
672 * @return int 0, 90, 180 or 270
673 */
674 public function getRotation( $file ) {
675 $data = $file->getMetadata();
676 if ( !$data ) {
677 return 0;
678 }
679 $data = unserialize( $data );
680 if ( isset( $data['Orientation'] ) ) {
681 # See http://sylvana.net/jpegcrop/exif_orientation.html
682 switch ( $data['Orientation'] ) {
683 case 8:
684 return 90;
685 case 3:
686 return 180;
687 case 6:
688 return 270;
689 default:
690 return 0;
691 }
692 }
693 return 0;
694 }
695 /**
696 * Returns whether the current scaler supports rotation (im and gd do)
697 *
698 * @return bool
699 */
700 public static function canRotate() {
701 $scaler = self::getScalerType( null, false );
702 switch ( $scaler ) {
703 case 'im':
704 # ImageMagick supports autorotation
705 return true;
706 case 'gd':
707 # GD's imagerotate function is used to rotate images, but not
708 # all precompiled PHP versions have that function
709 return function_exists( 'imagerotate' );
710 default:
711 # Other scalers don't support rotation
712 return false;
713 }
714 }
715
716 /**
717 * Rerurns whether the file needs to be rendered. Returns true if the
718 * file requires rotation and we are able to rotate it.
719 *
720 * @param $file File
721 * @return bool
722 */
723 public function mustRender( $file ) {
724 return self::canRotate() && $this->getRotation( $file ) != 0;
725 }
726 }