Special:Userrights didn't recognize user as self if person didn't capitalize
[lhc/web/wiklou.git] / includes / filerepo / LocalFile.php
index a2e19c8..c321d91 100644 (file)
@@ -5,7 +5,7 @@
 /**
  * Bump this number when serialized cache records may be incompatible.
  */
-define( 'MW_FILE_VERSION', 4 );
+define( 'MW_FILE_VERSION', 8 );
 
 /**
  * Class to represent a local file in the wiki's own database
@@ -14,7 +14,7 @@ define( 'MW_FILE_VERSION', 4 );
  * to generate image thumbnails or for uploading.
  *
  * Note that only the repo object knows what its file class is called. You should
- * never name a file class explictly outside of the repo class. Instead use the 
+ * never name a file class explictly outside of the repo class. Instead use the
  * repo's factory functions to generate file objects, for example:
  *
  * RepoGroup::singleton()->getLocalRepo()->newFile($title);
@@ -22,39 +22,44 @@ define( 'MW_FILE_VERSION', 4 );
  * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
  * in most cases.
  *
- * @addtogroup FileRepo
+ * @ingroup FileRepo
  */
-class LocalFile extends File
-{
+class LocalFile extends File {
        /**#@+
         * @private
         */
-       var     $fileExists,    # does the file file exist on disk? (loadFromXxx)
-               $historyLine,   # Number of line to return by nextHistoryLine() (constructor)
-               $historyRes,    # result of the query for the file's history (nextHistoryLine)
-               $width,         # \
-               $height,        #  |
-               $bits,          #   --- returned by getimagesize (loadFromXxx)
-               $attr,          # /
-               $media_type,    # MEDIATYPE_xxx (bitmap, drawing, audio...)
-               $mime,          # MIME type, determined by MimeMagic::guessMimeType
-               $major_mime,    # Major mime type
-               $minor_mime,    # Minor mime type
-               $size,          # Size in bytes (loadFromXxx)
-               $metadata,      # Handler-specific metadata
-               $timestamp,     # Upload timestamp
-               $sha1,          # SHA-1 base 36 content hash
-               $dataLoaded,    # Whether or not all this has been loaded from the database (loadFromXxx)
-               $upgraded,      # Whether the row was upgraded on load
-               $locked;        # True if the image row is locked
+       var     $fileExists,       # does the file file exist on disk? (loadFromXxx)
+               $historyLine,      # Number of line to return by nextHistoryLine() (constructor)
+               $historyRes,       # result of the query for the file's history (nextHistoryLine)
+               $width,            # \
+               $height,           #  |
+               $bits,             #   --- returned by getimagesize (loadFromXxx)
+               $attr,             # /
+               $media_type,       # MEDIATYPE_xxx (bitmap, drawing, audio...)
+               $mime,             # MIME type, determined by MimeMagic::guessMimeType
+               $major_mime,       # Major mime type
+               $minor_mime,       # Minor mime type
+               $size,             # Size in bytes (loadFromXxx)
+               $metadata,         # Handler-specific metadata
+               $timestamp,        # Upload timestamp
+               $sha1,             # SHA-1 base 36 content hash
+               $user, $user_text, # User, who uploaded the file
+               $description,      # Description of current revision of the file
+               $dataLoaded,       # Whether or not all this has been loaded from the database (loadFromXxx)
+               $upgraded,         # Whether the row was upgraded on load
+               $locked,           # True if the image row is locked
+               $missing,          # True if file is not present in file system. Not to be cached in memcached
+               $deleted;       # Bitfield akin to rev_deleted
 
        /**#@-*/
 
        /**
         * Create a LocalFile from a title
         * Do not call this except from inside a repo class.
+        *
+        * Note: $unused param is only here to avoid an E_STRICT
         */
-       static function newFromTitle( $title, $repo ) {
+       static function newFromTitle( $title, $repo, $unused = null ) {
                return new self( $title, $repo );
        }
 
@@ -63,11 +68,53 @@ class LocalFile extends File
         * Do not call this except from inside a repo class.
         */
        static function newFromRow( $row, $repo ) {
-               $title = Title::makeTitle( NS_IMAGE, $row->img_name );
+               $title = Title::makeTitle( NS_FILE, $row->img_name );
                $file = new self( $title, $repo );
                $file->loadFromRow( $row );
                return $file;
        }
+       
+       /**
+        * Create a LocalFile from a SHA-1 key
+        * Do not call this except from inside a repo class.
+        */
+       static function newFromKey( $sha1, $repo, $timestamp = false ) {
+               # Polymorphic function name to distinguish foreign and local fetches
+               $fname = get_class( $this ) . '::' . __FUNCTION__;
+
+               $conds = array( 'img_sha1' => $sha1 );
+               if( $timestamp ) {
+                       $conds['img_timestamp'] = $timestamp;
+               }
+               $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ), $conds, $fname );
+               if( $row ) {
+                       return self::newFromRow( $row, $repo );
+               } else {
+                       return false;
+               }
+       }
+       
+       /**
+        * Fields in the image table
+        */
+       static function selectFields() {
+               return array(
+                       'img_name',
+                       'img_size',
+                       'img_width',
+                       'img_height',
+                       'img_metadata',
+                       'img_bits',
+                       'img_media_type',
+                       'img_major_mime',
+                       'img_minor_mime',
+                       'img_description',
+                       'img_user',
+                       'img_user_text',
+                       'img_timestamp',
+                       'img_sha1',
+               );
+       }
 
        /**
         * Constructor.
@@ -75,7 +122,7 @@ class LocalFile extends File
         */
        function __construct( $title, $repo ) {
                if( !is_object( $title ) ) {
-                       throw new MWException( __CLASS__.' constructor given bogus title.' );
+                       throw new MWException( __CLASS__ . ' constructor given bogus title.' );
                }
                parent::__construct( $title, $repo );
                $this->metadata = '';
@@ -85,11 +132,12 @@ class LocalFile extends File
        }
 
        /**
-        * Get the memcached key
+        * Get the memcached key for the main data for this file, or false if 
+        * there is no access to the shared cache.
         */
        function getCacheKey() {
-               $hashedName = md5($this->getName());
-               return wfMemcKey( 'file', $hashedName );
+               $hashedName = md5( $this->getName() );
+               return $this->repo->getSharedCacheKey( 'file', $hashedName );
        }
 
        /**
@@ -101,21 +149,19 @@ class LocalFile extends File
                $this->dataLoaded = false;
                $key = $this->getCacheKey();
                if ( !$key ) {
+                       wfProfileOut( __METHOD__ );
                        return false;
                }
                $cachedValues = $wgMemc->get( $key );
 
                // Check if the key existed and belongs to this version of MediaWiki
-               if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
+               if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
                        wfDebug( "Pulling file metadata from cache key $key\n" );
                        $this->fileExists = $cachedValues['fileExists'];
                        if ( $this->fileExists ) {
-                               unset( $cachedValues['version'] );
-                               unset( $cachedValues['fileExists'] );
-                               foreach ( $cachedValues as $name => $value ) {
-                                       $this->$name = $value;
-                               }
+                               $this->setProps( $cachedValues );
                        }
+                       $this->dataLoaded = true;
                }
                if ( $this->dataLoaded ) {
                        wfIncrStats( 'image_cache_hit' );
@@ -157,8 +203,8 @@ class LocalFile extends File
        }
 
        function getCacheFields( $prefix = 'img_' ) {
-               static $fields = array( 'size', 'width', 'height', 'bits', 'media_type', 
-                       'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1' );
+               static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
+                       'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
                static $results = array();
                if ( $prefix == '' ) {
                        return $fields;
@@ -184,7 +230,7 @@ class LocalFile extends File
                # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
                $this->dataLoaded = true;
 
-               $dbr = $this->repo->getSlaveDB();
+               $dbr = $this->repo->getMasterDB();
 
                $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
                        array( 'img_name' => $this->getName() ), $fname );
@@ -198,7 +244,7 @@ class LocalFile extends File
        }
 
        /**
-        * Decode a row from the database (either object or array) to an array 
+        * Decode a row from the database (either object or array) to an array
         * with timestamps and MIME types decoded, and the field prefix removed.
         */
        function decodeRow( $row, $prefix = 'img_' ) {
@@ -206,7 +252,7 @@ class LocalFile extends File
                $prefixLength = strlen( $prefix );
                // Sanity check prefix once
                if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
-                       throw new MWException( __METHOD__. ': incorrect $prefix parameter' );
+                       throw new MWException( __METHOD__ .  ': incorrect $prefix parameter' );
                }
                $decoded = array();
                foreach ( $array as $name => $value ) {
@@ -214,19 +260,19 @@ class LocalFile extends File
                }
                $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
                if ( empty( $decoded['major_mime'] ) ) {
-                       $decoded['mime'] = "unknown/unknown";
+                       $decoded['mime'] = 'unknown/unknown';
                } else {
-                       if (!$decoded['minor_mime']) {
-                               $decoded['minor_mime'] = "unknown";
+                       if ( !$decoded['minor_mime'] ) {
+                               $decoded['minor_mime'] = 'unknown';
                        }
-                       $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
+                       $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
                }
                # Trim zero padding from char/binary field
                $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
                return $decoded;
        }
 
-       /*
+       /**
         * Load file metadata from a DB result row
         */
        function loadFromRow( $row, $prefix = 'img_' ) {
@@ -236,7 +282,6 @@ class LocalFile extends File
                        $this->$name = $value;
                }
                $this->fileExists = true;
-               // Check for rows from a previous schema, quietly upgrade them
                $this->maybeUpgradeRow();
        }
 
