3 * Controller-like object for creating and updating pages by creating new revisions.
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.
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.
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
22 * @author Daniel Kinzler
25 namespace MediaWiki\Storage
;
27 use AtomicSectionUpdate
;
29 use CommentStoreComment
;
34 use InvalidArgumentException
;
37 use MediaWiki\Linker\LinkTarget
;
45 use Wikimedia\Assert\Assert
;
46 use Wikimedia\Rdbms\DBConnRef
;
47 use Wikimedia\Rdbms\DBUnexpectedError
;
48 use Wikimedia\Rdbms\LoadBalancer
;
52 * Controller-like object for creating and updating pages by creating new revisions.
54 * PageUpdater instances provide compare-and-swap (CAS) protection against concurrent updates
55 * between the time grabParentRevision() is called and saveRevision() inserts a new revision.
56 * This allows application logic to safely perform edit conflict resolution using the parent
59 * @see docs/pageupdater.txt for more information.
61 * MCR migration note: this replaces the relevant methods in WikiPage.
79 * @var DerivedPageDataUpdater
81 private $derivedDataUpdater;
86 private $loadBalancer;
91 private $revisionStore;
94 * @var boolean see $wgUseAutomaticEditSummaries
95 * @see $wgUseAutomaticEditSummaries
97 private $useAutomaticEditSummaries = true;
100 * @var int the RC patrol status the new revision should be marked with.
102 private $rcPatrolStatus = RecentChange
::PRC_UNPATROLLED
;
105 * @var bool whether to create a log entry for new page creations.
107 private $usePageCreationLog = true;
110 * @var boolean see $wgAjaxEditStash
112 private $ajaxEditStash = true;
117 private $originalRevId = false;
127 private $undidRevId = 0;
130 * @var RevisionSlotsUpdate
132 private $slotsUpdate;
137 private $status = null;
141 * @param WikiPage $wikiPage
142 * @param DerivedPageDataUpdater $derivedDataUpdater
143 * @param LoadBalancer $loadBalancer
144 * @param RevisionStore $revisionStore
146 public function __construct(
149 DerivedPageDataUpdater
$derivedDataUpdater,
150 LoadBalancer
$loadBalancer,
151 RevisionStore
$revisionStore
154 $this->wikiPage
= $wikiPage;
155 $this->derivedDataUpdater
= $derivedDataUpdater;
157 $this->loadBalancer
= $loadBalancer;
158 $this->revisionStore
= $revisionStore;
160 $this->slotsUpdate
= new RevisionSlotsUpdate();
164 * Can be used to enable or disable automatic summaries that are applied to certain kinds of
165 * changes, like completely blanking a page.
167 * @param bool $useAutomaticEditSummaries
168 * @see $wgUseAutomaticEditSummaries
170 public function setUseAutomaticEditSummaries( $useAutomaticEditSummaries ) {
171 $this->useAutomaticEditSummaries
= $useAutomaticEditSummaries;
175 * Sets the "patrolled" status of the edit.
176 * Callers should check the "patrol" and "autopatrol" permissions as appropriate.
178 * @see $wgUseRCPatrol
179 * @see $wgUseNPPatrol
181 * @param int $status RC patrol status, e.g. RecentChange::PRC_AUTOPATROLLED.
183 public function setRcPatrolStatus( $status ) {
184 $this->rcPatrolStatus
= $status;
188 * Whether to create a log entry for new page creations.
190 * @see $wgPageCreationLog
194 public function setUsePageCreationLog( $use ) {
195 $this->usePageCreationLog
= $use;
199 * @param bool $ajaxEditStash
200 * @see $wgAjaxEditStash
202 public function setAjaxEditStash( $ajaxEditStash ) {
203 $this->ajaxEditStash
= $ajaxEditStash;
206 private function getWikiId() {
207 return false; // TODO: get from RevisionStore!
211 * @param int $mode DB_MASTER or DB_REPLICA
215 private function getDBConnectionRef( $mode ) {
216 return $this->loadBalancer
->getConnectionRef( $mode, [], $this->getWikiId() );
222 private function getLinkTarget() {
223 // NOTE: eventually, we won't get a WikiPage passed into the constructor any more
224 return $this->wikiPage
->getTitle();
230 private function getTitle() {
231 // NOTE: eventually, we won't get a WikiPage passed into the constructor any more
232 return $this->wikiPage
->getTitle();
238 private function getWikiPage() {
239 // NOTE: eventually, we won't get a WikiPage passed into the constructor any more
240 return $this->wikiPage
;
244 * Checks whether this update conflicts with another update performed between the client
245 * loading data to prepare an edit, and the client committing the edit. This is intended to
246 * detect user level "edit conflict" when the latest revision known to the client
247 * is no longer the current revision when processing the update.
249 * An update expected to create a new page can be checked by setting $expectedParentRevision = 0.
250 * Such an update is considered to have a conflict if a current revision exists (that is,
251 * the page was created since the edit was initiated on the client).
253 * This method returning true indicates to calling code that edit conflict resolution should
254 * be applied before saving any data. It does not prevent the update from being performed, and
255 * it should not be confused with a "late" conflict indicated by the "edit-conflict" status.
256 * A "late" conflict is a CAS failure caused by an update being performed concurrently between
257 * the time grabParentRevision() was called and the time saveRevision() trying to insert the
260 * @note A user level edit conflict is not the same as the "edit-conflict" status triggered by
261 * a CAS failure. Calling this method establishes the CAS token, it does not check against it:
262 * This method calls grabParentRevision(), and thus causes the expected parent revision
263 * for the update to be fixed to the page's current revision at this point in time.
264 * It acts as a compare-and-swap (CAS) token in that it is guaranteed that saveRevision()
265 * will fail with the "edit-conflict" status if the current revision of the page changes after
266 * hasEditConflict() (or grabParentRevision()) was called and before saveRevision() could insert
269 * @see grabParentRevision()
271 * @param int $expectedParentRevision The ID of the revision the client expects to be the
272 * current one. Use 0 to indicate that the page is expected to not yet exist.
276 public function hasEditConflict( $expectedParentRevision ) {
277 $parent = $this->grabParentRevision();
278 $parentId = $parent ?
$parent->getId() : 0;
280 return $parentId !== $expectedParentRevision;
284 * Returns the revision that was the page's current revision when grabParentRevision()
285 * was first called. This revision is the expected parent revision of the update, and will be
286 * recorded as the new revision's parent revision (unless no new revision is created because
287 * the content was not changed).
289 * This method MUST not be called after saveRevision() was called!
291 * The current revision determined by the first call to this methods effectively acts a
292 * compare-and-swap (CAS) token which is checked by saveRevision(), which fails if any
293 * concurrent updates created a new revision.
295 * Application code should call this method before applying transformations to the new
296 * content that depend on the parent revision, e.g. adding/replacing sections, or resolving
297 * conflicts via a 3-way merge. This protects against race conditions triggered by concurrent
300 * @see DerivedPageDataUpdater::grabCurrentRevision()
302 * @note The expected parent revision is not to be confused with the logical base revision.
303 * The base revision is specified by the client, the parent revision is determined from the
304 * database. If base revision and parent revision are not the same, the updates is considered
305 * to require edit conflict resolution.
307 * @throws LogicException if called after saveRevision().
308 * @return RevisionRecord|null the parent revision, or null of the page does not yet exist.
310 public function grabParentRevision() {
311 return $this->derivedDataUpdater
->grabCurrentRevision();
317 private function getTimestampNow() {
318 // TODO: allow an override to be injected for testing
319 return wfTimestampNow();
323 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
326 * @return int Updated $flags
328 private function checkFlags( $flags ) {
329 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
330 $flags |
= ( $this->derivedDataUpdater
->pageExisted() ) ? EDIT_UPDATE
: EDIT_NEW
;
337 * Set the new content for the given slot role
339 * @param string $role A slot role name (such as "main")
340 * @param Content $content
342 public function setContent( $role, Content
$content ) {
343 // TODO: MCR: check the role and the content's model against the list of supported
344 // roles, see T194046.
346 if ( $role !== 'main' ) {
347 throw new InvalidArgumentException( 'Only the main slot is presently supported' );
350 $this->slotsUpdate
->modifyContent( $role, $content );
354 * Explicitly inherit a slot from some earlier revision.
356 * The primary use case for this is rollbacks, when slots are to be inherited from
357 * the rollback target, overriding the content from the parent revision (which is the
358 * revision being rolled back).
360 * This should typically not be used to inherit slots from the parent revision, which
361 * happens implicitly. Using this method causes the given slot to be treated as "modified"
362 * during revision creation, even if it has the same content as in the parent revision.
364 * @param SlotRecord $originalSlot A slot already existing in the database, to be inherited
365 * by the new revision.
367 public function inheritSlot( SlotRecord
$originalSlot ) {
368 // NOTE: this slot is inherited from some other revision, but it's
369 // a "modified" slot for the RevisionSlotsUpdate and DerivedPageDataUpdater,
370 // since it's not implicitly inherited from the parent revision.
371 $inheritedSlot = SlotRecord
::newInherited( $originalSlot );
372 $this->slotsUpdate
->modifySlot( $inheritedSlot );
376 * Removes the slot with the given role.
378 * This discontinues the "stream" of slots with this role on the page,
379 * preventing the new revision, and any subsequent revisions, from
380 * inheriting the slot with this role.
382 * @param string $role A slot role name (but not "main")
384 public function removeSlot( $role ) {
385 if ( $role === 'main' ) {
386 throw new InvalidArgumentException( 'Cannot remove the main slot!' );
389 $this->slotsUpdate
->removeSlot( $role );
393 * Returns the ID of an earlier revision that is being repeated or restored by this update.
395 * @return bool|int The original revision id, or false if no earlier revision is known to be
396 * repeated or restored by this update.
398 public function getOriginalRevisionId() {
399 return $this->originalRevId
;
403 * Sets the ID of an earlier revision that is being repeated or restored by this update.
404 * The new revision is expected to have the exact same content as the given original revision.
405 * This is used with rollbacks and with dummy "null" revisions which are created to record
406 * things like page moves.
408 * This value is passed to the PageContentSaveComplete and NewRevisionFromEditComplete hooks.
410 * @param int|bool $originalRevId The original revision id, or false if no earlier revision
411 * is known to be repeated or restored by this update.
413 public function setOriginalRevisionId( $originalRevId ) {
414 Assert
::parameterType( 'integer|boolean', $originalRevId, '$originalRevId' );
415 $this->originalRevId
= $originalRevId;
419 * Returns the revision ID set by setUndidRevisionId(), indicating what revision is being
420 * undone by this edit.
424 public function getUndidRevisionId() {
425 return $this->undidRevId
;
429 * Sets the ID of revision that was undone by the present update.
430 * This is used with the "undo" action, and is expected to hold the oldest revision ID
431 * in case more then one revision is being undone.
433 * @param int $undidRevId
435 public function setUndidRevisionId( $undidRevId ) {
436 Assert
::parameterType( 'integer', $undidRevId, '$undidRevId' );
437 $this->undidRevId
= $undidRevId;
441 * Sets a tag to apply to this update.
442 * Callers are responsible for permission checks,
443 * using ChangeTags::canAddTagsAccompanyingChange.
446 public function addTag( $tag ) {
447 Assert
::parameterType( 'string', $tag, '$tag' );
448 $this->tags
[] = trim( $tag );
452 * Sets tags to apply to this update.
453 * Callers are responsible for permission checks,
454 * using ChangeTags::canAddTagsAccompanyingChange.
455 * @param string[] $tags
457 public function addTags( array $tags ) {
458 Assert
::parameterElementType( 'string', $tags, '$tags' );
459 foreach ( $tags as $tag ) {
460 $this->addTag( $tag );
465 * Returns the list of tags set using the addTag() method.
469 public function getExplicitTags() {
474 * @param int $flags Bit mask: a bit mask of EDIT_XXX flags.
477 private function computeEffectiveTags( $flags ) {
480 foreach ( $this->slotsUpdate
->getModifiedRoles() as $role ) {
481 $old_content = $this->getParentContent( $role );
483 $handler = $this->getContentHandler( $role );
484 $content = $this->slotsUpdate
->getModifiedSlot( $role )->getContent();
486 // TODO: MCR: Do this for all slots. Also add tags for removing roles!
487 $tag = $handler->getChangeTag( $old_content, $content, $flags );
488 // If there is no applicable tag, null is returned, so we need to check
494 // Check for undo tag
495 if ( $this->undidRevId
!== 0 && in_array( 'mw-undo', ChangeTags
::getSoftwareTags() ) ) {
499 return array_unique( $tags );
503 * Returns the content of the given slot of the parent revision, with no audience checks applied.
504 * If there is no parent revision or the slot is not defined, this returns null.
506 * @param string $role slot role name
507 * @return Content|null
509 private function getParentContent( $role ) {
510 $parent = $this->grabParentRevision();
512 if ( $parent && $parent->hasSlot( $role ) ) {
513 return $parent->getContent( $role, RevisionRecord
::RAW
);
520 * @param string $role slot role name
521 * @return ContentHandler
523 private function getContentHandler( $role ) {
524 // TODO: inject something like a ContentHandlerRegistry
525 if ( $this->slotsUpdate
->isModifiedSlot( $role ) ) {
526 $slot = $this->slotsUpdate
->getModifiedSlot( $role );
528 $parent = $this->grabParentRevision();
531 $slot = $parent->getSlot( $role, RevisionRecord
::RAW
);
533 throw new RevisionAccessException( 'No such slot: ' . $role );
537 return ContentHandler
::getForModelID( $slot->getModel() );
541 * @param int $flags Bit mask: a bit mask of EDIT_XXX flags.
543 * @return CommentStoreComment
545 private function makeAutoSummary( $flags ) {
546 if ( !$this->useAutomaticEditSummaries ||
( $flags & EDIT_AUTOSUMMARY
) === 0 ) {
547 return CommentStoreComment
::newUnsavedComment( '' );
550 // NOTE: this generates an auto-summary for SOME RANDOM changed slot!
551 // TODO: combine auto-summaries for multiple slots!
552 // XXX: this logic should not be in the storage layer!
553 $roles = $this->slotsUpdate
->getModifiedRoles();
554 $role = reset( $roles );
556 if ( $role === false ) {
557 return CommentStoreComment
::newUnsavedComment( '' );
560 $handler = $this->getContentHandler( $role );
561 $content = $this->slotsUpdate
->getModifiedSlot( $role )->getContent();
562 $old_content = $this->getParentContent( $role );
563 $summary = $handler->getAutosummary( $old_content, $content, $flags );
565 return CommentStoreComment
::newUnsavedComment( $summary );
569 * Change an existing article or create a new article. Updates RC and all necessary caches,
570 * optionally via the deferred update array. This does not check user permissions.
572 * It is guaranteed that saveRevision() will fail if the current revision of the page
573 * changes after grabParentRevision() was called and before saveRevision() can insert
574 * a new revision, as per the CAS mechanism described above.
576 * The caller is however responsible for calling hasEditConflict() to detect a
577 * user-level edit conflict, and to adjust the content of the new revision accordingly,
578 * e.g. by using a 3-way-merge.
580 * MCR migration note: this replaces WikiPage::doEditContent. Callers that change to using
581 * saveRevision() now need to check the "minoredit" themselves before using EDIT_MINOR.
583 * @param CommentStoreComment $summary Edit summary
584 * @param int $flags Bitfield:
586 * Create a new page, or fail with "edit-already-exists" if the page exists.
588 * Create a new revision, or fail with "edit-gone-missing" if the page does not exist.
590 * Mark this revision as minor
592 * Do not log the change in recentchanges
594 * Mark the revision as automated ("bot edit")
596 * Fill in blank summaries with generated text where possible
598 * Signal that the page retrieve/save cycle happened entirely in this request.
600 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the expected state is detected
601 * automatically via grabParentRevision(). In this case, the "edit-already-exists" or
602 * "edit-gone-missing" errors may still be triggered due to race conditions, if the page
603 * was unexpectedly created or deleted while revision creation is in progress. This can be
604 * viewed as part of the CAS mechanism described above.
606 * @return RevisionRecord|null The new revision, or null if no new revision was created due
607 * to a failure or a null-edit. Use isUnchanged(), wasSuccessful() and getStatus()
608 * to determine the outcome of the revision creation.
610 * @throws MWException
611 * @throws RuntimeException
613 public function saveRevision( CommentStoreComment
$summary, $flags = 0 ) {
614 // Defend against mistakes caused by differences with the
615 // signature of WikiPage::doEditContent.
616 Assert
::parameterType( 'integer', $flags, '$flags' );
617 Assert
::parameterType( 'CommentStoreComment', $summary, '$summary' );
619 if ( $this->wasCommitted() ) {
620 throw new RuntimeException( 'saveRevision() has already been called on this PageUpdater!' );
623 // Low-level sanity check
624 if ( $this->getLinkTarget()->getText() === '' ) {
625 throw new RuntimeException( 'Something is trying to edit an article with an empty title' );
628 // TODO: MCR: check the role and the content's model against the list of supported
629 // and required roles, see T194046.
631 // Make sure the given content type is allowed for this page
632 // TODO: decide: Extend check to other slots? Consider the role in check? [PageType]
633 $mainContentHandler = $this->getContentHandler( 'main' );
634 if ( !$mainContentHandler->canBeUsedOn( $this->getTitle() ) ) {
635 $this->status
= Status
::newFatal( 'content-not-allowed-here',
636 ContentHandler
::getLocalizedName( $mainContentHandler->getModelID() ),
637 $this->getTitle()->getPrefixedText()
642 // Load the data from the master database if needed. Needed to check flags.
643 // NOTE: This grabs the parent revision as the CAS token, if grabParentRevision
644 // wasn't called yet. If the page is modified by another process before we are done with
645 // it, this method must fail (with status 'edit-conflict')!
646 // NOTE: The parent revision may be different from $this->baseRevisionId.
647 $this->grabParentRevision();
648 $flags = $this->checkFlags( $flags );
650 // Avoid statsd noise and wasted cycles check the edit stash (T136678)
651 if ( ( $flags & EDIT_INTERNAL
) ||
( $flags & EDIT_FORCE_BOT
) ) {
654 $useStashed = $this->ajaxEditStash
;
657 // TODO: use this only for the legacy hook, and only if something uses the legacy hook
658 $wikiPage = $this->getWikiPage();
662 // Prepare the update. This performs PST and generates the canonical ParserOutput.
663 $this->derivedDataUpdater
->prepareContent(
669 // TODO: don't force initialization here!
670 // This is a hack to work around the fact that late initialization of the ParserOutput
671 // causes ApiFlowEditHeaderTest::testCache to fail. Whether that failure indicates an
672 // actual problem, or is just an issue with the test setup, remains to be determined
674 // Anomie said in 2018-03:
676 I suspect that what's breaking is this:
678 The old version of WikiPage::doEditContent() called prepareContentForEdit() which
679 generated the ParserOutput right then, so when doEditUpdates() gets called from the
680 DeferredUpdate scheduled by WikiPage::doCreate() there's no need to parse. I note
681 there's a comment there that says "Get the pre-save transform content and final
683 The new version of WikiPage::doEditContent() makes a PageUpdater and calls its
684 saveRevision(), which calls DerivedPageDataUpdater::prepareContent() and
685 PageUpdater::doCreate() without ever having to actually generate a ParserOutput.
686 Thus, when DerivedPageDataUpdater::doUpdates() is called from the DeferredUpdate
687 scheduled by PageUpdater::doCreate(), it does find that it needs to parse at that point.
689 And the order of operations in that Flow test is presumably:
691 - Create a page with a call to WikiPage::doEditContent(), in a way that somehow avoids
692 processing the DeferredUpdate.
693 - Set up the "no set!" mock cache in Flow\Tests\Api\ApiTestCase::expectCacheInvalidate()
694 - Then, during the course of doing that test, a $db->commit() results in the
695 DeferredUpdates being run.
697 $this->derivedDataUpdater
->getCanonicalParserOutput();
699 $mainContent = $this->derivedDataUpdater
->getSlots()->getContent( 'main' );
701 // Trigger pre-save hook (using provided edit summary)
702 $hookStatus = Status
::newGood( [] );
703 // TODO: replace legacy hook!
704 // TODO: avoid pass-by-reference, see T193950
705 $hook_args = [ &$wikiPage, &$user, &$mainContent, &$summary,
706 $flags & EDIT_MINOR
, null, null, &$flags, &$hookStatus ];
707 // Check if the hook rejected the attempted save
708 if ( !Hooks
::run( 'PageContentSave', $hook_args ) ) {
709 if ( $hookStatus->isOK() ) {
710 // Hook returned false but didn't call fatal(); use generic message
711 $hookStatus->fatal( 'edit-hook-aborted' );
714 $this->status
= $hookStatus;
718 // Provide autosummaries if one is not provided and autosummaries are enabled
719 // XXX: $summary == null seems logical, but the empty string may actually come from the user
720 // XXX: Move this logic out of the storage layer! It does not belong here! Use a callback?
721 if ( $summary->text
=== '' && $summary->data
=== null ) {
722 $summary = $this->makeAutoSummary( $flags );
725 // Actually create the revision and create/update the page.
726 // Do NOT yet set $this->status!
727 if ( $flags & EDIT_UPDATE
) {
728 $status = $this->doModify( $summary, $this->user
, $flags );
730 $status = $this->doCreate( $summary, $this->user
, $flags );
733 // Promote user to any groups they meet the criteria for
734 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
735 $user->addAutopromoteOnceGroups( 'onEdit' );
736 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
739 // NOTE: set $this->status only after all hooks have been called,
740 // so wasCommitted doesn't return true wehn called indirectly from a hook handler!
741 $this->status
= $status;
743 // TODO: replace bad status with Exceptions!
744 return ( $this->status
&& $this->status
->isOK() )
745 ?
$this->status
->value
['revision-record']
750 * Whether saveRevision() has been called on this instance
754 public function wasCommitted() {
755 return $this->status
!== null;
759 * The Status object indicating whether saveRevision() was successful, or null if
760 * saveRevision() was not yet called on this instance.
762 * @note This is here for compatibility with WikiPage::doEditContent. It may be deprecated
765 * Possible status errors:
766 * edit-hook-aborted: The ArticleSave hook aborted the update but didn't
767 * set the fatal flag of $status.
768 * edit-gone-missing: In update mode, but the article didn't exist.
769 * edit-conflict: In update mode, the article changed unexpectedly.
770 * edit-no-change: Warning that the text was the same as before.
771 * edit-already-exists: In creation mode, but the article already exists.
773 * Extensions may define additional errors.
775 * $return->value will contain an associative array with members as follows:
776 * new: Boolean indicating if the function attempted to create a new article.
777 * revision: The revision object for the inserted revision, or null.
779 * @return null|Status
781 public function getStatus() {
782 return $this->status
;
786 * Whether saveRevision() completed successfully
790 public function wasSuccessful() {
791 return $this->status
&& $this->status
->isOK();
795 * Whether saveRevision() was called and created a new page.
799 public function isNew() {
800 return $this->status
&& $this->status
->isOK() && $this->status
->value
['new'];
804 * Whether saveRevision() did not create a revision because the content didn't change
805 * (null-edit). Whether the content changed or not is determined by
806 * DerivedPageDataUpdater::isChange().
810 public function isUnchanged() {
812 && $this->status
->isOK()
813 && $this->status
->value
['revision-record'] === null;
817 * The new revision created by saveRevision(), or null if saveRevision() has not yet been
818 * called, failed, or did not create a new revision because the content did not change.
820 * @return RevisionRecord|null
822 public function getNewRevision() {
823 return ( $this->status
&& $this->status
->isOK() )
824 ?
$this->status
->value
['revision-record']
829 * Constructs a MutableRevisionRecord based on the Content prepared by the
830 * DerivedPageDataUpdater. This takes care of inheriting slots, updating slots
831 * with PST applied, and removing discontinued slots.
833 * This calls Content::prepareSave() to verify that the slot content can be saved.
834 * The $status parameter is updated with any errors or warnings found by Content::prepareSave().
836 * @param CommentStoreComment $comment
838 * @param string $timestamp
840 * @param Status $status
842 * @return MutableRevisionRecord
844 private function makeNewRevision(
845 CommentStoreComment
$comment,
851 $wikiPage = $this->getWikiPage();
852 $title = $this->getTitle();
853 $parent = $this->grabParentRevision();
855 $rev = new MutableRevisionRecord( $title, $this->getWikiId() );
856 $rev->setPageId( $title->getArticleID() );
859 $oldid = $parent->getId();
860 $rev->setParentId( $oldid );
865 $rev->setComment( $comment );
866 $rev->setUser( $user );
867 $rev->setTimestamp( $timestamp );
868 $rev->setMinorEdit( ( $flags & EDIT_MINOR
) > 0 );
870 foreach ( $this->derivedDataUpdater
->getSlots()->getSlots() as $slot ) {
871 $content = $slot->getContent();
873 // XXX: We may push this up to the "edit controller" level, see T192777.
874 // TODO: change the signature of PrepareSave to not take a WikiPage!
875 $prepStatus = $content->prepareSave( $wikiPage, $flags, $oldid, $user );
877 if ( $prepStatus->isOK() ) {
878 $rev->setSlot( $slot );
881 // TODO: MCR: record which problem arose in which slot.
882 $status->merge( $prepStatus );
889 * @param CommentStoreComment $summary The edit summary
890 * @param User $user The revision's author
891 * @param int $flags EXIT_XXX constants
893 * @throws MWException
896 private function doModify( CommentStoreComment
$summary, User
$user, $flags ) {
897 $wikiPage = $this->getWikiPage(); // TODO: use for legacy hooks only!
899 // Update article, but only if changed.
900 $status = Status
::newGood( [ 'new' => false, 'revision' => null, 'revision-record' => null ] );
902 // Convenience variables
903 $now = $this->getTimestampNow();
905 $oldRev = $this->grabParentRevision();
906 $oldid = $oldRev ?
$oldRev->getId() : 0;
909 // Article gone missing
910 $status->fatal( 'edit-gone-missing' );
915 $newRevisionRecord = $this->makeNewRevision(
923 if ( !$status->isOK() ) {
927 // XXX: we may want a flag that allows a null revision to be forced!
928 $changed = $this->derivedDataUpdater
->isChange();
929 $mainContent = $newRevisionRecord->getContent( 'main' );
931 $dbw = $this->getDBConnectionRef( DB_MASTER
);
934 $dbw->startAtomic( __METHOD__
);
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' );
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).
956 // Save revision content and meta-data
957 $newRevisionRecord = $this->revisionStore
->insertRevisionOn( $newRevisionRecord, $dbw );
958 $newLegacyRevision = new Revision( $newRevisionRecord );
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." );
967 // TODO: replace legacy hook!
968 $tags = $this->computeEffectiveTags( $flags );
970 'NewRevisionFromEditComplete',
971 [ $wikiPage, $newLegacyRevision, $this->getOriginalRevisionId(), $user, &$tags ]
974 // Update recentchanges
975 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
976 // Add RC row to the DB
977 RecentChange
::notifyEdit(
980 $newRevisionRecord->isMinor(),
982 $summary->text
, // TODO: pass object when that becomes possible
984 $newRevisionRecord->getTimestamp(),
985 ( $flags & EDIT_FORCE_BOT
) > 0,
988 $newRevisionRecord->getSize(),
989 $newRevisionRecord->getId(),
990 $this->rcPatrolStatus
,
995 $user->incEditCount();
997 $dbw->endAtomic( __METHOD__
);
999 // T34948: revision ID must be set to page {{REVISIONID}} and
1000 // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1001 // Since we don't insert a new revision into the database, the least
1002 // error-prone way is to reuse given old revision.
1003 $newRevisionRecord = $oldRev;
1004 $newLegacyRevision = new Revision( $newRevisionRecord );
1008 // Return the new revision to the caller
1009 $status->value
['revision-record'] = $newRevisionRecord;
1011 // TODO: globally replace usages of 'revision' with getNewRevision()
1012 $status->value
['revision'] = $newLegacyRevision;
1014 $status->warning( 'edit-no-change' );
1015 // Update page_touched as updateRevisionOn() was not called.
1016 // Other cache updates are managed in WikiPage::onArticleEdit()
1017 // via WikiPage::doEditUpdates().
1018 $this->getTitle()->invalidateCache( $now );
1021 // Do secondary updates once the main changes have been committed...
1022 // NOTE: the updates have to be processed before sending the response to the client
1023 // (DeferredUpdates::PRESEND), otherwise the client may already be following the
1024 // HTTP redirect to the standard view before dervide data has been created - most
1025 // importantly, before the parser cache has been updated. This would cause the
1026 // content to be parsed a second time, or may cause stale content to be shown.
1027 DeferredUpdates
::addUpdate(
1028 new AtomicSectionUpdate(
1032 $wikiPage, $newRevisionRecord, $newLegacyRevision, $user, $mainContent,
1033 $summary, $flags, $changed, $status
1035 // Update links tables, site stats, etc.
1036 $this->derivedDataUpdater
->prepareUpdate(
1039 'changed' => $changed,
1042 $this->derivedDataUpdater
->doUpdates();
1044 // Trigger post-save hook
1045 // TODO: replace legacy hook!
1046 // TODO: avoid pass-by-reference, see T193950
1047 $params = [ &$wikiPage, &$user, $mainContent, $summary->text
, $flags & EDIT_MINOR
,
1048 null, null, &$flags, $newLegacyRevision, &$status, $this->getOriginalRevisionId(),
1049 $this->undidRevId
];
1050 Hooks
::run( 'PageContentSaveComplete', $params );
1053 DeferredUpdates
::PRESEND
1060 * @param CommentStoreComment $summary The edit summary
1061 * @param User $user The revision's author
1062 * @param int $flags EXIT_XXX constants
1064 * @throws DBUnexpectedError
1065 * @throws MWException
1068 private function doCreate( CommentStoreComment
$summary, User
$user, $flags ) {
1069 $wikiPage = $this->getWikiPage(); // TODO: use for legacy hooks only!
1071 if ( !$this->derivedDataUpdater
->getSlots()->hasSlot( 'main' ) ) {
1072 throw new PageUpdateException( 'Must provide a main slot when creating a page!' );
1075 $status = Status
::newGood( [ 'new' => true, 'revision' => null, 'revision-record' => null ] );
1077 $now = $this->getTimestampNow();
1079 $newRevisionRecord = $this->makeNewRevision(
1087 if ( !$status->isOK() ) {
1091 $dbw = $this->getDBConnectionRef( DB_MASTER
);
1092 $dbw->startAtomic( __METHOD__
);
1094 // Add the page record unless one already exists for the title
1095 // TODO: move to storage service
1096 $newid = $wikiPage->insertOn( $dbw );
1097 if ( $newid === false ) {
1098 $dbw->endAtomic( __METHOD__
); // nothing inserted
1099 $status->fatal( 'edit-already-exists' );
1101 return $status; // nothing done
1104 // At this point we are now comitted to returning an OK
1105 // status unless some DB query error or other exception comes up.
1106 // This way callers don't have to call rollback() if $status is bad
1107 // unless they actually try to catch exceptions (which is rare).
1108 $newRevisionRecord->setPageId( $newid );
1110 // Save the revision text...
1111 $newRevisionRecord = $this->revisionStore
->insertRevisionOn( $newRevisionRecord, $dbw );
1112 $newLegacyRevision = new Revision( $newRevisionRecord );
1114 // Update the page record with revision data
1115 // TODO: move to storage service
1116 if ( !$wikiPage->updateRevisionOn( $dbw, $newLegacyRevision, 0 ) ) {
1117 throw new PageUpdateException( "Failed to update page row to use new revision." );
1120 // TODO: replace legacy hook!
1121 $tags = $this->computeEffectiveTags( $flags );
1123 'NewRevisionFromEditComplete',
1124 [ $wikiPage, $newLegacyRevision, false, $user, &$tags ]
1127 // Update recentchanges
1128 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1129 // Add RC row to the DB
1130 RecentChange
::notifyNew(
1133 $newRevisionRecord->isMinor(),
1135 $summary->text
, // TODO: pass object when that becomes possible
1136 ( $flags & EDIT_FORCE_BOT
) > 0,
1138 $newRevisionRecord->getSize(),
1139 $newRevisionRecord->getId(),
1140 $this->rcPatrolStatus
,
1145 $user->incEditCount();
1147 if ( $this->usePageCreationLog
) {
1148 // Log the page creation
1149 // @TODO: Do we want a 'recreate' action?
1150 $logEntry = new ManualLogEntry( 'create', 'create' );
1151 $logEntry->setPerformer( $user );
1152 $logEntry->setTarget( $this->getTitle() );
1153 $logEntry->setComment( $summary->text
);
1154 $logEntry->setTimestamp( $now );
1155 $logEntry->setAssociatedRevId( $newRevisionRecord->getId() );
1156 $logEntry->insert();
1157 // Note that we don't publish page creation events to recentchanges
1158 // (i.e. $logEntry->publish()) since this would create duplicate entries,
1159 // one for the edit and one for the page creation.
1162 $dbw->endAtomic( __METHOD__
);
1164 // Return the new revision to the caller
1165 // TODO: globally replace usages of 'revision' with getNewRevision()
1166 $status->value
['revision'] = $newLegacyRevision;
1167 $status->value
['revision-record'] = $newRevisionRecord;
1169 // XXX: make sure we are not loading the Content from the DB
1170 $mainContent = $newRevisionRecord->getContent( 'main' );
1172 // Do secondary updates once the main changes have been committed...
1173 DeferredUpdates
::addUpdate(
1174 new AtomicSectionUpdate(
1187 // Update links, etc.
1188 $this->derivedDataUpdater
->prepareUpdate(
1190 [ 'created' => true ]
1192 $this->derivedDataUpdater
->doUpdates();
1194 // Trigger post-create hook
1195 // TODO: replace legacy hook!
1196 // TODO: avoid pass-by-reference, see T193950
1197 $params = [ &$wikiPage, &$user, $mainContent, $summary->text
,
1198 $flags & EDIT_MINOR
, null, null, &$flags, $newLegacyRevision ];
1199 Hooks
::run( 'PageContentInsertComplete', $params );
1200 // Trigger post-save hook
1201 // TODO: replace legacy hook!
1202 $params = array_merge( $params, [ &$status, $this->getOriginalRevisionId(), 0 ] );
1203 Hooks
::run( 'PageContentSaveComplete', $params );
1206 DeferredUpdates
::PRESEND