MediaWiki master
ImportableOldRevisionImporter.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Import;
4
5use InvalidArgumentException;
18use Psr\Log\LoggerInterface;
19use RuntimeException;
23
28
29 private readonly WikiPageFactory $wikiPageFactory;
30 private readonly PageUpdaterFactory $pageUpdaterFactory;
31 private readonly UserFactory $userFactory;
32
33 public function __construct(
34 private readonly bool $doUpdates,
35 private readonly LoggerInterface $logger,
36 private readonly IConnectionProvider $dbProvider,
37 private readonly RevisionStore $revisionStore,
38 private readonly SlotRoleRegistry $slotRoleRegistry,
39 ?WikiPageFactory $wikiPageFactory = null,
40 ?PageUpdaterFactory $pageUpdaterFactory = null,
41 ?UserFactory $userFactory = null,
42 ) {
44 // @todo: temporary - remove when FileImporter extension is updated
45 $this->wikiPageFactory = $wikiPageFactory ?? $services->getWikiPageFactory();
46 $this->pageUpdaterFactory = $pageUpdaterFactory ?? $services->getPageUpdaterFactory();
47 $this->userFactory = $userFactory ?? $services->getUserFactory();
48 }
49
51 public function import( ImportableOldRevision $importableRevision, $doUpdates = true ) {
52 $dbw = $this->dbProvider->getPrimaryDatabase();
53
54 # Sneak a single revision into place
55 $user = $importableRevision->getUserObj() ?: $this->userFactory->newFromName( $importableRevision->getUser() );
56 if ( $user ) {
57 $userId = $user->getId();
58 $userText = $user->getName();
59 } else {
60 $userId = 0;
61 $userText = $importableRevision->getUser();
62 }
63
64 // avoid memory leak...?
65 Title::clearCaches();
66
67 $page = $this->wikiPageFactory->newFromTitle( $importableRevision->getTitle() );
68 $page->loadPageData( IDBAccessObject::READ_LATEST );
69 $mustCreatePage = !$page->exists();
70 if ( $mustCreatePage ) {
71 $pageId = $page->insertOn( $dbw );
72 } else {
73 $pageId = $page->getId();
74
75 // Note: sha1 has been in XML dumps since 2012. If you have an
76 // older dump, the duplicate detection here won't work.
77 $importContentHash = $importableRevision->getSha1Base36();
78
79 if ( $importContentHash ) {
80 // Get revision IDs for the page at the given timestamp
81 $revIds = $dbw->newSelectQueryBuilder()
82 ->select( 'rev_id' )
83 ->from( 'revision' )
84 ->where( [
85 'rev_page' => $pageId,
86 'rev_timestamp' => $dbw->timestamp( $importableRevision->getTimestamp() ),
87 ] )
88 ->caller( __METHOD__ )
89 ->fetchFieldValues();
90
91 foreach ( $revIds as $revId ) {
92 $revision = $this->revisionStore->getRevisionById( $revId );
93 if ( !$revision ) {
94 throw new RuntimeException( "Revision $revId not found" );
95 }
96
97 if ( $revision->getSha1() === $importContentHash ) {
98 $this->logger->debug( __METHOD__ . ": skipping existing revision for [[" .
99 $importableRevision->getTitle()->getPrefixedText() . "]], timestamp " .
100 $importableRevision->getTimestamp() . "\n" );
101 return false;
102 }
103 }
104 }
105 }
106
107 if ( !$pageId ) {
108 // This seems to happen if two clients simultaneously try to import the
109 // same page
110 $this->logger->debug( __METHOD__ . ': got invalid $pageId when importing revision of [[' .
111 $importableRevision->getTitle()->getPrefixedText() . ']], timestamp ' .
112 $importableRevision->getTimestamp() . "\n" );
113 return false;
114 }
115
116 // Select previous version to make size diffs correct
117 // @todo This assumes that multiple revisions of the same page are imported
118 // in order from oldest to newest.
119 $queryBuilder = $this->revisionStore->newSelectQueryBuilder( $dbw )
120 ->joinComment()
121 ->where( [ 'rev_page' => $pageId ] )
122 ->andWhere( $dbw->expr(
123 'rev_timestamp', '<=', $dbw->timestamp( $importableRevision->getTimestamp() )
124 ) )
125 ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_DESC );
126 $prevRevRow = $queryBuilder->caller( __METHOD__ )->fetchRow();
127
128 # @todo FIXME: Use original rev_id optionally (better for backups)
129 # Insert the row
130 $revisionRecord = new MutableRevisionRecord( $importableRevision->getTitle() );
131 $revisionRecord->setParentId( $prevRevRow ? (int)$prevRevRow->rev_id : 0 );
132 $revisionRecord->setComment(
133 CommentStoreComment::newUnsavedComment( $importableRevision->getComment() )
134 );
135
136 try {
137 $revUser = $this->userFactory->newFromAnyId( $userId, $userText );
138 } catch ( InvalidArgumentException ) {
139 $revUser = RequestContext::getMain()->getUser();
140 }
141 $revisionRecord->setUser( $revUser );
142
143 $originalRevision = $prevRevRow
144 ? $this->revisionStore->newRevisionFromRow(
145 $prevRevRow,
146 IDBAccessObject::READ_LATEST,
147 $importableRevision->getTitle()
148 )
149 : null;
150
151 foreach ( $importableRevision->getSlotRoles() as $role ) {
152 if ( !$this->slotRoleRegistry->isDefinedRole( $role ) ) {
153 throw new RuntimeException( "Undefined slot role $role" );
154 }
155
156 $newContent = $importableRevision->getContent( $role );
157 if ( !$originalRevision || !$originalRevision->hasSlot( $role ) ) {
158 $revisionRecord->setContent( $role, $newContent );
159 } else {
160 $originalSlot = $originalRevision->getSlot( $role );
161 if ( !$originalSlot->hasSameContent( $importableRevision->getSlot( $role ) ) ) {
162 $revisionRecord->setContent( $role, $newContent );
163 } else {
164 $revisionRecord->inheritSlot( $originalRevision->getSlot( $role ) );
165 }
166 }
167 }
168
169 $revisionRecord->setTimestamp( $importableRevision->getTimestamp() );
170 $revisionRecord->setMinorEdit( $importableRevision->getMinor() );
171 $revisionRecord->setPageId( $pageId );
172
173 $updater = $this->pageUpdaterFactory->newDerivedPageDataUpdater( $page );
174 $latestRev = $updater->grabLatestRevision();
175 $latestRevId = $latestRev ? $latestRev->getId() : null;
176
177 $inserted = $this->revisionStore->insertRevisionOn( $revisionRecord, $dbw );
178 if ( $latestRev ) {
179 // If not found (false), cast to 0 so that the page is updated
180 // Just to be on the safe side, even though it should always be found
181 $latestRevTimestamp = $latestRev->getTimestamp();
182 } else {
183 $latestRevTimestamp = 0;
184 }
185 if ( $importableRevision->getTimestamp() >= $latestRevTimestamp ) {
186 $changed = $page->updateRevisionOn( $dbw, $inserted, $latestRevId );
187 } else {
188 $changed = false;
189 }
190
191 $tags = $importableRevision->getTags();
192 if ( $tags !== [] ) {
193 MediaWikiServices::getInstance()->getChangeTagsStore()->addTags( $tags, null, $inserted->getId() );
194 }
195
196 if ( $changed !== false && $this->doUpdates ) {
197 $this->logger->debug( __METHOD__ . ": running updates" );
198 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
199
200 $options = [
201 PageLatestRevisionChangedEvent::FLAG_SILENT => true,
202 PageLatestRevisionChangedEvent::FLAG_IMPLICIT => true,
203 'created' => $mustCreatePage,
204 'oldcountable' => 'no-change',
205 ];
206
207 $updater->setCause( PageUpdater::CAUSE_IMPORT );
208 $updater->setPerformer( RequestContext::getMain()->getUser() );
209 $updater->prepareUpdate( $inserted, $options );
210 $updater->doUpdates();
211 }
212
213 return true;
214 }
215
216}
217
219class_alias( ImportableOldRevisionImporter::class, 'ImportableOldRevisionImporter' );
Value object for a comment stored by CommentStore.
Group all the pieces relevant to the context of a request into one instance.
__construct(private readonly bool $doUpdates, private readonly LoggerInterface $logger, private readonly IConnectionProvider $dbProvider, private readonly RevisionStore $revisionStore, private readonly SlotRoleRegistry $slotRoleRegistry, ?WikiPageFactory $wikiPageFactory=null, ?PageUpdaterFactory $pageUpdaterFactory=null, ?UserFactory $userFactory=null,)
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Domain event representing a change to the page's latest revision.
Service for creating WikiPage objects.
Service for looking up page revisions.
A registry service for SlotRoleHandlers, used to define which slot roles are available on which page.
A factory for PageUpdater and DerivedPageDataUpdater instances.
Controller-like object for creating and updating pages by creating new revisions.
Represents a title within MediaWiki.
Definition Title.php:69
Create User objects.
Build SELECT queries with a fluent interface.
getContent( $role=SlotRecord::MAIN)
Provide primary and replica IDatabase connections.
Interface for database access objects.