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