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