MediaWiki  master
LocalFileRestoreBatch.php
Go to the documentation of this file.
1 <?php
25 
32  private $file;
33 
35  private $cleanupBatch;
36 
38  private $ids;
39 
41  private $all;
42 
44  private $unsuppress = false;
45 
50  public function __construct( LocalFile $file, $unsuppress = false ) {
51  $this->file = $file;
52  $this->cleanupBatch = [];
53  $this->ids = [];
54  $this->unsuppress = $unsuppress;
55  }
56 
61  public function addId( $fa_id ) {
62  $this->ids[] = $fa_id;
63  }
64 
69  public function addIds( $ids ) {
70  $this->ids = array_merge( $this->ids, $ids );
71  }
72 
76  public function addAll() {
77  $this->all = true;
78  }
79 
88  public function execute() {
90  global $wgLang;
91 
92  $repo = $this->file->getRepo();
93  if ( !$this->all && !$this->ids ) {
94  // Do nothing
95  return $repo->newGood();
96  }
97 
98  $lockOwnsTrx = $this->file->lock();
99 
100  $dbw = $this->file->repo->getMasterDB();
101 
102  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
103  $actorMigration = ActorMigration::newMigration();
104 
105  $status = $this->file->repo->newGood();
106 
107  $exists = (bool)$dbw->selectField( 'image', '1',
108  [ 'img_name' => $this->file->getName() ],
109  __METHOD__,
110  // The lock() should already prevents changes, but this still may need
111  // to bypass any transaction snapshot. However, if lock() started the
112  // trx (which it probably did) then snapshot is post-lock and up-to-date.
113  $lockOwnsTrx ? [] : [ 'LOCK IN SHARE MODE' ]
114  );
115 
116  // Fetch all or selected archived revisions for the file,
117  // sorted from the most recent to the oldest.
118  $conditions = [ 'fa_name' => $this->file->getName() ];
119 
120  if ( !$this->all ) {
121  $conditions['fa_id'] = $this->ids;
122  }
123 
124  $arFileQuery = ArchivedFile::getQueryInfo();
125  $result = $dbw->select(
126  $arFileQuery['tables'],
127  $arFileQuery['fields'],
128  $conditions,
129  __METHOD__,
130  [ 'ORDER BY' => 'fa_timestamp DESC' ],
131  $arFileQuery['joins']
132  );
133 
134  $idsPresent = [];
135  $storeBatch = [];
136  $insertBatch = [];
137  $insertCurrent = false;
138  $deleteIds = [];
139  $first = true;
140  $archiveNames = [];
141 
142  foreach ( $result as $row ) {
143  $idsPresent[] = $row->fa_id;
144 
145  if ( $row->fa_name != $this->file->getName() ) {
146  $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
147  $status->failCount++;
148  continue;
149  }
150 
151  if ( $row->fa_storage_key == '' ) {
152  // Revision was missing pre-deletion
153  $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
154  $status->failCount++;
155  continue;
156  }
157 
158  $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
159  $row->fa_storage_key;
160  $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
161 
162  if ( isset( $row->fa_sha1 ) ) {
163  $sha1 = $row->fa_sha1;
164  } else {
165  // old row, populate from key
166  $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
167  }
168 
169  # Fix leading zero
170  if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
171  $sha1 = substr( $sha1, 1 );
172  }
173 
174  if ( $row->fa_major_mime === null || $row->fa_major_mime == 'unknown'
175  || $row->fa_minor_mime === null || $row->fa_minor_mime == 'unknown'
176  || $row->fa_media_type === null || $row->fa_media_type == 'UNKNOWN'
177  || $row->fa_metadata === null
178  ) {
179  // Refresh our metadata
180  // Required for a new current revision; nice for older ones too. :)
181  // @phan-suppress-next-line SecurityCheck-PathTraversal False positive T268920
182  $props = MediaWikiServices::getInstance()->getRepoGroup()->getFileProps( $deletedUrl );
183  } else {
184  $props = [
185  'minor_mime' => $row->fa_minor_mime,
186  'major_mime' => $row->fa_major_mime,
187  'media_type' => $row->fa_media_type,
188  'metadata' => $row->fa_metadata
189  ];
190  }
191 
192  $comment = $commentStore->getComment( 'fa_description', $row );
193  $user = User::newFromAnyId( $row->fa_user, $row->fa_user_text, $row->fa_actor );
194  if ( $first && !$exists ) {
195  // This revision will be published as the new current version
196  $destRel = $this->file->getRel();
197  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
198  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
199  $insertCurrent = [
200  'img_name' => $row->fa_name,
201  'img_size' => $row->fa_size,
202  'img_width' => $row->fa_width,
203  'img_height' => $row->fa_height,
204  'img_metadata' => $props['metadata'],
205  'img_bits' => $row->fa_bits,
206  'img_media_type' => $props['media_type'],
207  'img_major_mime' => $props['major_mime'],
208  'img_minor_mime' => $props['minor_mime'],
209  'img_timestamp' => $row->fa_timestamp,
210  'img_sha1' => $sha1
211  ] + $commentFields + $actorFields;
212 
213  // The live (current) version cannot be hidden!
214  if ( !$this->unsuppress && $row->fa_deleted ) {
215  $status->fatal( 'undeleterevdel' );
216  $this->file->unlock();
217  return $status;
218  }
219  } else {
220  $archiveName = $row->fa_archive_name;
221 
222  if ( $archiveName == '' ) {
223  // This was originally a current version; we
224  // have to devise a new archive name for it.
225  // Format is <timestamp of archiving>!<name>
226  $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
227 
228  do {
229  $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
230  $timestamp++;
231  } while ( isset( $archiveNames[$archiveName] ) );
232  }
233 
234  $archiveNames[$archiveName] = true;
235  $destRel = $this->file->getArchiveRel( $archiveName );
236  $insertBatch[] = [
237  'oi_name' => $row->fa_name,
238  'oi_archive_name' => $archiveName,
239  'oi_size' => $row->fa_size,
240  'oi_width' => $row->fa_width,
241  'oi_height' => $row->fa_height,
242  'oi_bits' => $row->fa_bits,
243  'oi_timestamp' => $row->fa_timestamp,
244  'oi_metadata' => $props['metadata'],
245  'oi_media_type' => $props['media_type'],
246  'oi_major_mime' => $props['major_mime'],
247  'oi_minor_mime' => $props['minor_mime'],
248  'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
249  'oi_sha1' => $sha1
250  ] + $commentStore->insert( $dbw, 'oi_description', $comment )
251  + $actorMigration->getInsertValues( $dbw, 'oi_user', $user );
252  }
253 
254  $deleteIds[] = $row->fa_id;
255 
256  if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
257  // private files can stay where they are
258  $status->successCount++;
259  } else {
260  $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
261  $this->cleanupBatch[] = $row->fa_storage_key;
262  }
263 
264  $first = false;
265  }
266 
267  unset( $result );
268 
269  // Add a warning to the status object for missing IDs
270  $missingIds = array_diff( $this->ids, $idsPresent );
271 
272  foreach ( $missingIds as $id ) {
273  $status->error( 'undelete-missing-filearchive', $id );
274  }
275 
276  if ( !$repo->hasSha1Storage() ) {
277  // Remove missing files from batch, so we don't get errors when undeleting them
278  $checkStatus = $this->removeNonexistentFiles( $storeBatch );
279  if ( !$checkStatus->isGood() ) {
280  $status->merge( $checkStatus );
281  return $status;
282  }
283  $storeBatch = $checkStatus->value;
284 
285  // Run the store batch
286  // Use the OVERWRITE_SAME flag to smooth over a common error
287  $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
288  $status->merge( $storeStatus );
289 
290  if ( !$status->isGood() ) {
291  // Even if some files could be copied, fail entirely as that is the
292  // easiest thing to do without data loss
293  $this->cleanupFailedBatch( $storeStatus, $storeBatch );
294  $status->setOK( false );
295  $this->file->unlock();
296 
297  return $status;
298  }
299  }
300 
301  // Run the DB updates
302  // Because we have locked the image row, key conflicts should be rare.
303  // If they do occur, we can roll back the transaction at this time with
304  // no data loss, but leaving unregistered files scattered throughout the
305  // public zone.
306  // This is not ideal, which is why it's important to lock the image row.
307  if ( $insertCurrent ) {
308  $dbw->insert( 'image', $insertCurrent, __METHOD__ );
309  }
310 
311  if ( $insertBatch ) {
312  $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
313  }
314 
315  if ( $deleteIds ) {
316  $dbw->delete( 'filearchive',
317  [ 'fa_id' => $deleteIds ],
318  __METHOD__ );
319  }
320 
321  // If store batch is empty (all files are missing), deletion is to be considered successful
322  if ( $status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
323  if ( !$exists ) {
324  wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current" );
325 
327 
328  $this->file->purgeEverything();
329  } else {
330  wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions" );
331  $this->file->purgeDescription();
332  }
333  }
334 
335  $this->file->unlock();
336 
337  return $status;
338  }
339 
345  protected function removeNonexistentFiles( $triplets ) {
346  $files = $filteredTriplets = [];
347  foreach ( $triplets as $file ) {
348  $files[$file[0]] = $file[0];
349  }
350 
351  $result = $this->file->repo->fileExistsBatch( $files );
352  if ( in_array( null, $result, true ) ) {
353  return Status::newFatal( 'backend-fail-internal',
354  $this->file->repo->getBackend()->getName() );
355  }
356 
357  foreach ( $triplets as $file ) {
358  if ( $result[$file[0]] ) {
359  $filteredTriplets[] = $file;
360  }
361  }
362 
363  return Status::newGood( $filteredTriplets );
364  }
365 
371  protected function removeNonexistentFromCleanup( $batch ) {
372  $files = $newBatch = [];
373  $repo = $this->file->repo;
374 
375  foreach ( $batch as $file ) {
376  $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
377  rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
378  }
379 
380  $result = $repo->fileExistsBatch( $files );
381 
382  foreach ( $batch as $file ) {
383  if ( $result[$file] ) {
384  $newBatch[] = $file;
385  }
386  }
387 
388  return $newBatch;
389  }
390 
396  public function cleanup() {
397  if ( !$this->cleanupBatch ) {
398  return $this->file->repo->newGood();
399  }
400 
401  $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
402 
403  $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
404 
405  return $status;
406  }
407 
415  protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
416  $cleanupBatch = [];
417 
418  foreach ( $storeStatus->success as $i => $success ) {
419  // Check if this item of the batch was successfully copied
420  if ( $success ) {
421  // Item was successfully copied and needs to be removed again
422  // Extract ($dstZone, $dstRel) from the batch
423  $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
424  }
425  }
426  $this->file->repo->cleanupBatch( $cleanupBatch );
427  }
428 }
LocalFileRestoreBatch
Helper class for file undeletion.
Definition: LocalFileRestoreBatch.php:30
LocalFileRestoreBatch\$cleanupBatch
string[] $cleanupBatch
List of file IDs to restore.
Definition: LocalFileRestoreBatch.php:35
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
FileRepo\OVERWRITE_SAME
const OVERWRITE_SAME
Definition: FileRepo.php:44
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
LocalFileRestoreBatch\execute
execute()
Run the transaction, except the cleanup batch.
Definition: LocalFileRestoreBatch.php:88
LocalFileRestoreBatch\addId
addId( $fa_id)
Add a file by ID.
Definition: LocalFileRestoreBatch.php:61
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1831
LocalFileRestoreBatch\$ids
string[] $ids
List of file IDs to restore.
Definition: LocalFileRestoreBatch.php:38
LocalFileRestoreBatch\$all
bool $all
Add all revisions of the file.
Definition: LocalFileRestoreBatch.php:41
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:119
ArchivedFile\getQueryInfo
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new archivedfile object.
Definition: ArchivedFile.php:234
LocalFileRestoreBatch\$file
LocalFile $file
Definition: LocalFileRestoreBatch.php:32
$success
$success
Definition: NoLocalSettings.php:42
$wgLang
$wgLang
Definition: Setup.php:777
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:156
LocalRepo\getHashFromKey
static getHashFromKey( $key)
Gets the SHA1 hash from a storage key.
Definition: LocalRepo.php:190
LocalFileRestoreBatch\cleanupFailedBatch
cleanupFailedBatch( $storeStatus, $storeBatch)
Cleanup a failed batch.
Definition: LocalFileRestoreBatch.php:415
SiteStatsUpdate\factory
static factory(array $deltas)
Definition: SiteStatsUpdate.php:71
User\newFromAnyId
static newFromAnyId( $userId, $userName, $actorId, $dbDomain=false)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:656
LocalFileRestoreBatch\addAll
addAll()
Add all revisions of the file.
Definition: LocalFileRestoreBatch.php:76
LocalFileRestoreBatch\$unsuppress
bool $unsuppress
Whether to remove all settings for suppressed fields.
Definition: LocalFileRestoreBatch.php:44
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:914
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:59
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
LocalFileRestoreBatch\__construct
__construct(LocalFile $file, $unsuppress=false)
Definition: LocalFileRestoreBatch.php:50
LocalFileRestoreBatch\addIds
addIds( $ids)
Add a whole lot of files by ID.
Definition: LocalFileRestoreBatch.php:69
LocalFileRestoreBatch\cleanup
cleanup()
Delete unused files in the deleted zone.
Definition: LocalFileRestoreBatch.php:396
LocalFileRestoreBatch\removeNonexistentFiles
removeNonexistentFiles( $triplets)
Removes non-existent files from a store batch.
Definition: LocalFileRestoreBatch.php:345
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:67
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
LocalFileRestoreBatch\removeNonexistentFromCleanup
removeNonexistentFromCleanup( $batch)
Removes non-existent files from a cleanup batch.
Definition: LocalFileRestoreBatch.php:371