* Adding wfSuppressWarnings() before the Exif validation, some of the type
[lhc/web/wiklou.git] / includes / Image.php
index 8dd6c27..5817272 100644 (file)
@@ -3,6 +3,17 @@
  * @package MediaWiki
  */
 
+# NOTE FOR WINDOWS USERS:
+# To enable EXIF functions, add the folloing lines to the
+# "Windows extensions" section of php.ini:
+#
+# extension=extensions/php_mbstring.dll
+# extension=extensions/php_exif.dll
+
+if ($wgShowEXIF)
+       require_once('Exif.php');
+
+
 /**
  * Class to represent an image
  * 
@@ -29,6 +40,7 @@ class Image
                $type,          #  |
                $attr,          # /
                $size,          # Size in bytes (loadFromXxx)
+               $exif,                  # EXIF data
                $dataLoaded;    # Whether or not all this has been loaded from the database (loadFromXxx)
 
 
@@ -55,6 +67,7 @@ class Image
        function Image( $title ) {
                $this->title =& $title;
                $this->name = $title->getDBkey();
+               $this->exif = serialize ( array() ) ;
 
                $n = strrpos( $this->name, '.' );
                $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
@@ -105,9 +118,11 @@ class Image
                                                $this->height = $commonsCachedValues['height'];
                                                $this->bits = $commonsCachedValues['bits'];
                                                $this->type = $commonsCachedValues['type'];
+                                               $this->exif = $commonsCachedValues['exif'];
                                                $this->size = $commonsCachedValues['size'];
                                                $this->fromSharedDirectory = true;
                                                $this->dataLoaded = true;
+                                               $this->imagePath = $this->getFullPath(true);
                                        }
                                }
                        }
@@ -119,9 +134,11 @@ class Image
                                $this->height = $cachedValues['height'];
                                $this->bits = $cachedValues['bits'];
                                $this->type = $cachedValues['type'];
+                               $this->exif = $cachedValues['exif'];
                                $this->size = $cachedValues['size'];
                                $this->fromSharedDirectory = false;
                                $this->dataLoaded = true;
+                               $this->imagePath = $this->getFullPath();
                        }
                }
 
@@ -148,6 +165,7 @@ class Image
                                                                  'height' => $this->height,
                                                                  'bits' => $this->bits,
                                                                  'type' => $this->type,
+                                                                 'exif' => $this->exif,
                                                                  'size' => $this->size);
 
                        $wgMemc->set( $keys[0], $cachedValues );
@@ -163,6 +181,7 @@ class Image
                wfProfileIn( $fname );
                $this->imagePath = $this->getFullPath();
                $this->fileExists = file_exists( $this->imagePath );
+               $this->fromSharedDirectory = false;
                $gis = false;
 
                # If the file is not found, and a shared upload directory is used, look for it there.
@@ -174,15 +193,14 @@ class Image
                        $this->fileExists = file_exists( $sharedImage->getFullPath(true) );
                        if ( $this->fileExists ) {
                                $this->name = $sharedImage->name;
-                               $this->imagePath = $this->getFulPath(true);
+                               $this->imagePath = $this->getFullPath(true);
                                $this->fromSharedDirectory = true;
                        }
                }
 
                if ( $this->fileExists ) {
                        # Get size in bytes
-                       $s = stat( $this->imagePath );
-                       $this->size = $s['size'];
+                       $this->size = filesize( $this->imagePath );
 
                        # Height and width
                        # Don't try to get the width and height of sound and video files, that's bad for performance
@@ -203,10 +221,12 @@ class Image
                        $this->height = 0;
                        $this->bits = 0;
                        $this->type = 0;
+                       $this->exif = serialize ( array() ) ;
                } else {
                        $this->width = $gis[0];
                        $this->height = $gis[1];
                        $this->type = $gis[2];
+                       $this->exif = serialize ( $this->retrieveExifData() ) ;
                        if ( isset( $gis['bits'] ) )  {
                                $this->bits = $gis['bits'];
                        } else {
@@ -227,13 +247,17 @@ class Image
                
                $dbr =& wfGetDB( DB_SLAVE );
                $row = $dbr->selectRow( 'image', 
-                       array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
+                       array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_metadata' ),
                        array( 'img_name' => $this->name ), $fname );
                if ( $row ) {
                        $this->fromSharedDirectory = false;
                        $this->fileExists = true;
                        $this->loadFromRow( $row );
                        $this->imagePath = $this->getFullPath();
+                       // Check for rows from a previous schema, quietly upgrade them
+                       if ( $this->type == -1 ) {
+                               $this->upgradeRow();
+                       }
                } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
                        # In case we're on a wgCapitalLinks=false wiki, we 
                        # capitalize the first letter of the filename before 
@@ -246,9 +270,14 @@ class Image
                        if ( $row ) {
                                $this->fromSharedDirectory = true;
                                $this->fileExists = true;
-                               $this->imagePath = '';
+                               $this->imagePath = $this->getFullPath(true);
                                $this->name = $name;
                                $this->loadFromRow( $row );
+                               
+                               // Check for rows from a previous schema, quietly upgrade them
+                               if ( $this->type == -1 ) {
+                                       $this->upgradeRow();
+                               }
                        }
                }
                
@@ -260,6 +289,7 @@ class Image
                        $this->type = 0;
                        $this->fileExists = false;
                        $this->fromSharedDirectory = false;
+                       $this->exif = serialize ( array() ) ;
                }
 
                # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
@@ -275,6 +305,8 @@ class Image
                $this->height = $row->img_height;
                $this->bits = $row->img_bits;
                $this->type = $row->img_type;
+               $this->exif = $row->img_metadata;
+               if ( $this->exif == "" ) $this->exif = serialize ( array() ) ;
                $this->dataLoaded = true;
        }
 
@@ -282,10 +314,13 @@ class Image
         * Load image metadata from cache or DB, unless already loaded
         */
        function load() {
+               global $wgSharedUploadDBname, $wgUseSharedUploads;
                if ( !$this->dataLoaded ) {
                        if ( !$this->loadFromCache() ) {
                                $this->loadFromDB();
-                               if ( $this->fileExists ) {
+                               if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
+                                       $this->loadFromFile();
+                               } elseif ( $this->fileExists ) {
                                        $this->saveToCache();
                                }
                        }
@@ -293,6 +328,39 @@ class Image
                }
        }
 
