30use Psr\Log\LoggerInterface;
32use Wikimedia\Assert\Assert;
33use Wikimedia\Message\ITextFormatter;
34use Wikimedia\Message\MessageValue;
35use Wikimedia\Rdbms\IConnectionProvider;
36use Wikimedia\Rdbms\IDatabase;
37use Wikimedia\Rdbms\IDBAccessObject;
38use Wikimedia\Rdbms\ReadOnlyMode;
39use Wikimedia\Timestamp\TimestampFormat as TS;
49 public const FILES_RESTORED =
'files';
50 public const REVISIONS_RESTORED =
'revs';
55 private $revisionStatus;
57 private $timestamps = [];
59 private $fileVersions = [];
61 private $unsuppress =
false;
65 private $associatedTalk;
67 private HookRunner $hookRunner;
68 private JobQueueGroup $jobQueueGroup;
69 private IConnectionProvider $dbProvider;
70 private ReadOnlyMode $readOnlyMode;
71 private RepoGroup $repoGroup;
72 private LoggerInterface
$logger;
73 private RevisionStore $revisionStore;
74 private WikiPageFactory $wikiPageFactory;
75 private PageUpdaterFactory $pageUpdaterFactory;
76 private IContentHandlerFactory $contentHandlerFactory;
77 private ArchivedRevisionLookup $archivedRevisionLookup;
78 private NamespaceInfo $namespaceInfo;
79 private ITextFormatter $contLangMsgTextFormatter;
80 private ProperPageIdentity $page;
81 private Authority $performer;
87 HookContainer $hookContainer,
88 JobQueueGroup $jobQueueGroup,
89 IConnectionProvider $dbProvider,
90 ReadOnlyMode $readOnlyMode,
92 LoggerInterface $logger,
93 RevisionStore $revisionStore,
94 WikiPageFactory $wikiPageFactory,
95 PageUpdaterFactory $pageUpdaterFactory,
96 IContentHandlerFactory $contentHandlerFactory,
97 ArchivedRevisionLookup $archivedRevisionLookup,
98 NamespaceInfo $namespaceInfo,
99 ITextFormatter $contLangMsgTextFormatter,
100 ProperPageIdentity $page,
103 $this->hookRunner =
new HookRunner( $hookContainer );
104 $this->jobQueueGroup = $jobQueueGroup;
105 $this->dbProvider = $dbProvider;
106 $this->readOnlyMode = $readOnlyMode;
107 $this->repoGroup = $repoGroup;
109 $this->revisionStore = $revisionStore;
110 $this->wikiPageFactory = $wikiPageFactory;
111 $this->pageUpdaterFactory = $pageUpdaterFactory;
112 $this->contentHandlerFactory = $contentHandlerFactory;
113 $this->archivedRevisionLookup = $archivedRevisionLookup;
114 $this->namespaceInfo = $namespaceInfo;
115 $this->contLangMsgTextFormatter = $contLangMsgTextFormatter;
118 $this->performer = $performer;
127 public function setUnsuppress(
bool $unsuppress ): self {
128 $this->unsuppress = $unsuppress;
138 public function setTags( array $tags ): self {
149 public function setUndeleteOnlyTimestamps( array $timestamps ): self {
150 $this->timestamps = $timestamps;
160 public function setUndeleteOnlyFileVersions( array $fileVersions ): self {
161 $this->fileVersions = $fileVersions;
170 public function canProbablyUndeleteAssociatedTalk(): StatusValue {
171 if ( $this->namespaceInfo->isTalk( $this->page->getNamespace() ) ) {
175 $thisWikiPage = $this->wikiPageFactory->newFromTitle( $this->page );
176 $talkPage = $this->wikiPageFactory->newFromLinkTarget(
177 $this->namespaceInfo->getTalkPage( $thisWikiPage->getTitle() )
180 if ( !$this->archivedRevisionLookup->hasArchivedRevisions( $talkPage ) ) {
192 public function setUndeleteAssociatedTalk(
bool $undelete ): self {
194 $this->associatedTalk =
null;
199 $thisWikiPage = $this->wikiPageFactory->newFromTitle( $this->page );
200 $this->associatedTalk = $this->wikiPageFactory->newFromLinkTarget(
201 $this->namespaceInfo->getTalkPage( $thisWikiPage->getTitle() )
212 public function undeleteIfAllowed(
string $comment ): StatusValue {
213 $status = $this->authorizeUndeletion();
214 if ( !$status->isGood() ) {
218 return $this->undeleteUnsafe( $comment );
221 private function authorizeUndeletion(): PermissionStatus {
222 $status = PermissionStatus::newEmpty();
223 $this->performer->authorizeWrite(
'undelete', $this->page, $status );
224 if ( $this->associatedTalk ) {
225 $this->performer->authorizeWrite(
'undelete', $this->associatedTalk, $status );
228 $status->merge( ChangeTags::canAddTagsAccompanyingChange( $this->tags, $this->performer ) );
251 public function undeleteUnsafe(
string $comment ): StatusValue {
252 $hookStatus = $this->runPreUndeleteHook( $comment );
253 if ( !$hookStatus->isGood() ) {
258 $restoreAll = $this->timestamps === [] && $this->fileVersions === [];
260 $restoreText = $restoreAll || $this->timestamps !== [];
261 $restoreFiles = $restoreAll || $this->fileVersions !== [];
263 $resStatus = StatusValue::newGood();
265 if ( $restoreFiles && $this->page->getNamespace() ===
NS_FILE ) {
267 $img = $this->repoGroup->getLocalRepo()->newFile( $this->page );
268 $img->load( IDBAccessObject::READ_LATEST );
269 $this->fileStatus = $img->restore( $this->fileVersions, $this->unsuppress );
270 if ( !$this->fileStatus->isOK() ) {
271 return $this->fileStatus;
273 $filesRestored = $this->fileStatus->successCount;
274 $resStatus->merge( $this->fileStatus );
278 $pageCreated =
false;
279 $restoredRevision =
null;
280 $restoredPageIds = [];
281 if ( $restoreText ) {
283 $acceptNoRevisions = $filesRestored > 0;
284 $this->revisionStatus = $this->undeleteRevisions(
285 $this->page, $this->timestamps,
286 $comment, $acceptNoRevisions
288 if ( !$this->revisionStatus->isOK() ) {
291 return $this->revisionStatus;
294 [ $textRestored, $pageCreated, $restoredRevision, $restoredPageIds ] = $this->revisionStatus->getValue();
295 $resStatus->merge( $this->revisionStatus );
299 $talkCreated =
false;
300 $restoredTalkRevision =
null;
301 $restoredTalkPageIds = [];
302 if ( $this->associatedTalk ) {
303 $talkStatus = $this->canProbablyUndeleteAssociatedTalk();
305 if ( $talkStatus->isGood() && $resStatus->isGood() ) {
306 $talkStatus = $this->undeleteRevisions( $this->associatedTalk, [], $comment,
false );
307 if ( !$talkStatus->isOK() ) {
312 [ $talkRestored, $talkCreated, $restoredTalkRevision, $restoredTalkPageIds ] = $talkStatus->getValue();
316 foreach ( $talkStatus->getMessages() as $msg ) {
317 $resStatus->warning( $msg );
322 $resStatus->value = [
323 self::REVISIONS_RESTORED => $textRestored + $talkRestored,
324 self::FILES_RESTORED => $filesRestored
327 if ( !$textRestored && !$filesRestored && !$talkRestored ) {
328 $this->logger->debug(
"Undelete: nothing undeleted..." );
332 if ( $textRestored || $filesRestored ) {
333 $logEntry = $this->addLogEntry( $this->page, $comment, $textRestored, $filesRestored );
335 if ( $textRestored ) {
336 $this->hookRunner->onPageUndeleteComplete(
350 if ( $talkRestored ) {
351 $talkRestoredComment = $this->contLangMsgTextFormatter->format(
352 MessageValue::new(
'undelete-talk-summary-prefix' )->plaintextParams( $comment )
354 $logEntry = $this->addLogEntry( $this->associatedTalk, $talkRestoredComment, $talkRestored, 0 );
356 $this->hookRunner->onPageUndeleteComplete(
357 $this->associatedTalk,
359 $talkRestoredComment,
361 $restoredTalkRevision,
375 private function runPreUndeleteHook(
string $comment ): StatusValue {
376 $checkPages = [ $this->page ];
377 if ( $this->associatedTalk ) {
378 $checkPages[] = $this->associatedTalk;
380 foreach ( $checkPages as $page ) {
382 $hookRes = $this->hookRunner->onPageUndelete(
391 if ( !$hookRes && !$hookStatus->isGood() ) {
396 return Status::newGood();
407 private function addLogEntry(
408 ProperPageIdentity $page,
413 $logEntry = new ManualLogEntry(
'delete',
'restore' );
414 $logEntry->setPerformer( $this->performer->getUser() );
415 $logEntry->setTarget( $page );
416 $logEntry->setComment( $comment );
417 $logEntry->addTags( $this->tags );
418 $logEntry->setParameters( [
420 'revisions' => $textRestored,
421 'files' => $filesRestored,
425 $logid = $logEntry->insert();
426 $logEntry->publish( $logid );
443 private function undeleteRevisions(
444 ProperPageIdentity $page, array $timestamps,
445 string $comment,
bool $acceptNoRevisions
447 if ( $this->readOnlyMode->isReadOnly() ) {
448 throw new ReadOnlyError();
451 $dbw = $this->dbProvider->getPrimaryDatabase();
452 $dbw->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
455 'ar_namespace' => $page->getNamespace(),
456 'ar_title' => $page->getDBkey(),
459 $oldWhere[
'ar_timestamp'] = array_map( $dbw->timestamp( ... ), $timestamps );
462 $revisionStore = $this->revisionStore;
463 $result = $revisionStore->newArchiveSelectQueryBuilder( $dbw )
465 ->leftJoin(
'revision',
null,
'ar_rev_id=rev_id' )
468 ->orderBy(
'ar_timestamp' )
469 ->caller( __METHOD__ )->fetchResultSet();
471 $rev_count = $result->numRows();
473 $this->logger->debug( __METHOD__ .
": no revisions to restore" );
477 $status = Status::newGood( [ 0,
false,
null, [] ] );
478 if ( !$acceptNoRevisions ) {
479 $status->error(
"undelete-no-results" );
481 $dbw->endAtomic( __METHOD__ );
486 $result->seek( $rev_count - 1 );
487 $latestRestorableRow = $result->current();
492 $wikiPage = $this->wikiPageFactory->newFromTitle( $page );
495 $oldcountable =
false;
496 $updatedCurrentRevision =
false;
497 $restoredRevCount = 0;
501 $oldPageId = (int)$latestRestorableRow->ar_page_id;
506 $revision = $revisionStore->newRevisionFromArchiveRow(
507 $latestRestorableRow,
512 foreach ( $revision->getSlotRoles() as $role ) {
513 $content = $revision->getContent( $role, RevisionRecord::RAW );
515 $contentHandler = $this->contentHandlerFactory->getContentHandler( $content->getModel() );
516 $validationParams =
new ValidationParams( $wikiPage, 0 );
518 $status = $contentHandler->validateSave( $content, $validationParams );
519 if ( !$status->isOK() ) {
520 $dbw->endAtomic( __METHOD__ );
527 $updater = $this->pageUpdaterFactory->newDerivedPageDataUpdater( $wikiPage );
528 $updater->grabLatestRevision();
530 $pageId = $wikiPage->insertOn( $dbw, $latestRestorableRow->ar_page_id );
531 if ( $pageId ===
false ) {
533 $pageId = $wikiPage->insertOn( $dbw );
534 if ( $pageId ===
false ) {
540 # Does this page already exist? We'll have to update it...
542 # Load latest data for the current page (T33179)
543 $wikiPage->loadPageData( IDBAccessObject::READ_EXCLUSIVE );
544 $pageId = $wikiPage->getId();
545 $oldcountable = $wikiPage->isCountable();
547 $previousTimestamp =
false;
548 $latestRevId = $wikiPage->getLatest();
549 if ( $latestRevId ) {
550 $previousTimestamp = $revisionStore->getTimestampFromId(
552 IDBAccessObject::READ_LATEST
555 if ( $previousTimestamp ===
false ) {
556 $this->logger->debug( __METHOD__ .
": existing page refers to a page_latest that does not exist" );
560 $status = Status::newGood( [ 0,
false,
null, [] ] );
561 $status->error(
'undeleterevision-missing' );
562 $dbw->cancelAtomic( __METHOD__ );
567 $previousTimestamp = 0;
571 $page = PageIdentityValue::localIdentity(
573 $page->getNamespace(),
577 Assert::postcondition( $page->exists(),
'The page should exist now' );
580 $latestRestorableRowTimestamp =
wfTimestamp( TS::MW, $latestRestorableRow->ar_timestamp );
581 if ( $latestRestorableRowTimestamp > $previousTimestamp ) {
583 if ( !$this->unsuppress
584 && ( $latestRestorableRow->ar_deleted & RevisionRecord::DELETED_TEXT )
586 $dbw->cancelAtomic( __METHOD__ );
588 return Status::newFatal(
"undeleterevdel" );
590 $updatedCurrentRevision =
true;
593 foreach ( $result as $row ) {
596 $revision = $revisionStore->newRevisionFromArchiveRow(
601 'page_id' => $pageId,
602 'deleted' => $this->unsuppress ? 0 : $row->ar_deleted
607 $revision = $revisionStore->insertRevisionOn( $revision, $dbw );
611 $this->hookRunner->onRevisionUndeleted( $revision, $row->ar_page_id );
613 $restoredPages[$row->ar_page_id] =
true;
617 $dbw->newDeleteQueryBuilder()
618 ->deleteFrom(
'archive' )
620 ->caller( __METHOD__ )->execute();
624 $status = Status::newGood( [ $restoredRevCount, $created, $revision, $restoredPages ] );
627 if ( $restoredRevCount ) {
629 if ( $updatedCurrentRevision ) {
632 $wasnew = $wikiPage->updateRevisionOn(
635 $created ? 0 : $wikiPage->getLatest()
641 if ( $created || $wasnew ) {
644 PageLatestRevisionChangedEvent::FLAG_SILENT =>
true,
645 PageLatestRevisionChangedEvent::FLAG_IMPLICIT =>
true,
646 'created' => $created,
647 'oldcountable' => $oldcountable,
651 $updater->setCause( PageUpdater::CAUSE_UNDELETE );
652 $updater->setPerformer( $this->performer->getUser() );
653 $updater->prepareUpdate( $revision, $options );
654 $updater->doUpdates();
657 $this->hookRunner->onArticleUndelete(
658 $wikiPage->getTitle(), $created, $comment, $oldPageId, $restoredPages );
660 if ( $page->getNamespace() ===
NS_FILE ) {
661 $job = HTMLCacheUpdateJob::newForBacklinks(
664 [
'causeAction' =>
'undelete-file' ]
666 $this->jobQueueGroup->lazyPush(
$job );
670 $dbw->endAtomic( __METHOD__ );
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
if(!defined('MW_SETUP_CALLBACK'))
setTags( $tags)
Specify the tags the user wants to add, and check permissions.
Class for creating new log entries and inserting them into the database.
Domain event representing a change to the page's latest revision.
A factory for PageUpdater and DerivedPageDataUpdater instances.
Controller-like object for creating and updating pages by creating new revisions.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
static newGood( $value=null)
Factory function for good results.
if(count( $args)< 1) $job