Merge "rdbms: add resolveDomainID() method to LBFactory/LoadBalancer"
[lhc/web/wiklou.git] / includes / Storage / PageUpdater.php
1 <?php
2 /**
3 * Controller-like object for creating and updating pages by creating new revisions.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 *
22 * @author Daniel Kinzler
23 */
24
25 namespace MediaWiki\Storage;
26
27 use AtomicSectionUpdate;
28 use ChangeTags;
29 use CommentStoreComment;
30 use Content;
31 use ContentHandler;
32 use DeferredUpdates;
33 use Hooks;
34 use InvalidArgumentException;
35 use LogicException;
36 use ManualLogEntry;
37 use MediaWiki\Linker\LinkTarget;
38 use MWException;
39 use RecentChange;
40 use Revision;
41 use RuntimeException;
42 use Status;
43 use Title;
44 use User;
45 use Wikimedia\Assert\Assert;
46 use Wikimedia\Rdbms\DBConnRef;
47 use Wikimedia\Rdbms\DBUnexpectedError;
48 use Wikimedia\Rdbms\IDatabase;
49 use Wikimedia\Rdbms\LoadBalancer;
50 use WikiPage;
51
52 /**
53 * Controller-like object for creating and updating pages by creating new revisions.
54 *
55 * PageUpdater instances provide compare-and-swap (CAS) protection against concurrent updates
56 * between the time grabParentRevision() is called and saveRevision() inserts a new revision.
57 * This allows application logic to safely perform edit conflict resolution using the parent
58 * revision's content.
59 *
60 * @see docs/pageupdater.txt for more information.
61 *
62 * MCR migration note: this replaces the relevant methods in WikiPage.
63 *
64 * @since 1.32
65 * @ingroup Page
66 */
67 class PageUpdater {
68
69 /**
70 * @var User
71 */
72 private $user;
73
74 /**
75 * @var WikiPage
76 */
77 private $wikiPage;
78
79 /**
80 * @var DerivedPageDataUpdater
81 */
82 private $derivedDataUpdater;
83
84 /**
85 * @var LoadBalancer
86 */
87 private $loadBalancer;
88
89 /**
90 * @var RevisionStore
91 */
92 private $revisionStore;
93
94 /**
95 * @var boolean see $wgUseAutomaticEditSummaries
96 * @see $wgUseAutomaticEditSummaries
97 */
98 private $useAutomaticEditSummaries = true;
99
100 /**
101 * @var int the RC patrol status the new revision should be marked with.
102 */
103 private $rcPatrolStatus = RecentChange::PRC_UNPATROLLED;
104
105 /**
106 * @var bool whether to create a log entry for new page creations.
107 */
108 private $usePageCreationLog = true;
109
110 /**
111 * @var boolean see $wgAjaxEditStash
112 */
113 private $ajaxEditStash = true;
114
115 /**
116 * @var bool|int
117 */
118 private $originalRevId = false;
119
120 /**
121 * @var array
122 */
123 private $tags = [];
124
125 /**
126 * @var int
127 */
128 private $undidRevId = 0;
129
130 /**
131 * @var RevisionSlotsUpdate
132 */
133 private $slotsUpdate;
134
135 /**
136 * @var Status|null
137 */
138 private $status = null;
139
140 /**
141 * @param User $user
142 * @param WikiPage $wikiPage
143 * @param DerivedPageDataUpdater $derivedDataUpdater
144 * @param LoadBalancer $loadBalancer
145 * @param RevisionStore $revisionStore
146 */
147 public function __construct(
148 User $user,
149 WikiPage $wikiPage,
150 DerivedPageDataUpdater $derivedDataUpdater,
151 LoadBalancer $loadBalancer,
152 RevisionStore $revisionStore
153 ) {
154 $this->user = $user;
155 $this->wikiPage = $wikiPage;
156 $this->derivedDataUpdater = $derivedDataUpdater;
157
158 $this->loadBalancer = $loadBalancer;
159 $this->revisionStore = $revisionStore;
160
161 $this->slotsUpdate = new RevisionSlotsUpdate();
162 }
163
164 /**
165 * Can be used to enable or disable automatic summaries that are applied to certain kinds of
166 * changes, like completely blanking a page.
167 *
168 * @param bool $useAutomaticEditSummaries
169 * @see $wgUseAutomaticEditSummaries
170 */
171 public function setUseAutomaticEditSummaries( $useAutomaticEditSummaries ) {
172 $this->useAutomaticEditSummaries = $useAutomaticEditSummaries;
173 }
174
175 /**
176 * Sets the "patrolled" status of the edit.
177 * Callers should check the "patrol" and "autopatrol" permissions as appropriate.
178 *
179 * @see $wgUseRCPatrol
180 * @see $wgUseNPPatrol
181 *
182 * @param int $status RC patrol status, e.g. RecentChange::PRC_AUTOPATROLLED.
183 */
184 public function setRcPatrolStatus( $status ) {
185 $this->rcPatrolStatus = $status;
186 }
187
188 /**
189 * Whether to create a log entry for new page creations.
190 *
191 * @see $wgPageCreationLog
192 *
193 * @param bool $use
194 */
195 public function setUsePageCreationLog( $use ) {
196 $this->usePageCreationLog = $use;
197 }
198
199 /**
200 * @param bool $ajaxEditStash
201 * @see $wgAjaxEditStash
202 */
203 public function setAjaxEditStash( $ajaxEditStash ) {
204 $this->ajaxEditStash = $ajaxEditStash;
205 }
206
207 private function getWikiId() {
208 return false; // TODO: get from RevisionStore!
209 }
210
211 /**
212 * @param int $mode DB_MASTER or DB_REPLICA
213 *
214 * @return DBConnRef
215 */
216 private function getDBConnectionRef( $mode ) {
217 return $this->loadBalancer->getConnectionRef( $mode, [], $this->getWikiId() );
218 }
219
220 /**
221 * @return LinkTarget
222 */
223 private function getLinkTarget() {
224 // NOTE: eventually, we won't get a WikiPage passed into the constructor any more
225 return $this->wikiPage->getTitle();
226 }
227
228 /**
229 * @return Title
230 */
231 private function getTitle() {
232 // NOTE: eventually, we won't get a WikiPage passed into the constructor any more
233 return $this->wikiPage->getTitle();
234 }
235
236 /**
237 * @return WikiPage
238 */
239 private function getWikiPage() {
240 // NOTE: eventually, we won't get a WikiPage passed into the constructor any more
241 return $this->wikiPage;
242 }
243
244 /**
245 * Checks whether this update conflicts with another update performed between the client
246 * loading data to prepare an edit, and the client committing the edit. This is intended to
247 * detect user level "edit conflict" when the latest revision known to the client
248 * is no longer the current revision when processing the update.
249 *
250 * An update expected to create a new page can be checked by setting $expectedParentRevision = 0.
251 * Such an update is considered to have a conflict if a current revision exists (that is,
252 * the page was created since the edit was initiated on the client).
253 *
254 * This method returning true indicates to calling code that edit conflict resolution should
255 * be applied before saving any data. It does not prevent the update from being performed, and
256 * it should not be confused with a "late" conflict indicated by the "edit-conflict" status.
257 * A "late" conflict is a CAS failure caused by an update being performed concurrently between
258 * the time grabParentRevision() was called and the time saveRevision() trying to insert the
259 * new revision.
260 *
261 * @note A user level edit conflict is not the same as the "edit-conflict" status triggered by
262 * a CAS failure. Calling this method establishes the CAS token, it does not check against it:
263 * This method calls grabParentRevision(), and thus causes the expected parent revision
264 * for the update to be fixed to the page's current revision at this point in time.
265 * It acts as a compare-and-swap (CAS) token in that it is guaranteed that saveRevision()
266 * will fail with the "edit-conflict" status if the current revision of the page changes after
267 * hasEditConflict() (or grabParentRevision()) was called and before saveRevision() could insert
268 * a new revision.
269 *
270 * @see grabParentRevision()
271 *
272 * @param int $expectedParentRevision The ID of the revision the client expects to be the
273 * current one. Use 0 to indicate that the page is expected to not yet exist.
274 *
275 * @return bool
276 */
277 public function hasEditConflict( $expectedParentRevision ) {
278 $parent = $this->grabParentRevision();
279 $parentId = $parent ? $parent->getId() : 0;
280
281 return $parentId !== $expectedParentRevision;
282 }
283
284 /**
285 * Returns the revision that was the page's current revision when grabParentRevision()
286 * was first called. This revision is the expected parent revision of the update, and will be
287 * recorded as the new revision's parent revision (unless no new revision is created because
288 * the content was not changed).
289 *
290 * This method MUST not be called after saveRevision() was called!
291 *
292 * The current revision determined by the first call to this methods effectively acts a
293 * compare-and-swap (CAS) token which is checked by saveRevision(), which fails if any
294 * concurrent updates created a new revision.
295 *
296 * Application code should call this method before applying transformations to the new
297 * content that depend on the parent revision, e.g. adding/replacing sections, or resolving
298 * conflicts via a 3-way merge. This protects against race conditions triggered by concurrent
299 * updates.
300 *
301 * @see DerivedPageDataUpdater::grabCurrentRevision()
302 *
303 * @note The expected parent revision is not to be confused with the logical base revision.
304 * The base revision is specified by the client, the parent revision is determined from the
305 * database. If base revision and parent revision are not the same, the updates is considered
306 * to require edit conflict resolution.
307 *
308 * @throws LogicException if called after saveRevision().
309 * @return RevisionRecord|null the parent revision, or null of the page does not yet exist.
310 */
311 public function grabParentRevision() {
312 return $this->derivedDataUpdater->grabCurrentRevision();
313 }
314
315 /**
316 * @return string
317 */
318 private function getTimestampNow() {
319 // TODO: allow an override to be injected for testing
320 return wfTimestampNow();
321 }
322
323 /**
324 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
325 *
326 * @param int $flags
327 * @return int Updated $flags
328 */
329 private function checkFlags( $flags ) {
330 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
331 $flags |= ( $this->derivedDataUpdater->pageExisted() ) ? EDIT_UPDATE : EDIT_NEW;
332 }
333
334 return $flags;
335 }
336
337 /**
338 * Set the new content for the given slot role
339 *
340 * @param string $role A slot role name (such as "main")
341 * @param Content $content
342 */
343 public function setContent( $role, Content $content ) {
344 // TODO: MCR: check the role and the content's model against the list of supported
345 // roles, see T194046.
346
347 if ( $role !== 'main' ) {
348 throw new InvalidArgumentException( 'Only the main slot is presently supported' );
349 }
350
351 $this->slotsUpdate->modifyContent( $role, $content );
352 }
353
354 /**
355 * Explicitly inherit a slot from some earlier revision.
356 *
357 * The primary use case for this is rollbacks, when slots are to be inherited from
358 * the rollback target, overriding the content from the parent revision (which is the
359 * revision being rolled back).
360 *
361 * This should typically not be used to inherit slots from the parent revision, which
362 * happens implicitly. Using this method causes the given slot to be treated as "modified"
363 * during revision creation, even if it has the same content as in the parent revision.
364 *
365 * @param SlotRecord $originalSlot A slot already existing in the database, to be inherited
366 * by the new revision.
367 */
368 public function inheritSlot( SlotRecord $originalSlot ) {
369 // NOTE: this slot is inherited from some other revision, but it's
370 // a "modified" slot for the RevisionSlotsUpdate and DerivedPageDataUpdater,
371 // since it's not implicitly inherited from the parent revision.
372 $inheritedSlot = SlotRecord::newInherited( $originalSlot );
373 $this->slotsUpdate->modifySlot( $inheritedSlot );
374 }
375
376 /**
377 * Removes the slot with the given role.
378 *
379 * This discontinues the "stream" of slots with this role on the page,
380 * preventing the new revision, and any subsequent revisions, from
381 * inheriting the slot with this role.
382 *
383 * @param string $role A slot role name (but not "main")
384 */
385 public function removeSlot( $role ) {
386 if ( $role === 'main' ) {
387 throw new InvalidArgumentException( 'Cannot remove the main slot!' );
388 }
389
390 $this->slotsUpdate->removeSlot( $role );
391 }
392
393 /**
394 * Returns the ID of an earlier revision that is being repeated or restored by this update.
395 *
396 * @return bool|int The original revision id, or false if no earlier revision is known to be
397 * repeated or restored by this update.
398 */
399 public function getOriginalRevisionId() {
400 return $this->originalRevId;
401 }
402
403 /**
404 * Sets the ID of an earlier revision that is being repeated or restored by this update.
405 * The new revision is expected to have the exact same content as the given original revision.
406 * This is used with rollbacks and with dummy "null" revisions which are created to record
407 * things like page moves.
408 *
409 * This value is passed to the PageContentSaveComplete and NewRevisionFromEditComplete hooks.
410 *
411 * @param int|bool $originalRevId The original revision id, or false if no earlier revision
412 * is known to be repeated or restored by this update.
413 */
414 public function setOriginalRevisionId( $originalRevId ) {
415 Assert::parameterType( 'integer|boolean', $originalRevId, '$originalRevId' );
416 $this->originalRevId = $originalRevId;
417 }
418
419 /**
420 * Returns the revision ID set by setUndidRevisionId(), indicating what revision is being
421 * undone by this edit.
422 *
423 * @return int
424 */
425 public function getUndidRevisionId() {
426 return $this->undidRevId;
427 }
428
429 /**
430 * Sets the ID of revision that was undone by the present update.
431 * This is used with the "undo" action, and is expected to hold the oldest revision ID
432 * in case more then one revision is being undone.
433 *
434 * @param int $undidRevId
435 */
436 public function setUndidRevisionId( $undidRevId ) {
437 Assert::parameterType( 'integer', $undidRevId, '$undidRevId' );
438 $this->undidRevId = $undidRevId;
439 }
440
441 /**
442 * Sets a tag to apply to this update.
443 * Callers are responsible for permission checks,
444 * using ChangeTags::canAddTagsAccompanyingChange.
445 * @param string $tag
446 */
447 public function addTag( $tag ) {
448 Assert::parameterType( 'string', $tag, '$tag' );
449 $this->tags[] = trim( $tag );
450 }
451
452 /**
453 * Sets tags to apply to this update.
454 * Callers are responsible for permission checks,
455 * using ChangeTags::canAddTagsAccompanyingChange.
456 * @param string[] $tags
457 */
458 public function addTags( array $tags ) {
459 Assert::parameterElementType( 'string', $tags, '$tags' );
460 foreach ( $tags as $tag ) {
461 $this->addTag( $tag );
462 }
463 }
464
465 /**
466 * Returns the list of tags set using the addTag() method.
467 *
468 * @return string[]
469 */
470 public function getExplicitTags() {
471 return $this->tags;
472 }
473
474 /**
475 * @param int $flags Bit mask: a bit mask of EDIT_XXX flags.
476 * @return string[]
477 */
478 private function computeEffectiveTags( $flags ) {
479 $tags = $this->tags;
480
481 foreach ( $this->slotsUpdate->getModifiedRoles() as $role ) {
482 $old_content = $this->getParentContent( $role );
483
484 $handler = $this->getContentHandler( $role );
485 $content = $this->slotsUpdate->getModifiedSlot( $role )->getContent();
486
487 // TODO: MCR: Do this for all slots. Also add tags for removing roles!
488 $tag = $handler->getChangeTag( $old_content, $content, $flags );
489 // If there is no applicable tag, null is returned, so we need to check
490 if ( $tag ) {
491 $tags[] = $tag;
492 }
493 }
494
495 // Check for undo tag
496 if ( $this->undidRevId !== 0 && in_array( 'mw-undo', ChangeTags::getSoftwareTags() ) ) {
497 $tags[] = 'mw-undo';
498 }
499
500 return array_unique( $tags );
501 }
502
503 /**
504 * Returns the content of the given slot of the parent revision, with no audience checks applied.
505 * If there is no parent revision or the slot is not defined, this returns null.
506 *
507 * @param string $role slot role name
508 * @return Content|null
509 */
510 private function getParentContent( $role ) {
511 $parent = $this->grabParentRevision();
512
513 if ( $parent && $parent->hasSlot( $role ) ) {
514 return $parent->getContent( $role, RevisionRecord::RAW );
515 }
516
517 return null;
518 }
519
520 /**
521 * @param string $role slot role name
522 * @return ContentHandler
523 */
524 private function getContentHandler( $role ) {
525 // TODO: inject something like a ContentHandlerRegistry
526 if ( $this->slotsUpdate->isModifiedSlot( $role ) ) {
527 $slot = $this->slotsUpdate->getModifiedSlot( $role );
528 } else {
529 $parent = $this->grabParentRevision();
530
531 if ( $parent ) {
532 $slot = $parent->getSlot( $role, RevisionRecord::RAW );
533 } else {
534 throw new RevisionAccessException( 'No such slot: ' . $role );
535 }
536 }
537
538 return ContentHandler::getForModelID( $slot->getModel() );
539 }
540
541 /**
542 * @param int $flags Bit mask: a bit mask of EDIT_XXX flags.
543 *
544 * @return CommentStoreComment
545 */
546 private function makeAutoSummary( $flags ) {
547 if ( !$this->useAutomaticEditSummaries || ( $flags & EDIT_AUTOSUMMARY ) === 0 ) {
548 return CommentStoreComment::newUnsavedComment( '' );
549 }
550
551 // NOTE: this generates an auto-summary for SOME RANDOM changed slot!
552 // TODO: combine auto-summaries for multiple slots!
553 // XXX: this logic should not be in the storage layer!
554 $roles = $this->slotsUpdate->getModifiedRoles();
555 $role = reset( $roles );
556
557 if ( $role === false ) {
558 return CommentStoreComment::newUnsavedComment( '' );
559 }
560
561 $handler = $this->getContentHandler( $role );
562 $content = $this->slotsUpdate->getModifiedSlot( $role )->getContent();
563 $old_content = $this->getParentContent( $role );
564 $summary = $handler->getAutosummary( $old_content, $content, $flags );
565
566 return CommentStoreComment::newUnsavedComment( $summary );
567 }
568
569 /**
570 * Change an existing article or create a new article. Updates RC and all necessary caches,
571 * optionally via the deferred update array. This does not check user permissions.
572 *
573 * It is guaranteed that saveRevision() will fail if the current revision of the page
574 * changes after grabParentRevision() was called and before saveRevision() can insert
575 * a new revision, as per the CAS mechanism described above.
576 *
577 * The caller is however responsible for calling hasEditConflict() to detect a
578 * user-level edit conflict, and to adjust the content of the new revision accordingly,
579 * e.g. by using a 3-way-merge.
580 *
581 * MCR migration note: this replaces WikiPage::doEditContent. Callers that change to using
582 * saveRevision() now need to check the "minoredit" themselves before using EDIT_MINOR.
583 *
584 * @param CommentStoreComment $summary Edit summary
585 * @param int $flags Bitfield:
586 * EDIT_NEW
587 * Create a new page, or fail with "edit-already-exists" if the page exists.
588 * EDIT_UPDATE
589 * Create a new revision, or fail with "edit-gone-missing" if the page does not exist.
590 * EDIT_MINOR
591 * Mark this revision as minor
592 * EDIT_SUPPRESS_RC
593 * Do not log the change in recentchanges
594 * EDIT_FORCE_BOT
595 * Mark the revision as automated ("bot edit")
596 * EDIT_AUTOSUMMARY
597 * Fill in blank summaries with generated text where possible
598 * EDIT_INTERNAL
599 * Signal that the page retrieve/save cycle happened entirely in this request.
600 *
601 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the expected state is detected
602 * automatically via grabParentRevision(). In this case, the "edit-already-exists" or
603 * "edit-gone-missing" errors may still be triggered due to race conditions, if the page
604 * was unexpectedly created or deleted while revision creation is in progress. This can be
605 * viewed as part of the CAS mechanism described above.
606 *
607 * @return RevisionRecord|null The new revision, or null if no new revision was created due
608 * to a failure or a null-edit. Use isUnchanged(), wasSuccessful() and getStatus()
609 * to determine the outcome of the revision creation.
610 *
611 * @throws MWException
612 * @throws RuntimeException
613 */
614 public function saveRevision( CommentStoreComment $summary, $flags = 0 ) {
615 // Defend against mistakes caused by differences with the
616 // signature of WikiPage::doEditContent.
617 Assert::parameterType( 'integer', $flags, '$flags' );
618 Assert::parameterType( 'CommentStoreComment', $summary, '$summary' );
619
620 if ( $this->wasCommitted() ) {
621 throw new RuntimeException( 'saveRevision() has already been called on this PageUpdater!' );
622 }
623
624 // Low-level sanity check
625 if ( $this->getLinkTarget()->getText() === '' ) {
626 throw new RuntimeException( 'Something is trying to edit an article with an empty title' );
627 }
628
629 // TODO: MCR: check the role and the content's model against the list of supported
630 // and required roles, see T194046.
631
632 // Make sure the given content type is allowed for this page
633 // TODO: decide: Extend check to other slots? Consider the role in check? [PageType]
634 $mainContentHandler = $this->getContentHandler( 'main' );
635 if ( !$mainContentHandler->canBeUsedOn( $this->getTitle() ) ) {
636 $this->status = Status::newFatal( 'content-not-allowed-here',
637 ContentHandler::getLocalizedName( $mainContentHandler->getModelID() ),
638 $this->getTitle()->getPrefixedText()
639 );
640 return null;
641 }
642
643 // Load the data from the master database if needed. Needed to check flags.
644 // NOTE: This grabs the parent revision as the CAS token, if grabParentRevision
645 // wasn't called yet. If the page is modified by another process before we are done with
646 // it, this method must fail (with status 'edit-conflict')!
647 // NOTE: The parent revision may be different from $this->originalRevisionId.
648 $this->grabParentRevision();
649 $flags = $this->checkFlags( $flags );
650
651 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
652 if ( ( $flags & EDIT_INTERNAL ) || ( $flags & EDIT_FORCE_BOT ) ) {
653 $useStashed = false;
654 } else {
655 $useStashed = $this->ajaxEditStash;
656 }
657
658 // TODO: use this only for the legacy hook, and only if something uses the legacy hook
659 $wikiPage = $this->getWikiPage();
660
661 $user = $this->user;
662
663 // Prepare the update. This performs PST and generates the canonical ParserOutput.
664 $this->derivedDataUpdater->prepareContent(
665 $this->user,
666 $this->slotsUpdate,
667 $useStashed
668 );
669
670 // TODO: don't force initialization here!
671 // This is a hack to work around the fact that late initialization of the ParserOutput
672 // causes ApiFlowEditHeaderTest::testCache to fail. Whether that failure indicates an
673 // actual problem, or is just an issue with the test setup, remains to be determined
674 // [dk, 2018-03].
675 // Anomie said in 2018-03:
676 /*
677 I suspect that what's breaking is this:
678
679 The old version of WikiPage::doEditContent() called prepareContentForEdit() which
680 generated the ParserOutput right then, so when doEditUpdates() gets called from the
681 DeferredUpdate scheduled by WikiPage::doCreate() there's no need to parse. I note
682 there's a comment there that says "Get the pre-save transform content and final
683 parser output".
684 The new version of WikiPage::doEditContent() makes a PageUpdater and calls its
685 saveRevision(), which calls DerivedPageDataUpdater::prepareContent() and
686 PageUpdater::doCreate() without ever having to actually generate a ParserOutput.
687 Thus, when DerivedPageDataUpdater::doUpdates() is called from the DeferredUpdate
688 scheduled by PageUpdater::doCreate(), it does find that it needs to parse at that point.
689
690 And the order of operations in that Flow test is presumably:
691
692 - Create a page with a call to WikiPage::doEditContent(), in a way that somehow avoids
693 processing the DeferredUpdate.
694 - Set up the "no set!" mock cache in Flow\Tests\Api\ApiTestCase::expectCacheInvalidate()
695 - Then, during the course of doing that test, a $db->commit() results in the
696 DeferredUpdates being run.
697 */
698 $this->derivedDataUpdater->getCanonicalParserOutput();
699
700 $mainContent = $this->derivedDataUpdater->getSlots()->getContent( 'main' );
701
702 // Trigger pre-save hook (using provided edit summary)
703 $hookStatus = Status::newGood( [] );
704 // TODO: replace legacy hook!
705 // TODO: avoid pass-by-reference, see T193950
706 $hook_args = [ &$wikiPage, &$user, &$mainContent, &$summary,
707 $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
708 // Check if the hook rejected the attempted save
709 if ( !Hooks::run( 'PageContentSave', $hook_args ) ) {
710 if ( $hookStatus->isOK() ) {
711 // Hook returned false but didn't call fatal(); use generic message
712 $hookStatus->fatal( 'edit-hook-aborted' );
713 }
714
715 $this->status = $hookStatus;
716 return null;
717 }
718
719 // Provide autosummaries if one is not provided and autosummaries are enabled
720 // XXX: $summary == null seems logical, but the empty string may actually come from the user
721 // XXX: Move this logic out of the storage layer! It does not belong here! Use a callback?
722 if ( $summary->text === '' && $summary->data === null ) {
723 $summary = $this->makeAutoSummary( $flags );
724 }
725
726 // Actually create the revision and create/update the page.
727 // Do NOT yet set $this->status!
728 if ( $flags & EDIT_UPDATE ) {
729 $status = $this->doModify( $summary, $this->user, $flags );
730 } else {
731 $status = $this->doCreate( $summary, $this->user, $flags );
732 }
733
734 // Promote user to any groups they meet the criteria for
735 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
736 $user->addAutopromoteOnceGroups( 'onEdit' );
737 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
738 } );
739
740 // NOTE: set $this->status only after all hooks have been called,
741 // so wasCommitted doesn't return true wehn called indirectly from a hook handler!
742 $this->status = $status;
743
744 // TODO: replace bad status with Exceptions!
745 return ( $this->status && $this->status->isOK() )
746 ? $this->status->value['revision-record']
747 : null;
748 }
749
750 /**
751 * Whether saveRevision() has been called on this instance
752 *
753 * @return bool
754 */
755 public function wasCommitted() {
756 return $this->status !== null;
757 }
758
759 /**
760 * The Status object indicating whether saveRevision() was successful, or null if
761 * saveRevision() was not yet called on this instance.
762 *
763 * @note This is here for compatibility with WikiPage::doEditContent. It may be deprecated
764 * soon.
765 *
766 * Possible status errors:
767 * edit-hook-aborted: The ArticleSave hook aborted the update but didn't
768 * set the fatal flag of $status.
769 * edit-gone-missing: In update mode, but the article didn't exist.
770 * edit-conflict: In update mode, the article changed unexpectedly.
771 * edit-no-change: Warning that the text was the same as before.
772 * edit-already-exists: In creation mode, but the article already exists.
773 *
774 * Extensions may define additional errors.
775 *
776 * $return->value will contain an associative array with members as follows:
777 * new: Boolean indicating if the function attempted to create a new article.
778 * revision: The revision object for the inserted revision, or null.
779 *
780 * @return null|Status
781 */
782 public function getStatus() {
783 return $this->status;
784 }
785
786 /**
787 * Whether saveRevision() completed successfully
788 *
789 * @return bool
790 */
791 public function wasSuccessful() {
792 return $this->status && $this->status->isOK();
793 }
794
795 /**
796 * Whether saveRevision() was called and created a new page.
797 *
798 * @return bool
799 */
800 public function isNew() {
801 return $this->status && $this->status->isOK() && $this->status->value['new'];
802 }
803
804 /**
805 * Whether saveRevision() did not create a revision because the content didn't change
806 * (null-edit). Whether the content changed or not is determined by
807 * DerivedPageDataUpdater::isChange().
808 *
809 * @return bool
810 */
811 public function isUnchanged() {
812 return $this->status
813 && $this->status->isOK()
814 && $this->status->value['revision-record'] === null;
815 }
816
817 /**
818 * The new revision created by saveRevision(), or null if saveRevision() has not yet been
819 * called, failed, or did not create a new revision because the content did not change.
820 *
821 * @return RevisionRecord|null
822 */
823 public function getNewRevision() {
824 return ( $this->status && $this->status->isOK() )
825 ? $this->status->value['revision-record']
826 : null;
827 }
828
829 /**
830 * Constructs a MutableRevisionRecord based on the Content prepared by the
831 * DerivedPageDataUpdater. This takes care of inheriting slots, updating slots
832 * with PST applied, and removing discontinued slots.
833 *
834 * This calls Content::prepareSave() to verify that the slot content can be saved.
835 * The $status parameter is updated with any errors or warnings found by Content::prepareSave().
836 *
837 * @param CommentStoreComment $comment
838 * @param User $user
839 * @param string $timestamp
840 * @param int $flags
841 * @param Status $status
842 *
843 * @return MutableRevisionRecord
844 */
845 private function makeNewRevision(
846 CommentStoreComment $comment,
847 User $user,
848 $timestamp,
849 $flags,
850 Status $status
851 ) {
852 $wikiPage = $this->getWikiPage();
853 $title = $this->getTitle();
854 $parent = $this->grabParentRevision();
855
856 $rev = new MutableRevisionRecord( $title, $this->getWikiId() );
857 $rev->setPageId( $title->getArticleID() );
858
859 if ( $parent ) {
860 $oldid = $parent->getId();
861 $rev->setParentId( $oldid );
862 } else {
863 $oldid = 0;
864 }
865
866 $rev->setComment( $comment );
867 $rev->setUser( $user );
868 $rev->setTimestamp( $timestamp );
869 $rev->setMinorEdit( ( $flags & EDIT_MINOR ) > 0 );
870
871 foreach ( $this->derivedDataUpdater->getSlots()->getSlots() as $slot ) {
872 $content = $slot->getContent();
873
874 // XXX: We may push this up to the "edit controller" level, see T192777.
875 // TODO: change the signature of PrepareSave to not take a WikiPage!
876 $prepStatus = $content->prepareSave( $wikiPage, $flags, $oldid, $user );
877
878 if ( $prepStatus->isOK() ) {
879 $rev->setSlot( $slot );
880 }
881
882 // TODO: MCR: record which problem arose in which slot.
883 $status->merge( $prepStatus );
884 }
885
886 return $rev;
887 }
888
889 /**
890 * @param CommentStoreComment $summary The edit summary
891 * @param User $user The revision's author
892 * @param int $flags EXIT_XXX constants
893 *
894 * @throws MWException
895 * @return Status
896 */
897 private function doModify( CommentStoreComment $summary, User $user, $flags ) {
898 $wikiPage = $this->getWikiPage(); // TODO: use for legacy hooks only!
899
900 // Update article, but only if changed.
901 $status = Status::newGood( [ 'new' => false, 'revision' => null, 'revision-record' => null ] );
902
903 // Convenience variables
904 $now = $this->getTimestampNow();
905
906 $oldRev = $this->grabParentRevision();
907 $oldid = $oldRev ? $oldRev->getId() : 0;
908
909 if ( !$oldRev ) {
910 // Article gone missing
911 $status->fatal( 'edit-gone-missing' );
912
913 return $status;
914 }
915
916 $newRevisionRecord = $this->makeNewRevision(
917 $summary,
918 $user,
919 $now,
920 $flags,
921 $status
922 );
923
924 if ( !$status->isOK() ) {
925 return $status;
926 }
927
928 // XXX: we may want a flag that allows a null revision to be forced!
929 $changed = $this->derivedDataUpdater->isChange();
930
931 $dbw = $this->getDBConnectionRef( DB_MASTER );
932
933 if ( $changed ) {
934 $dbw->startAtomic( __METHOD__ );
935
936 // Get the latest page_latest value while locking it.
937 // Do a CAS style check to see if it's the same as when this method
938 // started. If it changed then bail out before touching the DB.
939 $latestNow = $wikiPage->lockAndGetLatest(); // TODO: move to storage service, pass DB
940 if ( $latestNow != $oldid ) {
941 // We don't need to roll back, since we did not modify the database yet.
942 // XXX: Or do we want to rollback, any transaction started by calling
943 // code will fail? If we want that, we should probably throw an exception.
944 $dbw->endAtomic( __METHOD__ );
945 // Page updated or deleted in the mean time
946 $status->fatal( 'edit-conflict' );
947
948 return $status;
949 }
950
951 // At this point we are now comitted to returning an OK
952 // status unless some DB query error or other exception comes up.
953 // This way callers don't have to call rollback() if $status is bad
954 // unless they actually try to catch exceptions (which is rare).
955
956 // Save revision content and meta-data
957 $newRevisionRecord = $this->revisionStore->insertRevisionOn( $newRevisionRecord, $dbw );
958 $newLegacyRevision = new Revision( $newRevisionRecord );
959
960 // Update page_latest and friends to reflect the new revision
961 // TODO: move to storage service
962 $wasRedirect = $this->derivedDataUpdater->wasRedirect();
963 if ( !$wikiPage->updateRevisionOn( $dbw, $newLegacyRevision, null, $wasRedirect ) ) {
964 throw new PageUpdateException( "Failed to update page row to use new revision." );
965 }
966
967 // TODO: replace legacy hook!
968 $tags = $this->computeEffectiveTags( $flags );
969 Hooks::run(
970 'NewRevisionFromEditComplete',
971 [ $wikiPage, $newLegacyRevision, $this->getOriginalRevisionId(), $user, &$tags ]
972 );
973
974 // Update recentchanges
975 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
976 // Add RC row to the DB
977 RecentChange::notifyEdit(
978 $now,
979 $this->getTitle(),
980 $newRevisionRecord->isMinor(),
981 $user,
982 $summary->text, // TODO: pass object when that becomes possible
983 $oldid,
984 $newRevisionRecord->getTimestamp(),
985 ( $flags & EDIT_FORCE_BOT ) > 0,
986 '',
987 $oldRev->getSize(),
988 $newRevisionRecord->getSize(),
989 $newRevisionRecord->getId(),
990 $this->rcPatrolStatus,
991 $tags
992 );
993 }
994
995 $user->incEditCount();
996
997 $dbw->endAtomic( __METHOD__ );
998
999 // Return the new revision to the caller
1000 $status->value['revision-record'] = $newRevisionRecord;
1001
1002 // TODO: globally replace usages of 'revision' with getNewRevision()
1003 $status->value['revision'] = $newLegacyRevision;
1004 } else {
1005 // T34948: revision ID must be set to page {{REVISIONID}} and
1006 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1007 // Since we don't insert a new revision into the database, the least
1008 // error-prone way is to reuse given old revision.
1009 $newRevisionRecord = $oldRev;
1010
1011 $status->warning( 'edit-no-change' );
1012 // Update page_touched as updateRevisionOn() was not called.
1013 // Other cache updates are managed in WikiPage::onArticleEdit()
1014 // via WikiPage::doEditUpdates().
1015 $this->getTitle()->invalidateCache( $now );
1016 }
1017
1018 // Do secondary updates once the main changes have been committed...
1019 // NOTE: the updates have to be processed before sending the response to the client
1020 // (DeferredUpdates::PRESEND), otherwise the client may already be following the
1021 // HTTP redirect to the standard view before dervide data has been created - most
1022 // importantly, before the parser cache has been updated. This would cause the
1023 // content to be parsed a second time, or may cause stale content to be shown.
1024 DeferredUpdates::addUpdate(
1025 $this->getAtomicSectionUpdate(
1026 $dbw,
1027 $wikiPage,
1028 $newRevisionRecord,
1029 $user,
1030 $summary,
1031 $flags,
1032 $status,
1033 [ 'changed' => $changed, ]
1034 ),
1035 DeferredUpdates::PRESEND
1036 );
1037
1038 return $status;
1039 }
1040
1041 /**
1042 * @param CommentStoreComment $summary The edit summary
1043 * @param User $user The revision's author
1044 * @param int $flags EXIT_XXX constants
1045 *
1046 * @throws DBUnexpectedError
1047 * @throws MWException
1048 * @return Status
1049 */
1050 private function doCreate( CommentStoreComment $summary, User $user, $flags ) {
1051 $wikiPage = $this->getWikiPage(); // TODO: use for legacy hooks only!
1052
1053 if ( !$this->derivedDataUpdater->getSlots()->hasSlot( 'main' ) ) {
1054 throw new PageUpdateException( 'Must provide a main slot when creating a page!' );
1055 }
1056
1057 $status = Status::newGood( [ 'new' => true, 'revision' => null, 'revision-record' => null ] );
1058
1059 $now = $this->getTimestampNow();
1060
1061 $newRevisionRecord = $this->makeNewRevision(
1062 $summary,
1063 $user,
1064 $now,
1065 $flags,
1066 $status
1067 );
1068
1069 if ( !$status->isOK() ) {
1070 return $status;
1071 }
1072
1073 $dbw = $this->getDBConnectionRef( DB_MASTER );
1074 $dbw->startAtomic( __METHOD__ );
1075
1076 // Add the page record unless one already exists for the title
1077 // TODO: move to storage service
1078 $newid = $wikiPage->insertOn( $dbw );
1079 if ( $newid === false ) {
1080 $dbw->endAtomic( __METHOD__ ); // nothing inserted
1081 $status->fatal( 'edit-already-exists' );
1082
1083 return $status; // nothing done
1084 }
1085
1086 // At this point we are now comitted to returning an OK
1087 // status unless some DB query error or other exception comes up.
1088 // This way callers don't have to call rollback() if $status is bad
1089 // unless they actually try to catch exceptions (which is rare).
1090 $newRevisionRecord->setPageId( $newid );
1091
1092 // Save the revision text...
1093 $newRevisionRecord = $this->revisionStore->insertRevisionOn( $newRevisionRecord, $dbw );
1094 $newLegacyRevision = new Revision( $newRevisionRecord );
1095
1096 // Update the page record with revision data
1097 // TODO: move to storage service
1098 if ( !$wikiPage->updateRevisionOn( $dbw, $newLegacyRevision, 0 ) ) {
1099 throw new PageUpdateException( "Failed to update page row to use new revision." );
1100 }
1101
1102 // TODO: replace legacy hook!
1103 $tags = $this->computeEffectiveTags( $flags );
1104 Hooks::run(
1105 'NewRevisionFromEditComplete',
1106 [ $wikiPage, $newLegacyRevision, false, $user, &$tags ]
1107 );
1108
1109 // Update recentchanges
1110 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1111 // Add RC row to the DB
1112 RecentChange::notifyNew(
1113 $now,
1114 $this->getTitle(),
1115 $newRevisionRecord->isMinor(),
1116 $user,
1117 $summary->text, // TODO: pass object when that becomes possible
1118 ( $flags & EDIT_FORCE_BOT ) > 0,
1119 '',
1120 $newRevisionRecord->getSize(),
1121 $newRevisionRecord->getId(),
1122 $this->rcPatrolStatus,
1123 $tags
1124 );
1125 }
1126
1127 $user->incEditCount();
1128
1129 if ( $this->usePageCreationLog ) {
1130 // Log the page creation
1131 // @TODO: Do we want a 'recreate' action?
1132 $logEntry = new ManualLogEntry( 'create', 'create' );
1133 $logEntry->setPerformer( $user );
1134 $logEntry->setTarget( $this->getTitle() );
1135 $logEntry->setComment( $summary->text );
1136 $logEntry->setTimestamp( $now );
1137 $logEntry->setAssociatedRevId( $newRevisionRecord->getId() );
1138 $logEntry->insert();
1139 // Note that we don't publish page creation events to recentchanges
1140 // (i.e. $logEntry->publish()) since this would create duplicate entries,
1141 // one for the edit and one for the page creation.
1142 }
1143
1144 $dbw->endAtomic( __METHOD__ );
1145
1146 // Return the new revision to the caller
1147 // TODO: globally replace usages of 'revision' with getNewRevision()
1148 $status->value['revision'] = $newLegacyRevision;
1149 $status->value['revision-record'] = $newRevisionRecord;
1150
1151 // Do secondary updates once the main changes have been committed...
1152 DeferredUpdates::addUpdate(
1153 $this->getAtomicSectionUpdate(
1154 $dbw,
1155 $wikiPage,
1156 $newRevisionRecord,
1157 $user,
1158 $summary,
1159 $flags,
1160 $status,
1161 [ 'created' => true ]
1162 ),
1163 DeferredUpdates::PRESEND
1164 );
1165
1166 return $status;
1167 }
1168
1169 private function getAtomicSectionUpdate(
1170 IDatabase $dbw,
1171 WikiPage $wikiPage,
1172 RevisionRecord $newRevisionRecord,
1173 User $user,
1174 CommentStoreComment $summary,
1175 $flags,
1176 Status $status,
1177 $hints = []
1178 ) {
1179 return new AtomicSectionUpdate(
1180 $dbw,
1181 __METHOD__,
1182 function () use (
1183 $wikiPage, $newRevisionRecord, $user,
1184 $summary, $flags, $status, $hints
1185 ) {
1186 $newLegacyRevision = new Revision( $newRevisionRecord );
1187 $mainContent = $newRevisionRecord->getContent( 'main', RevisionRecord::RAW );
1188
1189 // Update links tables, site stats, etc.
1190 $this->derivedDataUpdater->prepareUpdate( $newRevisionRecord, $hints );
1191 $this->derivedDataUpdater->doUpdates();
1192
1193 // TODO: replace legacy hook!
1194 // TODO: avoid pass-by-reference, see T193950
1195
1196 if ( $hints['created'] ?? false ) {
1197 // Trigger post-create hook
1198 $params = [ &$wikiPage, &$user, $mainContent, $summary->text,
1199 $flags & EDIT_MINOR, null, null, &$flags, $newLegacyRevision ];
1200 Hooks::run( 'PageContentInsertComplete', $params );
1201 }
1202
1203 // Trigger post-save hook
1204 $params = [ &$wikiPage, &$user, $mainContent, $summary->text,
1205 $flags & EDIT_MINOR, null, null, &$flags, $newLegacyRevision,
1206 &$status, $this->getOriginalRevisionId(), $this->undidRevId ];
1207 Hooks::run( 'PageContentSaveComplete', $params );
1208 }
1209 );
1210 }
1211
1212 }