@@ -260,9 +305,8 @@ class LocalFile extends File
                if ( wfReadOnly() ) {
                        return;
                }
-               if ( is_null($this->media_type) || 
-                       $this->mime == 'image/svg' || 
-                       $this->sha1 == ''
+               if ( is_null( $this->media_type ) ||
+                       $this->mime == 'image/svg'
                ) {
                        $this->upgradeRow();
                        $this->upgraded = true;
@@ -289,13 +333,18 @@ class LocalFile extends File
 
                # Don't destroy file info of missing files
                if ( !$this->fileExists ) {
-                       wfDebug( __METHOD__.": file does not exist, aborting\n" );
+                       wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
+                       wfProfileOut( __METHOD__ );
                        return;
                }
                $dbw = $this->repo->getMasterDB();
                list( $major, $minor ) = self::splitMime( $this->mime );
 
-               wfDebug(__METHOD__.': upgrading '.$this->getName()." to the current schema\n");
+               if ( wfReadOnly() ) {
+                       wfProfileOut( __METHOD__ );
+                       return;
+               }
+               wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
 
                $dbw->update( 'image',
                        array(
@@ -314,6 +363,13 @@ class LocalFile extends File
                wfProfileOut( __METHOD__ );
        }
 
+       /**
+        * Set properties in this object to be equal to those given in the
+        * associative array $info. Only cacheable fields can be set.
+        *
+        * If 'mime' is given, it will be split into major_mime/minor_mime.
+        * If major_mime/minor_mime are given, $this->mime will also be set.
+        */
        function setProps( $info ) {
                $this->dataLoaded = true;
                $fields = $this->getCacheFields( '' );
@@ -337,14 +393,22 @@ class LocalFile extends File
        /** getURL inherited */
        /** getViewURL inherited */
        /** getPath inherited */
+       /** isVisible inhereted */
+
+       function isMissing() {
+               if( $this->missing === null ) {
+                       list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo::FILES_ONLY );
+                       $this->missing = !$fileExists;
+               }
+               return $this->missing;
+       }
 
        /**
         * Return the width of the image
         *
         * Returns false on error
-        * @public
         */
-       function getWidth( $page = 1 ) {
+       public function getWidth( $page = 1 ) {
                $this->load();
                if ( $this->isMultipage() ) {
                        $dim = $this->getHandler()->getPageDimensions( $this, $page );
@@ -362,9 +426,8 @@ class LocalFile extends File
         * Return the height of the image
         *
         * Returns false on error
-        * @public
         */
-       function getHeight( $page = 1 ) {
+       public function getHeight( $page = 1 ) {
                $this->load();
                if ( $this->isMultipage() ) {
                        $dim = $this->getHandler()->getPageDimensions( $this, $page );
@@ -378,6 +441,20 @@ class LocalFile extends File
                }
        }
 
+       /**
+        * Returns ID or name of user who uploaded the file
+        *
+        * @param $type string 'text' or 'id'
+        */
+       function getUser( $type = 'text' ) {
+               $this->load();
+               if( $type == 'text' ) {
+                       return $this->user_text;
+               } elseif( $type == 'id' ) {
+                       return $this->user;
+               }
+       }
+
        /**
         * Get handler-specific metadata
         */
@@ -386,11 +463,15 @@ class LocalFile extends File
                return $this->metadata;
        }
 
+       function getBitDepth() {
+               $this->load();
+               return $this->bits;
+       }
+
        /**
         * Return the size of the image file, in bytes
-        * @public
         */
-       function getSize() {
+       public function getSize() {
                $this->load();
                return $this->size;
        }
@@ -421,9 +502,8 @@ class LocalFile extends File
        /**
         * Returns true if the file file exists on disk.
         * @return boolean Whether file file exist on disk.
-        * @public
         */
-       function exists() {
+       public function exists() {
                $this->load();
                return $this->fileExists;
        }
@@ -434,7 +514,7 @@ class LocalFile extends File
        /** createThumb inherited */
        /** getThumbnail inherited */
        /** transform inherited */
-       
+
        /**
         * Fix thumbnail files from 1.4 or before, with extreme prejudice
         */
@@ -446,7 +526,7 @@ class LocalFile extends File
                        // This happened occasionally due to broken migration code in 1.5
                        // Rename to broken-*
                        for ( $i = 0; $i < 100 ; $i++ ) {
-                               $broken = $this->repo->getZonePath('public') . "/broken-$i-$thumbName";
+                               $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
                                if ( !file_exists( $broken ) ) {
                                        rename( $thumbPath, $broken );
                                        break;
@@ -471,25 +551,21 @@ class LocalFile extends File
         * Get all thumbnail names previously generated for this file
         */
        function getThumbnails() {
-               if ( $this->isHashed() ) {
-                       $this->load();
-                       $files = array();
-                       $dir = $this->getThumbPath();
-
-                       if ( is_dir( $dir ) ) {
-                               $handle = opendir( $dir );
-
-                               if ( $handle ) {
-                                       while ( false !== ( $file = readdir($handle) ) ) {
-                                               if ( $file{0} != '.' ) {
-                                                       $files[] = $file;
-                                               }
+               $this->load();
+               $files = array();
+               $dir = $this->getThumbPath();
+
+               if ( is_dir( $dir ) ) {
+                       $handle = opendir( $dir );
+
+                       if ( $handle ) {
+                               while ( false !== ( $file = readdir( $handle ) ) ) {
+                                       if ( $file{0} != '.' ) {
+                                               $files[] = $file;
                                        }
-                                       closedir( $handle );
                                }
+                               closedir( $handle );
                        }
-               } else {
-                       $files = array();
                }
 
                return $files;
@@ -509,9 +585,11 @@ class LocalFile extends File
         */
        function purgeHistory() {
                global $wgMemc;
-               $hashedName = md5($this->getName());
-               $oldKey = wfMemcKey( 'oldfile', $hashedName );
-               $wgMemc->delete( $oldKey );
+               $hashedName = md5( $this->getName() );
+               $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
+               if ( $oldKey ) {
+                       $wgMemc->delete( $oldKey );
+               }
        }
 
        /**
@@ -525,7 +603,7 @@ class LocalFile extends File
                $this->purgeThumbnails();
 
                // Purge squid cache for this file
-               wfPurgeSquidServers( array( $this->getURL() ) );
+               SquidUpdate::purge( array( $this->getURL() ) );
        }
 
        /**
@@ -549,13 +627,52 @@ class LocalFile extends File
 
                // Purge the squid
                if ( $wgUseSquid ) {
-                       wfPurgeSquidServers( $urls );
+                       SquidUpdate::purge( $urls );
                }
        }
 
        /** purgeDescription inherited */
        /** purgeEverything inherited */
 
+       function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
+               $dbr = $this->repo->getSlaveDB();
+               $tables = array( 'oldimage' );
+               $fields = OldLocalFile::selectFields();
+               $conds = $opts = $join_conds = array();
+               $eq = $inc ? '=' : '';
+               $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
+               if( $start ) {
+                       $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
+               }
+               if( $end ) {
+                       $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
+               }
+               if( $limit ) {
+                       $opts['LIMIT'] = $limit;
+               }
+               // Search backwards for time > x queries
+               $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
+               $opts['ORDER BY'] = "oi_timestamp $order";
+               $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
+
+               wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields, 
+                       &$conds, &$opts, &$join_conds ) );
+
+               $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
+               $r = array();
+               while( $row = $dbr->fetchObject( $res ) ) {
+                       if ( $this->repo->oldFileFromRowFactory ) {
+                               $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
+                       } else {
+                               $r[] = OldLocalFile::newFromRow( $row, $this->repo );
+                       }
+               }
+               if( $order == 'ASC' ) {
+                       $r = array_reverse( $r ); // make sure it ends up descending
+               }
+               return $r;
+       }
+
        /**
         * Return the history of this file, line by line.
         * starts with current version, then old versions.
@@ -563,31 +680,34 @@ class LocalFile extends File
         *  0      return line for current version
         *  1      query for old versions, return first one
         *  2, ... return next old version from above query
-        *
-        * @public
         */
-       function nextHistoryLine() {
+       public function nextHistoryLine() {
+               # Polymorphic function name to distinguish foreign and local fetches
+               $fname = get_class( $this ) . '::' . __FUNCTION__;
+
                $dbr = $this->repo->getSlaveDB();
 
                if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
-                       $this->historyRes = $dbr->select( 'image', 
+                       $this->historyRes = $dbr->select( 'image',
                                array(
                                        '*',
-                                       "'' AS oi_archive_name"
+                                       "'' AS oi_archive_name",
+                                       '0 as oi_deleted',
+                                       'img_sha1'
                                ),
                                array( 'img_name' => $this->title->getDBkey() ),
-                               __METHOD__
+                               $fname
                        );
                        if ( 0 == $dbr->numRows( $this->historyRes ) ) {
-                               $dbr->freeResult($this->historyRes);
+                               $dbr->freeResult( $this->historyRes );
                                $this->historyRes = null;
-                               return FALSE;
+                               return false;
                        }
-               } else if ( $this->historyLine == 1 ) {
-                       $dbr->freeResult($this->historyRes);
-                       $this->historyRes = $dbr->select( 'oldimage', '*', 
+               } elseif ( $this->historyLine == 1 ) {
+                       $dbr->freeResult( $this->historyRes );
+                       $this->historyRes = $dbr->select( 'oldimage', '*',
                                array( 'oi_name' => $this->title->getDBkey() ),
-                               __METHOD__,
+                               $fname,
                                array( 'ORDER BY' => 'oi_timestamp DESC' )
                        );
                }
@@ -598,12 +718,11 @@ class LocalFile extends File
 
        /**
         * Reset the history pointer to the first element of the history
-        * @public
         */
-       function resetHistory() {
+       public function resetHistory() {
                $this->historyLine = 0;
-               if (!is_null($this->historyRes)) {
-                       $this->repo->getSlaveDB()->freeResult($this->historyRes);
+               if ( !is_null( $this->historyRes ) ) {
+                       $this->repo->getSlaveDB()->freeResult( $this->historyRes );
                        $this->historyRes = null;
                }
        }
@@ -624,23 +743,25 @@ class LocalFile extends File
 
        /**
         * Upload a file and record it in the DB
-        * @param string $srcPath Source path or virtual URL
-        * @param string $comment Upload description
-        * @param string $pageText Text to use for the new description page, if a new description page is created
-        * @param integer $flags Flags for publish()
-        * @param array $props File properties, if known. This can be used to reduce the
-        *                         upload time when uploading virtual URLs for which the file info
-        *                         is already known
-        * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
+        * @param $srcPath String: source path or virtual URL
+        * @param $comment String: upload description
+        * @param $pageText String: text to use for the new description page,
+        *                  if a new description page is created
+        * @param $flags Integer: flags for publish()
+        * @param $props Array: File properties, if known. This can be used to reduce the
+        *               upload time when uploading virtual URLs for which the file info
+        *               is already known
+        * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
+        * @param $user Mixed: User object or null to use $wgUser
         *
         * @return FileRepoStatus object. On success, the value member contains the
-        *     archive name, or an empty string if it was a new file. 
+        *     archive name, or an empty string if it was a new file.
         */
-       function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
+       function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
                $this->lock();
                $status = $this->publish( $srcPath, $flags );
-               if ( $status->ok ) { 
-                       if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp ) ) {
+               if ( $status->ok ) {
+                       if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
                                $status->fatal( 'filenotfound', $srcPath );
                        }
                }
@@ -652,10 +773,10 @@ class LocalFile extends File
         * Record a file upload in the upload log and the image table
         * @deprecated use upload()
         */
-       function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', 
-               $watch = false, $timestamp = false ) 
+       function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
+               $watch = false, $timestamp = false )
        {
-               $pageText = UploadForm::getInitialPageText( $desc, $license, $copyStatus, $source );
+               $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
                if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
                        return false;
                }
@@ -670,25 +791,33 @@ class LocalFile extends File
        /**
         * Record a file upload in the upload log and the image table
         */
-       function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false ) 
+       function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
        {
-               global $wgUser;
+               if( is_null( $user ) ) {
+                       global $wgUser;
+                       $user = $wgUser; 
+               }
 
                $dbw = $this->repo->getMasterDB();
+               $dbw->begin();
 
                if ( !$props ) {
                        $props = $this->repo->getFileProps( $this->getVirtualUrl() );
                }
+               $props['description'] = $comment;
+               $props['user'] = $user->getId();
+               $props['user_text'] = $user->getName();
+               $props['timestamp'] = wfTimestamp( TS_MW );
                $this->setProps( $props );
 
                // Delete thumbnails and refresh the metadata cache
                $this->purgeThumbnails();
                $this->saveToCache();
-               wfPurgeSquidServers( array( $this->getURL() ) );
+               SquidUpdate::purge( array( $this->getURL() ) );
 
                // Fail now if the file isn't there
                if ( !$this->fileExists ) {
-                       wfDebug( __METHOD__.": File ".$this->getPath()." went missing!\n" );
+                       wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
                        return false;
                }
 
@@ -712,8 +841,8 @@ class LocalFile extends File
                                'img_minor_mime' => $this->minor_mime,
                                'img_timestamp' => $timestamp,
                                'img_description' => $comment,
-                               'img_user' => $wgUser->getID(),
-                               'img_user_text' => $wgUser->getName(),
+                               'img_user' => $user->getId(),
+                               'img_user_text' => $user->getName(),
                                'img_metadata' => $this->metadata,
                                'img_sha1' => $this->sha1
                        ),
@@ -723,7 +852,7 @@ class LocalFile extends File
 
                if( $dbw->affectedRows() == 0 ) {
                        $reupload = true;
-               
+
                        # Collision, this is an update of a file
                        # Insert previous contents into oldimage
                        $dbw->insertSelect( 'oldimage', 'image',
@@ -742,7 +871,7 @@ class LocalFile extends File
                                        'oi_media_type' => 'img_media_type',
                                        'oi_major_mime' => 'img_major_mime',
                                        'oi_minor_mime' => 'img_minor_mime',
-                                       'oi_sha1' => 'img_sha1',
+                                       'oi_sha1' => 'img_sha1'
                                ), array( 'img_name' => $this->getName() ), __METHOD__
                        );
 
@@ -758,8 +887,8 @@ class LocalFile extends File
                                        'img_minor_mime' => $this->minor_mime,
                                        'img_timestamp' => $timestamp,
                                        'img_description' => $comment,
-                                       'img_user' => $wgUser->getID(),
-                                       'img_user_text' => $wgUser->getName(),
+                                       'img_user' => $user->getId(),
+                                       'img_user_text' => $user->getName(),
                                        'img_metadata' => $this->metadata,
                                        'img_sha1' => $this->sha1
                                ), array( /* WHERE */
@@ -774,17 +903,22 @@ class LocalFile extends File
                }
 
                $descTitle = $this->getTitle();
-               $article = new Article( $descTitle );
+               $article = new ImagePage( $descTitle );
+               $article->setFile( $this );
 
                # Add the log entry
                $log = new LogPage( 'upload' );
                $action = $reupload ? 'overwrite' : 'upload';
-               $log->addEntry( $action, $descTitle, $comment );
+               $log->addEntry( $action, $descTitle, $comment, array(), $user );
 
                if( $descTitle->exists() ) {
                        # Create a null revision
-                       $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
+                       $latest = $descTitle->getLatestRevID();
+                       $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(),
+                               $log->getRcComment(), false );
                        $nullRevision->insertOn( $dbw );
+                       
+                       wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
                        $article->updateRevisionOn( $dbw, $nullRevision );
 
                        # Invalidate the cache for the description page
@@ -801,30 +935,35 @@ class LocalFile extends File
 
                # Commit the transaction now, in case something goes wrong later
                # The most important thing is that files don't get lost, especially archives
-               $dbw->immediateCommit();
+               $dbw->commit();
 
                # Invalidate cache for all pages using this file
                $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
                $update->doUpdate();
+               # Invalidate cache for all pages that redirects on this page
+               $redirs = $this->getTitle()->getRedirectsHere();
+               foreach( $redirs as $redir ) {
+                       $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
+                       $update->doUpdate();
+               }
 
                return true;
        }
 
        /**
-        * Move or copy a file to its public location. If a file exists at the  
-        * destination, move it to an archive. Returns the archive name on success 
-        * or an empty string if it was a new file, and a wikitext-formatted 
-        * WikiError object on failure. 
+        * Move or copy a file to its public location. If a file exists at the
+        * destination, move it to an archive. Returns a FileRepoStatus object with
+        * the archive name in the "value" member on success.
         *
         * The archive name should be passed through to recordUpload for database
         * registration.
         *
-        * @param string $sourcePath Local filesystem path to the source image
-        * @param integer $flags A bitwise combination of:
-        *     File::DELETE_SOURCE    Delete the source file, i.e. move 
+        * @param $srcPath String: local filesystem path to the source image
+        * @param $flags Integer: a bitwise combination of:
+        *     File::DELETE_SOURCE    Delete the source file, i.e. move
         *         rather than copy
         * @return FileRepoStatus object. On success, the value member contains the
-        *     archive name, or an empty string if it was a new file. 
+        *     archive name, or an empty string if it was a new file.
         */
        function publish( $srcPath, $flags = 0 ) {
                $this->lock();
@@ -846,7 +985,44 @@ class LocalFile extends File
        /** getExifData inherited */
        /** isLocal inherited */
        /** wasDeleted inherited */
-       
+
+       /**
+        * Move file to the new title
+        *
+        * Move current, old version and all thumbnails
+        * to the new filename. Old file is deleted.
+        *
+        * Cache purging is done; checks for validity
+        * and logging are caller's responsibility
+        *
+        * @param $target Title New file name
+        * @return FileRepoStatus object.
+        */
+       function move( $target ) {
+               wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
+               $this->lock();
+               $batch = new LocalFileMoveBatch( $this, $target );
+               $batch->addCurrent();
+               $batch->addOlds();
+
+               $status = $batch->execute();
+               wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
+               $this->purgeEverything();
+               $this->unlock();
+
+               if ( $status->isOk() ) {
+                       // Now switch the object
+                       $this->title = $target;
+                       // Force regeneration of the name and hashpath
+                       unset( $this->name );
+                       unset( $this->hashPath );
+                       // Purge the new image
+                       $this->purgeEverything();
+               }
+               
+               return $status;
+       }
+
        /**
         * Delete all versions of the file.
         *
@@ -856,11 +1032,12 @@ class LocalFile extends File
         * Cache purging is done; logging is caller's responsibility.
         *
         * @param $reason
+        * @param $suppress
         * @return FileRepoStatus object.
         */
-       function delete( $reason ) {
+       function delete( $reason, $suppress = false ) {
                $this->lock();
-               $batch = new LocalFileDeleteBatch( $this, $reason );
+               $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
                $batch->addCurrent();
 
                # Get old version relative paths
@@ -892,13 +1069,15 @@ class LocalFile extends File
         *
         * Cache purging is done; logging is caller's responsibility.
         *
-        * @param $reason
-        * @throws MWException or FSException on database or filestore failure
+        * @param $archiveName String
+        * @param $reason String
+        * @param $suppress Boolean
+        * @throws MWException or FSException on database or file store failure
         * @return FileRepoStatus object.
         */
-       function deleteOld( $archiveName, $reason ) {
+       function deleteOld( $archiveName, $reason, $suppress=false ) {
                $this->lock();
-               $batch = new LocalFileDeleteBatch( $this, $reason );
+               $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
                $batch->addOld( $archiveName );
                $status = $batch->execute();
                $this->unlock();
@@ -917,10 +1096,11 @@ class LocalFile extends File
         *
         * @param $versions set of record ids of deleted items to restore,
         *                    or empty to restore all revisions.
+        * @param $unsuppress Boolean
         * @return FileRepoStatus
         */
        function restore( $versions = array(), $unsuppress = false ) {
-               $batch = new LocalFileRestoreBatch( $this );
+               $batch = new LocalFileRestoreBatch( $this, $unsuppress );
                if ( !$versions ) {
                        $batch->addAll();
                } else {
@@ -942,9 +1122,9 @@ class LocalFile extends File
        /** pageCount inherited */
        /** scaleHeight inherited */
        /** getImageSize inherited */
-       
+
        /**
-        * Get the URL of the file description page. 
+        * Get the URL of the file description page.
         */
        function getDescriptionUrl() {
                return $this->title->getLocalUrl();
@@ -961,8 +1141,13 @@ class LocalFile extends File
                if ( !$revision ) return false;
                $text = $revision->getText();
                if ( !$text ) return false;
-               $html = $wgParser->parse( $text, new ParserOptions );
-               return $html;
+               $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
+               return $pout->getText();
+       }
+
+       function getDescription() {
+               $this->load();
+               return $this->description;
        }
 
        function getTimestamp() {
@@ -972,6 +1157,19 @@ class LocalFile extends File
 
        function getSha1() {
                $this->load();
+               // Initialise now if necessary
+               if ( $this->sha1 == '' && $this->fileExists ) {
+                       $this->sha1 = File::sha1Base36( $this->getPath() );
+                       if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
+                               $dbw = $this->repo->getMasterDB();
+                               $dbw->update( 'image',
+                                       array( 'img_sha1' => $this->sha1 ),
+                                       array( 'img_name' => $this->getName() ),
+                                       __METHOD__ );
+                               $this->saveToCache();
+                       }
+               }
+
                return $this->sha1;
        }
 
@@ -990,7 +1188,7 @@ class LocalFile extends File
        }
 
        /**
-        * Decrement the lock reference count. If the reference count is reduced to zero, commits 
+        * Decrement the lock reference count. If the reference count is reduced to zero, commits
         * the transaction and thereby releases the image lock.
         */
        function unlock() {
@@ -1015,85 +1213,18 @@ class LocalFile extends File
 
 #------------------------------------------------------------------------------
 
-/**
- * Backwards compatibility class
- */
-class Image extends LocalFile {
-       function __construct( $title ) {
-               $repo = RepoGroup::singleton()->getLocalRepo();
-               parent::__construct( $title, $repo );
-       }
-
-       /**
-        * Wrapper for wfFindFile(), for backwards-compatibility only
-        * Do not use in core code.
-        * @deprecated
-        */
-       static function newFromTitle( $title, $time = false ) {
-               $img = wfFindFile( $title, $time );
-               if ( !$img ) {
-                       $img = wfLocalFile( $title );
-               }
-               return $img;
-       }
-       
-       /**
-        * Wrapper for wfFindFile(), for backwards-compatibility only.
-        * Do not use in core code.
-        *
-        * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
-        * @return image object or null if invalid title
-        * @deprecated
-        */
-       static function newFromName( $name ) {
-               $title = Title::makeTitleSafe( NS_IMAGE, $name );
-               if ( is_object( $title ) ) {
-                       $img = wfFindFile( $title );
-                       if ( !$img ) {
-                               $img = wfLocalFile( $title );
-                       }
-                       return $img;
-               } else {
-                       return NULL;
-               }
-       }
-       
-       /**
-        * Return the URL of an image, provided its name.
-        *
-        * Backwards-compatibility for extensions.
-        * Note that fromSharedDirectory will only use the shared path for files
-        * that actually exist there now, and will return local paths otherwise.
-        *
-        * @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
-        * @deprecated
-        */
-       static function imageUrl( $name, $fromSharedDirectory = false ) {
-               $image = null;
-               if( $fromSharedDirectory ) {
-                       $image = wfFindFile( $name );
-               }
-               if( !$image ) {
-                       $image = wfLocalFile( $name );
-               }
-               return $image->getUrl();
-       }
-}
-
-#------------------------------------------------------------------------------
-
 /**
  * Helper class for file deletion
+ * @ingroup FileRepo
  */
 class LocalFileDeleteBatch {
-       var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch;
+       var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
        var $status;
 
-       function __construct( File $file, $reason = '' ) {
+       function __construct( File $file, $reason = '', $suppress = false ) {
                $this->file = $file;
                $this->reason = $reason;
+               $this->suppress = $suppress;
                $this->status = $file->repo->newGood();
        }
 
@@ -1136,7 +1267,7 @@ class LocalFileDeleteBatch {
                                        $props = $this->file->repo->getFileProps( $oldUrl );
                                        if ( $props['fileExists'] ) {
                                                // Upgrade the oldimage row
-                                               $dbw->update( 'oldimage', 
+                                               $dbw->update( 'oldimage',
                                                        array( 'oi_sha1' => $props['sha1'] ),
                                                        array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
                                                        __METHOD__ );
@@ -1175,17 +1306,29 @@ class LocalFileDeleteBatch {
                $encExt = $dbw->addQuotes( $dotExt );
                list( $oldRels, $deleteCurrent ) = $this->getOldRels();
 
+               // Bitfields to further suppress the content
+               if ( $this->suppress ) {
+                       $bitfield = 0;
+                       // This should be 15...
+                       $bitfield |= Revision::DELETED_TEXT;
+                       $bitfield |= Revision::DELETED_COMMENT;
+                       $bitfield |= Revision::DELETED_USER;
+                       $bitfield |= Revision::DELETED_RESTRICTED;
+               } else {
+                       $bitfield = 'oi_deleted';
+               }
+
                if ( $deleteCurrent ) {
+                       $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
                        $where = array( 'img_name' => $this->file->getName() );
                        $dbw->insertSelect( 'filearchive', 'image',
                                array(
                                        'fa_storage_group' => $encGroup,
-                                       'fa_storage_key'   => "IF(img_sha1='', '', CONCAT(img_sha1,$encExt))",
-
+                                       'fa_storage_key'   => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
                                        'fa_deleted_user'      => $encUserId,
                                        'fa_deleted_timestamp' => $encTimestamp,
                                        'fa_deleted_reason'    => $encReason,
-                                       'fa_deleted'               => 0,
+                                       'fa_deleted'               => $this->suppress ? $bitfield : 0,
 
                                        'fa_name'         => 'img_name',
                                        'fa_archive_name' => 'NULL',
@@ -1205,19 +1348,18 @@ class LocalFileDeleteBatch {
                }
 
                if ( count( $oldRels ) ) {
+                       $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
                        $where = array(
                                'oi_name' => $this->file->getName(),
                                'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
-
-                       $dbw->insertSelect( 'filearchive', 'oldimage', 
+                       $dbw->insertSelect( 'filearchive', 'oldimage',
                                array(
                                        'fa_storage_group' => $encGroup,
-                                       'fa_storage_key'   => "IF(oi_sha1='', '', CONCAT(oi_sha1,$encExt))",
-
+                                       'fa_storage_key'   => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
                                        'fa_deleted_user'      => $encUserId,
                                        'fa_deleted_timestamp' => $encTimestamp,
                                        'fa_deleted_reason'    => $encReason,
-                                       'fa_deleted'               => 0,
+                                       'fa_deleted'               => $this->suppress ? $bitfield : 'oi_deleted',
 
                                        'fa_name'         => 'oi_name',
                                        'fa_archive_name' => 'oi_archive_name',
@@ -1232,7 +1374,8 @@ class LocalFileDeleteBatch {
                                        'fa_description'  => 'oi_description',
                                        'fa_user'         => 'oi_user',
                                        'fa_user_text'    => 'oi_user_text',
-                                       'fa_timestamp'    => 'oi_timestamp'
+                                       'fa_timestamp'    => 'oi_timestamp',
+                                       'fa_deleted'      => $bitfield
                                ), $where, __METHOD__ );
                }
        }
@@ -1240,35 +1383,50 @@ class LocalFileDeleteBatch {
        function doDBDeletes() {
                $dbw = $this->file->repo->getMasterDB();
                list( $oldRels, $deleteCurrent ) = $this->getOldRels();
-               if ( $deleteCurrent ) {
-                       $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
-               }
                if ( count( $oldRels ) ) {
-                       $dbw->delete( 'oldimage', 
+                       $dbw->delete( 'oldimage',
                                array(
                                        'oi_name' => $this->file->getName(),
-                                       'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' 
+                                       'oi_archive_name' => array_keys( $oldRels )
                                ), __METHOD__ );
                }
+               if ( $deleteCurrent ) {
+                       $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
+               }
        }
 
        /**
         * Run the transaction
         */
        function execute() {
-               global $wgUser, $wgUseSquid;
+               global $wgUseSquid;
                wfProfileIn( __METHOD__ );
 
                $this->file->lock();
-
+               // Leave private files alone
+               $privateFiles = array();
+               list( $oldRels, $deleteCurrent ) = $this->getOldRels();
+               $dbw = $this->file->repo->getMasterDB();
+               if( !empty( $oldRels ) ) {
+                       $res = $dbw->select( 'oldimage',
+                               array( 'oi_archive_name' ),
+                               array( 'oi_name' => $this->file->getName(),
+                                       'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
+                                       $dbw->bitAnd('oi_deleted', File::DELETED_FILE) => File::DELETED_FILE ),
+                               __METHOD__ );
+                       while( $row = $dbw->fetchObject( $res ) ) {
+                               $privateFiles[$row->oi_archive_name] = 1;
+                       }
+               }
                // Prepare deletion batch
                $hashes = $this->getHashes();
                $this->deletionBatch = array();
                $ext = $this->file->getExtension();
                $dotExt = $ext === '' ? '' : ".$ext";
                foreach ( $this->srcRels as $name => $srcRel ) {
-                       // Skip files that have no hash (missing source)
-                       if ( isset( $hashes[$name] ) ) {
+                       // Skip files that have no hash (missing source).
+                       // Keep private files where they are.
+                       if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
                                $hash = $hashes[$name];
                                $key = $hash . $dotExt;
                                $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
@@ -1279,11 +1437,14 @@ class LocalFileDeleteBatch {
                // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
                // We acquire this lock by running the inserts now, before the file operations.
                //
-               // This potentially has poor lock contention characteristics -- an alternative 
+               // This potentially has poor lock contention characteristics -- an alternative
                // scheme would be to insert stub filearchive entries with no fa_name and commit
                // them in a separate transaction, then run the file ops, then update the fa_name fields.
                $this->doDBInserts();
 
+               // Removes non-existent file from the batch, so we don't get errors.
+               $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
+
                // Execute the file deletion batch
                $status = $this->file->repo->deleteBatch( $this->deletionBatch );
                if ( !$status->isGood() ) {
@@ -1295,6 +1456,7 @@ class LocalFileDeleteBatch {
                        // Roll back inserts, release lock and abort
                        // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
                        $this->file->unlockAndRollback();
+                       wfProfileOut( __METHOD__ );
                        return $this->status;
                }
 
@@ -1303,7 +1465,7 @@ class LocalFileDeleteBatch {
                        $urls = array();
                        foreach ( $this->srcRels as $srcRel ) {
                                $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
-                               $urls[] = $this->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
+                               $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
                        }
                        SquidUpdate::purge( $urls );
                }
@@ -1316,20 +1478,38 @@ class LocalFileDeleteBatch {
                wfProfileOut( __METHOD__ );
                return $this->status;
        }
+
+       /**
+        * Removes non-existent files from a deletion batch.
+        */
+       function removeNonexistentFiles( $batch ) {
+               $files = $newBatch = array();
+               foreach( $batch as $batchItem ) {
+                       list( $src, $dest ) = $batchItem;
+                       $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
+               }
+               $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
+               foreach( $batch as $batchItem )
+                       if( $result[$batchItem[0]] )
+                               $newBatch[] = $batchItem;
+               return $newBatch;
+       }
 }
 
 #------------------------------------------------------------------------------
 
 /**
  * Helper class for file undeletion
+ * @ingroup FileRepo
  */
 class LocalFileRestoreBatch {
        var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
 
-       function __construct( File $file ) {
+       function __construct( File $file, $unsuppress = false ) {
                $this->file = $file;
                $this->cleanupBatch = $this->ids = array();
                $this->ids = array();
+               $this->unsuppress = $unsuppress;
        }
 
        /**
@@ -1352,16 +1532,16 @@ class LocalFileRestoreBatch {
        function addAll() {
                $this->all = true;
        }
-       
+
        /**
-        * Run the transaction, except the cleanup batch. 
+        * Run the transaction, except the cleanup batch.
         * The cleanup batch should be run in a separate transaction, because it locks different
         * rows and there's no need to keep the image row locked while it's acquiring those locks
         * The caller may have its own transaction open.
         * So we save the batch and let the caller call cleanup()
         */
        function execute() {
-               global $wgUser, $wgLang;
+               global $wgLang;
                if ( !$this->all && !$this->ids ) {
                        // Do nothing
                        return $this->file->repo->newGood();
@@ -1370,7 +1550,7 @@ class LocalFileRestoreBatch {
                $exists = $this->file->lock();
                $dbw = $this->file->repo->getMasterDB();
                $status = $this->file->repo->newGood();
-               
+
                // Fetch all or selected archived revisions for the file,
                // sorted from the most recent to the oldest.
                $conditions = array( 'fa_name' => $this->file->getName() );
@@ -1381,7 +1561,8 @@ class LocalFileRestoreBatch {
                $result = $dbw->select( 'filearchive', '*',
                        $conditions,
                        __METHOD__,
-                       array( 'ORDER BY' => 'fa_timestamp DESC' ) );
+                       array( 'ORDER BY' => 'fa_timestamp DESC' )
+               );
 
                $idsPresent = array();
                $storeBatch = array();
@@ -1392,12 +1573,7 @@ class LocalFileRestoreBatch {
                $archiveNames = array();
                while( $row = $dbw->fetchObject( $result ) ) {
                        $idsPresent[] = $row->fa_id;
-                       if ( $this->unsuppress ) {
-                               // Currently, fa_deleted flags fall off upon restore, lets be careful about this
-                       } else if ( ($row->fa_deleted & Revision::DELETED_RESTRICTED) && !$wgUser->isAllowed('hiderevision') ) {
-                               // Skip restoring file revisions that the user cannot restore
-                               continue;
-                       }
+
                        if ( $row->fa_name != $this->file->getName() ) {
                                $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
                                $status->failCount++;
@@ -1419,6 +1595,22 @@ class LocalFileRestoreBatch {
                                $sha1 = substr( $sha1, 1 );
                        }
 
+                       if( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
+                               || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
+                               || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
+                               || is_null( $row->fa_metadata ) ) {
+                               // Refresh our metadata
+                               // Required for a new current revision; nice for older ones too. :)
+                               $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
+                       } else {
+                               $props = array(
+                                       'minor_mime' => $row->fa_minor_mime,
+                                       'major_mime' => $row->fa_major_mime,
+                                       'media_type' => $row->fa_media_type,
+                                       'metadata'   => $row->fa_metadata
+                               );
+                       }
+
                        if ( $first && !$exists ) {
                                // This revision will be published as the new current version
                                $destRel = $this->file->getRel();
@@ -1427,16 +1619,22 @@ class LocalFileRestoreBatch {
                                        'img_size'        => $row->fa_size,
                                        'img_width'       => $row->fa_width,
                                        'img_height'      => $row->fa_height,
-                                       'img_metadata'    => $row->fa_metadata,
+                                       'img_metadata'    => $props['metadata'],
                                        'img_bits'        => $row->fa_bits,
-                                       'img_media_type'  => $row->fa_media_type,
-                                       'img_major_mime'  => $row->fa_major_mime,
-                                       'img_minor_mime'  => $row->fa_minor_mime,
+                                       'img_media_type'  => $props['media_type'],
+                                       'img_major_mime'  => $props['major_mime'],
+                                       'img_minor_mime'  => $props['minor_mime'],
                                        'img_description' => $row->fa_description,
                                        'img_user'        => $row->fa_user,
                                        'img_user_text'   => $row->fa_user_text,
                                        'img_timestamp'   => $row->fa_timestamp,
-                                       'img_sha1'        => $sha1);
+                                       'img_sha1'        => $sha1
+                               );
+                               // The live (current) version cannot be hidden!
+                               if( !$this->unsuppress && $row->fa_deleted ) {
+                                       $storeBatch[] = array( $deletedUrl, 'public', $destRel );
+                                       $this->cleanupBatch[] = $row->fa_storage_key;
+                               }
                        } else {
                                $archiveName = $row->fa_archive_name;
                                if( $archiveName == '' ) {
@@ -1462,17 +1660,22 @@ class LocalFileRestoreBatch {
                                        'oi_user'         => $row->fa_user,
                                        'oi_user_text'    => $row->fa_user_text,
                                        'oi_timestamp'    => $row->fa_timestamp,
-                                       'oi_metadata'     => $row->fa_metadata,
-                                       'oi_media_type'   => $row->fa_media_type,
-                                       'oi_major_mime'   => $row->fa_major_mime,
-                                       'oi_minor_mime'   => $row->fa_minor_mime,
-                                       'oi_deleted'      => $row->fa_deleted,
+                                       'oi_metadata'     => $props['metadata'],
+                                       'oi_media_type'   => $props['media_type'],
+                                       'oi_major_mime'   => $props['major_mime'],
+                                       'oi_minor_mime'   => $props['minor_mime'],
+                                       'oi_deleted'      => $this->unsuppress ? 0 : $row->fa_deleted,
                                        'oi_sha1'         => $sha1 );
                        }
 
                        $deleteIds[] = $row->fa_id;
-                       $storeBatch[] = array( $deletedUrl, 'public', $destRel );
-                       $this->cleanupBatch[] = $row->fa_storage_key;
+                       if( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
+                               // private files can stay where they are
+                               $status->successCount++;
+                       } else {
+                               $storeBatch[] = array( $deletedUrl, 'public', $destRel );
+                               $this->cleanupBatch[] = $row->fa_storage_key;
+                       }
                        $first = false;
                }
                unset( $result );
@@ -1483,6 +1686,9 @@ class LocalFileRestoreBatch {
                        $status->error( 'undelete-missing-filearchive', $id );
                }
 
+               // Remove missing files from batch, so we don't get errors when undeleting them
+               $storeBatch = $this->removeNonexistentFiles( $storeBatch );
+
                // Run the store batch
                // Use the OVERWRITE_SAME flag to smooth over a common error
                $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
@@ -1497,8 +1703,8 @@ class LocalFileRestoreBatch {
 
                // Run the DB updates
                // Because we have locked the image row, key conflicts should be rare.
-               // If they do occur, we can roll back the transaction at this time with 
-               // no data loss, but leaving unregistered files scattered throughout the 
+               // If they do occur, we can roll back the transaction at this time with
+               // no data loss, but leaving unregistered files scattered throughout the
                // public zone.
                // This is not ideal, which is why it's important to lock the image row.
                if ( $insertCurrent ) {
@@ -1508,14 +1714,15 @@ class LocalFileRestoreBatch {
                        $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
                }
                if ( $deleteIds ) {
-                       $dbw->delete( 'filearchive', 
-                               array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ), 
+                       $dbw->delete( 'filearchive',
+                               array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
                                __METHOD__ );
                }
 
-               if( $status->successCount > 0 ) {
+               // If store batch is empty (all files are missing), deletion is to be considered successful
+               if( $status->successCount > 0 || !$storeBatch ) {
                        if( !$exists ) {
-                               wfDebug( __METHOD__." restored {$status->successCount} items, creating a new current\n" );
+                               wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
 
                                // Update site_stats
                                $site_stats = $dbw->tableName( 'site_stats' );
@@ -1523,7 +1730,7 @@ class LocalFileRestoreBatch {
 
                                $this->file->purgeEverything();
                        } else {
-                               wfDebug( __METHOD__." restored {$status->successCount} as archived versions\n" );
+                               wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
                                $this->file->purgeDescription();
                                $this->file->purgeHistory();
                        }
@@ -1532,6 +1739,38 @@ class LocalFileRestoreBatch {
                return $status;
        }
 
+       /**
+        * Removes non-existent files from a store batch.
+        */
+       function removeNonexistentFiles( $triplets ) {
+               $files = $filteredTriplets = array();
+               foreach( $triplets as $file )
+                       $files[$file[0]] = $file[0];
+               $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
+               foreach( $triplets as $file )
+                       if( $result[$file[0]] )
+                               $filteredTriplets[] = $file;
+               return $filteredTriplets;
+       }
+
+       /**
+        * Removes non-existent files from a cleanup batch.
+        */
+       function removeNonexistentFromCleanup( $batch ) {
+               $files = $newBatch = array();
+               $repo = $this->file->repo;
+               foreach( $batch as $file ) {
+                       $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
+                               rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
+               }
+
+               $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
+               foreach( $batch as $file )
+                       if( $result[$file] )
+                               $newBatch[] = $file;
+               return $newBatch;
+       }
+
        /**
         * Delete unused files in the deleted zone.
         * This should be called from outside the transaction in which execute() was called.
@@ -1540,7 +1779,173 @@ class LocalFileRestoreBatch {
                if ( !$this->cleanupBatch ) {
                        return $this->file->repo->newGood();
                }
+               $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
                $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
                return $status;
        }
 }
+
+#------------------------------------------------------------------------------
+
+/**
+ * Helper class for file movement
+ * @ingroup FileRepo
+ */
+class LocalFileMoveBatch {
+       var $file, $cur, $olds, $oldCount, $archive, $target, $db;
+
+       function __construct( File $file, Title $target ) {
+               $this->file = $file;
+               $this->target = $target;
+               $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
+               $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
+               $this->oldName = $this->file->getName();
+               $this->newName = $this->file->repo->getNameFromTitle( $this->target );
+               $this->oldRel = $this->oldHash . $this->oldName;
+               $this->newRel = $this->newHash . $this->newName;
+               $this->db = $file->repo->getMasterDb();
+       }
+
+       /**
+        * Add the current image to the batch
+        */
+       function addCurrent() {
+               $this->cur = array( $this->oldRel, $this->newRel );
+       }
+
+       /**
+        * Add the old versions of the image to the batch
+        */
+       function addOlds() {
+               $archiveBase = 'archive';
+               $this->olds = array();
+               $this->oldCount = 0;
+
+               $result = $this->db->select( 'oldimage',
+                       array( 'oi_archive_name', 'oi_deleted' ),
+                       array( 'oi_name' => $this->oldName ),
+                       __METHOD__
+               );
+               while( $row = $this->db->fetchObject( $result ) ) {
+                       $oldName = $row->oi_archive_name;
+                       $bits = explode( '!', $oldName, 2 );
+                       if( count( $bits ) != 2 ) {
+                               wfDebug( "Invalid old file name: $oldName \n" );
+                               continue;
+                       }
+                       list( $timestamp, $filename ) = $bits;
+                       if( $this->oldName != $filename ) {
+                               wfDebug( "Invalid old file name: $oldName \n" );
+                               continue;
+                       }
+                       $this->oldCount++;
+                       // Do we want to add those to oldCount?
+                       if( $row->oi_deleted & File::DELETED_FILE ) {
+                               continue;
+                       }
+                       $this->olds[] = array(
+                               "{$archiveBase}/{$this->oldHash}{$oldName}",
+                               "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
+                       );
+               }
+               $this->db->freeResult( $result );
+       }
+
+       /**
+        * Perform the move.
+        */
+       function execute() {
+               $repo = $this->file->repo;
+               $status = $repo->newGood();
+               $triplets = $this->getMoveTriplets();
+
+               $triplets = $this->removeNonexistentFiles( $triplets );
+               $statusDb = $this->doDBUpdates();
+               wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
+               $statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
+               wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
+               if( !$statusMove->isOk() ) {
+                       wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
+                       $this->db->rollback();
+               }
+
+               $status->merge( $statusDb );
+               $status->merge( $statusMove );
+               return $status;
+       }
+
+       /**
+        * Do the database updates and return a new FileRepoStatus indicating how
+        * many rows where updated.
+        *
+        * @return FileRepoStatus
+        */
+       function doDBUpdates() {
+               $repo = $this->file->repo;
+               $status = $repo->newGood();
+               $dbw = $this->db;
+
+               // Update current image
+               $dbw->update( 
+                       'image',
+                       array( 'img_name' => $this->newName ),
+                       array( 'img_name' => $this->oldName ),
+                       __METHOD__
+               );
+               if( $dbw->affectedRows() ) {
+                       $status->successCount++;
+               } else {
+                       $status->failCount++;
+               }
+
+               // Update old images
+               $dbw->update(
+                       'oldimage',
+                       array(
+                               'oi_name' => $this->newName,
+                               'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName), $dbw->addQuotes($this->newName) ),
+                       ),
+                       array( 'oi_name' => $this->oldName ),
+                       __METHOD__
+               );
+               $affected = $dbw->affectedRows();
+               $total = $this->oldCount;
+               $status->successCount += $affected;
+               $status->failCount += $total - $affected;
+
+               return $status;
+       }
+
+       /**
+        * Generate triplets for FSRepo::storeBatch().
+        */ 
+       function getMoveTriplets() {
+               $moves = array_merge( array( $this->cur ), $this->olds );
+               $triplets = array();    // The format is: (srcUrl, destZone, destUrl)
+               foreach( $moves as $move ) {
+                       // $move: (oldRelativePath, newRelativePath)
+                       $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
+                       $triplets[] = array( $srcUrl, 'public', $move[1] );
+                       wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
+               }
+               return $triplets;
+       }
+
+       /**
+        * Removes non-existent files from move batch.
+        */ 
+       function removeNonexistentFiles( $triplets ) {
+               $files = array();
+               foreach( $triplets as $file )
+                       $files[$file[0]] = $file[0];
+               $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
+               $filteredTriplets = array();
+               foreach( $triplets as $file )
+                       if( $result[$file[0]] ) {
+                               $filteredTriplets[] = $file;
+                       } else {
+                               wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
+                       }
+               return $filteredTriplets;
+       }
+}