summaryrefslogtreecommitdiff
path: root/includes/filerepo/LocalFile.php
diff options
context:
space:
mode:
Diffstat (limited to 'includes/filerepo/LocalFile.php')
-rw-r--r--includes/filerepo/LocalFile.php533
1 files changed, 370 insertions, 163 deletions
diff --git a/includes/filerepo/LocalFile.php b/includes/filerepo/LocalFile.php
index 9b06fe2d..57c0703d 100644
--- a/includes/filerepo/LocalFile.php
+++ b/includes/filerepo/LocalFile.php
@@ -5,7 +5,7 @@
/**
* Bump this number when serialized cache records may be incompatible.
*/
-define( 'MW_FILE_VERSION', 7 );
+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', 7 );
* 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,7 +22,7 @@ define( 'MW_FILE_VERSION', 7 );
* The convenience functions wfLocalFile() and wfFindFile() should be sufficient
* in most cases.
*
- * @addtogroup FileRepo
+ * @ingroup FileRepo
*/
class LocalFile extends File
{
@@ -48,15 +48,18 @@ class LocalFile extends 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
+ $locked, # True if the image row is locked
+ $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 );
}
@@ -70,6 +73,48 @@ class LocalFile extends File
$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.
@@ -156,7 +201,7 @@ class LocalFile extends File
}
function getCacheFields( $prefix = 'img_' ) {
- static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
+ 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 == '' ) {
@@ -197,7 +242,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_' ) {
@@ -235,7 +280,6 @@ class LocalFile extends File
$this->$name = $value;
}
$this->fileExists = true;
- // Check for rows from a previous schema, quietly upgrade them
$this->maybeUpgradeRow();
}
@@ -259,7 +303,7 @@ class LocalFile extends File
if ( wfReadOnly() ) {
return;
}
- if ( is_null($this->media_type) ||
+ if ( is_null($this->media_type) ||
$this->mime == 'image/svg'
) {
$this->upgradeRow();
@@ -316,10 +360,10 @@ class LocalFile extends File
}
/**
- * Set properties in this object to be equal to those given in the
+ * 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 '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 ) {
@@ -345,6 +389,7 @@ class LocalFile extends File
/** getURL inherited */
/** getViewURL inherited */
/** getPath inherited */
+ /** isVisible inhereted */
/**
* Return the width of the image
@@ -456,7 +501,7 @@ class LocalFile extends File
/** createThumb inherited */
/** getThumbnail inherited */
/** transform inherited */
-
+
/**
* Fix thumbnail files from 1.4 or before, with extreme prejudice
*/
@@ -493,25 +538,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;
@@ -547,7 +588,7 @@ class LocalFile extends File
$this->purgeThumbnails();
// Purge squid cache for this file
- wfPurgeSquidServers( array( $this->getURL() ) );
+ SquidUpdate::purge( array( $this->getURL() ) );
}
/**
@@ -571,7 +612,7 @@ class LocalFile extends File
// Purge the squid
if ( $wgUseSquid ) {
- wfPurgeSquidServers( $urls );
+ SquidUpdate::purge( $urls );
}
}
@@ -580,6 +621,9 @@ class LocalFile extends File
function getHistory($limit = null, $start = null, $end = null) {
$dbr = $this->repo->getSlaveDB();
+ $tables = array('oldimage');
+ $join_conds = array();
+ $fields = OldLocalFile::selectFields();
$conds = $opts = array();
$conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBKey() );
if( $start !== null ) {
@@ -592,14 +636,17 @@ class LocalFile extends File
$opts['LIMIT'] = $limit;
}
$opts['ORDER BY'] = 'oi_timestamp DESC';
- $res = $dbr->select('oldimage', '*', $conds, __METHOD__, $opts);
+
+ 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) ) {
$r[] = OldLocalFile::newFromRow($row, $this->repo);
}
return $r;
}
-
+
/**
* Return the history of this file, line by line.
* starts with current version, then old versions.
@@ -617,10 +664,12 @@ class LocalFile extends File
$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() ),
$fname
@@ -632,7 +681,7 @@ class LocalFile extends File
}
} else if ( $this->historyLine == 1 ) {
$dbr->freeResult($this->historyRes);
- $this->historyRes = $dbr->select( 'oldimage', '*',
+ $this->historyRes = $dbr->select( 'oldimage', '*',
array( 'oi_name' => $this->title->getDBkey() ),
$fname,
array( 'ORDER BY' => 'oi_timestamp DESC' )
@@ -681,12 +730,12 @@ class LocalFile extends File
* @param string $timestamp Timestamp for img_timestamp, or false to use the current time
*
* @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 ) {
$this->lock();
$status = $this->publish( $srcPath, $flags );
- if ( $status->ok ) {
+ if ( $status->ok ) {
if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp ) ) {
$status->fatal( 'filenotfound', $srcPath );
}
@@ -699,8 +748,8 @@ 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 );
if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
@@ -717,7 +766,7 @@ 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 )
{
global $wgUser;
@@ -727,7 +776,7 @@ class LocalFile extends File
$props = $this->repo->getFileProps( $this->getVirtualUrl() );
}
$props['description'] = $comment;
- $props['user'] = $wgUser->getID();
+ $props['user'] = $wgUser->getId();
$props['user_text'] = $wgUser->getName();
$props['timestamp'] = wfTimestamp( TS_MW );
$this->setProps( $props );
@@ -735,7 +784,7 @@ class LocalFile extends File
// 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 ) {
@@ -763,7 +812,7 @@ class LocalFile extends File
'img_minor_mime' => $this->minor_mime,
'img_timestamp' => $timestamp,
'img_description' => $comment,
- 'img_user' => $wgUser->getID(),
+ 'img_user' => $wgUser->getId(),
'img_user_text' => $wgUser->getName(),
'img_metadata' => $this->metadata,
'img_sha1' => $this->sha1
@@ -774,7 +823,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',
@@ -793,7 +842,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__
);
@@ -809,7 +858,7 @@ class LocalFile extends File
'img_minor_mime' => $this->minor_mime,
'img_timestamp' => $timestamp,
'img_description' => $comment,
- 'img_user' => $wgUser->getID(),
+ 'img_user' => $wgUser->getId(),
'img_user_text' => $wgUser->getName(),
'img_metadata' => $this->metadata,
'img_sha1' => $this->sha1
@@ -836,6 +885,8 @@ class LocalFile extends File
# Create a null revision
$nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
$nullRevision->insertOn( $dbw );
+
+ wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, false) );
$article->updateRevisionOn( $dbw, $nullRevision );
# Invalidate the cache for the description page
@@ -857,25 +908,31 @@ class LocalFile extends File
# 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 the archive name on success
+ * or an empty string if it was a new file, and a wikitext-formatted
+ * WikiError object on failure.
*
* 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
+ * 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();
@@ -897,7 +954,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.
*
@@ -907,11 +1001,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
@@ -944,12 +1039,13 @@ class LocalFile extends File
* Cache purging is done; logging is caller's responsibility.
*
* @param $reason
+ * @param $suppress
* @throws MWException or FSException on database or filestore 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();
@@ -968,10 +1064,11 @@ class LocalFile extends File
*
* @param $versions set of record ids of deleted items to restore,
* or empty to restore all revisions.
+ * @param $unuppress
* @return FileRepoStatus
*/
function restore( $versions = array(), $unsuppress = false ) {
- $batch = new LocalFileRestoreBatch( $this );
+ $batch = new LocalFileRestoreBatch( $this, $unsuppress );
if ( !$versions ) {
$batch->addAll();
} else {
@@ -993,9 +1090,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();
@@ -1033,7 +1130,7 @@ class LocalFile extends File
$this->sha1 = File::sha1Base36( $this->getPath() );
if ( strval( $this->sha1 ) != '' ) {
$dbw = $this->repo->getMasterDB();
- $dbw->update( 'image',
+ $dbw->update( 'image',
array( 'img_sha1' => $this->sha1 ),
array( 'img_name' => $this->getName() ),
__METHOD__ );
@@ -1059,7 +1156,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() {
@@ -1085,84 +1182,17 @@ 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();
}
@@ -1205,7 +1235,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__ );
@@ -1244,6 +1274,18 @@ 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() );
@@ -1254,7 +1296,7 @@ class LocalFileDeleteBatch {
'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',
@@ -1278,14 +1320,14 @@ class LocalFileDeleteBatch {
$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' => "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',
@@ -1300,7 +1342,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__ );
}
}
@@ -1309,10 +1352,10 @@ class LocalFileDeleteBatch {
$dbw = $this->file->repo->getMasterDB();
list( $oldRels, $deleteCurrent ) = $this->getOldRels();
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 IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
), __METHOD__ );
}
if ( $deleteCurrent ) {
@@ -1328,15 +1371,30 @@ class LocalFileDeleteBatch {
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) ) . ')',
+ '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;
@@ -1347,7 +1405,7 @@ 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();
@@ -1390,14 +1448,16 @@ class LocalFileDeleteBatch {
/**
* 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;
}
/**
@@ -1420,9 +1480,9 @@ 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.
@@ -1438,7 +1498,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() );
@@ -1460,12 +1520,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++;
@@ -1486,7 +1541,7 @@ class LocalFileRestoreBatch {
if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
$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'
@@ -1503,6 +1558,11 @@ class LocalFileRestoreBatch {
}
if ( $first && !$exists ) {
+ // The live (current) version cannot be hidden!
+ if( !$this->unsuppress && $row->fa_deleted ) {
+ $this->file->unlock();
+ return $status;
+ }
// This revision will be published as the new current version
$destRel = $this->file->getRel();
$insertCurrent = array(
@@ -1549,13 +1609,17 @@ class LocalFileRestoreBatch {
'oi_media_type' => $props['media_type'],
'oi_major_mime' => $props['major_mime'],
'oi_minor_mime' => $props['minor_mime'],
- 'oi_deleted' => $row->fa_deleted,
+ '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
+ } else {
+ $storeBatch[] = array( $deletedUrl, 'public', $destRel );
+ $this->cleanupBatch[] = $row->fa_storage_key;
+ }
$first = false;
}
unset( $result );
@@ -1580,8 +1644,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 ) {
@@ -1591,8 +1655,8 @@ 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__ );
}
@@ -1627,3 +1691,146 @@ class LocalFileRestoreBatch {
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 );
+ continue;
+ }
+ list( $timestamp, $filename ) = $bits;
+ if( $this->oldName != $filename ) {
+ wfDebug( 'Invalid old file name:' . $oldName );
+ 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();
+
+ $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 WikiError indicating how many
+ * rows where updated.
+ */
+ 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;
+ }
+}