Debian Codegraph @

includes/page/RollbackPage.php

raw symbols SCIP
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Page;
22
23 use ManualLogEntry;
24 use MediaWiki\CommentStore\CommentStoreComment;
25 use MediaWiki\Config\ServiceOptions;
26 use MediaWiki\HookContainer\HookContainer;
27 use MediaWiki\HookContainer\HookRunner;
28 use MediaWiki\Language\RawMessage;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\Message\Converter;
31 use MediaWiki\Message\Message;
32 use MediaWiki\Permissions\Authority;
33 use MediaWiki\Permissions\PermissionStatus;
34 use MediaWiki\Revision\RevisionRecord;
35 use MediaWiki\Revision\RevisionStore;
36 use MediaWiki\Revision\SlotRecord;
37 use MediaWiki\Storage\EditResult;
38 use MediaWiki\Title\TitleFormatter;
39 use MediaWiki\Title\TitleValue;
40 use MediaWiki\User\ActorMigration;
41 use MediaWiki\User\ActorNormalization;
42 use MediaWiki\User\UserFactory;
43 use MediaWiki\User\UserIdentity;
44 use RecentChange;
45 use StatusValue;
46 use Wikimedia\Message\MessageValue;
47 use Wikimedia\Rdbms\IConnectionProvider;
48 use Wikimedia\Rdbms\IDatabase;
49 use Wikimedia\Rdbms\IDBAccessObject;
50 use Wikimedia\Rdbms\ReadOnlyMode;
51 use Wikimedia\Rdbms\SelectQueryBuilder;
52
53 /**
54 * Backend logic for performing a page rollback action.
55 *
56 * @since 1.37
57 */
58 class RollbackPage {
59
60 /**
61 * @internal For use in PageCommandFactory only
62 */
63 public const CONSTRUCTOR_OPTIONS = [
64 MainConfigNames::UseRCPatrol,
65 MainConfigNames::DisableAnonTalk,
66 ];
67
68 /** @var string */
69 private $summary = '';
70
71 /** @var bool */
72 private $bot = false;
73
74 /** @var string[] */
75 private $tags = [];
76
77 private ServiceOptions $options;
78 private IConnectionProvider $dbProvider;
79 private UserFactory $userFactory;
80 private ReadOnlyMode $readOnlyMode;
81 private RevisionStore $revisionStore;
82 private TitleFormatter $titleFormatter;
83 private HookRunner $hookRunner;
84 private WikiPageFactory $wikiPageFactory;
85 private ActorMigration $actorMigration;
86 private ActorNormalization $actorNormalization;
87 private PageIdentity $page;
88 private Authority $performer;
89 /** @var UserIdentity who made the edits we are rolling back */
90 private UserIdentity $byUser;
91
92 /**
93 * @internal Create via the RollbackPageFactory service.
94 */
95 public function __construct(
96 ServiceOptions $options,
97 IConnectionProvider $dbProvider,
98 UserFactory $userFactory,
99 ReadOnlyMode $readOnlyMode,
100 RevisionStore $revisionStore,
101 TitleFormatter $titleFormatter,
102 HookContainer $hookContainer,
103 WikiPageFactory $wikiPageFactory,
104 ActorMigration $actorMigration,
105 ActorNormalization $actorNormalization,
106 PageIdentity $page,
107 Authority $performer,
108 UserIdentity $byUser
109 ) {
110 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
111 $this->options = $options;
112 $this->dbProvider = $dbProvider;
113 $this->userFactory = $userFactory;
114 $this->readOnlyMode = $readOnlyMode;
115 $this->revisionStore = $revisionStore;
116 $this->titleFormatter = $titleFormatter;
117 $this->hookRunner = new HookRunner( $hookContainer );
118 $this->wikiPageFactory = $wikiPageFactory;
119 $this->actorMigration = $actorMigration;
120 $this->actorNormalization = $actorNormalization;
121
122 $this->page = $page;
123 $this->performer = $performer;
124 $this->byUser = $byUser;
125 }
126
127 /**
128 * Set custom edit summary.
129 *
130 * @param string|null $summary
131 * @return $this
132 */
133 public function setSummary( ?string $summary ): self {
134 $this->summary = $summary ?? '';
135 return $this;
136 }
137
138 /**
139 * Mark all reverted edits as bot.
140 *
141 * @param bool|null $bot
142 * @return $this
143 */
144 public function markAsBot( ?bool $bot ): self {
145 if ( $bot && $this->performer->isAllowedAny( 'markbotedits', 'bot' ) ) {
146 $this->bot = true;
147 } elseif ( !$bot ) {
148 $this->bot = false;
149 }
150 return $this;
151 }
152
153 /**
154 * Change tags to apply to the rollback.
155 *
156 * @note Callers are responsible for permission checks (with ChangeTags::canAddTagsAccompanyingChange)
157 *
158 * @param string[]|null $tags
159 * @return $this
160 */
161 public function setChangeTags( ?array $tags ): self {
162 $this->tags = $tags ?: [];
163 return $this;
164 }
165
166 /**
167 * Authorize the rollback.
168 *
169 * @return PermissionStatus
170 */
171 public function authorizeRollback(): PermissionStatus {
172 $permissionStatus = PermissionStatus::newEmpty();
173 $this->performer->authorizeWrite( 'edit', $this->page, $permissionStatus );
174 $this->performer->authorizeWrite( 'rollback', $this->page, $permissionStatus );
175
176 if ( $this->readOnlyMode->isReadOnly() ) {
177 $permissionStatus->fatal( 'readonlytext' );
178 }
179
180 return $permissionStatus;
181 }
182
183 /**
184 * Rollback the most recent consecutive set of edits to a page
185 * from the same user; fails if there are no eligible edits to
186 * roll back to, e.g. user is the sole contributor. This function
187 * performs permissions checks and executes ::rollback.
188 *
189 * @return StatusValue see ::rollback for return value documentation.
190 * In case the rollback is not allowed, PermissionStatus is returned.
191 */
192 public function rollbackIfAllowed(): StatusValue {
193 $permissionStatus = $this->authorizeRollback();
194 if ( !$permissionStatus->isGood() ) {
195 return $permissionStatus;
196 }
197 return $this->rollback();
198 }
199
200 /**
201 * Backend implementation of rollbackIfAllowed().
202 *
203 * @note This function does NOT check ANY permissions, it just commits the
204 * rollback to the DB. Therefore, you should only call this function directly
205 * if you want to use custom permissions checks. If you don't, use
206 * ::rollbackIfAllowed() instead.
207 *
208 * @return StatusValue On success, wrapping the array with the following keys:
209 * 'summary' - rollback edit summary
210 * 'current-revision-record' - revision record that was current before rollback
211 * 'target-revision-record' - revision record we are rolling back to
212 * 'newid' => the id of the rollback revision
213 * 'tags' => the tags applied to the rollback
214 */
215 public function rollback() {
216 // Begin revision creation cycle by creating a PageUpdater.
217 // If the page is changed concurrently after grabParentRevision(), the rollback will fail.
218 // TODO: move PageUpdater to PageStore or PageUpdaterFactory or something?
219 $updater = $this->wikiPageFactory->newFromTitle( $this->page )->newPageUpdater( $this->performer );
220 $currentRevision = $updater->grabParentRevision();
221
222 if ( !$currentRevision ) {
223 // Something wrong... no page?
224 return StatusValue::newFatal( 'notanarticle' );
225 }
226
227 $currentEditor = $currentRevision->getUser( RevisionRecord::RAW );
228 $currentEditorForPublic = $currentRevision->getUser( RevisionRecord::FOR_PUBLIC );
229 // User name given should match up with the top revision.
230 if ( !$this->byUser->equals( $currentEditor ) ) {
231 $result = StatusValue::newGood( [
232 'current-revision-record' => $currentRevision
233 ] );
234 $result->fatal(
235 'alreadyrolled',
236 htmlspecialchars( $this->titleFormatter->getPrefixedText( $this->page ) ),
237 htmlspecialchars( $this->byUser->getName() ),
238 htmlspecialchars( $currentEditorForPublic ? $currentEditorForPublic->getName() : '' )
239 );
240 return $result;
241 }
242
243 $dbw = $this->dbProvider->getPrimaryDatabase();
244
245 // Get the last edit not by this person...
246 // Note: these may not be public values
247 $actorWhere = $this->actorMigration->getWhere( $dbw, 'rev_user', $currentEditor );
248 $queryBuilder = $this->revisionStore->newSelectQueryBuilder( $dbw )
249 ->where( [ 'rev_page' => $currentRevision->getPageId(), 'NOT(' . $actorWhere['conds'] . ')' ] )
250 ->useIndex( [ 'revision' => 'rev_page_timestamp' ] )
251 ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_DESC );
252 $targetRevisionRow = $queryBuilder->caller( __METHOD__ )->fetchRow();
253
254 if ( $targetRevisionRow === false ) {
255 // No one else ever edited this page
256 return StatusValue::newFatal( 'cantrollback' );
257 } elseif ( $targetRevisionRow->rev_deleted & RevisionRecord::DELETED_TEXT
258 || $targetRevisionRow->rev_deleted & RevisionRecord::DELETED_USER
259 ) {
260 // Only admins can see this text
261 return StatusValue::newFatal( 'notvisiblerev' );
262 }
263
264 // Generate the edit summary if necessary
265 $targetRevision = $this->revisionStore
266 ->getRevisionById( $targetRevisionRow->rev_id, IDBAccessObject::READ_LATEST );
267
268 // Save
269 $flags = EDIT_UPDATE | EDIT_INTERNAL;
270
271 if ( $this->performer->isAllowed( 'minoredit' ) ) {
272 $flags |= EDIT_MINOR;
273 }
274
275 if ( $this->bot ) {
276 $flags |= EDIT_FORCE_BOT;
277 }
278
279 // TODO: MCR: also log model changes in other slots, in case that becomes possible!
280 $currentContent = $currentRevision->getContent( SlotRecord::MAIN );
281 $targetContent = $targetRevision->getContent( SlotRecord::MAIN );
282 $changingContentModel = $targetContent->getModel() !== $currentContent->getModel();
283
284 // Build rollback revision:
285 // Restore old content
286 // TODO: MCR: test this once we can store multiple slots
287 foreach ( $targetRevision->getSlots()->getSlots() as $slot ) {
288 $updater->inheritSlot( $slot );
289 }
290
291 // Remove extra slots
292 // TODO: MCR: test this once we can store multiple slots
293 foreach ( $currentRevision->getSlotRoles() as $role ) {
294 if ( !$targetRevision->hasSlot( $role ) ) {
295 $updater->removeSlot( $role );
296 }
297 }
298
299 $updater->markAsRevert(
300 EditResult::REVERT_ROLLBACK,
301 $currentRevision->getId(),
302 $targetRevision->getId()
303 );
304
305 // TODO: this logic should not be in the storage layer, it's here for compatibility
306 // with 1.31 behavior. Applying the 'autopatrol' right should be done in the same
307 // place the 'bot' right is handled, which is currently in EditPage::attemptSave.
308 if ( $this->options->get( MainConfigNames::UseRCPatrol ) &&
309 $this->performer->authorizeWrite( 'autopatrol', $this->page )
310 ) {
311 $updater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
312 }
313
314 $summary = $this->getSummary( $currentRevision, $targetRevision );
315
316 // Actually store the rollback
317 $rev = $updater->addTags( $this->tags )->saveRevision(
318 CommentStoreComment::newUnsavedComment( $summary ),
319 $flags
320 );
321
322 // This is done even on edit failure to have patrolling in that case (T64157).
323 $this->updateRecentChange( $dbw, $currentRevision, $targetRevision );
324
325 if ( !$updater->wasSuccessful() ) {
326 return $updater->getStatus();
327 }
328
329 // Report if the edit was not created because it did not change the content.
330 if ( !$updater->wasRevisionCreated() ) {
331 $result = StatusValue::newGood( [
332 'current-revision-record' => $currentRevision
333 ] );
334 $result->fatal(
335 'alreadyrolled',
336 htmlspecialchars( $this->titleFormatter->getPrefixedText( $this->page ) ),
337 htmlspecialchars( $this->byUser->getName() ),
338 htmlspecialchars( $currentEditorForPublic ? $currentEditorForPublic->getName() : '' )
339 );
340 return $result;
341 }
342
343 if ( $changingContentModel ) {
344 // If the content model changed during the rollback,
345 // make sure it gets logged to Special:Log/contentmodel
346 $log = new ManualLogEntry( 'contentmodel', 'change' );
347 $log->setPerformer( $this->performer->getUser() );
348 $log->setTarget( new TitleValue( $this->page->getNamespace(), $this->page->getDBkey() ) );
349 $log->setComment( $summary );
350 $log->setParameters( [
351 '4::oldmodel' => $currentContent->getModel(),
352 '5::newmodel' => $targetContent->getModel(),
353 ] );
354
355 $logId = $log->insert( $dbw );
356 $log->publish( $logId );
357 }
358
359 $wikiPage = $this->wikiPageFactory->newFromTitle( $this->page );
360
361 $this->hookRunner->onRollbackComplete(
362 $wikiPage,
363 $this->performer->getUser(),
364 $targetRevision,
365 $currentRevision
366 );
367
368 return StatusValue::newGood( [
369 'summary' => $summary,
370 'current-revision-record' => $currentRevision,
371 'target-revision-record' => $targetRevision,
372 'newid' => $rev->getId(),
373 'tags' => array_merge( $this->tags, $updater->getEditResult()->getRevertTags() )
374 ] );
375 }
376
377 /**
378 * Set patrolling and bot flag on the edits which get rolled back.
379 *
380 * @param IDatabase $dbw
381 * @param RevisionRecord $current
382 * @param RevisionRecord $target
383 */
384 private function updateRecentChange(
385 IDatabase $dbw,
386 RevisionRecord $current,
387 RevisionRecord $target
388 ) {
389 $useRCPatrol = $this->options->get( MainConfigNames::UseRCPatrol );
390 if ( !$this->bot && !$useRCPatrol ) {
391 return;
392 }
393
394 $actorId = $this->actorNormalization->findActorId( $current->getUser( RevisionRecord::RAW ), $dbw );
395 $timestamp = $dbw->timestamp( $target->getTimestamp() );
396 $rows = $dbw->newSelectQueryBuilder()
397 ->select( [ 'rc_id', 'rc_patrolled' ] )
398 ->from( 'recentchanges' )
399 ->where( [ 'rc_cur_id' => $current->getPageId(), 'rc_actor' => $actorId, ] )
400 ->andWhere( $dbw->buildComparison( '>', [
401 'rc_timestamp' => $timestamp,
402 'rc_this_oldid' => $target->getId(),
403 ] ) )
404 ->caller( __METHOD__ )->fetchResultSet();
405
406 $all = [];
407 $patrolled = [];
408 $unpatrolled = [];
409 foreach ( $rows as $row ) {
410 $all[] = (int)$row->rc_id;
411 if ( $row->rc_patrolled ) {
412 $patrolled[] = (int)$row->rc_id;
413 } else {
414 $unpatrolled[] = (int)$row->rc_id;
415 }
416 }
417
418 if ( $useRCPatrol && $this->bot ) {
419 // Mark all reverted edits as if they were made by a bot
420 // Also mark only unpatrolled reverted edits as patrolled
421 if ( $unpatrolled ) {
422 $dbw->newUpdateQueryBuilder()
423 ->update( 'recentchanges' )
424 ->set( [ 'rc_bot' => 1, 'rc_patrolled' => RecentChange::PRC_AUTOPATROLLED ] )
425 ->where( [ 'rc_id' => $unpatrolled ] )
426 ->caller( __METHOD__ )->execute();
427 }
428 if ( $patrolled ) {
429 $dbw->newUpdateQueryBuilder()
430 ->update( 'recentchanges' )
431 ->set( [ 'rc_bot' => 1 ] )
432 ->where( [ 'rc_id' => $patrolled ] )
433 ->caller( __METHOD__ )->execute();
434 }
435 } elseif ( $useRCPatrol ) {
436 // Mark only unpatrolled reverted edits as patrolled
437 if ( $unpatrolled ) {
438 $dbw->newUpdateQueryBuilder()
439 ->update( 'recentchanges' )
440 ->set( [ 'rc_patrolled' => RecentChange::PRC_AUTOPATROLLED ] )
441 ->where( [ 'rc_id' => $unpatrolled ] )
442 ->caller( __METHOD__ )->execute();
443 }
444 } else {
445 // Edit is from a bot
446 if ( $all ) {
447 $dbw->newUpdateQueryBuilder()
448 ->update( 'recentchanges' )
449 ->set( [ 'rc_bot' => 1 ] )
450 ->where( [ 'rc_id' => $all ] )
451 ->caller( __METHOD__ )->execute();
452 }
453 }
454 }
455
456 /**
457 * Generate and format summary for the rollback.
458 *
459 * @param RevisionRecord $current
460 * @param RevisionRecord $target
461 * @return string
462 */
463 private function getSummary( RevisionRecord $current, RevisionRecord $target ): string {
464 $revisionsBetween = $this->revisionStore->countRevisionsBetween(
465 $current->getPageId(),
466 $target,
467 $current,
468 1000,
469 RevisionStore::INCLUDE_NEW
470 );
471 $currentEditorForPublic = $current->getUser( RevisionRecord::FOR_PUBLIC );
472 if ( $this->summary === '' ) {
473 if ( !$currentEditorForPublic ) { // no public user name
474 $summary = MessageValue::new( 'revertpage-nouser' );
475 } elseif ( $this->options->get( MainConfigNames::DisableAnonTalk ) &&
476 !$currentEditorForPublic->isRegistered() ) {
477 $summary = MessageValue::new( 'revertpage-anon' );
478 } else {
479 $summary = MessageValue::new( 'revertpage' );
480 }
481 } else {
482 $summary = $this->summary;
483 }
484
485 $targetEditorForPublic = $target->getUser( RevisionRecord::FOR_PUBLIC );
486 // Allow the custom summary to use the same args as the default message
487 $args = [
488 $targetEditorForPublic ? $targetEditorForPublic->getName() : null,
489 $currentEditorForPublic ? $currentEditorForPublic->getName() : null,
490 $target->getId(),
491 Message::dateTimeParam( $target->getTimestamp() ),
492 $current->getId(),
493 Message::dateTimeParam( $current->getTimestamp() ),
494 $revisionsBetween,
495 ];
496 if ( $summary instanceof MessageValue ) {
497 $summary = ( new Converter() )->convertMessageValue( $summary );
498 $summary = $summary->params( $args )->inContentLanguage()->text();
499 } else {
500 $summary = ( new RawMessage( $summary, $args ) )->inContentLanguage()->plain();
501 }
502
503 // Trim spaces on user supplied text
504 return trim( $summary );
505 }
506 }