3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\MediaWikiServices
;
22 use Wikimedia\Rdbms\ResultWrapper
;
23 use Wikimedia\Rdbms\IDatabase
;
26 * Used to show archived pages and eventually restore them.
33 protected $fileStatus;
36 protected $revisionStatus;
41 public function __construct( $title, Config
$config = null ) {
42 if ( is_null( $title ) ) {
43 throw new MWException( __METHOD__
. ' given a null title.' );
45 $this->title
= $title;
46 if ( $config === null ) {
47 wfDebug( __METHOD__
. ' did not have a Config object passed to it' );
48 $config = MediaWikiServices
::getInstance()->getMainConfig();
50 $this->config
= $config;
53 public function doesWrites() {
58 * List all deleted pages recorded in the archive table. Returns result
59 * wrapper with (ar_namespace, ar_title, count) fields, ordered by page
62 * @return ResultWrapper
64 public static function listAllPages() {
65 $dbr = wfGetDB( DB_REPLICA
);
67 return self
::listPages( $dbr, '' );
71 * List deleted pages recorded in the archive table matching the
73 * Returns result wrapper with (ar_namespace, ar_title, count) fields.
75 * @param string $prefix Title prefix
76 * @return ResultWrapper
78 public static function listPagesByPrefix( $prefix ) {
79 $dbr = wfGetDB( DB_REPLICA
);
81 $title = Title
::newFromText( $prefix );
83 $ns = $title->getNamespace();
84 $prefix = $title->getDBkey();
86 // Prolly won't work too good
87 // @todo handle bare namespace names cleanly?
92 'ar_namespace' => $ns,
93 'ar_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
96 return self
::listPages( $dbr, $conds );
100 * @param IDatabase $dbr
101 * @param string|array $condition
102 * @return bool|ResultWrapper
104 protected static function listPages( $dbr, $condition ) {
110 'count' => 'COUNT(*)'
115 'GROUP BY' => [ 'ar_namespace', 'ar_title' ],
116 'ORDER BY' => [ 'ar_namespace', 'ar_title' ],
123 * List the revisions of the given page. Returns result wrapper with
124 * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
126 * @return ResultWrapper
128 public function listRevisions() {
129 $dbr = wfGetDB( DB_REPLICA
);
131 $tables = [ 'archive' ];
134 'ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text',
135 'ar_comment', 'ar_len', 'ar_deleted', 'ar_rev_id', 'ar_sha1',
138 if ( $this->config
->get( 'ContentHandlerUseDB' ) ) {
139 $fields[] = 'ar_content_format';
140 $fields[] = 'ar_content_model';
143 $conds = [ 'ar_namespace' => $this->title
->getNamespace(),
144 'ar_title' => $this->title
->getDBkey() ];
146 $options = [ 'ORDER BY' => 'ar_timestamp DESC' ];
150 ChangeTags
::modifyDisplayQuery(
159 return $dbr->select( $tables,
169 * List the deleted file revisions for this page, if it's a file page.
170 * Returns a result wrapper with various filearchive fields, or null
171 * if not a file page.
173 * @return ResultWrapper
174 * @todo Does this belong in Image for fuller encapsulation?
176 public function listFiles() {
177 if ( $this->title
->getNamespace() != NS_FILE
) {
181 $dbr = wfGetDB( DB_REPLICA
);
184 ArchivedFile
::selectFields(),
185 [ 'fa_name' => $this->title
->getDBkey() ],
187 [ 'ORDER BY' => 'fa_timestamp DESC' ]
192 * Return a Revision object containing data for the deleted revision.
193 * Note that the result *may* or *may not* have a null page ID.
195 * @param string $timestamp
196 * @return Revision|null
198 public function getRevision( $timestamp ) {
199 $dbr = wfGetDB( DB_REPLICA
);
216 if ( $this->config
->get( 'ContentHandlerUseDB' ) ) {
217 $fields[] = 'ar_content_format';
218 $fields[] = 'ar_content_model';
221 $row = $dbr->selectRow( 'archive',
223 [ 'ar_namespace' => $this->title
->getNamespace(),
224 'ar_title' => $this->title
->getDBkey(),
225 'ar_timestamp' => $dbr->timestamp( $timestamp ) ],
229 return Revision
::newFromArchiveRow( $row, [ 'title' => $this->title
] );
236 * Return the most-previous revision, either live or deleted, against
237 * the deleted revision given by timestamp.
239 * May produce unexpected results in case of history merges or other
240 * unusual time issues.
242 * @param string $timestamp
243 * @return Revision|null Null when there is no previous revision
245 public function getPreviousRevision( $timestamp ) {
246 $dbr = wfGetDB( DB_REPLICA
);
248 // Check the previous deleted revision...
249 $row = $dbr->selectRow( 'archive',
251 [ 'ar_namespace' => $this->title
->getNamespace(),
252 'ar_title' => $this->title
->getDBkey(),
254 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ],
257 'ORDER BY' => 'ar_timestamp DESC',
259 $prevDeleted = $row ?
wfTimestamp( TS_MW
, $row->ar_timestamp
) : false;
261 $row = $dbr->selectRow( [ 'page', 'revision' ],
262 [ 'rev_id', 'rev_timestamp' ],
264 'page_namespace' => $this->title
->getNamespace(),
265 'page_title' => $this->title
->getDBkey(),
266 'page_id = rev_page',
268 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ],
271 'ORDER BY' => 'rev_timestamp DESC',
273 $prevLive = $row ?
wfTimestamp( TS_MW
, $row->rev_timestamp
) : false;
274 $prevLiveId = $row ?
intval( $row->rev_id
) : null;
276 if ( $prevLive && $prevLive > $prevDeleted ) {
277 // Most prior revision was live
278 return Revision
::newFromId( $prevLiveId );
279 } elseif ( $prevDeleted ) {
280 // Most prior revision was deleted
281 return $this->getRevision( $prevDeleted );
284 // No prior revision on this page.
289 * Get the text from an archive row containing ar_text, ar_flags and ar_text_id
291 * @param object $row Database row
294 public function getTextFromRow( $row ) {
295 if ( is_null( $row->ar_text_id
) ) {
296 // An old row from MediaWiki 1.4 or previous.
297 // Text is embedded in this row in classic compression format.
298 return Revision
::getRevisionText( $row, 'ar_' );
301 // New-style: keyed to the text storage backend.
302 $dbr = wfGetDB( DB_REPLICA
);
303 $text = $dbr->selectRow( 'text',
304 [ 'old_text', 'old_flags' ],
305 [ 'old_id' => $row->ar_text_id
],
308 return Revision
::getRevisionText( $text );
312 * Fetch (and decompress if necessary) the stored text of the most
313 * recently edited deleted revision of the page.
315 * If there are no archived revisions for the page, returns NULL.
317 * @return string|null
319 public function getLastRevisionText() {
320 $dbr = wfGetDB( DB_REPLICA
);
321 $row = $dbr->selectRow( 'archive',
322 [ 'ar_text', 'ar_flags', 'ar_text_id' ],
323 [ 'ar_namespace' => $this->title
->getNamespace(),
324 'ar_title' => $this->title
->getDBkey() ],
326 [ 'ORDER BY' => 'ar_timestamp DESC' ] );
329 return $this->getTextFromRow( $row );
336 * Quick check if any archived revisions are present for the page.
340 public function isDeleted() {
341 $dbr = wfGetDB( DB_REPLICA
);
342 $n = $dbr->selectField( 'archive', 'COUNT(ar_title)',
343 [ 'ar_namespace' => $this->title
->getNamespace(),
344 'ar_title' => $this->title
->getDBkey() ],
352 * Restore the given (or all) text and file revisions for the page.
353 * Once restored, the items will be removed from the archive tables.
354 * The deletion log will be updated with an undeletion notice.
356 * This also sets Status objects, $this->fileStatus and $this->revisionStatus
357 * (depending what operations are attempted).
359 * @param array $timestamps Pass an empty array to restore all revisions,
360 * otherwise list the ones to undelete.
361 * @param string $comment
362 * @param array $fileVersions
363 * @param bool $unsuppress
364 * @param User $user User performing the action, or null to use $wgUser
365 * @param string|string[] $tags Change tags to add to log entry
366 * ($user should be able to add the specified tags before this is called)
367 * @return array|bool array(number of file revisions restored, number of image revisions
368 * restored, log message) on success, false on failure.
370 public function undelete( $timestamps, $comment = '', $fileVersions = [],
371 $unsuppress = false, User
$user = null, $tags = null
373 // If both the set of text revisions and file revisions are empty,
374 // restore everything. Otherwise, just restore the requested items.
375 $restoreAll = empty( $timestamps ) && empty( $fileVersions );
377 $restoreText = $restoreAll ||
!empty( $timestamps );
378 $restoreFiles = $restoreAll ||
!empty( $fileVersions );
380 if ( $restoreFiles && $this->title
->getNamespace() == NS_FILE
) {
381 $img = wfLocalFile( $this->title
);
382 $img->load( File
::READ_LATEST
);
383 $this->fileStatus
= $img->restore( $fileVersions, $unsuppress );
384 if ( !$this->fileStatus
->isOK() ) {
387 $filesRestored = $this->fileStatus
->successCount
;
392 if ( $restoreText ) {
393 $this->revisionStatus
= $this->undeleteRevisions( $timestamps, $unsuppress, $comment );
394 if ( !$this->revisionStatus
->isOK() ) {
398 $textRestored = $this->revisionStatus
->getValue();
405 if ( $textRestored && $filesRestored ) {
406 $reason = wfMessage( 'undeletedrevisions-files' )
407 ->numParams( $textRestored, $filesRestored )->inContentLanguage()->text();
408 } elseif ( $textRestored ) {
409 $reason = wfMessage( 'undeletedrevisions' )->numParams( $textRestored )
410 ->inContentLanguage()->text();
411 } elseif ( $filesRestored ) {
412 $reason = wfMessage( 'undeletedfiles' )->numParams( $filesRestored )
413 ->inContentLanguage()->text();
415 wfDebug( "Undelete: nothing undeleted...\n" );
420 if ( trim( $comment ) != '' ) {
421 $reason .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
424 if ( $user === null ) {
429 $logEntry = new ManualLogEntry( 'delete', 'restore' );
430 $logEntry->setPerformer( $user );
431 $logEntry->setTarget( $this->title
);
432 $logEntry->setComment( $reason );
433 $logEntry->setTags( $tags );
435 Hooks
::run( 'ArticleUndeleteLogEntry', [ $this, &$logEntry, $user ] );
437 $logid = $logEntry->insert();
438 $logEntry->publish( $logid );
440 return [ $textRestored, $filesRestored, $reason ];
444 * This is the meaty bit -- It restores archived revisions of the given page
445 * to the revision table.
447 * @param array $timestamps Pass an empty array to restore all revisions,
448 * otherwise list the ones to undelete.
449 * @param bool $unsuppress Remove all ar_deleted/fa_deleted restrictions of seletected revs
450 * @param string $comment
451 * @throws ReadOnlyError
452 * @return Status Status object containing the number of revisions restored on success
454 private function undeleteRevisions( $timestamps, $unsuppress = false, $comment = '' ) {
455 if ( wfReadOnly() ) {
456 throw new ReadOnlyError();
459 $dbw = wfGetDB( DB_MASTER
);
460 $dbw->startAtomic( __METHOD__
);
462 $restoreAll = empty( $timestamps );
464 # Does this page already exist? We'll have to update it...
465 $article = WikiPage
::factory( $this->title
);
466 # Load latest data for the current page (T33179)
467 $article->loadPageData( 'fromdbmaster' );
468 $oldcountable = $article->isCountable();
470 $page = $dbw->selectRow( 'page',
471 [ 'page_id', 'page_latest' ],
472 [ 'page_namespace' => $this->title
->getNamespace(),
473 'page_title' => $this->title
->getDBkey() ],
475 [ 'FOR UPDATE' ] // lock page
480 # Page already exists. Import the history, and if necessary
481 # we'll update the latest revision field in the record.
483 # Get the time span of this page
484 $previousTimestamp = $dbw->selectField( 'revision', 'rev_timestamp',
485 [ 'rev_id' => $page->page_latest
],
488 if ( $previousTimestamp === false ) {
489 wfDebug( __METHOD__
. ": existing page refers to a page_latest that does not exist\n" );
491 $status = Status
::newGood( 0 );
492 $status->warning( 'undeleterevision-missing' );
493 $dbw->endAtomic( __METHOD__
);
498 # Have to create a new article...
500 $previousTimestamp = 0;
504 'ar_namespace' => $this->title
->getNamespace(),
505 'ar_title' => $this->title
->getDBkey(),
507 if ( !$restoreAll ) {
508 $oldWhere['ar_timestamp'] = array_map( [ &$dbw, 'timestamp' ], $timestamps );
529 if ( $this->config
->get( 'ContentHandlerUseDB' ) ) {
530 $fields[] = 'ar_content_format';
531 $fields[] = 'ar_content_model';
535 * Select each archived revision...
537 $result = $dbw->select(
538 [ 'archive', 'revision' ],
543 [ 'ORDER BY' => 'ar_timestamp' ],
544 [ 'revision' => [ 'LEFT JOIN', 'ar_rev_id=rev_id' ] ]
547 $rev_count = $result->numRows();
549 wfDebug( __METHOD__
. ": no revisions to restore\n" );
551 $status = Status
::newGood( 0 );
552 $status->warning( "undelete-no-results" );
553 $dbw->endAtomic( __METHOD__
);
558 // We use ar_id because there can be duplicate ar_rev_id even for the same
559 // page. In this case, we may be able to restore the first one.
560 $restoreFailedArIds = [];
562 // Map rev_id to the ar_id that is allowed to use it. When checking later,
563 // if it doesn't match, the current ar_id can not be restored.
565 // Value can be an ar_id or -1 (-1 means no ar_id can use it, since the
566 // rev_id is taken before we even start the restore).
567 $allowedRevIdToArIdMap = [];
569 $latestRestorableRow = null;
571 foreach ( $result as $row ) {
572 if ( $row->ar_rev_id
) {
573 // rev_id is taken even before we start restoring.
574 if ( $row->ar_rev_id
=== $row->rev_id
) {
575 $restoreFailedArIds[] = $row->ar_id
;
576 $allowedRevIdToArIdMap[$row->ar_rev_id
] = -1;
578 // rev_id is not taken yet in the DB, but it might be taken
579 // by a prior revision in the same restore operation. If
580 // not, we need to reserve it.
581 if ( isset( $allowedRevIdToArIdMap[$row->ar_rev_id
] ) ) {
582 $restoreFailedArIds[] = $row->ar_id
;
584 $allowedRevIdToArIdMap[$row->ar_rev_id
] = $row->ar_id
;
585 $latestRestorableRow = $row;
589 // If ar_rev_id is null, there can't be a collision, and a
590 // rev_id will be chosen automatically.
591 $latestRestorableRow = $row;
595 $result->seek( 0 ); // move back
598 if ( $latestRestorableRow !== null ) {
599 $oldPageId = (int)$latestRestorableRow->ar_page_id
; // pass this to ArticleUndelete hook
601 // grab the content to check consistency with global state before restoring the page.
602 $revision = Revision
::newFromArchiveRow( $latestRestorableRow,
604 'title' => $article->getTitle(), // used to derive default content model
607 $user = User
::newFromName( $revision->getUserText( Revision
::RAW
), false );
608 $content = $revision->getContent( Revision
::RAW
);
610 // NOTE: article ID may not be known yet. prepareSave() should not modify the database.
611 $status = $content->prepareSave( $article, 0, -1, $user );
612 if ( !$status->isOK() ) {
613 $dbw->endAtomic( __METHOD__
);
619 $newid = false; // newly created page ID
620 $restored = 0; // number of revisions restored
621 /** @var Revision $revision */
624 // If there are no restorable revisions, we can skip most of the steps.
625 if ( $latestRestorableRow === null ) {
626 $failedRevisionCount = $rev_count;
629 // Check the state of the newest to-be version...
631 && ( $latestRestorableRow->ar_deleted
& Revision
::DELETED_TEXT
)
633 $dbw->endAtomic( __METHOD__
);
635 return Status
::newFatal( "undeleterevdel" );
637 // Safe to insert now...
638 $newid = $article->insertOn( $dbw, $latestRestorableRow->ar_page_id
);
639 if ( $newid === false ) {
640 // The old ID is reserved; let's pick another
641 $newid = $article->insertOn( $dbw );
645 // Check if a deleted revision will become the current revision...
646 if ( $latestRestorableRow->ar_timestamp
> $previousTimestamp ) {
647 // Check the state of the newest to-be version...
649 && ( $latestRestorableRow->ar_deleted
& Revision
::DELETED_TEXT
)
651 $dbw->endAtomic( __METHOD__
);
653 return Status
::newFatal( "undeleterevdel" );
658 $pageId = $article->getId();
661 foreach ( $result as $row ) {
662 // Check for key dupes due to needed archive integrity.
663 if ( $row->ar_rev_id
&& $allowedRevIdToArIdMap[$row->ar_rev_id
] !== $row->ar_id
) {
666 // Insert one revision at a time...maintaining deletion status
667 // unless we are specifically removing all restrictions...
668 $revision = Revision
::newFromArchiveRow( $row,
671 'title' => $this->title
,
672 'deleted' => $unsuppress ?
0 : $row->ar_deleted
675 $revision->insertOn( $dbw );
678 Hooks
::run( 'ArticleRevisionUndeleted',
679 [ &$this->title
, $revision, $row->ar_page_id
] );
682 // Now that it's safely stored, take it out of the archive
683 // Don't delete rows that we failed to restore
684 $toDeleteConds = $oldWhere;
685 $failedRevisionCount = count( $restoreFailedArIds );
686 if ( $failedRevisionCount > 0 ) {
687 $toDeleteConds[] = 'ar_id NOT IN ( ' . $dbw->makeList( $restoreFailedArIds ) . ' )';
690 $dbw->delete( 'archive',
695 $status = Status
::newGood( $restored );
697 if ( $failedRevisionCount > 0 ) {
699 wfMessage( 'undeleterevision-duplicate-revid', $failedRevisionCount ) );
702 // Was anything restored at all?
704 $created = (bool)$newid;
705 // Attach the latest revision to the page...
706 $wasnew = $article->updateIfNewerOn( $dbw, $revision );
707 if ( $created ||
$wasnew ) {
708 // Update site stats, link tables, etc
709 $article->doEditUpdates(
711 User
::newFromName( $revision->getUserText( Revision
::RAW
), false ),
713 'created' => $created,
714 'oldcountable' => $oldcountable,
720 Hooks
::run( 'ArticleUndelete', [ &$this->title
, $created, $comment, $oldPageId ] );
721 if ( $this->title
->getNamespace() == NS_FILE
) {
722 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->title
, 'imagelinks' ) );
726 $dbw->endAtomic( __METHOD__
);
734 public function getFileStatus() {
735 return $this->fileStatus
;
741 public function getRevisionStatus() {
742 return $this->revisionStatus
;