Object return type hints
[lhc/web/wiklou.git] / includes / media / Bitmap.php
index ca82aab..4909af2 100644 (file)
@@ -1,7 +1,15 @@
 <?php
+/**
+ * Generic handler for bitmap images
+ *
+ * @file
+ * @ingroup Media
+ */
 
 /**
- * @addtogroup Media
+ * Generic handler for bitmap images
+ *
+ * @ingroup Media
  */
 class BitmapHandler extends ImageHandler {
        function normaliseParams( $image, &$params ) {
@@ -14,6 +22,18 @@ class BitmapHandler extends ImageHandler {
                $srcWidth = $image->getWidth( $params['page'] );
                $srcHeight = $image->getHeight( $params['page'] );
 
+               # Don't make an image bigger than the source
+               $params['physicalWidth'] = $params['width'];
+               $params['physicalHeight'] = $params['height'];
+
+               if ( $params['physicalWidth'] >= $srcWidth ) {
+                       $params['physicalWidth'] = $srcWidth;
+                       $params['physicalHeight'] = $srcHeight;
+                       # Skip scaling limit checks if no scaling is required
+                       if( !$image->mustRender() )
+                               return true;
+               }
+
                # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
                # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
                # an exception for it.
@@ -23,23 +43,21 @@ class BitmapHandler extends ImageHandler {
                        return false;
                }
 
-               # Don't make an image bigger than the source
-               $params['physicalWidth'] = $params['width'];
-               $params['physicalHeight'] = $params['height'];
-               
-               if ( $params['physicalWidth'] >= $srcWidth ) {
-                       $params['physicalWidth'] = $srcWidth;
-                       $params['physicalHeight'] = $srcHeight;
-                       return true;
-               }
-
                return true;
        }
        
+       
+       // Function that returns the number of pixels to be thumbnailed.
+       // Intended for animated GIFs to multiply by the number of frames.
+       function getImageArea( $image, $width, $height ) {
+               return $width * $height;
+       }
+
        function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
-               global $wgUseImageMagick, $wgImageMagickConvertCommand;
-               global $wgCustomConvertCommand;
+               global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
+               global $wgCustomConvertCommand, $wgUseImageResize;
                global $wgSharpenParameter, $wgSharpenReductionThreshold;
+               global $wgMaxAnimatedGifArea;
 
                if ( !$this->normaliseParams( $image, $params ) ) {
                        return new TransformParameterError( $params );
@@ -48,6 +66,7 @@ class BitmapHandler extends ImageHandler {
                $physicalHeight = $params['physicalHeight'];
                $clientWidth = $params['width'];
                $clientHeight = $params['height'];
+               $comment = isset( $params['descriptionUrl'] ) ? "File source: ". $params['descriptionUrl'] : '';
                $srcWidth = $image->getWidth();
                $srcHeight = $image->getHeight();
                $mimeType = $image->getMimeType();
@@ -55,7 +74,7 @@ class BitmapHandler extends ImageHandler {
                $retval = 0;
                wfDebug( __METHOD__.": creating {$physicalWidth}x{$physicalHeight} thumbnail at $dstPath\n" );
 
-               if ( $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
+               if ( !$image->mustRender() && $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
                        # normaliseParams (or the user) wants us to return the unscaled image
                        wfDebug( __METHOD__.": returning unscaled image\n" );
                        return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
@@ -64,6 +83,8 @@ class BitmapHandler extends ImageHandler {
                if ( !$dstPath ) {
                        // No output path available, client side scaling only
                        $scaler = 'client';
+               } elseif( !$wgUseImageResize ) {
+                       $scaler = 'client';
                } elseif ( $wgUseImageMagick ) {
                        $scaler = 'im';
                } elseif ( $wgCustomConvertCommand ) {
@@ -73,6 +94,7 @@ class BitmapHandler extends ImageHandler {
                } else {
                        $scaler = 'client';
                }
+               wfDebug( __METHOD__.": scaler $scaler\n" );
 
                if ( $scaler == 'client' ) {
                        # Client-side image scaling, use the source URL
@@ -81,49 +103,77 @@ class BitmapHandler extends ImageHandler {
                }
 
                if ( $flags & self::TRANSFORM_LATER ) {
+                       wfDebug( __METHOD__.": Transforming later per flags.\n" );
                        return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
                }
 
                if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
-                       return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, 
-                               wfMsg( 'thumbnail_dest_directory' ) );
+                       wfDebug( __METHOD__.": Unable to create thumbnail destination directory, falling back to client scaling\n" );
+                       return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
                }
 
                if ( $scaler == 'im' ) {
                        # use ImageMagick
 
+                       $quality = '';
                        $sharpen = '';
+                       $scene = false;
+                       $animation_pre = '';
+                       $animation_post = '';
+                       $decoderHint = '';
                        if ( $mimeType == 'image/jpeg' ) {
                                $quality = "-quality 80"; // 80%
                                # Sharpening, see bug 6193
                                if ( ( $physicalWidth + $physicalHeight ) / ( $srcWidth + $srcHeight ) < $wgSharpenReductionThreshold ) {
                                        $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
                                }
+                               // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
+                               $decoderHint = "-define jpeg:size={$physicalWidth}x{$physicalHeight}";
                        } elseif ( $mimeType == 'image/png' ) {
                                $quality = "-quality 95"; // zlib 9, adaptive filtering
-                       } else {
-                               $quality = ''; // default
+                       } elseif( $mimeType == 'image/gif' ) {
+                               if( $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxAnimatedGifArea ) {
+                                       // Extract initial frame only; we're so big it'll
+                                       // be a total drag. :P
+                                       $scene = 0;
+                               } elseif( $this->isAnimatedImage( $image ) ) {
+                                       // Coalesce is needed to scale animated GIFs properly (bug 1017).
+                                       $animation_pre = '-coalesce';
+                                       // We optimize the output, but -optimize is broken,
+                                       // use optimizeTransparency instead (bug 11822)
+                                       if( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
+                                               $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
+                                       }
+                               }
                        }
 
-                       # Specify white background color, will be used for transparent images
-                       # in Internet Explorer/Windows instead of default black.
-
-                       # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
-                       # It seems that ImageMagick has a bug wherein it produces thumbnails of
-                       # the wrong size in the second case.
+                       if ( strval( $wgImageMagickTempDir ) !== '' ) {
+                               $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
+                       } else {
+                               $tempEnv = '';
+                       }
 
-                       $cmd  =  wfEscapeShellArg($wgImageMagickConvertCommand) .
-                               " {$quality} -background white -size {$physicalWidth} ".
-                               wfEscapeShellArg($srcPath) .
-                               // Coalesce is needed to scale animated GIFs properly (bug 1017).
-                               ' -coalesce ' .
-                               // For the -resize option a "!" is needed to force exact size,
+                       $cmd  = 
+                               $tempEnv .
+                               // Use one thread only, to avoid deadlock bugs on OOM
+                               'OMP_NUM_THREADS=1 ' .
+                               wfEscapeShellArg( $wgImageMagickConvertCommand ) .
+                               // Specify white background color, will be used for transparent images
+                               // in Internet Explorer/Windows instead of default black.
+                               " {$quality} -background white".
+                               " {$decoderHint} " .
+                               wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
+                               " {$animation_pre}" .
+                               // For the -thumbnail option a "!" is needed to force exact size,
                                // or ImageMagick may decide your ratio is wrong and slice off
                                // a pixel.
                                " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
-                               " -depth 8 $sharpen " .
-                               wfEscapeShellArg($dstPath) . " 2>&1";
-                       wfDebug( __METHOD__.": running ImageMagick: $cmd\n");
+                               // Add the source url as a comment to the thumb.        
+                               " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
+                               " -depth 8 $sharpen" .
+                               " {$animation_post} " .
+                               wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
+                       wfDebug( __METHOD__.": running ImageMagick: $cmd\n" );
                        wfProfileIn( 'convert' );
                        $err = wfShellExec( $cmd, $retval );
                        wfProfileOut( 'convert' );
@@ -155,24 +205,33 @@ class BitmapHandler extends ImageHandler {
                        if( !isset( $typemap[$mimeType] ) ) {
                                $err = 'Image type not supported';
                                wfDebug( "$err\n" );
-                               return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
+                               $errMsg = wfMsg ( 'thumbnail_image-type' );
+                               return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
                        }
                        list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
 
                        if( !function_exists( $loader ) ) {
                                $err = "Incomplete GD library configuration: missing function $loader";
                                wfDebug( "$err\n" );
-                               return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
+                               $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
+                               return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
+                       }
+
+                       if ( !file_exists( $srcPath ) ) {
+                               $err = "File seems to be missing: $srcPath";
+                               wfDebug( "$err\n" );
+                               $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
+                               return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
                        }
 
                        $src_image = call_user_func( $loader, $srcPath );
                        $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
-                       
+
                        // Initialise the destination image to transparent instead of
                        // the default solid black, to support PNG and GIF transparency nicely
                        $background = imagecolorallocate( $dst_image, 0, 0, 0 );
                        imagecolortransparent( $dst_image, $background );
-                       imagealphablending( $dst_image, false ); 
+                       imagealphablending( $dst_image, false );
 
                        if( $colorStyle == 'palette' ) {
                                // Don't resample for paletted GIF images.
@@ -187,7 +246,7 @@ class BitmapHandler extends ImageHandler {
                        }
 
                        imagesavealpha( $dst_image, true );
-                       
+
                        call_user_func( $saveType, $dst_image, $dstPath );
                        imagedestroy( $dst_image );
                        imagedestroy( $src_image );
@@ -205,6 +264,117 @@ class BitmapHandler extends ImageHandler {
                }
        }
 
+       /**
+        * Escape a string for ImageMagick's property input (e.g. -set -comment)
+        * See InterpretImageProperties() in magick/property.c
+        */
+       function escapeMagickProperty( $s ) {
+               // Double the backslashes
+               $s = str_replace( '\\', '\\\\', $s );
+               // Double the percents
+               $s = str_replace( '%', '%%', $s );
+               // Escape initial - or @
+               if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
+                       $s = '\\' . $s;
+               }
+               return $s;
+       }
+
+       /**
+        * Escape a string for ImageMagick's input filenames. See ExpandFilenames() 
+        * and GetPathComponent() in magick/utility.c.
+        *
+        * This won't work with an initial ~ or @, so input files should be prefixed
+        * with the directory name. 
+        *
+        * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
+        * it's broken in a way that doesn't involve trying to convert every file 
+        * in a directory, so we're better off escaping and waiting for the bugfix
+        * to filter down to users.
+        *
+        * @param $path string The file path
+        * @param $scene string The scene specification, or false if there is none
+        */
+       function escapeMagickInput( $path, $scene = false ) {
+               # Die on initial metacharacters (caller should prepend path)
+               $firstChar = substr( $path, 0, 1 );
+               if ( $firstChar === '~' || $firstChar === '@' ) {
+                       throw new MWException( __METHOD__.': cannot escape this path name' );
+               }
+
+               # Escape glob chars
+               $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
+
+               return $this->escapeMagickPath( $path, $scene );
+       }
+
+       /**
+        * Escape a string for ImageMagick's output filename. See 
+        * InterpretImageFilename() in magick/image.c.
+        */
+       function escapeMagickOutput( $path, $scene = false ) {
+               $path = str_replace( '%', '%%', $path );
+               return $this->escapeMagickPath( $path, $scene );
+       }
+
+       /**
+        * Armour a string against ImageMagick's GetPathComponent(). This is a 
+        * helper function for escapeMagickInput() and escapeMagickOutput().
+        *
+        * @param $path string The file path
+        * @param $scene string The scene specification, or false if there is none
+        */
+       protected function escapeMagickPath( $path, $scene = false ) {
+               # Die on format specifiers (other than drive letters). The regex is
+               # meant to match all the formats you get from "convert -list format"
+               if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
+                       if ( wfIsWindows() && is_dir( $m[0] ) ) {
+                               // OK, it's a drive letter
+                               // ImageMagick has a similar exception, see IsMagickConflict()
+                       } else {
+                               throw new MWException( __METHOD__.': unexpected colon character in path name' );
+                       }
+               }
+
+               # If there are square brackets, add a do-nothing scene specification 
+               # to force a literal interpretation
+               if ( $scene === false ) {
+                       if ( strpos( $path, '[' ) !== false ) {
+                               $path .= '[0--1]';
+                       }
+               } else {
+                       $path .= "[$scene]";
+               }
+               return $path;
+       }
+
+       /**
+        * Retrieve the version of the installed ImageMagick
+        * You can use PHPs version_compare() to use this value
+        * Value is cached for one hour.
+        * @return String representing the IM version.
+        */
+       protected function getMagickVersion() {
+               global $wgMemc;
+
+               $cache = $wgMemc->get( "imagemagick-version" );
+               if( !$cache ) {
+                       global $wgImageMagickConvertCommand;
+                       $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
+                       wfDebug( __METHOD__.": Running convert -version\n" );
+                       $retval = '';
+                       $return = wfShellExec( $cmd, $retval );
+                       $x = preg_match('/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches);
+                       if( $x != 1 ) {
+                               wfDebug( __METHOD__.": ImageMagick version check failed\n" );
+                               return null;
+                       }
+                       $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
+                       return $matches[1];
+               }
+               return $cache;
+       }
+
        static function imageJpegWrapper( $dst_image, $thumbPath ) {
                imageinterlace( $dst_image );
                imagejpeg( $dst_image, $thumbPath, 95 );
@@ -241,7 +411,9 @@ class BitmapHandler extends ImageHandler {
                        # Special value indicating that there is no EXIF data in the file
                        return true;
                }
-               $exif = @unserialize( $metadata );
+               wfSuppressWarnings();
+               $exif = unserialize( $metadata );
+               wfRestoreWarnings();
                if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
                        $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
                {
@@ -303,5 +475,3 @@ class BitmapHandler extends ImageHandler {
                return $result;
        }
 }
-
-