Don't use @, use wfSuppress/RestoreWarnings
[lhc/web/wiklou.git] / includes / media / Bitmap.php
index e573e23..5a64b32 100644 (file)
@@ -8,75 +8,8 @@
  * @ingroup Media
  */
 class BitmapHandler extends ImageHandler {
-       /**
-        * Override parent method to add crop to param map.
-        */
-       public function getParamMap() {
-               return array(
-                       'img_width'     => 'width',
-                       'img_crop' => 'crop',
-               );
-       }
-       
-       /**
-        * Override param map to validate the crop param.
-        */
-       public function validateParam( $name, $value ) {
-               if ( $name == 'crop' ) {
-                       return $this->splitCropParam( $value ) !== false;
-               } else {
-                       return parent::validateParam( $name, $value );
-               }               
-       }
-       /**
-        * Split the crop param into up to 4 parts and convert them to integers.
-        * Returns false in case of malformed param.
-        */
-       protected function splitCropParam( $value ) {
-               $parts = explode( 'x', $value );
-               if ( count( $parts ) > 4 )
-                       return false;
-               foreach ( $parts as &$part ) {
-                       $intVal = intval( $part );
-                       if ( $intVal === 0 && !( $part === '0' || $part === '' ) )
-                               return false;
-                       if ( $intVal < 0 )
-                               return false;
-                       
-                       $part = $intVal;
-               }
-               
-               return $parts;
-       }
-       
-       /**
-        * Override parent method to check for optional crop parameter in param 
-        * string.
-        */
-       public function parseParamString( $str ) {
-               $res = parent::parseParamString( $str );
-               if ( $res === false ) {
-                       $m = false;
-                       if ( preg_match( '/^(\d+)px-([x0-9])crop$/', $str, $m ) ) {
-                               return array( 'width' => $m[1], 'crop' => $m[2] );
-                       } else {
-                               return false;
-                       }
-               }
-       }
-       /**
-        * Add the crop parameter the string generated by the parent.
-        */
-       public function makeParamString( $params ) { 
-               $res = parent::makeParamString( $params );
-               if ( !empty( $params['crop'] ) )
-                       $res .= '-'.implode( 'x', $params['crop'] ).'crop';
-               return $res;
-       }
-       
-       public function normaliseParams( $image, &$params ) {
+       function normaliseParams( $image, &$params ) {
                global $wgMaxImageArea;
-               # Parent fills in width, height and page and normalizes them.
                if ( !parent::normaliseParams( $image, $params ) ) {
                        return false;
                }
@@ -85,15 +18,6 @@ class BitmapHandler extends ImageHandler {
                $srcWidth = $image->getWidth( $params['page'] );
                $srcHeight = $image->getHeight( $params['page'] );
 
-               # 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.
-               if ( $mimeType !== 'image/jpeg' &&
-                       $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxImageArea )
-               {
-                       return false;
-               }
-
                # Don't make an image bigger than the source
                $params['physicalWidth'] = $params['width'];
                $params['physicalHeight'] = $params['height'];
@@ -101,60 +25,31 @@ class BitmapHandler extends ImageHandler {
                if ( $params['physicalWidth'] >= $srcWidth ) {
                        $params['physicalWidth'] = $srcWidth;
                        $params['physicalHeight'] = $srcHeight;
-                       return true;
+                       # Skip scaling limit checks if no scaling is required
+                       if( !$image->mustRender() )
+                               return true;
                }
-               
-               # Validate crop params
-               if ( isset( $params['crop'] ) ) {
-                       # $cropParams = array( x, y, width, height );
-                       $cropParams = $this->splitCropParam( $params['crop'] );
-                       # Fill up params
-                       switch ( count( $cropParams ) ) {
-                               # All fall through
-                               case 1:
-                                       $cropParams[1] = 0;
-                               case 2:
-                                       $cropParams[2] = $srcWidth - $cropParams[0];
-                               case 3:
-                                       $cropParams[3] = $srcHeight - $cropParams[1];
-                       }
-                       $cx = $cropParams[0] + $cropParams[2];
-                       $cy = $cropParams[1] + $cropParams[3];
-                       $targetWidth = $cropParams[2];
-                       $targetHeight = $cropParams[3];
-                       # Can't go outside image
-                       if ( $cx > $srcWidth || $cy > $srcHeight ) {
-                               # TODO: Maybe should fail gracefully?
-                               return false; 
-                       }
-                       if ( $targetWidth == $srcWidth && $targetHeight == $srcHeight )
-                       {
-                               # No need to crop
-                               $params['crop'] = false;
-                       }
-                       else
-                       {
-                               $params['crop'] = $cropParams;
-                               $params['height'] = $params['physicalHeight'] = File::scaleHeight( 
-                                               $targetWidth, $targetHeight, $params['width'] );
-                       }
-               } else {
-                       $params['crop'] = false;
+
+               # 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.
+               if ( $mimeType !== 'image/jpeg' &&
+                       $srcWidth * $srcHeight > $wgMaxImageArea )
+               {
+                       return false;
                }
 
                return true;
        }
        
        
-       /**
-        * Function that returns the number of pixels to be thumbnailed.
-        * Intended for animated GIFs to multiply by the number of frames.
-        */
-       protected function getImageArea( $image, $width, $height ) {
+       // 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;
        }
 
-       public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
+       function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
                global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
                global $wgCustomConvertCommand, $wgUseImageResize;
                global $wgSharpenParameter, $wgSharpenReductionThreshold;
@@ -167,6 +62,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();
@@ -217,7 +113,7 @@ class BitmapHandler extends ImageHandler {
 
                        $quality = '';
                        $sharpen = '';
-                       $frame = '';
+                       $scene = false;
                        $animation = '';
                        if ( $mimeType == 'image/jpeg' ) {
                                $quality = "-quality 80"; // 80%
@@ -228,10 +124,10 @@ class BitmapHandler extends ImageHandler {
                        } elseif ( $mimeType == 'image/png' ) {
                                $quality = "-quality 95"; // zlib 9, adaptive filtering
                        } elseif( $mimeType == 'image/gif' ) {
-                               if( $srcWidth * $srcHeight > $wgMaxAnimatedGifArea ) {
+                               if( $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxAnimatedGifArea ) {
                                        // Extract initial frame only; we're so big it'll
                                        // be a total drag. :P
-                                       $frame = '[0]';
+                                       $scene = 0;
                                } else {
                                        // Coalesce is needed to scale animated GIFs properly (bug 1017).
                                        $animation = ' -coalesce ';
@@ -243,13 +139,6 @@ class BitmapHandler extends ImageHandler {
                        } else {
                                $tempEnv = '';
                        }
-                       
-                       if ( $params['crop'] ) {
-                               $crop = $params['crop'];
-                               $cropCmd = "-crop {$crop[2]}x{$crop[3]}+{$crop[0]}+{$crop[1]}";
-                       }
-                       else
-                               $cropCmd = '';
 
                        # Specify white background color, will be used for transparent images
                        # in Internet Explorer/Windows instead of default black.
@@ -260,17 +149,19 @@ class BitmapHandler extends ImageHandler {
 
                        $cmd  = 
                                $tempEnv .
-                               wfEscapeShellArg($wgImageMagickConvertCommand) .
-                               " {$cropCmd} {$quality} -background white -size {$physicalWidth} ".
-                               wfEscapeShellArg($srcPath . $frame) .
+                               wfEscapeShellArg( $wgImageMagickConvertCommand ) .
+                               " {$quality} -background white -size {$physicalWidth} ".
+                               wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
                                $animation .
                                // For the -resize 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}!" ) .
+                               // Add the source url as a comment to the thumb.        
+                               " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
                                " -depth 8 $sharpen " .
-                               wfEscapeShellArg($dstPath) . " 2>&1";
-                       wfDebug( __METHOD__.": running ImageMagick: $cmd\n");
+                               wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
+                       wfDebug( __METHOD__.": running ImageMagick: $cmd\n" );
                        wfProfileIn( 'convert' );
                        $err = wfShellExec( $cmd, $retval );
                        wfProfileOut( 'convert' );
@@ -361,13 +252,97 @@ class BitmapHandler extends ImageHandler {
                }
        }
 
-       public static function imageJpegWrapper( $dst_image, $thumbPath ) {
+       /**
+        * 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;
+       }
+
+       static function imageJpegWrapper( $dst_image, $thumbPath ) {
                imageinterlace( $dst_image );
                imagejpeg( $dst_image, $thumbPath, 95 );
        }
 
 
-       public function getMetadata( $image, $filename ) {
+       function getMetadata( $image, $filename ) {
                global $wgShowEXIF;
                if( $wgShowEXIF && file_exists( $filename ) ) {
                        $exif = new Exif( $filename );
@@ -383,11 +358,11 @@ class BitmapHandler extends ImageHandler {
                }
        }
 
-       public function getMetadataType( $image ) {
+       function getMetadataType( $image ) {
                return 'exif';
        }
 
-       public function isMetadataValid( $image, $metadata ) {
+       function isMetadataValid( $image, $metadata ) {
                global $wgShowEXIF;
                if ( !$wgShowEXIF ) {
                        # Metadata disabled and so an empty field is expected
@@ -397,7 +372,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() )
                {
@@ -415,7 +392,7 @@ class BitmapHandler extends ImageHandler {
         * @return array of strings
         * @access private
         */
-       public function visibleMetadataFields() {
+       function visibleMetadataFields() {
                $fields = array();
                $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
                foreach( $lines as $line ) {
@@ -428,7 +405,7 @@ class BitmapHandler extends ImageHandler {
                return $fields;
        }
 
-       public function formatMetadata( $image ) {
+       function formatMetadata( $image ) {
                $result = array(
                        'visible' => array(),
                        'collapsed' => array()