Cripple the wiki text stuff for now. It doesn't SEEM dangerous but I haven't tested...
[lhc/web/wiklou.git] / includes / Image.php
index 9d23e95..3573d36 100644 (file)
@@ -12,9 +12,6 @@
  * extension=extensions/php_exif.dll
  */
 
-if ($wgShowEXIF)
-       require_once('Exif.php');
-
 /**
  * Bump this number when serialized cache records may be incompatible.
  */
@@ -30,7 +27,7 @@ define( 'MW_IMAGE_VERSION', 1 );
 class Image
 {
        /**#@+
-        * @access private
+        * @private
         */
        var     $name,          # name of the image (constructor)
                $imagePath,     # Path of the image (loadFromXxx)
@@ -58,7 +55,7 @@ class Image
         * Create an Image object from an image name
         *
         * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
-        * @access public
+        * @public
         */
        function newFromName( $name ) {
                $title = Title::makeTitleSafe( NS_IMAGE, $name );
@@ -71,6 +68,7 @@ class Image
 
        /**
         * Obsolete factory function, use constructor
+        * @deprecated
         */
        function newFromTitle( $title ) {
                return new Image( $title );
@@ -78,27 +76,51 @@ class Image
 
        function Image( $title ) {
                if( !is_object( $title ) ) {
-                       wfDebugDieBacktrace( 'Image constructor given bogus title.' );
+                       throw new MWException( 'Image constructor given bogus title.' );
                }
                $this->title =& $title;
                $this->name = $title->getDBkey();
                $this->metadata = serialize ( array() ) ;
 
                $n = strrpos( $this->name, '.' );
-               $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
+               $this->extension = Image::normalizeExtension( $n ?
+                       substr( $this->name, $n + 1 ) : '' );
                $this->historyLine = 0;
 
                $this->dataLoaded = false;
        }
 
+       
+       /**
+        * Normalize a file extension to the common form, and ensure it's clean.
+        * Extensions with non-alphanumeric characters will be discarded.
+        *
+        * @param $ext string (without the .)
+        * @return string
+        */
+       static function normalizeExtension( $ext ) {
+               $lower = strtolower( $ext );
+               $squish = array(
+                       'htm' => 'html',
+                       'jpeg' => 'jpg',
+                       'mpeg' => 'mpg',
+                       'tiff' => 'tif' );
+               if( isset( $squish[$lower] ) ) {
+                       return $squish[$lower];
+               } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
+                       return $lower;
+               } else {
+                       return '';
+               }
+       }
+       
        /**
         * Get the memcached keys
         * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
         */
-       function getCacheKeys( $shared = false ) {
+       function getCacheKeys( ) {
                global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
 
-               $foundCached = false;
                $hashedName = md5($this->name);
                $keys = array( "$wgDBname:Image:$hashedName" );
                if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
@@ -291,8 +313,7 @@ class Image
                $this->dataLoaded = true;
 
 
-               if ($this->fileExists && $wgShowEXIF) $this->metadata = serialize ( $this->retrieveExifData() ) ;
-               else $this->metadata = serialize ( array() ) ;
+               $this->metadata = serialize( $this->retrieveExifData( $this->imagePath ) );
 
                if ( isset( $gis['bits'] ) )  $this->bits = $gis['bits'];
                else $this->bits = 0;
@@ -330,8 +351,9 @@ class Image
                        # capitalize the first letter of the filename before
                        # looking it up in the shared repository.
                        $name = $wgContLang->ucfirst($this->name);
+                       $dbc =& wfGetDB( DB_SLAVE, 'commons' );
 
-                       $row = $dbr->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
+                       $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
                                array(
                                        'img_size', 'img_width', 'img_height', 'img_bits',
                                        'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
@@ -419,7 +441,6 @@ class Image
                wfProfileIn( $fname );
 
                $this->loadFromFile();
-               $dbw =& wfGetDB( DB_MASTER );
 
                if ( $this->fromSharedDirectory ) {
                        if ( !$wgSharedUploadDBname ) {
@@ -429,18 +450,15 @@ class Image
 
                        // Write to the other DB using selectDB, not database selectors
                        // This avoids breaking replication in MySQL
+                       $dbw =& wfGetDB( DB_MASTER, 'commons' );
                        $dbw->selectDB( $wgSharedUploadDBname );
+               } else {
+                       $dbw =& wfGetDB( DB_MASTER );
                }
 
                $this->checkDBSchema($dbw);
 
-               if (strpos($this->mime,'/')!==false) {
-                       list($major,$minor)= explode('/',$this->mime,2);
-               }
-               else {
-                       $major= $this->mime;
-                       $minor= "unknown";
-               }
+               list( $major, $minor ) = self::splitMime( $this->mime );
 
                wfDebug("$fname: upgrading ".$this->name." to 1.5 schema\n");
 
@@ -460,10 +478,25 @@ class Image
                }
                wfProfileOut( $fname );
        }
+       
+       /**
+        * Split an internet media type into its two components; if not
+        * a two-part name, set the minor type to 'unknown'.
+        *
+        * @param $mime "text/html" etc
+        * @return array ("text", "html") etc
+        */
+       static function splitMime( $mime ) {
+               if( strpos( $mime, '/' ) !== false ) {
+                       return explode( '/', $mime, 2 );
+               } else {
+                       return array( $mime, 'unknown' );
+               }
+       }
 
        /**
         * Return the name of this image
-        * @access public
+        * @public
         */
        function getName() {
                return $this->name;
@@ -471,7 +504,7 @@ class Image
 
        /**
         * Return the associated title object
-        * @access public
+        * @public
         */
        function getTitle() {
                return $this->title;
@@ -479,7 +512,7 @@ class Image
 
        /**
         * Return the URL of the image file
-        * @access public
+        * @public
         */
        function getURL() {
                if ( !$this->url ) {
@@ -510,7 +543,7 @@ class Image
        /**
         * Return the image path of the image in the
         * local file system as an absolute path
-        * @access public
+        * @public
         */
        function getImagePath() {
                $this->load();
@@ -521,7 +554,7 @@ class Image
         * Return the width of the image
         *
         * Returns -1 if the file specified is not a known image type
-        * @access public
+        * @public
         */
        function getWidth() {
                $this->load();
@@ -532,7 +565,7 @@ class Image
         * Return the height of the image
         *
         * Returns -1 if the file specified is not a known image type
-        * @access public
+        * @public
         */
        function getHeight() {
                $this->load();
@@ -541,7 +574,7 @@ class Image
 
        /**
         * Return the size of the image file, in bytes
-        * @access public
+        * @public
         */
        function getSize() {
                $this->load();
@@ -707,7 +740,7 @@ class Image
 
        /**
         * Return the escapeLocalURL of this image
-        * @access public
+        * @public
         */
        function getEscapeLocalURL() {
                $this->getTitle();
@@ -716,7 +749,7 @@ class Image
 
        /**
         * Return the escapeFullURL of this image
-        * @access public
+        * @public
         */
        function getEscapeFullURL() {
                $this->getTitle();
@@ -729,7 +762,7 @@ class Image
         * @param string $name  Name of the image, without the leading "Image:"
         * @param boolean $fromSharedDirectory  Should this be in $wgSharedUploadPath?
         * @return string URL of $name image
-        * @access public
+        * @public
         * @static
         */
        function imageUrl( $name, $fromSharedDirectory = false ) {
@@ -748,7 +781,7 @@ class Image
        /**
         * Returns true if the image file exists on disk.
         * @return boolean Whether image file exist on disk.
-        * @access public
+        * @public
         */
        function exists() {
                $this->load();
@@ -757,7 +790,7 @@ class Image
 
        /**
         * @todo document
-        * @access private
+        * @private
         */
        function thumbUrl( $width, $subdir='thumb') {
                global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
@@ -807,7 +840,7 @@ class Image
         *
         * @param integer $width        Width of the thumbnail image
         * @param boolean $shared       Does the thumbnail come from the shared repository?
-        * @access private
+        * @private
         */
        function thumbName( $width ) {
                $thumb = $width."px-".$this->name;
@@ -840,7 +873,7 @@ class Image
         *
         * @param integer $width        maximum width of the generated thumbnail
         * @param integer $height       maximum height of the image (optional)
-        * @access public
+        * @public
         */
        function createThumb( $width, $height=-1 ) {
                $thumb = $this->getThumbnail( $width, $height );
@@ -855,8 +888,8 @@ class Image
         *
         * @param integer $width        maximum width of the generated thumbnail
         * @param integer $height       maximum height of the image (optional)
-        * @return ThumbnailImage
-        * @access public
+        * @return ThumbnailImage or null on failure
+        * @public
         */
        function getThumbnail( $width, $height=-1 ) {
                if ( $height <= 0 ) {
@@ -871,9 +904,6 @@ class Image
                }
                else $thumb= NULL; #not a bitmap or renderable image, don't try.
 
-               if( is_null( $thumb ) ) {
-                       $thumb = $this->iconThumb();
-               }
                return $thumb;
        }
 
@@ -903,11 +933,11 @@ class Image
         * Returns an object which can return the pathname, URL, and physical
         * pixel size of the thumbnail -- or null on failure.
         *
-        * @return ThumbnailImage
-        * @access private
+        * @return ThumbnailImage or null on failure
+        * @private
         */
        function renderThumb( $width, $useScript = true ) {
-               global $wgUseSquid, $wgInternalServer;
+               global $wgUseSquid;
                global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
 
                $fname = 'Image::renderThumb';
@@ -995,7 +1025,7 @@ class Image
                                                        unlink( $thumbPath );
                                                } else {
                                                        // This should have been dealt with already
-                                                       wfDebugDieBacktrace( "Directory where image should be: $thumbPath" );
+                                                       throw new MWException( "Directory where image should be: $thumbPath" );
                                                }
                                        }
                                        // Rename the old image into the new location
@@ -1009,17 +1039,17 @@ class Image
                                $this->lastError = $this->reallyRenderThumb( $thumbPath, $width, $height );
                                if ( $this->lastError === true ) {
                                        $done = true;
+                               } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
+                                       // Log the error but output anyway.
+                                       // With luck it's a transitory error...
+                                       $done = true;
                                }
 
                                # 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 );
-                                       }
+                                       $urlArr = array( $url );
                                        wfPurgeSquidServers($urlArr);
                                }
                        }
@@ -1042,7 +1072,7 @@ class Image
         * @param int $width Desired width in pixels
         * @param int $height Desired height in pixels
         * @return bool True on error, false or error string on failure.
-        * @access private
+        * @private
         */
        function reallyRenderThumb( $thumbPath, $width, $height ) {
                global $wgSVGConverters, $wgSVGConverter;
@@ -1052,6 +1082,9 @@ class Image
                $this->load();
 
                $err = false;
+               $cmd = "";
+               $retval = 0;
+               
                if( $this->mime === "image/svg" ) {
                        #Right now we have only SVG
 
@@ -1068,7 +1101,7 @@ class Image
                                        $wgSVGConverters[$wgSVGConverter] );
                                wfProfileIn( 'rsvg' );
                                wfDebug( "reallyRenderThumb SVG: $cmd\n" );
-                               $err = wfShellExec( $cmd );
+                               $err = wfShellExec( $cmd, $retval );
                                wfProfileOut( 'rsvg' );
                        }
                } elseif ( $wgUseImageMagick ) {
@@ -1092,6 +1125,8 @@ class Image
                        $cmd  =  wfEscapeShellArg($wgImageMagickConvertCommand) .
                                " {$quality} -background white -size {$width} ".
                                wfEscapeShellArg($this->imagePath) .
+                               // Coalesce is needed to scale animated GIFs properly (bug 1017).
+                               ' -coalesce ' .
                                // For the -resize option a "!" is needed to force exact size,
                                // or ImageMagick may decide your ratio is wrong and slice off
                                // a pixel.
@@ -1100,7 +1135,7 @@ class Image
                                wfEscapeShellArg($thumbPath) . " 2>&1";
                        wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
                        wfProfileIn( 'convert' );
-                       $err = wfShellExec( $cmd );
+                       $err = wfShellExec( $cmd, $retval );
                        wfProfileOut( 'convert' );
                } elseif( $wgCustomConvertCommand ) {
                        # Use a custom convert command
@@ -1112,7 +1147,7 @@ class Image
                        $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
                        wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
                        wfProfileIn( 'convert' );
-                       $err = wfShellExec( $cmd );
+                       $err = wfShellExec( $cmd, $retval );
                        wfProfileOut( 'convert' );
                } else {
                        # Use PHP's builtin GD library functions.
@@ -1167,14 +1202,17 @@ class Image
                #
                if( file_exists( $thumbPath ) ) {
                        $thumbstat = stat( $thumbPath );
-                       if( $thumbstat['size'] == 0 ) {
+                       if( $thumbstat['size'] == 0 || $retval != 0 ) {
+                               wfDebugLog( 'thumbnail',
+                                       sprintf( 'Removing bad %d-byte thumbnail "%s"',
+                                               $thumbstat['size'], $thumbPath ) );
                                unlink( $thumbPath );
-                       } else {
-                               // All good
-                               $err = true;
                        }
                }
-               if ( $err !== true ) {
+               if ( $retval != 0 ) {
+                       wfDebugLog( 'thumbnail',
+                               sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
+                                       wfHostname(), $retval, trim($err), $cmd ) );
                        return wfMsg( 'thumbnail_error', $err );
                } else {
                        return true;
@@ -1230,7 +1268,7 @@ class Image
         * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
         */
        function purgeCache( $archiveFiles = array(), $shared = false ) {
-               global $wgInternalServer, $wgUseSquid;
+               global $wgUseSquid;
 
                // Refresh metadata cache
                $this->purgeMetadataCache();
@@ -1241,20 +1279,46 @@ class Image
                $urls = array();
                foreach ( $files as $file ) {
                        if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
-                               $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
+                               $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory );
                                @unlink( "$dir/$file" );
                        }
                }
 
                // Purge the squid
                if ( $wgUseSquid ) {
-                       $urls[] = $wgInternalServer . $this->getViewURL();
+                       $urls[] = $this->getViewURL();
                        foreach ( $archiveFiles as $file ) {
-                               $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
+                               $urls[] = wfImageArchiveUrl( $file );
                        }
                        wfPurgeSquidServers( $urls );
                }
        }
+       
+       /**
+        * Purge the image description page, but don't go after
+        * pages using the image. Use when modifying file history
+        * but not the current data.
+        */
+       function purgeDescription() {
+               $page = Title::makeTitle( NS_IMAGE, $this->name );
+               $page->invalidateCache();
+       }
+       
+       /**
+        * Purge metadata and all affected pages when the image is created,
+        * deleted, or majorly updated. A set of additional URLs may be
+        * passed to purge, such as specific image files which have changed.
+        * @param $urlArray array
+        */
+       function purgeEverything( $urlArr=array() ) {
+               // Delete thumbnails and refresh image metadata cache
+               $this->purgeCache();
+               $this->purgeDescription();
+               
+               // Purge cache of all pages using this image
+               $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
+               $update->doUpdate();
+       }
 
        function checkDBSchema(&$db) {
                global $wgCheckDBSchema;
@@ -1263,16 +1327,24 @@ class Image
                }
                # img_name must be unique
                if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
-                       wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
+                       throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
                }
 
-               #new fields must exist
+               # new fields must exist
+               # 
+               # Not really, there's hundreds of checks like this that we could do and they're all pointless, because 
+               # if the fields are missing, the database will loudly report a query error, the first time you try to do 
+               # something. The only reason I put the above schema check in was because the absence of that particular
+               # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
+               # uploads. -- TS
+               /*
                if ( !$db->fieldExists( 'image', 'img_media_type' )
                  || !$db->fieldExists( 'image', 'img_metadata' )
                  || !$db->fieldExists( 'image', 'img_width' ) ) {
 
-                       wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
-               }
+                       throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
+                }
+                */
        }
 
        /**
@@ -1283,7 +1355,7 @@ class Image
         *  1      query for old versions, return first one
         *  2, ... return next old version from above query
         *
-        * @access public
+        * @public
         */
        function nextHistoryLine() {
                $fname = 'Image::nextHistoryLine()';
@@ -1332,7 +1404,7 @@ class Image
 
        /**
         * Reset the history pointer to the first element of the history
-        * @access public
+        * @public
         */
        function resetHistory() {
                $this->historyLine = 0;
@@ -1346,7 +1418,7 @@ class Image
        * i.e. whether the images are all found in the same directory,
        * or in hashed paths like /images/3/3c.
        *
-       * @access public
+       * @public
        * @param boolean $fromSharedDirectory Return the path to the file
        *   in a shared repository (see $wgUseSharedRepository and related
        *   options in DefaultSettings.php) instead of a local one.
@@ -1381,7 +1453,7 @@ class Image
         * Record an image upload in the upload log and the image table
         */
        function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
-               global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
+               global $wgUser, $wgUseCopyrightUpload;
 
                $fname = 'Image::recordUpload';
                $dbw =& wfGetDB( DB_MASTER );
@@ -1448,8 +1520,6 @@ class Image
                        $fname,
                        'IGNORE'
                );
-               $descTitle = $this->getTitle();
-               $purgeURLs = array();
 
                if( $dbw->affectedRows() == 0 ) {
                        # Collision, this is an update of an image
@@ -1495,6 +1565,7 @@ class Image
                        $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
                }
 
+               $descTitle = $this->getTitle();
                $article = new Article( $descTitle );
                $minor = false;
                $watch = $watch || $wgUser->isWatched( $descTitle );
@@ -1508,24 +1579,24 @@ class Image
 
                        # Invalidate the cache for the description page
                        $descTitle->invalidateCache();
-                       $purgeURLs[] = $descTitle->getInternalURL();
+                       $descTitle->purgeSquid();
                } else {
                        // New image; create the description page.
                        $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
                }
 
-               # 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 );
-
+               # Add the log entry
                $log = new LogPage( 'upload' );
                $log->addEntry( 'upload', $descTitle, $desc );
 
+               # Commit the transaction now, in case something goes wrong later
+               # The most important thing is that images don't get lost, especially archives
+               $dbw->immediateCommit();
+
+               # Invalidate cache for all pages using this image
+               $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
+               $update->doUpdate();
+
                return true;
        }
 
@@ -1534,6 +1605,8 @@ class Image
         * Also adds their IDs to the link cache
         *
         * This is mostly copied from Title::getLinksTo()
+        *
+        * @deprecated Use HTMLCacheUpdate, this function uses too much memory
         */
        function getLinksTo( $options = '' ) {
                $fname = 'Image::getLinksTo';
@@ -1564,20 +1637,28 @@ class Image
                wfProfileOut( $fname );
                return $retVal;
        }
+       
        /**
-        * Retrive Exif data from the database
-        *
-        * Retrive Exif data from the database and prune unrecognized tags
+        * Retrive Exif data from the file and prune unrecognized tags
         * and/or tags with invalid contents
         *
+        * @param $filename
         * @return array
         */
-       function retrieveExifData() {
+       private function retrieveExifData( $filename ) {
+               global $wgShowEXIF;
+               
+               /*
                if ( $this->getMimeType() !== "image/jpeg" )
                        return array();
+               */
 
-               $exif = new Exif( $this->imagePath );
-               return $exif->getFilteredData();
+               if( $wgShowEXIF && file_exists( $filename ) ) {
+                       $exif = new Exif( $filename );
+                       return $exif->getFilteredData();
+               }
+               
+               return array();
        }
 
        function getExifData() {
@@ -1609,7 +1690,7 @@ class Image
                        return;
 
                # Get EXIF data from image
-               $exif = $this->retrieveExifData();
+               $exif = $this->retrieveExifData( $this->imagePath );
                if ( count( $exif ) ) {
                        $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
                        $this->metadata = serialize( $exif );
@@ -1638,7 +1719,452 @@ class Image
        function isLocal() {
                return !$this->fromSharedDirectory;
        }
+       
+       /**
+        * Was this image ever deleted from the wiki?
+        *
+        * @return bool
+        */
+       function wasDeleted() {
+               $title = Title::makeTitle( NS_IMAGE, $this->name );
+               return ( $title->isDeleted() > 0 );
+       }
+       
+       /**
+        * Delete all versions of the image.
+        *
+        * Moves the files into an archive directory (or deletes them)
+        * and removes the database rows.
+        *
+        * Cache purging is done; logging is caller's responsibility.
+        *
+        * @param $reason
+        * @return true on success, false on some kind of failure
+        */
+       function delete( $reason ) {
+               $fname = __CLASS__ . '::' . __FUNCTION__;
+               $transaction = new FSTransaction();
+               $urlArr = array( $this->getURL() );
+               
+               if( !FileStore::lock() ) {
+                       wfDebug( "$fname: failed to acquire file store lock, aborting\n" );
+                       return false;
+               }
+               
+               try {
+                       $dbw = wfGetDB( DB_MASTER );
+                       $dbw->begin();
+                       
+                       // Delete old versions
+                       $result = $dbw->select( 'oldimage',
+                               array( 'oi_archive_name' ),
+                               array( 'oi_name' => $this->name ) );
+                       
+                       while( $row = $dbw->fetchObject( $result ) ) {
+                               $oldName = $row->oi_archive_name;
+                               
+                               $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
+                               
+                               // We'll need to purge this URL from caches...
+                               $urlArr[] = wfImageArchiveUrl( $oldName );
+                       }
+                       $dbw->freeResult( $result );
+                       
+                       // And the current version...
+                       $transaction->add( $this->prepareDeleteCurrent( $reason ) );
+                       
+                       $dbw->immediateCommit();
+               } catch( MWException $e ) {
+                       wfDebug( "$fname: db error, rolling back file transactions\n" );
+                       $transaction->rollback();
+                       FileStore::unlock();
+                       throw $e;
+               }
+               
+               wfDebug( "$fname: deleted db items, applying file transactions\n" );
+               $transaction->commit();
+               FileStore::unlock();
+
+               
+               // Update site_stats
+               $site_stats = $dbw->tableName( 'site_stats' );
+               $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", $fname );
+               
+               $this->purgeEverything( $urlArr );
+               
+               return true;
+       }
+       
+       
+       /**
+        * Delete an old version of the image.
+        *
+        * Moves the file into an archive directory (or deletes it)
+        * and removes the database row.
+        *
+        * Cache purging is done; logging is caller's responsibility.
+        *
+        * @param $reason
+        * @throws MWException or FSException on database or filestore failure
+        * @return true on success, false on some kind of failure
+        */
+       function deleteOld( $archiveName, $reason ) {
+               $fname = __CLASS__ . '::' . __FUNCTION__;
+               $transaction = new FSTransaction();
+               $urlArr = array();
+               
+               if( !FileStore::lock() ) {
+                       wfDebug( "$fname: failed to acquire file store lock, aborting\n" );
+                       return false;
+               }
+               
+               $transaction = new FSTransaction();
+               try {
+                       $dbw = wfGetDB( DB_MASTER );
+                       $dbw->begin();
+                       $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
+                       $dbw->immediateCommit();
+               } catch( MWException $e ) {
+                       wfDebug( "$fname: db error, rolling back file transaction\n" );
+                       $transaction->rollback();
+                       FileStore::unlock();
+                       throw $e;
+               }
+               
+               wfDebug( "$fname: deleted db items, applying file transaction\n" );
+               $transaction->commit();
+               FileStore::unlock();
+               
+               $this->purgeDescription();
+
+               // Squid purging
+               global $wgUseSquid;
+               if ( $wgUseSquid ) {
+                       $urlArr = array(
+                               wfImageArchiveUrl( $archiveName ),
+                               $page->getInternalURL()
+                       );
+                       wfPurgeSquidServers( $urlArr );
+               }
+               return true;
+       }
+       
+       /**
+        * Delete the current version of a file.
+        * May throw a database error.
+        * @return true on success, false on failure
+        */
+       private function prepareDeleteCurrent( $reason ) {
+               $fname = __CLASS__ . '::' . __FUNCTION__;
+               return $this->prepareDeleteVersion(
+                       $this->getFullPath(),
+                       $reason,
+                       'image',
+                       array(
+                               'fa_name'         => 'img_name',
+                               'fa_archive_name' => 'NULL',
+                               'fa_size'         => 'img_size',
+                               'fa_width'        => 'img_width',
+                               'fa_height'       => 'img_height',
+                               'fa_metadata'     => 'img_metadata',
+                               'fa_bits'         => 'img_bits',
+                               'fa_media_type'   => 'img_media_type',
+                               'fa_major_mime'   => 'img_major_mime',
+                               'fa_minor_mime'   => 'img_minor_mime',
+                               'fa_description'  => 'img_description',
+                               'fa_user'         => 'img_user',
+                               'fa_user_text'    => 'img_user_text',
+                               'fa_timestamp'    => 'img_timestamp' ),
+                       array( 'img_name' => $this->name ),
+                       $fname );
+       }
 
+       /**
+        * Delete a given older version of a file.
+        * May throw a database error.
+        * @return true on success, false on failure
+        */
+       private function prepareDeleteOld( $archiveName, $reason ) {
+               $fname = __CLASS__ . '::' . __FUNCTION__;
+               $oldpath = wfImageArchiveDir( $this->name ) .
+                       DIRECTORY_SEPARATOR . $archiveName;
+               return $this->prepareDeleteVersion(
+                       $oldpath,
+                       $reason,
+                       'oldimage',
+                       array(
+                               'fa_name'         => 'oi_name',
+                               'fa_archive_name' => 'oi_archive_name',
+                               'fa_size'         => 'oi_size',
+                               'fa_width'        => 'oi_width',
+                               'fa_height'       => 'oi_height',
+                               'fa_metadata'     => 'NULL',
+                               'fa_bits'         => 'oi_bits',
+                               'fa_media_type'   => 'NULL',
+                               'fa_major_mime'   => 'NULL',
+                               'fa_minor_mime'   => 'NULL',
+                               'fa_description'  => 'oi_description',
+                               'fa_user'         => 'oi_user',
+                               'fa_user_text'    => 'oi_user_text',
+                               'fa_timestamp'    => 'oi_timestamp' ),
+                       array(
+                               'oi_name' => $this->name,
+                               'oi_archive_name' => $archiveName ),
+                       $fname );
+       }
+
+       /**
+        * Do the dirty work of backing up an image row and its file
+        * (if $wgSaveDeletedFiles is on) and removing the originals.
+        *
+        * Must be run while the file store is locked and a database
+        * transaction is open to avoid race conditions.
+        *
+        * @return FSTransaction
+        */
+       private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
+               global $wgUser, $wgSaveDeletedFiles;
+               
+               // Dupe the file into the file store
+               if( file_exists( $path ) ) {
+                       if( $wgSaveDeletedFiles ) {
+                               $group = 'deleted';
+                               
+                               $store = FileStore::get( $group );
+                               $key = FileStore::calculateKey( $path, $this->extension );
+                               $transaction = $store->insert( $key, $path,
+                                       FileStore::DELETE_ORIGINAL );
+                       } else {
+                               $group = null;
+                               $key = null;
+                               $transaction = FileStore::deleteFile( $path );
+                       }
+               } else {
+                       wfDebug( "$fname deleting already-missing '$path'; moving on to database\n" );
+                       $group = null;
+                       $key = null;
+                       $transaction = new FSTransaction(); // empty
+               }
+               
+               if( $transaction === false ) {
+                       // Fail to restore?
+                       wfDebug( "$fname: import to file store failed, aborting\n" );
+                       throw new MWException( "Could not archive and delete file $path" );
+                       return false;
+               }
+               
+               $dbw = wfGetDB( DB_MASTER );
+               $storageMap = array(
+                       'fa_storage_group' => $dbw->addQuotes( $group ),
+                       'fa_storage_key'   => $dbw->addQuotes( $key ),
+                       
+                       'fa_deleted_user'      => $dbw->addQuotes( $wgUser->getId() ),
+                       'fa_deleted_timestamp' => $dbw->timestamp(),
+                       'fa_deleted_reason'    => $dbw->addQuotes( $reason ) );
+               $allFields = array_merge( $storageMap, $fieldMap );
+               
+               try {
+                       if( $wgSaveDeletedFiles ) {
+                               $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
+                       }
+                       $dbw->delete( $table, $where, $fname );
+               } catch( DBQueryError $e ) {
+                       // Something went horribly wrong!
+                       // Leave the file as it was...
+                       wfDebug( "$fname: database error, rolling back file transaction\n" );
+                       $transaction->rollback();
+                       throw $e;
+               }
+               
+               return $transaction;
+       }
+       
+       /**
+        * Restore all or specified deleted revisions to the given file.
+        * Permissions and logging are left to the caller.
+        *
+        * May throw database exceptions on error.
+        *
+        * @param $versions set of record ids of deleted items to restore,
+        *                    or empty to restore all revisions.
+        * @return the number of file revisions restored if successful,
+        *         or false on failure
+        */
+       function restore( $versions=array() ) {
+               $fname = __CLASS__ . '::' . __FUNCTION__;
+               if( !FileStore::lock() ) {
+                       wfDebug( "$fname could not acquire filestore lock\n" );
+                       return false;
+               }
+               
+               $transaction = new FSTransaction();
+               try {
+                       $dbw = wfGetDB( DB_MASTER );
+                       $dbw->begin();
+                       
+                       // Re-confirm whether this image presently exists;
+                       // if no we'll need to create an image record for the
+                       // first item we restore.
+                       $exists = $dbw->selectField( 'image', '1',
+                               array( 'img_name' => $this->name ),
+                               $fname );
+                       
+                       // Fetch all or selected archived revisions for the file,
+                       // sorted from the most recent to the oldest.
+                       $conditions = array( 'fa_name' => $this->name );
+                       if( $versions ) {
+                               $conditions['fa_id'] = $versions;
+                       }
+                       
+                       $result = $dbw->select( 'filearchive', '*',
+                               $conditions,
+                               $fname,
+                               array( 'ORDER BY' => 'fa_timestamp DESC' ) );
+                       
+                       if( $dbw->numRows( $result ) < count( $versions ) ) {
+                               // There's some kind of conflict or confusion;
+                               // we can't restore everything we were asked to.
+                               wfDebug( "$fname: couldn't find requested items\n" );
+                               $dbw->rollback();
+                               FileStore::unlock();
+                               return false;
+                       }
+
+                       if( $dbw->numRows( $result ) == 0 ) {
+                               // Nothing to do.
+                               wfDebug( "$fname: nothing to do\n" );
+                               $dbw->rollback();
+                               FileStore::unlock();
+                               return true;
+                       }
+                       
+                       $revisions = 0;
+                       while( $row = $dbw->fetchObject( $result ) ) {
+                               $revisions++;
+                               $store = FileStore::get( $row->fa_storage_group );
+                               if( !$store ) {
+                                       wfDebug( "$fname: skipping row with no file.\n" );
+                                       continue;
+                               }
+                               
+                               if( $revisions == 1 && !$exists ) {
+                                       $destPath = wfImageDir( $row->fa_name ) .
+                                               DIRECTORY_SEPARATOR .
+                                               $row->fa_name;
+                                       
+                                       // We may have to fill in data if this was originally
+                                       // an archived file revision.
+                                       if( is_null( $row->fa_metadata ) ) {
+                                               $tempFile = $store->filePath( $row->fa_storage_key );
+                                               $metadata = serialize( $this->retrieveExifData( $tempFile ) );
+                                               
+                                               $magic = wfGetMimeMagic();
+                                               $mime = $magic->guessMimeType( $tempFile, true );
+                                               $media_type = $magic->getMediaType( $tempFile, $mime );
+                                               list( $major_mime, $minor_mime ) = self::splitMime( $mime );
+                                       } else {
+                                               $metadata   = $row->fa_metadata;
+                                               $major_mime = $row->fa_major_mime;
+                                               $minor_mime = $row->fa_minor_mime;
+                                               $media_type = $row->fa_media_type;
+                                       }
+                                       
+                                       $table = 'image';
+                                       $fields = array(
+                                               'img_name'        => $row->fa_name,
+                                               'img_size'        => $row->fa_size,
+                                               'img_width'       => $row->fa_width,
+                                               'img_height'      => $row->fa_height,
+                                               'img_metadata'    => $metadata,
+                                               'img_bits'        => $row->fa_bits,
+                                               'img_media_type'  => $media_type,
+                                               'img_major_mime'  => $major_mime,
+                                               'img_minor_mime'  => $minor_mime,
+                                               'img_description' => $row->fa_description,
+                                               'img_user'        => $row->fa_user,
+                                               'img_user_text'   => $row->fa_user_text,
+                                               'img_timestamp'   => $row->fa_timestamp );
+                               } else {
+                                       $archiveName = $row->fa_archive_name;
+                                       if( $archiveName == '' ) {
+                                               // This was originally a current version; we
+                                               // have to devise a new archive name for it.
+                                               // Format is <timestamp of archiving>!<name>
+                                               $archiveName =
+                                                       wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
+                                                       '!' . $row->fa_name;
+                                       }
+                                       $destPath = wfImageArchiveDir( $row->fa_name ) .
+                                               DIRECTORY_SEPARATOR . $archiveName;
+                                       
+                                       $table = 'oldimage';
+                                       $fields = array(
+                                               'oi_name'         => $row->fa_name,
+                                               'oi_archive_name' => $archiveName,
+                                               'oi_size'         => $row->fa_size,
+                                               'oi_width'        => $row->fa_width,
+                                               'oi_height'       => $row->fa_height,
+                                               'oi_bits'         => $row->fa_bits,
+                                               'oi_description'  => $row->fa_description,
+                                               'oi_user'         => $row->fa_user,
+                                               'oi_user_text'    => $row->fa_user_text,
+                                               'oi_timestamp'    => $row->fa_timestamp );
+                               }
+                               
+                               $dbw->insert( $table, $fields, $fname );
+                               /// @fixme this delete is not totally safe, potentially
+                               $dbw->delete( 'filearchive',
+                                       array( 'fa_id' => $row->fa_id ),
+                                       $fname );
+                               
+                               // Check if any other stored revisions use this file;
+                               // if so, we shouldn't remove the file from the deletion
+                               // archives so they will still work.
+                               $useCount = $dbw->selectField( 'filearchive',
+                                       'COUNT(*)',
+                                       array(
+                                               'fa_storage_group' => $row->fa_storage_group,
+                                               'fa_storage_key'   => $row->fa_storage_key ),
+                                       $fname );
+                               if( $useCount == 0 ) {
+                                       wfDebug( "$fname: nothing else using {$row->fa_storage_key}, will deleting after\n" );
+                                       $flags = FileStore::DELETE_ORIGINAL;
+                               } else {
+                                       $flags = 0;
+                               }
+                               
+                               $transaction->add( $store->export( $row->fa_storage_key,
+                                       $destPath, $flags ) );
+                       }
+                       
+                       $dbw->immediateCommit();
+               } catch( MWException $e ) {
+                       wfDebug( "$fname caught error, aborting\n" );
+                       $transaction->rollback();
+                       throw $e;
+               }
+               
+               $transaction->commit();
+               FileStore::unlock();
+               
+               if( $revisions > 0 ) {
+                       if( !$exists ) {
+                               wfDebug( "$fname restored $revisions items, creating a new current\n" );
+                               
+                               // Update site_stats
+                               $site_stats = $dbw->tableName( 'site_stats' );
+                               $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
+                               
+                               $this->purgeEverything();
+                       } else {
+                               wfDebug( "$fname restored $revisions as archived versions\n" );
+                               $this->purgeDescription();
+                       }
+               }
+               
+               return $revisions;
+       }
+       
 } //class
 
 
@@ -1649,8 +2175,8 @@ class Image
  *
  * This function is called from thumb.php before Setup.php is included
  *
- * @param string $fname                file name of the image file
- * @access public
+ * @param $fname String: file name of the image file.
+ * @public
  */
 function wfImageDir( $fname ) {
        global $wgUploadDirectory, $wgHashedUploadDirectory;
@@ -1675,10 +2201,9 @@ function wfImageDir( $fname ) {
  *
  * This function is called from thumb.php before Setup.php is included
  *
- * @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
+ * @param $fname String: file name of the original image file
+ * @param $shared Boolean: (optional) use the shared upload directory (default: 'false').
+ * @public
  */
 function wfImageThumbDir( $fname, $shared = false ) {
        $base = wfImageArchiveDir( $fname, 'thumb', $shared );
@@ -1721,10 +2246,10 @@ function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
  *
  * 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 $subdir       (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
- * @param boolean $shared      (optional) use the shared upload directory (only relevant for other functions which call this one)
- * @access public
+ * @param $fname String: file name of the thumbnail file, including file size prefix.
+ * @param $subdir String: subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'.
+ * @param $shared Boolean use the shared upload directory (only relevant for other functions which call this one). Default is 'false'.
+ * @public
  */
 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
        global $wgUploadDirectory, $wgHashedUploadDirectory;
@@ -1772,9 +2297,9 @@ function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
 /**
  * Returns the image URL of an image's old version
  *
- * @param string $fname                file name of the image file
- * @param string $subdir       (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
- * @access public
+ * @param $name String: file name of the image file
+ * @param $subdir String: (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
+ * @public
  */
 function wfImageArchiveUrl( $name, $subdir='archive' ) {
        global $wgUploadPath, $wgHashedUploadDirectory;
@@ -1793,8 +2318,8 @@ function wfImageArchiveUrl( $name, $subdir='archive' ) {
  * Return a rounded pixel equivalent for a labeled CSS/SVG length.
  * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
  *
- * @param string $length
- * @return int Length in pixels
+ * @param $length String: CSS/SVG length.
+ * @return Integer: length in pixels
  */
 function wfScaleSVGUnit( $length ) {
        static $unitLength = array(
@@ -1823,7 +2348,7 @@ function wfScaleSVGUnit( $length ) {
  * @todo check XML more carefully
  * @todo sensible defaults
  *
- * @param string $filename
+ * @param $filename String: full name of the file (passed to php fopen()).
  * @return array
  */
 function wfGetSVGsize( $filename ) {
@@ -1853,26 +2378,26 @@ function wfGetSVGsize( $filename ) {
 }
 
 /**
- * Determine if an image exists on the 'bad image list'
+ * Determine if an image exists on the 'bad image list'.
  *
- * @param string $name The image to check
+ * @param $name String: the image name to check
  * @return bool
  */
 function wfIsBadImage( $name ) {
-       global $wgContLang;
        static $titleList = false;
-       if ( $titleList === false ) {
+       
+       if( !$titleList ) {
+               # Build the list now
                $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;
+               $lines = explode( "\n", wfMsgForContent( 'bad_image_list' ) );
+               foreach( $lines as $line ) {
+                       if( preg_match( '/^\*\s*\[\[:?(.*?)\]\]/i', $line, $matches ) ) {
+                               $title = Title::newFromText( $matches[1] );
+                               if( is_object( $title ) && $title->getNamespace() == NS_IMAGE )
+                                       $titleList[ $title->getDBkey() ] = true;
                        }
                }
        }
-
        return array_key_exists( $name, $titleList );
 }
 
@@ -1886,7 +2411,7 @@ class ThumbnailImage {
        /**
         * @param string $path Filesystem path to the thumb
         * @param string $url URL path to the thumb
-        * @access private
+        * @private
         */
        function ThumbnailImage( $url, $width, $height, $path = false ) {
                $this->url = $url;
@@ -1915,7 +2440,7 @@ class ThumbnailImage {
         *
         * @param array $attribs
         * @return string
-        * @access public
+        * @public
         */
        function toHtml( $attribs = array() ) {
                $attribs['src'] = $this->url;
@@ -1936,10 +2461,10 @@ class ThumbnailImage {
 /**
  * Calculate the largest thumbnail width for a given original file size
  * such that the thumbnail's height is at most $maxHeight.
- * @param int $boxWidth
- * @param int $boxHeight
- * @param int $maxHeight
- * @return int
+ * @param $boxWidth Integer Width of the thumbnail box.
+ * @param $boxHeight Integer Height of the thumbnail box.
+ * @param $maxHeight Integer Maximum height expected for the thumbnail.
+ * @return Integer.
  */
 function wfFitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
        $idealWidth = $boxWidth * $maxHeight / $boxHeight;