+       /** 
+        * Metadata was loaded from the database, but the row had a marker indicating it needs to be 
+        * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
+        */
+       function upgradeRow() {
+               global $wgDBname, $wgSharedUploadDBname;
+               $fname = 'Image::upgradeRow';
+               $this->loadFromFile();
+               $dbw =& wfGetDB( DB_MASTER );
+
+               if ( $this->fromSharedDirectory ) {
+                       if ( !$wgSharedUploadDBname ) {
+                               return;
+                       }
+
+                       // Write to the other DB using selectDB, not database selectors
+                       // This avoids breaking replication in MySQL
+                       $dbw->selectDB( $wgSharedUploadDBname );
+               }
+               $dbw->update( 'image', 
+                       array( 
+                               'img_width' => $this->width,
+                               'img_height' => $this->height,
+                               'img_bits' => $this->bits,
+                               'img_type' => $this->type,
+                               'img_metadata' => $this->exif,
+                       ), array( 'img_name' => $this->name ), $fname
+               );
+               if ( $this->fromSharedDirectory ) {
+                       $dbw->selectDB( $wgDBname );
+               }
+       }
+                               
        /**
         * Return the name of this image
         * @access public
@@ -443,19 +511,43 @@ class Image
         */
        function thumbUrl( $width, $subdir='thumb') {
                global $wgUploadPath, $wgUploadBaseUrl,
-                      $wgSharedUploadPath,$wgSharedUploadDirectory;
-               $name = $this->thumbName( $width );             
-               if($this->fromSharedDirectory) {
-                       $base = '';
-                       $path = $wgSharedUploadPath;
+                      $wgSharedUploadPath,$wgSharedUploadDirectory,
+                          $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
+
+               // Generate thumb.php URL if possible
+               $script = false;
+               $url = false;
+
+               if ( $this->fromSharedDirectory ) {
+                       if ( $wgSharedThumbnailScriptPath ) {
+                               $script = $wgSharedThumbnailScriptPath;
+                       }
                } else {
-                       $base = $wgUploadBaseUrl;
-                       $path = $wgUploadPath;
+                       if ( $wgThumbnailScriptPath ) {
+                               $script = $wgThumbnailScriptPath;
+                       }
+               }
+               if ( $script ) {
+                       $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
+               } else {  
+                       $name = $this->thumbName( $width );             
+                       if($this->fromSharedDirectory) {
+                               $base = '';
+                               $path = $wgSharedUploadPath;
+                       } else {
+                               $base = $wgUploadBaseUrl;
+                               $path = $wgUploadPath;
+                       }
+                       if ( Image::isHashed( $this->fromSharedDirectory ) ) {
+                               $url = "{$base}{$path}/{$subdir}" . 
+                               wfGetHashPath($this->name, $this->fromSharedDirectory)
+                               . $this->name.'/'.$name;
+                               $url = wfUrlencode( $url );
+                       } else {
+                               $url = "{$base}{$path}/{$subdir}/{$name}";
+                       }
                }
-               $url = "{$base}{$path}/{$subdir}" . 
-               wfGetHashPath($name, $this->fromSharedDirectory)
-               . "{$name}";
-               return wfUrlencode($url);
+               return array( $script !== false, $url );
        }
 
        /**
@@ -465,7 +557,7 @@ class Image
         * @param boolean $shared       Does the thumbnail come from the shared repository?
         * @access private
         */
-       function thumbName( $width, $shared=false ) {
+       function thumbName( $width ) {
                $thumb = $width."px-".$this->name;
                if( $this->extension == 'svg' ) {
                        # Rasterize SVG vector images to PNG
@@ -558,19 +650,13 @@ class Image
         * @return ThumbnailImage
         * @access private
         */
-       function /* private */ renderThumb( $width, $useScript = true ) {
-               global $wgImageMagickConvertCommand;
-               global $wgUseImageMagick;
+       function renderThumb( $width, $useScript = true ) {
                global $wgUseSquid, $wgInternalServer;
                global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
                
                $width = IntVal( $width );
 
                $this->load();
-               $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
-               $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
-               $thumbUrl  = $this->thumbUrl( $width );
-               #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
                if ( ! $this->exists() )
                {
                        # If there is no image, there will be no thumbnail
@@ -590,137 +676,206 @@ class Image
                
                $height = floor( $this->height * ( $width/$this->width ) );
                
-               // Generate thumb.php URL if possible
-               $thumbScript = false;
-               $scriptUrl = false;
+               list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
+               if ( $isScriptUrl && $useScript ) {
+                       // Use thumb.php to render the image
+                       return new ThumbnailImage( $url, $width, $height );
+               }
 
-               if ( $this->fromSharedDirectory ) {
-                       if ( $wgSharedThumbnailScriptPath ) {
-                               $thumbScript = $wgSharedThumbnailScriptPath;
+               $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
+               $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
+
+               if ( !file_exists( $thumbPath ) ) {
+                       $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
+                               '/'.$thumbName;
+                       $done = false;
+                       if ( file_exists( $oldThumbPath ) ) {
+                               if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
+                                       rename( $oldThumbPath, $thumbPath );
+                                       $done = true;
+                               } else {
+                                       unlink( $oldThumbPath );
+                               }
                        }
+                       if ( !$done ) {
+                               $this->reallyRenderThumb( $thumbPath, $width, $height );
+
+                               # Purge squid
+                               # This has to be done after the image is updated and present for all machines on NFS, 
+                               # or else the old version might be stored into the squid again
+                               if ( $wgUseSquid ) {
+                                       if ( substr( $url, 0, 4 ) == 'http' ) {
+                                               $urlArr = array( $url );
+                                       } else {
+                                               $urlArr = array( $wgInternalServer.$url );
+                                       }
+                                       wfPurgeSquidServers($urlArr);
+                               }
+                       }
+               }
+               return new ThumbnailImage( $url, $width, $height, $thumbPath );
+       } // END OF function renderThumb
+
+       /**
+        * Really render a thumbnail
+        *
+        * @access private
+        */
+       function reallyRenderThumb( $thumbPath, $width, $height ) {
+               global $wgSVGConverters, $wgSVGConverter,
+                       $wgUseImageMagick, $wgImageMagickConvertCommand;
+               
+               $this->load();
+               
+               if( $this->extension == 'svg' ) {
+                       global $wgSVGConverters, $wgSVGConverter;
+                       if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
+                               global $wgSVGConverterPath;
+                               $cmd = str_replace(
+                                       array( '$path/', '$width', '$input', '$output' ),
+                                       array( $wgSVGConverterPath,
+                                                  $width,
+                                                  escapeshellarg( $this->imagePath ),
+                                                  escapeshellarg( $thumbPath ) ),
+                                       $wgSVGConverters[$wgSVGConverter] );
+                               $conv = shell_exec( $cmd );
+                       } else {
+                               $conv = false;
+                       }
+               } elseif ( $wgUseImageMagick ) {
+                       # use ImageMagick
+                       # Specify white background color, will be used for transparent images
+                       # in Internet Explorer/Windows instead of default black.
+                       $cmd  =  $wgImageMagickConvertCommand .
+                               " -quality 85 -background white -geometry {$width} ".
+                               escapeshellarg($this->imagePath) . " " .
+                               escapeshellarg($thumbPath);                             
+                       $conv = shell_exec( $cmd );
                } else {
-                       if ( $wgThumbnailScriptPath ) {
-                               $thumbScript = $wgThumbnailScriptPath;
+                       # Use PHP's builtin GD library functions.
+                       #
+                       # First find out what kind of file this is, and select the correct
+                       # input routine for this.
+
+                       $truecolor = false;
+                       
+                       switch( $this->type ) {
+                               case 1: # GIF
+                                       $src_image = imagecreatefromgif( $this->imagePath );
+                                       break;
+                               case 2: # JPG
+                                       $src_image = imagecreatefromjpeg( $this->imagePath );
+                                       $truecolor = true;
+                                       break;
+                               case 3: # PNG
+                                       $src_image = imagecreatefrompng( $this->imagePath );
+                                       $truecolor = ( $this->bits > 8 );
+                                       break;
+                               case 15: # WBMP for WML
+                                       $src_image = imagecreatefromwbmp( $this->imagePath );
+                                       break;
+                               case 16: # XBM
+                                       $src_image = imagecreatefromxbm( $this->imagePath );
+                                       break;
+                               default:
+                                       return 'Image type not supported';
+                                       break;
+                       }
+                       if ( $truecolor ) {
+                               $dst_image = imagecreatetruecolor( $width, $height );
+                       } else {
+                               $dst_image = imagecreate( $width, $height );
                        }
+                       imagecopyresampled( $dst_image, $src_image, 
+                                               0,0,0,0,
+                                               $width, $height, $this->width, $this->height );
+                       switch( $this->type ) {
+                               case 1:  # GIF
+                               case 3:  # PNG
+                               case 15: # WBMP
+                               case 16: # XBM
+                                       imagepng( $dst_image, $thumbPath );
+                                       break;
+                               case 2:  # JPEG
+                                       imageinterlace( $dst_image );
+                                       imagejpeg( $dst_image, $thumbPath, 95 );
+                                       break;
+                               default:
+                                       break;
+                       }
+                       imagedestroy( $dst_image );
+                       imagedestroy( $src_image );
                }
-               if ( $thumbScript ) {
-                       $scriptUrl = $thumbScript . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
-                       if ( $useScript ) {
-                               // Use thumb.php to render the image
-                               return new ThumbnailImage( , $width, $height );
+               #
+               # Check for zero-sized thumbnails. Those can be generated when 
+               # no disk space is available or some other error occurs
+               #
+               if( file_exists( $thumbPath ) ) {
+                       $thumbstat = stat( $thumbPath );
+                       if( $thumbstat['size'] == 0 ) {
+                               unlink( $thumbPath );
                        }
                }
+       }
 
-               if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
-                       if( $this->extension == 'svg' ) {
-                               global $wgSVGConverters, $wgSVGConverter;
-                               if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
-                                       global $wgSVGConverterPath;
-                                       $cmd = str_replace(
-                                               array( '$path/', '$width', '$input', '$output' ),
-                                               array( $wgSVGConverterPath,
-                                                          $width,
-                                                          escapeshellarg( $this->imagePath ),
-                                                          escapeshellarg( $thumbPath ) ),
-                                               $wgSVGConverters[$wgSVGConverter] );
-                                       $conv = shell_exec( $cmd );
-                               } else {
-                                       $conv = false;
-                               }
-                       } elseif ( $wgUseImageMagick ) {
-                               # use ImageMagick
-                               # Specify white background color, will be used for transparent images
-                               # in Internet Explorer/Windows instead of default black.
-                               $cmd  =  $wgImageMagickConvertCommand .
-                                       " -quality 85 -background white -geometry {$width} ".
-                                       escapeshellarg($this->imagePath) . " " .
-                                       escapeshellarg($thumbPath);                             
-                               $conv = shell_exec( $cmd );
-                       } else {
-                               # Use PHP's builtin GD library functions.
-                               #
-                               # First find out what kind of file this is, and select the correct
-                               # input routine for this.
+       /** 
+        * Get all thumbnail names previously generated for this image
+        */
+       function getThumbnails( $shared = false ) {
+               if ( Image::isHashed( $shared ) ) {
+                       $this->load();
+                       $files = array();
+                       $dir = wfImageThumbDir( $this->name, $shared );
 
-                               $truecolor = false;
-                               
-                               switch( $this->type ) {
-                                       case 1: # GIF
-                                               $src_image = imagecreatefromgif( $this->imagePath );
-                                               break;
-                                       case 2: # JPG
-                                               $src_image = imagecreatefromjpeg( $this->imagePath );
-                                               $truecolor = true;
-                                               break;
-                                       case 3: # PNG
-                                               $src_image = imagecreatefrompng( $this->imagePath );
-                                               $truecolor = ( $this->bits > 8 );
-                                               break;
-                                       case 15: # WBMP for WML
-                                               $src_image = imagecreatefromwbmp( $this->imagePath );
-                                               break;
-                                       case 16: # XBM
-                                               $src_image = imagecreatefromxbm( $this->imagePath );
-                                               break;
-                                       default:
-                                               return 'Image type not supported';
-                                               break;
-                               }
-                               if ( $truecolor ) {
-                                       $dst_image = imagecreatetruecolor( $width, $height );
-                               } else {
-                                       $dst_image = imagecreate( $width, $height );
-                               }
-                               imagecopyresampled( $dst_image, $src_image, 
-                                                       0,0,0,0,
-                                                       $width, $height, $this->width, $this->height );
-                               switch( $this->type ) {
-                                       case 1:  # GIF
-                                       case 3:  # PNG
-                                       case 15: # WBMP
-                                       case 16: # XBM
-                                               #$thumbUrl .= ".png";
-                                               #$thumbPath .= ".png";
-                                               imagepng( $dst_image, $thumbPath );
-                                               break;
-                                       case 2:  # JPEG
-                                               #$thumbUrl .= ".jpg";
-                                               #$thumbPath .= ".jpg";
-                                               imageinterlace( $dst_image );
-                                               imagejpeg( $dst_image, $thumbPath, 95 );
-                                               break;
-                                       default:
-                                               break;
+                       // This generates an error on failure, hence the @
+                       $handle = @opendir( $dir );
+                       
+                       if ( $handle ) {
+                               while ( false !== ( $file = readdir($handle) ) ) { 
+                                       if ( $file{0} != '.' ) {
+                                               $files[] = $file;
+                                       }
                                }
-                               imagedestroy( $dst_image );
-                               imagedestroy( $src_image );
+                               closedir( $handle );
                        }
-                       #
-                       # Check for zero-sized thumbnails. Those can be generated when 
-                       # no disk space is available or some other error occurs
-                       #
-                       if( file_exists( $thumbPath ) ) {
-                               $thumbstat = stat( $thumbPath );
-                               if( $thumbstat['size'] == 0 ) {
-                                       unlink( $thumbPath );
-                               }
+               } else {
+                       $files = array();
+               }
+               
+               return $files;
+       }
+
+       /**
+        * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
+        */
+       function purgeCache( $archiveFiles = array(), $shared = false ) {
+               global $wgInternalServer, $wgUseSquid;
+
+               // Refresh metadata cache
+               clearstatcache();
+               $this->loadFromFile();
+               $this->saveToCache();
+
+               // Delete thumbnails
+               $files = $this->getThumbnails( $shared );
+               $dir = wfImageThumbDir( $this->name, $shared );
+               $urls = array();
+               foreach ( $files as $file ) {
+                       if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
+                               $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
+                               @unlink( "$dir/$file" );
                        }
+               }
 
-                       # Purge squid
-                       # This has to be done after the image is updated and present for all machines on NFS, 
-                       # or else the old version might be stored into the squid again
-                       if ( $wgUseSquid ) {
-                               $urlArr = Array(
-                                       $wgInternalServer.$thumbUrl
-                               );
-                               if ( $scriptUrl ) {
-                                       $urlArr[] = $scriptUrl;
-                               }
-                               wfPurgeSquidServers($urlArr);
+               // Purge the squid
+               if ( $wgUseSquid ) {
+                       $urls[] = $wgInternalServer . $this->getViewURL();
+                       foreach ( $archiveFiles as $file ) {
+                               $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
                        }
+                       wfPurgeSquidServers( $urls );
                }
-               return new ThumbnailImage( $thumbUrl, $width, $height );
-       } // END OF function createThumb
+       }
 
        /**
         * Return the image history of this image, line by line.
@@ -794,10 +949,25 @@ class Image
                
                $dir      = $fromSharedRepository ? $wgSharedUploadDirectory :
                                                    $wgUploadDirectory;
-               $name     = $this->name;                                                        
-               $fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;         
+               
+               // $wgSharedUploadDirectory may be false, if thumb.php is used
+               if ( $dir ) {
+                       $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;             
+               } else {
+                       $fullpath = false;
+               }
+
                return $fullpath;
        }
+
+       /**
+        * @return bool
+        * @static
+        */
+       function isHashed( $shared ) {
+               global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
+               return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
+       }
        
        /**
         * @return bool
@@ -813,7 +983,7 @@ class Image
         */
        function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
                global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
-               global $wgUseCopyrightUpload;
+               global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
 
                $fname = 'Image::recordUpload';
                $dbw =& wfGetDB( DB_MASTER );
@@ -823,9 +993,8 @@ class Image
                        wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
                }
 
-               // Fill metadata fields by querying the file
-               $this->loadFromFile();
-               $this->saveToCache();
+               // Delete thumbnails and refresh the metadata cache
+               $this->purgeCache();
 
                // Fail now if the image isn't there
                if ( !$this->fileExists || $this->fromSharedDirectory ) {
@@ -840,7 +1009,7 @@ class Image
                        $textdesc = $desc;
                }
 
-               $now = wfTimestampNow();
+               $now = $dbw->timestamp();
 
                # Test to see if the row exists using INSERT IGNORE
                # This avoids race conditions by locking the row until the commit, and also
@@ -853,13 +1022,15 @@ class Image
                                'img_height' => $this->height,
                                'img_bits' => $this->bits,
                                'img_type' => $this->type,
-                               'img_timestamp' => $dbw->timestamp($now),
+                               'img_timestamp' => $now,
                                'img_description' => $desc,
                                'img_user' => $wgUser->getID(),
                                'img_user_text' => $wgUser->getName(),
+                               'img_metadata' => $this->exif,
                        ), $fname, 'IGNORE' 
                );
                $descTitle = $this->getTitle();
+               $purgeURLs = array();
 
                if ( $dbw->affectedRows() ) {
                        # Successfully inserted, this is a new image
@@ -896,10 +1067,11 @@ class Image
                                        'img_height' => $this->height,
                                        'img_bits' => $this->bits,
                                        'img_type' => $this->type,
-                                       'img_timestamp' => $dbw->timestamp(),
+                                       'img_timestamp' => $now,
                                        'img_user' => $wgUser->getID(),
                                        'img_user_text' => $wgUser->getName(),
                                        'img_description' => $desc,
+                                       'img_metadata' => $this->exif,
                                ), array( /* WHERE */
                                        'img_name' => $this->name
                                ), $fname
@@ -907,14 +1079,111 @@ class Image
                        
                        # Invalidate the cache for the description page
                        $descTitle->invalidateCache();
+                       $purgeURLs[] = $descTitle->getInternalURL();
                }
 
+               # Invalidate cache for all pages using this image
+               $linksTo = $this->getLinksTo();
+               
+               if ( $wgUseSquid ) {
+                       $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
+                       array_push( $wgPostCommitUpdateList, $u );
+               }
+               Title::touchArray( $linksTo );
+               
                $log = new LogPage( 'upload' );
                $log->addEntry( 'upload', $descTitle, $desc );
 
                return true;
        }
+
+       /**
+        * Get an array of Title objects which are articles which use this image
+        * Also adds their IDs to the link cache
+        * 
+        * This is mostly copied from Title::getLinksTo()
+        */
+       function getLinksTo( $options = '' ) {
+               global $wgLinkCache;
+               $fname = 'Image::getLinksTo';
+               wfProfileIn( $fname );
+               
+               if ( $options ) {
+                       $db =& wfGetDB( DB_MASTER );
+               } else {
+                       $db =& wfGetDB( DB_SLAVE );
+               }
+
+               extract( $db->tableNames( 'page', 'imagelinks' ) );
+               $encName = $db->addQuotes( $this->name );
+               $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
+               $res = $db->query( $sql, $fname );
+               
+               $retVal = array();
+               if ( $db->numRows( $res ) ) {
+                       while ( $row = $db->fetchObject( $res ) ) {
+                               if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
+                                       $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
+                                       $retVal[] = $titleObj;
+                               }
+                       }
+               }
+               $db->freeResult( $res );
+               return $retVal;
+       }
        
+       function retrieveExifData () {
+               global $wgShowEXIF ;
+               if ( ! $wgShowEXIF ) return array ();
+               if ( $this->type !== '2' ) return array ();
+
+               $exif = exif_read_data( $this->imagePath );
+
+               $obj = new Exif;
+               // Some of the type checks in validate will spew warnings on invalid data
+               wfSuppressWarnings();
+               foreach($exif as $k => $v) {
+                       if ( !in_array($k, $obj->mValidExif) || !$obj->validate($k, $v) )
+                               unset($exif[$k]);
+               }
+               wfRestoreWarnings();
+               
+               return $exif;
+       }
+               
+       function getExifData () {
+               global $wgRequest;
+               
+               $ret = unserialize ( $this->exif );
+
+               if ( count( $ret) == 0 || $wgRequest->getVal( 'action' ) == 'purge' ) { # No EXIF data was stored for this image
+                       $this->updateExifData() ;
+                       $ret = unserialize ( $this->exif ) ;
+               }
+               
+               return $ret ;
+       }
+
+       function updateExifData () {
+               global $wgShowEXIF ;
+               if ( ! $wgShowEXIF ) return ;
+               if ( false === $this->getImagePath() ) return ; # Not a local image
+               
+               $fname = "Image:updateExifData" ;
+               
+               # Get EXIF data from image
+               $exif = $this->retrieveExifData () ;
+               $this->exif = serialize ( $exif ) ;
+               
+               # Update EXIF data in database
+               $dbw =& wfGetDB( DB_MASTER );
+               $dbw->update( 'image', 
+                       array( 'img_metadata' => $this->exif ),
+                       array( 'img_name' => $this->name ),
+                       $fname
+               );
+       }
+
 } //class
 
 
@@ -951,13 +1220,39 @@ function wfImageDir( $fname ) {
  *
  * This function is called from thumb.php before Setup.php is included
  * 
- * @param string $fname                file name of the thumbnail file, including file size prefix
+ * @param string $fname                file name of the original image file
  * @param string $subdir       (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
  * @param boolean $shared      (optional) use the shared upload directory
  * @access public
  */
-function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
-       return wfImageArchiveDir( $fname, $subdir, $shared );
+function wfImageThumbDir( $fname, $shared = false ) {
+       $base = wfImageArchiveDir( $fname, 'thumb', $shared );
+       if ( Image::isHashed( $shared ) ) {
+               $dir =  "$base/$fname";
+
+               if ( !is_dir( $base ) ) {
+                       $oldumask = umask(0);
+                       @mkdir( $base, 0777 ); 
+                       umask( $oldumask );
+               }
+
+               if ( ! is_dir( $dir ) ) { 
+                       $oldumask = umask(0);
+                       @mkdir( $dir, 0777 ); 
+                       umask( $oldumask );
+               }
+       } else {
+               $dir = $base;
+       }
+
+       return $dir;
+}
+
+/**
+ * Old thumbnail directory, kept for conversion
+ */
+function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
+       return wfImageArchiveDir( $thumbName, $subdir, $shared );
 }
 
 /**
@@ -980,15 +1275,19 @@ function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
        if (!$hashdir) { return $dir.'/'.$subdir; }
        $hash = md5( $fname );
        $oldumask = umask(0);
+       
        # Suppress warning messages here; if the file itself can't
        # be written we'll worry about it then.
+       wfSuppressWarnings();
+       
        $archive = $dir.'/'.$subdir;
-       if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
+       if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
        $archive .= '/' . $hash{0};
-       if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
+       if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
        $archive .= '/' . substr( $hash, 0, 2 );
-       if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
+       if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
 
+       wfRestoreWarnings();
        umask( $oldumask );
        return $archive;
 }
@@ -1006,9 +1305,7 @@ function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
        global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
        global $wgHashedUploadDirectory;
        
-       $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
-                                          $wgHashedUploadDirectory;
-       if($ishashed) {
+       if( Image::isHashed( $fromSharedDirectory ) ) {
                $hash = md5($dbkey);
                return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
        } else {
@@ -1100,21 +1397,27 @@ function wfGetSVGsize( $filename ) {
 }
 
 /**
- * Is an image on the bad image list?
+ * Determine if an image exists on the 'bad image list'
+ *
+ * @param string $name The image to check
+ * @return bool
  */
 function wfIsBadImage( $name ) {
-       global $wgLang;
-
-       $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
-       foreach ( $lines as $line ) {
-               if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE ) . ':.*(?=]]))\]\]/', $line, $m ) ) {
-                       $t = Title::newFromText( $m[1] );
-                       if ( $t->getDBkey() == $name ) {
-                               return true;
+       global $wgContLang;
+       static $titleList = false;
+       if ( $titleList === false ) {
+               $titleList = array();
+
+               $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
+               foreach ( $lines as $line ) {
+                       if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
+                               $t = Title::newFromText( $m[1] );
+                               $titleList[$t->getDBkey()] = 1;
                        }
                }
        }
-       return false;
+
+       return array_key_exists( $name, $titleList );
 }
        
 
@@ -1129,10 +1432,11 @@ class ThumbnailImage {
         * @param string $url URL path to the thumb
         * @access private
         */
-       function ThumbnailImage( $url, $width, $height ) {
+       function ThumbnailImage( $url, $width, $height, $path = false ) {
                $this->url = $url;
                $this->width = $width;
                $this->height = $height;
+               $this->path = $path;
        }
 
        /**