3 * Service for looking up page 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
20 * Attribution notice: when this file was created, much of its content was taken
21 * from the Revision.php file as present in release 1.30. Refer to the history
22 * of that file for original authorship.
27 namespace MediaWiki\Storage
;
31 use CommentStoreComment
;
34 use DBAccessObjectUtils
;
37 use InvalidArgumentException
;
40 use MediaWiki\Linker\LinkTarget
;
41 use MediaWiki\User\UserIdentity
;
42 use MediaWiki\User\UserIdentityValue
;
45 use MWUnknownContentModelException
;
46 use Psr\Log\LoggerAwareInterface
;
47 use Psr\Log\LoggerInterface
;
48 use Psr\Log\NullLogger
;
55 use Wikimedia\Assert\Assert
;
56 use Wikimedia\Rdbms\Database
;
57 use Wikimedia\Rdbms\DBConnRef
;
58 use Wikimedia\Rdbms\IDatabase
;
59 use Wikimedia\Rdbms\LoadBalancer
;
62 * Service for looking up page revisions.
66 * @note This was written to act as a drop-in replacement for the corresponding
67 * static methods in Revision.
70 implements IDBAccessObject
, RevisionFactory
, RevisionLookup
, LoggerAwareInterface
{
72 const ROW_CACHE_KEY
= 'revision-row-1.29';
87 private $contentHandlerUseDB = true;
92 private $loadBalancer;
102 private $commentStore;
105 * @var ActorMigration
107 private $actorMigration;
110 * @var LoggerInterface
115 * @var NameTableStore
117 private $contentModelStore;
120 * @var NameTableStore
122 private $slotRoleStore;
124 /** @var int An appropriate combination of SCHEMA_COMPAT_XXX flags. */
125 private $mcrMigrationStage;
128 * @todo $blobStore should be allowed to be any BlobStore!
130 * @param LoadBalancer $loadBalancer
131 * @param SqlBlobStore $blobStore
132 * @param WANObjectCache $cache
133 * @param CommentStore $commentStore
134 * @param NameTableStore $contentModelStore
135 * @param NameTableStore $slotRoleStore
136 * @param int $mcrMigrationStage An appropriate combination of SCHEMA_COMPAT_XXX flags
137 * @param ActorMigration $actorMigration
138 * @param bool|string $wikiId
140 * @throws MWException if $mcrMigrationStage or $wikiId is invalid.
142 public function __construct(
143 LoadBalancer
$loadBalancer,
144 SqlBlobStore
$blobStore,
145 WANObjectCache
$cache,
146 CommentStore
$commentStore,
147 NameTableStore
$contentModelStore,
148 NameTableStore
$slotRoleStore,
150 ActorMigration
$actorMigration,
153 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
154 Assert
::parameterType( 'integer', $mcrMigrationStage, '$mcrMigrationStage' );
156 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== SCHEMA_COMPAT_READ_BOTH
,
157 '$mcrMigrationStage',
158 'Reading from the old and the new schema at the same time is not supported.'
161 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== 0,
162 '$mcrMigrationStage',
163 'Reading needs to be enabled for the old or the new schema.'
166 ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) !== 0,
167 '$mcrMigrationStage',
168 'Writing needs to be enabled for the old or the new schema.'
171 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_OLD
) === 0
172 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) !== 0,
173 '$mcrMigrationStage',
174 'Cannot read the old schema when not also writing it.'
177 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_NEW
) === 0
178 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) !== 0,
179 '$mcrMigrationStage',
180 'Cannot read the new schema when not also writing it.'
183 $this->loadBalancer
= $loadBalancer;
184 $this->blobStore
= $blobStore;
185 $this->cache
= $cache;
186 $this->commentStore
= $commentStore;
187 $this->contentModelStore
= $contentModelStore;
188 $this->slotRoleStore
= $slotRoleStore;
189 $this->mcrMigrationStage
= $mcrMigrationStage;
190 $this->actorMigration
= $actorMigration;
191 $this->wikiId
= $wikiId;
192 $this->logger
= new NullLogger();
196 * @param int $flags A combination of SCHEMA_COMPAT_XXX flags.
197 * @return bool True if all the given flags were set in the $mcrMigrationStage
198 * parameter passed to the constructor.
200 private function hasMcrSchemaFlags( $flags ) {
201 return ( $this->mcrMigrationStage
& $flags ) === $flags;
204 public function setLogger( LoggerInterface
$logger ) {
205 $this->logger
= $logger;
209 * @return bool Whether the store is read-only
211 public function isReadOnly() {
212 return $this->blobStore
->isReadOnly();
218 public function getContentHandlerUseDB() {
219 return $this->contentHandlerUseDB
;
223 * @param bool $contentHandlerUseDB
224 * @throws MWException
226 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
227 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
)
228 ||
$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
)
230 if ( !$contentHandlerUseDB ) {
231 throw new MWException(
232 'Content model must be stored in the database for multi content revision migration.'
236 $this->contentHandlerUseDB
= $contentHandlerUseDB;
240 * @return LoadBalancer
242 private function getDBLoadBalancer() {
243 return $this->loadBalancer
;
247 * @param int $mode DB_MASTER or DB_REPLICA
251 private function getDBConnection( $mode ) {
252 $lb = $this->getDBLoadBalancer();
253 return $lb->getConnection( $mode, [], $this->wikiId
);
257 * @param IDatabase $connection
259 private function releaseDBConnection( IDatabase
$connection ) {
260 $lb = $this->getDBLoadBalancer();
261 $lb->reuseConnection( $connection );
265 * @param int $mode DB_MASTER or DB_REPLICA
269 private function getDBConnectionRef( $mode ) {
270 $lb = $this->getDBLoadBalancer();
271 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
275 * Determines the page Title based on the available information.
277 * MCR migration note: this corresponds to Revision::getTitle
279 * @note this method should be private, external use should be avoided!
281 * @param int|null $pageId
282 * @param int|null $revId
283 * @param int $queryFlags
286 * @throws RevisionAccessException
288 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
289 if ( !$pageId && !$revId ) {
290 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
293 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
294 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
295 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
296 $queryFlags = self
::READ_NORMAL
;
299 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false );
300 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
301 $titleFlags = ( $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0 );
303 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
304 if ( $canUseTitleNewFromId ) {
305 // TODO: better foreign title handling (introduce TitleFactory)
306 $title = Title
::newFromID( $pageId, $titleFlags );
312 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
313 $canUseRevId = ( $revId !== null && $revId > 0 );
315 if ( $canUseRevId ) {
316 $dbr = $this->getDBConnectionRef( $dbMode );
317 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
318 $row = $dbr->selectRow(
319 [ 'revision', 'page' ],
328 [ 'rev_id' => $revId ],
331 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
334 // TODO: better foreign title handling (introduce TitleFactory)
335 return Title
::newFromRow( $row );
339 // If we still don't have a title, fallback to master if that wasn't already happening.
340 if ( $dbMode !== DB_MASTER
) {
341 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
344 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
345 [ 'trace' => wfBacktrace() ]
351 throw new RevisionAccessException(
352 "Could not determine title for page ID $pageId and revision ID $revId"
357 * @param mixed $value
358 * @param string $name
360 * @throws IncompleteRevisionException if $value is null
361 * @return mixed $value, if $value is not null
363 private function failOnNull( $value, $name ) {
364 if ( $value === null ) {
365 throw new IncompleteRevisionException(
366 "$name must not be " . var_export( $value, true ) . "!"
374 * @param mixed $value
375 * @param string $name
377 * @throws IncompleteRevisionException if $value is empty
378 * @return mixed $value, if $value is not null
380 private function failOnEmpty( $value, $name ) {
381 if ( $value === null ||
$value === 0 ||
$value === '' ) {
382 throw new IncompleteRevisionException(
383 "$name must not be " . var_export( $value, true ) . "!"
391 * Insert a new revision into the database, returning the new revision record
392 * on success and dies horribly on failure.
394 * MCR migration note: this replaces Revision::insertOn
396 * @param RevisionRecord $rev
397 * @param IDatabase $dbw (master connection)
399 * @throws InvalidArgumentException
400 * @return RevisionRecord the new revision record.
402 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
403 // TODO: pass in a DBTransactionContext instead of a database connection.
404 $this->checkDatabaseWikiId( $dbw );
406 $slotRoles = $rev->getSlotRoles();
408 // Make sure the main slot is always provided throughout migration
409 if ( !in_array( 'main', $slotRoles ) ) {
410 throw new InvalidArgumentException(
411 'main slot must be provided'
415 // While inserting into the old schema make sure only the main slot is allowed.
416 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) && $slotRoles !== [ 'main' ] ) {
417 throw new InvalidArgumentException(
418 'Only the main slot is supported when writing to the pre-MCR schema!'
423 $this->failOnNull( $rev->getSize(), 'size field' );
424 $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
425 $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
426 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
427 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
428 $this->failOnNull( $user->getId(), 'user field' );
429 $this->failOnEmpty( $user->getName(), 'user_text field' );
431 // TODO: we shouldn't need an actual Title here.
432 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
433 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
435 $parentId = $rev->getParentId() === null
436 ?
$this->getPreviousRevisionId( $dbw, $rev )
437 : $rev->getParentId();
439 /** @var RevisionRecord $rev */
440 $rev = $dbw->doAtomicSection(
442 function ( IDatabase
$dbw, $fname ) use (
450 return $this->insertRevisionInternal(
463 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
464 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
465 Assert
::postcondition(
466 $rev->getComment( RevisionRecord
::RAW
) !== null,
467 'revision must have a comment'
469 Assert
::postcondition(
470 $rev->getUser( RevisionRecord
::RAW
) !== null,
471 'revision must have a user'
474 // Trigger exception if the main slot is missing.
475 // Technically, this could go away after MCR migration: while
476 // calling code may require a main slot to exist, RevisionStore
477 // really should not know or care about that requirement.
478 $rev->getSlot( 'main', RevisionRecord
::RAW
);
480 foreach ( $slotRoles as $role ) {
481 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
482 Assert
::postcondition(
483 $slot->getContent() !== null,
484 $role . ' slot must have content'
486 Assert
::postcondition(
487 $slot->hasRevision(),
488 $role . ' slot must have a revision associated'
492 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
494 // TODO: deprecate in 1.32!
495 $legacyRevision = new Revision( $rev );
496 Hooks
::run( 'RevisionInsertComplete', [ &$legacyRevision, null, null ] );
501 private function insertRevisionInternal(
505 CommentStoreComment
$comment,
510 $slotRoles = $rev->getSlotRoles();
512 $revisionRow = $this->insertRevisionRowOn(
519 $revisionId = $revisionRow['rev_id'];
522 BlobStore
::PAGE_HINT
=> $pageId,
523 BlobStore
::REVISION_HINT
=> $revisionId,
524 BlobStore
::PARENT_HINT
=> $parentId,
528 foreach ( $slotRoles as $role ) {
529 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
531 if ( $slot->hasRevision() ) {
532 // If the SlotRecord already has a revision ID set, this means it already exists
533 // in the database, and should already belong to the current revision.
534 // TODO: properly abort transaction if the assertion fails!
536 $slot->getRevision() === $revisionId,
537 'slot role ' . $slot->getRole(),
538 'Existing slot should belong to revision '
539 . $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
542 // Slot exists, nothing to do, move along.
543 // This happens when restoring archived revisions.
545 $newSlots[$role] = $slot;
547 // Write the main slot's text ID to the revision table for backwards compatibility
548 if ( $slot->getRole() === 'main'
549 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
551 $blobAddress = $slot->getAddress();
552 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
555 $newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $title, $blobHints );
559 $this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
561 $rev = new RevisionStoreRecord(
565 (object)$revisionRow,
566 new RevisionSlots( $newSlots ),
574 * @param IDatabase $dbw
575 * @param int $revisionId
576 * @param string &$blobAddress (may change!)
578 private function updateRevisionTextId( IDatabase
$dbw, $revisionId, &$blobAddress ) {
579 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
581 throw new LogicException(
582 'Blob address not supported in 1.29 database schema: ' . $blobAddress
586 // getTextIdFromAddress() is free to insert something into the text table, so $textId
587 // may be a new value, not anything already contained in $blobAddress.
588 $blobAddress = SqlBlobStore
::makeAddressFromTextId( $textId );
592 [ 'rev_text_id' => $textId ],
593 [ 'rev_id' => $revisionId ],
599 * @param IDatabase $dbw
600 * @param int $revisionId
601 * @param SlotRecord $protoSlot
602 * @param Title $title
603 * @param array $blobHints See the BlobStore::XXX_HINT constants
606 private function insertSlotOn(
609 SlotRecord
$protoSlot,
611 array $blobHints = []
613 if ( $protoSlot->hasAddress() ) {
614 $blobAddress = $protoSlot->getAddress();
616 $blobAddress = $this->storeContentBlob( $protoSlot, $title, $blobHints );
619 // Write the main slot's text ID to the revision table for backwards compatibility
620 if ( $protoSlot->getRole() === 'main'
621 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
623 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
626 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
627 if ( $protoSlot->hasContentId() ) {
628 $contentId = $protoSlot->getContentId();
630 $contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
633 $this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
638 $savedSlot = SlotRecord
::newSaved(
649 * Insert IP revision into ip_changes for use when querying for a range.
650 * @param IDatabase $dbw
652 * @param RevisionRecord $rev
653 * @param int $revisionId
655 private function insertIpChangesRow(
661 if ( $user->getId() === 0 && IP
::isValid( $user->getName() ) ) {
663 'ipc_rev_id' => $revisionId,
664 'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
665 'ipc_hex' => IP
::toHex( $user->getName() ),
667 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
672 * @param IDatabase $dbw
673 * @param RevisionRecord $rev
674 * @param Title $title
675 * @param int $parentId
677 * @return array a revision table row
679 * @throws MWException
680 * @throws MWUnknownContentModelException
682 private function insertRevisionRowOn(
688 $revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $title, $parentId );
690 list( $commentFields, $commentCallback ) =
691 $this->commentStore
->insertWithTempTable(
694 $rev->getComment( RevisionRecord
::RAW
)
696 $revisionRow +
= $commentFields;
698 list( $actorFields, $actorCallback ) =
699 $this->actorMigration
->getInsertValuesWithTempTable(
702 $rev->getUser( RevisionRecord
::RAW
)
704 $revisionRow +
= $actorFields;
706 $dbw->insert( 'revision', $revisionRow, __METHOD__
);
708 if ( !isset( $revisionRow['rev_id'] ) ) {
709 // only if auto-increment was used
710 $revisionRow['rev_id'] = intval( $dbw->insertId() );
713 $commentCallback( $revisionRow['rev_id'] );
714 $actorCallback( $revisionRow['rev_id'], $revisionRow );
720 * @param IDatabase $dbw
721 * @param RevisionRecord $rev
722 * @param Title $title
723 * @param int $parentId
725 * @return array [ 0 => array $revisionRow, 1 => callable ]
726 * @throws MWException
727 * @throws MWUnknownContentModelException
729 private function getBaseRevisionRow(
735 // Record the edit in revisions
737 'rev_page' => $rev->getPageId(),
738 'rev_parent_id' => $parentId,
739 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
740 'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
741 'rev_deleted' => $rev->getVisibility(),
742 'rev_len' => $rev->getSize(),
743 'rev_sha1' => $rev->getSha1(),
746 if ( $rev->getId() !== null ) {
747 // Needed to restore revisions with their original ID
748 $revisionRow['rev_id'] = $rev->getId();
751 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
752 // In non MCR mode this IF section will relate to the main slot
753 $mainSlot = $rev->getSlot( 'main' );
754 $model = $mainSlot->getModel();
755 $format = $mainSlot->getFormat();
757 // MCR migration note: rev_content_model and rev_content_format will go away
758 if ( $this->contentHandlerUseDB
) {
759 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
760 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
762 $revisionRow['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
763 $revisionRow['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
771 * @param SlotRecord $slot
772 * @param Title $title
773 * @param array $blobHints See the BlobStore::XXX_HINT constants
775 * @throws MWException
776 * @return string the blob address
778 private function storeContentBlob(
781 array $blobHints = []
783 $content = $slot->getContent();
784 $format = $content->getDefaultFormat();
785 $model = $content->getModel();
787 $this->checkContent( $content, $title );
789 return $this->blobStore
->storeBlob(
790 $content->serialize( $format ),
791 // These hints "leak" some information from the higher abstraction layer to
792 // low level storage to allow for optimization.
796 BlobStore
::DESIGNATION_HINT
=> 'page-content',
797 BlobStore
::ROLE_HINT
=> $slot->getRole(),
798 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
799 BlobStore
::MODEL_HINT
=> $model,
800 BlobStore
::FORMAT_HINT
=> $format,
807 * @param SlotRecord $slot
808 * @param IDatabase $dbw
809 * @param int $revisionId
810 * @param int $contentId
812 private function insertSlotRowOn( SlotRecord
$slot, IDatabase
$dbw, $revisionId, $contentId ) {
814 'slot_revision_id' => $revisionId,
815 'slot_role_id' => $this->slotRoleStore
->acquireId( $slot->getRole() ),
816 'slot_content_id' => $contentId,
817 // If the slot has a specific origin use that ID, otherwise use the ID of the revision
818 // that we just inserted.
819 'slot_origin' => $slot->hasOrigin() ?
$slot->getOrigin() : $revisionId,
821 $dbw->insert( 'slots', $slotRow, __METHOD__
);
825 * @param SlotRecord $slot
826 * @param IDatabase $dbw
827 * @param string $blobAddress
828 * @return int content row ID
830 private function insertContentRowOn( SlotRecord
$slot, IDatabase
$dbw, $blobAddress ) {
832 'content_size' => $slot->getSize(),
833 'content_sha1' => $slot->getSha1(),
834 'content_model' => $this->contentModelStore
->acquireId( $slot->getModel() ),
835 'content_address' => $blobAddress,
837 $dbw->insert( 'content', $contentRow, __METHOD__
);
838 return intval( $dbw->insertId() );
842 * MCR migration note: this corresponds to Revision::checkContentModel
844 * @param Content $content
845 * @param Title $title
847 * @throws MWException
848 * @throws MWUnknownContentModelException
850 private function checkContent( Content
$content, Title
$title ) {
851 // Note: may return null for revisions that have not yet been inserted
853 $model = $content->getModel();
854 $format = $content->getDefaultFormat();
855 $handler = $content->getContentHandler();
859 if ( !$handler->isSupportedFormat( $format ) ) {
860 throw new MWException( "Can't use format $format with content model $model on $name" );
863 if ( !$this->contentHandlerUseDB
) {
864 // if $wgContentHandlerUseDB is not set,
865 // all revisions must use the default content model and format.
867 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
868 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
869 $defaultFormat = $defaultHandler->getDefaultFormat();
871 if ( $model != $defaultModel ) {
872 throw new MWException( "Can't save non-default content model with "
873 . "\$wgContentHandlerUseDB disabled: model is $model, "
874 . "default for $name is $defaultModel"
878 if ( $format != $defaultFormat ) {
879 throw new MWException( "Can't use non-default content format with "
880 . "\$wgContentHandlerUseDB disabled: format is $format, "
881 . "default for $name is $defaultFormat"
886 if ( !$content->isValid() ) {
887 throw new MWException(
888 "New content for $name is not valid! Content model is $model"
894 * Create a new null-revision for insertion into a page's
895 * history. This will not re-save the text, but simply refer
896 * to the text from the previous version.
898 * Such revisions can for instance identify page rename
899 * operations and other such meta-modifications.
901 * @note: This method grabs a FOR UPDATE lock on the relevant row of the page table,
902 * to prevent a new revision from being inserted before the null revision has been written
905 * MCR migration note: this replaces Revision::newNullRevision
907 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
910 * @param IDatabase $dbw used for obtaining the lock on the page table row
911 * @param Title $title Title of the page to read from
912 * @param CommentStoreComment $comment RevisionRecord's summary
913 * @param bool $minor Whether the revision should be considered as minor
914 * @param User $user The user to attribute the revision to
916 * @return RevisionRecord|null RevisionRecord or null on error
918 public function newNullRevision(
921 CommentStoreComment
$comment,
925 $this->checkDatabaseWikiId( $dbw );
927 // T51581: Lock the page table row to ensure no other process
928 // is adding a revision to the page at the same time.
929 // Avoid locking extra tables, compare T191892.
930 $pageLatest = $dbw->selectField(
933 [ 'page_id' => $title->getArticleID() ],
938 if ( !$pageLatest ) {
942 // Fetch the actual revision row, without locking all extra tables.
943 $oldRevision = $this->loadRevisionFromId( $dbw, $pageLatest );
945 // Construct the new revision
946 $timestamp = wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
947 $newRevision = MutableRevisionRecord
::newFromParentRevision( $oldRevision );
949 $newRevision->setComment( $comment );
950 $newRevision->setUser( $user );
951 $newRevision->setTimestamp( $timestamp );
952 $newRevision->setMinorEdit( $minor );
958 * MCR migration note: this replaces Revision::isUnpatrolled
960 * @todo This is overly specific, so move or kill this method.
962 * @param RevisionRecord $rev
964 * @return int Rcid of the unpatrolled row, zero if there isn't one
966 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
967 $rc = $this->getRecentChange( $rev );
968 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == RecentChange
::PRC_UNPATROLLED
) {
969 return $rc->getAttribute( 'rc_id' );
976 * Get the RC object belonging to the current revision, if there's one
978 * MCR migration note: this replaces Revision::getRecentChange
980 * @todo move this somewhere else?
982 * @param RevisionRecord $rev
983 * @param int $flags (optional) $flags include:
984 * IDBAccessObject::READ_LATEST: Select the data from the master
986 * @return null|RecentChange
988 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
989 $dbr = $this->getDBConnection( DB_REPLICA
);
991 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
993 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
995 if ( !$userIdentity ) {
996 // If the revision has no user identity, chances are it never went
997 // into the database, and doesn't have an RC entry.
1001 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
1002 $actorWhere = $this->actorMigration
->getWhere( $dbr, 'rc_user', $rev->getUser(), false );
1003 $rc = RecentChange
::newFromConds(
1005 $actorWhere['conds'],
1006 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
1007 'rc_this_oldid' => $rev->getId()
1013 $this->releaseDBConnection( $dbr );
1015 // XXX: cache this locally? Glue it to the RevisionRecord?
1020 * Maps fields of the archive row to corresponding revision rows.
1022 * @param object $archiveRow
1024 * @return object a revision row object, corresponding to $archiveRow.
1026 private static function mapArchiveFields( $archiveRow ) {
1028 // keep with ar prefix:
1031 // not the same suffix:
1032 'ar_page_id' => 'rev_page',
1033 'ar_rev_id' => 'rev_id',
1036 'ar_text_id' => 'rev_text_id',
1037 'ar_timestamp' => 'rev_timestamp',
1038 'ar_user_text' => 'rev_user_text',
1039 'ar_user' => 'rev_user',
1040 'ar_actor' => 'rev_actor',
1041 'ar_minor_edit' => 'rev_minor_edit',
1042 'ar_deleted' => 'rev_deleted',
1043 'ar_len' => 'rev_len',
1044 'ar_parent_id' => 'rev_parent_id',
1045 'ar_sha1' => 'rev_sha1',
1046 'ar_comment' => 'rev_comment',
1047 'ar_comment_cid' => 'rev_comment_cid',
1048 'ar_comment_id' => 'rev_comment_id',
1049 'ar_comment_text' => 'rev_comment_text',
1050 'ar_comment_data' => 'rev_comment_data',
1051 'ar_comment_old' => 'rev_comment_old',
1052 'ar_content_format' => 'rev_content_format',
1053 'ar_content_model' => 'rev_content_model',
1056 $revRow = new stdClass();
1057 foreach ( $fieldMap as $arKey => $revKey ) {
1058 if ( property_exists( $archiveRow, $arKey ) ) {
1059 $revRow->$revKey = $archiveRow->$arKey;
1067 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
1069 * @param object|array $row Either a database row or an array
1070 * @param int $queryFlags for callbacks
1071 * @param Title $title
1073 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
1074 * @throws MWException
1076 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
1077 $mainSlotRow = new stdClass();
1078 $mainSlotRow->role_name
= 'main';
1079 $mainSlotRow->model_name
= null;
1080 $mainSlotRow->slot_revision_id
= null;
1081 $mainSlotRow->content_address
= null;
1087 if ( is_object( $row ) ) {
1088 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1089 // Don't emulate from a row when using the new schema.
1090 // Emulating from an array is still OK.
1091 throw new LogicException( 'Can\'t emulate the main slot when using MCR schema.' );
1095 if ( !isset( $row->rev_id
) && ( isset( $row->ar_user
) ||
isset( $row->ar_actor
) ) ) {
1096 $row = $this->mapArchiveFields( $row );
1099 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
1100 $mainSlotRow->content_address
= SqlBlobStore
::makeAddressFromTextId(
1105 // This is used by null-revisions
1106 $mainSlotRow->slot_origin
= isset( $row->slot_origin
)
1107 ?
intval( $row->slot_origin
)
1110 if ( isset( $row->old_text
) ) {
1111 // this happens when the text-table gets joined directly, in the pre-1.30 schema
1112 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
1113 // Check against selects that might have not included old_flags
1114 if ( !property_exists( $row, 'old_flags' ) ) {
1115 throw new InvalidArgumentException( 'old_flags was not set in $row' );
1117 $blobFlags = ( $row->old_flags
=== null ) ?
'' : $row->old_flags
;
1120 $mainSlotRow->slot_revision_id
= intval( $row->rev_id
);
1122 $mainSlotRow->content_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
1123 $mainSlotRow->content_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
1124 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
1125 ?
strval( $row->rev_content_model
)
1127 // XXX: in the future, we'll probably always use the default format, and drop content_format
1128 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
1129 ?
strval( $row->rev_content_format
)
1131 } elseif ( is_array( $row ) ) {
1132 $mainSlotRow->slot_revision_id
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
1134 $mainSlotRow->slot_origin
= isset( $row['slot_origin'] )
1135 ?
intval( $row['slot_origin'] )
1137 $mainSlotRow->content_address
= isset( $row['text_id'] )
1138 ? SqlBlobStore
::makeAddressFromTextId( intval( $row['text_id'] ) )
1140 $mainSlotRow->content_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
1141 $mainSlotRow->content_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
1143 $mainSlotRow->model_name
= isset( $row['content_model'] )
1144 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
1145 // XXX: in the future, we'll probably always use the default format, and drop content_format
1146 $mainSlotRow->format_name
= isset( $row['content_format'] )
1147 ?
strval( $row['content_format'] ) : null;
1148 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
1149 // XXX: If the flags field is not set then $blobFlags should be null so that no
1150 // decoding will happen. An empty string will result in default decodings.
1151 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
1153 // if we have a Content object, override mText and mContentModel
1154 if ( !empty( $row['content'] ) ) {
1155 if ( !( $row['content'] instanceof Content
) ) {
1156 throw new MWException( 'content field must contain a Content object.' );
1159 /** @var Content $content */
1160 $content = $row['content'];
1161 $handler = $content->getContentHandler();
1163 $mainSlotRow->model_name
= $content->getModel();
1165 // XXX: in the future, we'll probably always use the default format.
1166 if ( $mainSlotRow->format_name
=== null ) {
1167 $mainSlotRow->format_name
= $handler->getDefaultFormat();
1171 throw new MWException( 'Revision constructor passed invalid row format.' );
1174 // With the old schema, the content changes with every revision,
1175 // except for null-revisions.
1176 if ( !isset( $mainSlotRow->slot_origin
) ) {
1177 $mainSlotRow->slot_origin
= $mainSlotRow->slot_revision_id
;
1180 if ( $mainSlotRow->model_name
=== null ) {
1181 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
1182 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
1183 // TODO: MCR: deprecate $title->getModel().
1184 return ContentHandler
::getDefaultModelFor( $title );
1189 // XXX: We should perhaps fail if $blobData is null and $mainSlotRow->content_address
1190 // is missing, but "empty revisions" with no content are used in some edge cases.
1192 $content = function ( SlotRecord
$slot )
1193 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
1195 return $this->loadSlotContent(
1199 $mainSlotRow->format_name
,
1205 // NOTE: this callback will be looped through RevisionSlot::newInherited(), allowing
1206 // the inherited slot to have the same content_id as the original slot. In that case,
1207 // $slot will be the inherited slot, while $mainSlotRow still refers to the original slot.
1208 $mainSlotRow->slot_content_id
=
1209 function ( SlotRecord
$slot ) use ( $queryFlags, $mainSlotRow ) {
1210 list( $dbMode, ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
1211 $db = $this->getDBConnectionRef( $dbMode );
1212 return $this->findSlotContentId( $db, $mainSlotRow->slot_revision_id
, 'main' );
1215 return new SlotRecord( $mainSlotRow, $content );
1219 * Loads a Content object based on a slot row.
1221 * This method does not call $slot->getContent(), and may be used as a callback
1222 * called by $slot->getContent().
1224 * MCR migration note: this roughly corresponds to Revision::getContentInternal
1226 * @param SlotRecord $slot The SlotRecord to load content for
1227 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
1228 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
1229 * Use null if no processing should happen. That is in constrast to the empty string,
1230 * which causes the blob to be decoded according to the configured legacy encoding.
1231 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
1232 * @param int $queryFlags
1234 * @throws RevisionAccessException
1237 private function loadSlotContent(
1244 if ( $blobData !== null ) {
1245 Assert
::parameterType( 'string', $blobData, '$blobData' );
1246 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
1248 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
1250 if ( $blobFlags === null ) {
1251 // No blob flags, so use the blob verbatim.
1254 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
1255 if ( $data === false ) {
1256 throw new RevisionAccessException(
1257 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
1263 $address = $slot->getAddress();
1265 $data = $this->blobStore
->getBlob( $address, $queryFlags );
1266 } catch ( BlobAccessException
$e ) {
1267 throw new RevisionAccessException(
1268 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
1273 // Unserialize content
1274 $handler = ContentHandler
::getForModelID( $slot->getModel() );
1276 $content = $handler->unserializeContent( $data, $blobFormat );
1281 * Load a page revision from a given revision ID number.
1282 * Returns null if no such revision can be found.
1284 * MCR migration note: this replaces Revision::newFromId
1287 * IDBAccessObject::READ_LATEST: Select the data from the master
1288 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1291 * @param int $flags (optional)
1292 * @return RevisionRecord|null
1294 public function getRevisionById( $id, $flags = 0 ) {
1295 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
1299 * Load either the current, or a specified, revision
1300 * that's attached to a given link target. If not attached
1301 * to that link target, will return null.
1303 * MCR migration note: this replaces Revision::newFromTitle
1306 * IDBAccessObject::READ_LATEST: Select the data from the master
1307 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1309 * @param LinkTarget $linkTarget
1310 * @param int $revId (optional)
1311 * @param int $flags Bitfield (optional)
1312 * @return RevisionRecord|null
1314 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
1316 'page_namespace' => $linkTarget->getNamespace(),
1317 'page_title' => $linkTarget->getDBkey()
1320 // Use the specified revision ID.
1321 // Note that we use newRevisionFromConds here because we want to retry
1322 // and fall back to master if the page is not found on a replica.
1323 // Since the caller supplied a revision ID, we are pretty sure the revision is
1324 // supposed to exist, so we should try hard to find it.
1325 $conds['rev_id'] = $revId;
1326 return $this->newRevisionFromConds( $conds, $flags );
1328 // Use a join to get the latest revision.
1329 // Note that we don't use newRevisionFromConds here because we don't want to retry
1330 // and fall back to master. The assumption is that we only want to force the fallback
1331 // if we are quite sure the revision exists because the caller supplied a revision ID.
1332 // If the page isn't found at all on a replica, it probably simply does not exist.
1333 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1335 $conds[] = 'rev_id=page_latest';
1336 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1338 $this->releaseDBConnection( $db );
1344 * Load either the current, or a specified, revision
1345 * that's attached to a given page ID.
1346 * Returns null if no such revision can be found.
1348 * MCR migration note: this replaces Revision::newFromPageId
1351 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
1352 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1354 * @param int $pageId
1355 * @param int $revId (optional)
1356 * @param int $flags Bitfield (optional)
1357 * @return RevisionRecord|null
1359 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1360 $conds = [ 'page_id' => $pageId ];
1362 // Use the specified revision ID.
1363 // Note that we use newRevisionFromConds here because we want to retry
1364 // and fall back to master if the page is not found on a replica.
1365 // Since the caller supplied a revision ID, we are pretty sure the revision is
1366 // supposed to exist, so we should try hard to find it.
1367 $conds['rev_id'] = $revId;
1368 return $this->newRevisionFromConds( $conds, $flags );
1370 // Use a join to get the latest revision.
1371 // Note that we don't use newRevisionFromConds here because we don't want to retry
1372 // and fall back to master. The assumption is that we only want to force the fallback
1373 // if we are quite sure the revision exists because the caller supplied a revision ID.
1374 // If the page isn't found at all on a replica, it probably simply does not exist.
1375 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1377 $conds[] = 'rev_id=page_latest';
1378 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1380 $this->releaseDBConnection( $db );
1386 * Load the revision for the given title with the given timestamp.
1387 * WARNING: Timestamps may in some circumstances not be unique,
1388 * so this isn't the best key to use.
1390 * MCR migration note: this replaces Revision::loadFromTimestamp
1392 * @param Title $title
1393 * @param string $timestamp
1394 * @return RevisionRecord|null
1396 public function getRevisionByTimestamp( $title, $timestamp ) {
1397 $db = $this->getDBConnection( DB_REPLICA
);
1398 return $this->newRevisionFromConds(
1400 'rev_timestamp' => $db->timestamp( $timestamp ),
1401 'page_namespace' => $title->getNamespace(),
1402 'page_title' => $title->getDBkey()
1410 * @param int $revId The revision to load slots for.
1411 * @param int $queryFlags
1413 * @return SlotRecord[]
1415 private function loadSlotRecords( $revId, $queryFlags ) {
1416 $revQuery = self
::getSlotsQueryInfo( [ 'content' ] );
1418 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
1419 $db = $this->getDBConnectionRef( $dbMode );
1422 $revQuery['tables'],
1423 $revQuery['fields'],
1425 'slot_revision_id' => $revId,
1434 foreach ( $res as $row ) {
1435 $contentCallback = function ( SlotRecord
$slot ) use ( $queryFlags, $row ) {
1436 return $this->loadSlotContent( $slot, null, null, null, $queryFlags );
1439 $slots[$row->role_name
] = new SlotRecord( $row, $contentCallback );
1442 if ( !isset( $slots['main'] ) ) {
1443 throw new RevisionAccessException(
1444 'Main slot of revision ' . $revId . ' not found in database!'
1452 * Factory method for RevisionSlots.
1454 * @note If other code has a need to construct RevisionSlots objects, this should be made
1455 * public, since RevisionSlots instances should not be constructed directly.
1458 * @param object $revisionRow
1459 * @param int $queryFlags
1460 * @param Title $title
1462 * @return RevisionSlots
1463 * @throws MWException
1465 private function newRevisionSlots(
1471 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1472 $mainSlot = $this->emulateMainSlot_1_29( $revisionRow, $queryFlags, $title );
1473 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1475 // XXX: do we need the same kind of caching here
1476 // that getKnownCurrentRevision uses (if $revId == page_latest?)
1478 $slots = new RevisionSlots( function () use( $revId, $queryFlags ) {
1479 return $this->loadSlotRecords( $revId, $queryFlags );
1487 * Make a fake revision object from an archive table row. This is queried
1488 * for permissions or even inserted (as in Special:Undelete)
1490 * MCR migration note: this replaces Revision::newFromArchiveRow
1492 * @param object $row
1493 * @param int $queryFlags
1494 * @param Title|null $title
1495 * @param array $overrides associative array with fields of $row to override. This may be
1496 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1497 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1498 * override ar_parent_id.
1500 * @return RevisionRecord
1501 * @throws MWException
1503 public function newRevisionFromArchiveRow(
1506 Title
$title = null,
1507 array $overrides = []
1509 Assert
::parameterType( 'object', $row, '$row' );
1511 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1512 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1514 if ( !$title && isset( $overrides['title'] ) ) {
1515 if ( !( $overrides['title'] instanceof Title
) ) {
1516 throw new MWException( 'title field override must contain a Title object.' );
1519 $title = $overrides['title'];
1522 if ( !isset( $title ) ) {
1523 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1524 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1526 throw new InvalidArgumentException(
1527 'A Title or ar_namespace and ar_title must be given'
1532 foreach ( $overrides as $key => $value ) {
1534 $row->$field = $value;
1538 $user = User
::newFromAnyId(
1539 $row->ar_user ??
null,
1540 $row->ar_user_text ??
null,
1541 $row->ar_actor ??
null
1543 } catch ( InvalidArgumentException
$ex ) {
1544 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1545 $user = new UserIdentityValue( 0, '', 0 );
1548 $comment = $this->commentStore
1549 // Legacy because $row may have come from self::selectFields()
1550 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'ar_comment', $row, true );
1552 $slots = $this->newRevisionSlots( $row->ar_rev_id
, $row, $queryFlags, $title );
1554 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1558 * @see RevisionFactory::newRevisionFromRow
1560 * MCR migration note: this replaces Revision::newFromRow
1562 * @param object $row
1563 * @param int $queryFlags
1564 * @param Title|null $title
1566 * @return RevisionRecord
1568 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1569 Assert
::parameterType( 'object', $row, '$row' );
1572 $pageId = $row->rev_page ??
0; // XXX: also check page_id?
1573 $revId = $row->rev_id ??
0;
1575 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1578 if ( !isset( $row->page_latest
) ) {
1579 $row->page_latest
= $title->getLatestRevID();
1580 if ( $row->page_latest
=== 0 && $title->exists() ) {
1581 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1586 $user = User
::newFromAnyId(
1587 $row->rev_user ??
null,
1588 $row->rev_user_text ??
null,
1589 $row->rev_actor ??
null
1591 } catch ( InvalidArgumentException
$ex ) {
1592 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1593 $user = new UserIdentityValue( 0, '', 0 );
1596 $comment = $this->commentStore
1597 // Legacy because $row may have come from self::selectFields()
1598 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'rev_comment', $row, true );
1600 $slots = $this->newRevisionSlots( $row->rev_id
, $row, $queryFlags, $title );
1602 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1606 * Constructs a new MutableRevisionRecord based on the given associative array following
1607 * the MW1.29 convention for the Revision constructor.
1609 * MCR migration note: this replaces Revision::newFromRow
1611 * @param array $fields
1612 * @param int $queryFlags
1613 * @param Title|null $title
1615 * @return MutableRevisionRecord
1616 * @throws MWException
1617 * @throws RevisionAccessException
1619 public function newMutableRevisionFromArray(
1624 if ( !$title && isset( $fields['title'] ) ) {
1625 if ( !( $fields['title'] instanceof Title
) ) {
1626 throw new MWException( 'title field must contain a Title object.' );
1629 $title = $fields['title'];
1633 $pageId = $fields['page'] ??
0;
1634 $revId = $fields['id'] ??
0;
1636 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1639 if ( !isset( $fields['page'] ) ) {
1640 $fields['page'] = $title->getArticleID( $queryFlags );
1643 // if we have a content object, use it to set the model and type
1644 if ( !empty( $fields['content'] ) ) {
1645 if ( !( $fields['content'] instanceof Content
) && !is_array( $fields['content'] ) ) {
1646 throw new MWException(
1647 'content field must contain a Content object or an array of Content objects.'
1652 if ( !empty( $fields['text_id'] ) ) {
1653 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
1654 throw new MWException( "The text_id field is only available in the pre-MCR schema" );
1657 if ( !empty( $fields['content'] ) ) {
1658 throw new MWException(
1659 "Text already stored in external store (id {$fields['text_id']}), " .
1660 "can't specify content object"
1666 isset( $fields['comment'] )
1667 && !( $fields['comment'] instanceof CommentStoreComment
)
1669 $commentData = $fields['comment_data'] ??
null;
1671 if ( $fields['comment'] instanceof Message
) {
1672 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1677 $commentText = trim( strval( $fields['comment'] ) );
1678 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1685 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1686 $this->initializeMutableRevisionFromArray( $revision, $fields );
1688 if ( isset( $fields['content'] ) && is_array( $fields['content'] ) ) {
1689 foreach ( $fields['content'] as $role => $content ) {
1690 $revision->setContent( $role, $content );
1693 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1694 $revision->setSlot( $mainSlot );
1701 * @param MutableRevisionRecord $record
1702 * @param array $fields
1704 private function initializeMutableRevisionFromArray(
1705 MutableRevisionRecord
$record,
1708 /** @var UserIdentity $user */
1711 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1712 $user = $fields['user'];
1715 $user = User
::newFromAnyId(
1716 $fields['user'] ??
null,
1717 $fields['user_text'] ??
null,
1718 $fields['actor'] ??
null
1720 } catch ( InvalidArgumentException
$ex ) {
1726 $record->setUser( $user );
1729 $timestamp = isset( $fields['timestamp'] )
1730 ?
strval( $fields['timestamp'] )
1731 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1733 $record->setTimestamp( $timestamp );
1735 if ( isset( $fields['page'] ) ) {
1736 $record->setPageId( intval( $fields['page'] ) );
1739 if ( isset( $fields['id'] ) ) {
1740 $record->setId( intval( $fields['id'] ) );
1742 if ( isset( $fields['parent_id'] ) ) {
1743 $record->setParentId( intval( $fields['parent_id'] ) );
1746 if ( isset( $fields['sha1'] ) ) {
1747 $record->setSha1( $fields['sha1'] );
1749 if ( isset( $fields['size'] ) ) {
1750 $record->setSize( intval( $fields['size'] ) );
1753 if ( isset( $fields['minor_edit'] ) ) {
1754 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1756 if ( isset( $fields['deleted'] ) ) {
1757 $record->setVisibility( intval( $fields['deleted'] ) );
1760 if ( isset( $fields['comment'] ) ) {
1761 Assert
::parameterType(
1762 CommentStoreComment
::class,
1766 $record->setComment( $fields['comment'] );
1771 * Load a page revision from a given revision ID number.
1772 * Returns null if no such revision can be found.
1774 * MCR migration note: this corresponds to Revision::loadFromId
1776 * @note direct use is deprecated!
1777 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1779 * @param IDatabase $db
1782 * @return RevisionRecord|null
1784 public function loadRevisionFromId( IDatabase
$db, $id ) {
1785 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1789 * Load either the current, or a specified, revision
1790 * that's attached to a given page. If not attached
1791 * to that page, will return null.
1793 * MCR migration note: this replaces Revision::loadFromPageId
1795 * @note direct use is deprecated!
1796 * @todo remove when unused!
1798 * @param IDatabase $db
1799 * @param int $pageid
1801 * @return RevisionRecord|null
1803 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1804 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1806 $conds['rev_id'] = intval( $id );
1808 $conds[] = 'rev_id=page_latest';
1810 return $this->loadRevisionFromConds( $db, $conds );
1814 * Load either the current, or a specified, revision
1815 * that's attached to a given page. If not attached
1816 * to that page, will return null.
1818 * MCR migration note: this replaces Revision::loadFromTitle
1820 * @note direct use is deprecated!
1821 * @todo remove when unused!
1823 * @param IDatabase $db
1824 * @param Title $title
1827 * @return RevisionRecord|null
1829 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1831 $matchId = intval( $id );
1833 $matchId = 'page_latest';
1836 return $this->loadRevisionFromConds(
1840 'page_namespace' => $title->getNamespace(),
1841 'page_title' => $title->getDBkey()
1849 * Load the revision for the given title with the given timestamp.
1850 * WARNING: Timestamps may in some circumstances not be unique,
1851 * so this isn't the best key to use.
1853 * MCR migration note: this replaces Revision::loadFromTimestamp
1855 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1856 * @todo remove when unused!
1858 * @param IDatabase $db
1859 * @param Title $title
1860 * @param string $timestamp
1861 * @return RevisionRecord|null
1863 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1864 return $this->loadRevisionFromConds( $db,
1866 'rev_timestamp' => $db->timestamp( $timestamp ),
1867 'page_namespace' => $title->getNamespace(),
1868 'page_title' => $title->getDBkey()
1876 * Given a set of conditions, fetch a revision
1878 * This method should be used if we are pretty sure the revision exists.
1879 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1880 * on a replica before hitting the master database.
1882 * MCR migration note: this corresponds to Revision::newFromConds
1884 * @param array $conditions
1885 * @param int $flags (optional)
1886 * @param Title $title
1888 * @return RevisionRecord|null
1890 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1891 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1892 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1893 $this->releaseDBConnection( $db );
1895 $lb = $this->getDBLoadBalancer();
1897 // Make sure new pending/committed revision are visibile later on
1898 // within web requests to certain avoid bugs like T93866 and T94407.
1900 && !( $flags & self
::READ_LATEST
)
1901 && $lb->getServerCount() > 1
1902 && $lb->hasOrMadeRecentMasterChanges()
1904 $flags = self
::READ_LATEST
;
1905 $db = $this->getDBConnection( DB_MASTER
);
1906 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1907 $this->releaseDBConnection( $db );
1914 * Given a set of conditions, fetch a revision from
1915 * the given database connection.
1917 * MCR migration note: this corresponds to Revision::loadFromConds
1919 * @param IDatabase $db
1920 * @param array $conditions
1921 * @param int $flags (optional)
1922 * @param Title $title
1924 * @return RevisionRecord|null
1926 private function loadRevisionFromConds(
1932 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1934 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1943 * Throws an exception if the given database connection does not belong to the wiki this
1944 * RevisionStore is bound to.
1946 * @param IDatabase $db
1947 * @throws MWException
1949 private function checkDatabaseWikiId( IDatabase
$db ) {
1950 $storeWiki = $this->wikiId
;
1951 $dbWiki = $db->getDomainID();
1953 if ( $dbWiki === $storeWiki ) {
1957 // XXX: we really want the default database ID...
1958 $storeWiki = $storeWiki ?
: wfWikiID();
1959 $dbWiki = $dbWiki ?
: wfWikiID();
1961 if ( $dbWiki === $storeWiki ) {
1965 // HACK: counteract encoding imposed by DatabaseDomain
1966 $storeWiki = str_replace( '?h', '-', $storeWiki );
1967 $dbWiki = str_replace( '?h', '-', $dbWiki );
1969 if ( $dbWiki === $storeWiki ) {
1973 throw new MWException( "RevisionStore for $storeWiki "
1974 . "cannot be used with a DB connection for $dbWiki" );
1978 * Given a set of conditions, return a row with the
1979 * fields necessary to build RevisionRecord objects.
1981 * MCR migration note: this corresponds to Revision::fetchFromConds
1983 * @param IDatabase $db
1984 * @param array $conditions
1985 * @param int $flags (optional)
1987 * @return object|false data row as a raw object
1989 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1990 $this->checkDatabaseWikiId( $db );
1992 $revQuery = $this->getQueryInfo( [ 'page', 'user' ] );
1994 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1995 $options[] = 'FOR UPDATE';
1997 return $db->selectRow(
1998 $revQuery['tables'],
1999 $revQuery['fields'],
2008 * Finds the ID of a content row for a given revision and slot role.
2009 * This can be used to re-use content rows even while the content ID
2010 * is still missing from SlotRecords, when writing to both the old and
2011 * the new schema during MCR schema migration.
2013 * @todo remove after MCR schema migration is complete.
2015 * @param IDatabase $db
2017 * @param string $role
2021 private function findSlotContentId( IDatabase
$db, $revId, $role ) {
2022 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
2027 $roleId = $this->slotRoleStore
->getId( $role );
2029 'slot_revision_id' => $revId,
2030 'slot_role_id' => $roleId,
2033 $contentId = $db->selectField( 'slots', 'slot_content_id', $conditions, __METHOD__
);
2035 return $contentId ?
: null;
2036 } catch ( NameTableAccessException
$ex ) {
2037 // If the role is missing from the slot_roles table,
2038 // the corresponding row in slots cannot exist.
2044 * Return the tables, fields, and join conditions to be selected to create
2045 * a new RevisionStoreRecord object.
2047 * MCR migration note: this replaces Revision::getQueryInfo
2049 * If the format of fields returned changes in any way then the cache key provided by
2050 * self::getRevisionRowCacheKey should be updated.
2054 * @param array $options Any combination of the following strings
2055 * - 'page': Join with the page table, and select fields to identify the page
2056 * - 'user': Join with the user table, and select the user name
2057 * - 'text': Join with the text table, and select fields to load page text. This
2058 * option is deprecated in MW 1.32 when the MCR migration flag SCHEMA_COMPAT_WRITE_NEW
2059 * is set, and disallowed when SCHEMA_COMPAT_READ_OLD is not set.
2061 * @return array With three keys:
2062 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2063 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2064 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2066 public function getQueryInfo( $options = [] ) {
2073 $ret['tables'][] = 'revision';
2074 $ret['fields'] = array_merge( $ret['fields'], [
2085 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
2086 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
2087 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
2088 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
2090 $actorQuery = $this->actorMigration
->getJoin( 'rev_user' );
2091 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
2092 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
2093 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
2095 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2096 $ret['fields'][] = 'rev_text_id';
2098 if ( $this->contentHandlerUseDB
) {
2099 $ret['fields'][] = 'rev_content_format';
2100 $ret['fields'][] = 'rev_content_model';
2104 if ( in_array( 'page', $options, true ) ) {
2105 $ret['tables'][] = 'page';
2106 $ret['fields'] = array_merge( $ret['fields'], [
2114 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
2117 if ( in_array( 'user', $options, true ) ) {
2118 $ret['tables'][] = 'user';
2119 $ret['fields'] = array_merge( $ret['fields'], [
2122 $u = $actorQuery['fields']['rev_user'];
2123 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
2126 if ( in_array( 'text', $options, true ) ) {
2127 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
2128 throw new InvalidArgumentException( 'text table can no longer be joined directly' );
2129 } elseif ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2130 // NOTE: even when this class is set to not read from the old schema, callers
2131 // should still be able to join against the text table, as long as we are still
2132 // writing the old schema for compatibility.
2133 wfDeprecated( __METHOD__
. ' with `text` option', '1.32' );
2136 $ret['tables'][] = 'text';
2137 $ret['fields'] = array_merge( $ret['fields'], [
2141 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
2148 * Return the tables, fields, and join conditions to be selected to create
2153 * @param array $options Any combination of the following strings
2154 * - 'content': Join with the content table, and select content meta-data fields
2156 * @return array With three keys:
2157 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2158 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2159 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2161 public function getSlotsQueryInfo( $options = [] ) {
2168 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2169 $db = $this->getDBConnectionRef( DB_REPLICA
);
2170 $ret['tables']['slots'] = 'revision';
2172 $ret['fields']['slot_revision_id'] = 'slots.rev_id';
2173 $ret['fields']['slot_content_id'] = 'NULL';
2174 $ret['fields']['slot_origin'] = 'slots.rev_id';
2175 $ret['fields']['role_name'] = $db->addQuotes( 'main' );
2177 if ( in_array( 'content', $options, true ) ) {
2178 $ret['fields']['content_size'] = 'slots.rev_len';
2179 $ret['fields']['content_sha1'] = 'slots.rev_sha1';
2180 $ret['fields']['content_address']
2181 = $db->buildConcat( [ $db->addQuotes( 'tt:' ), 'slots.rev_text_id' ] );
2183 if ( $this->contentHandlerUseDB
) {
2184 $ret['fields']['model_name'] = 'slots.rev_content_model';
2186 $ret['fields']['model_name'] = 'NULL';
2190 $ret['tables'][] = 'slots';
2191 $ret['tables'][] = 'slot_roles';
2192 $ret['fields'] = array_merge( $ret['fields'], [
2198 $ret['joins']['slot_roles'] = [ 'INNER JOIN', [ 'slot_role_id = role_id' ] ];
2200 if ( in_array( 'content', $options, true ) ) {
2201 $ret['tables'][] = 'content';
2202 $ret['tables'][] = 'content_models';
2203 $ret['fields'] = array_merge( $ret['fields'], [
2209 $ret['joins']['content'] = [ 'INNER JOIN', [ 'slot_content_id = content_id' ] ];
2210 $ret['joins']['content_models'] = [ 'INNER JOIN', [ 'content_model = model_id' ] ];
2218 * Return the tables, fields, and join conditions to be selected to create
2219 * a new RevisionArchiveRecord object.
2221 * MCR migration note: this replaces Revision::getArchiveQueryInfo
2225 * @return array With three keys:
2226 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2227 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2228 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2230 public function getArchiveQueryInfo() {
2231 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
2232 $actorQuery = $this->actorMigration
->getJoin( 'ar_user' );
2234 'tables' => [ 'archive' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
2247 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
2248 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
2251 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2252 $ret['fields'][] = 'ar_text_id';
2254 if ( $this->contentHandlerUseDB
) {
2255 $ret['fields'][] = 'ar_content_format';
2256 $ret['fields'][] = 'ar_content_model';
2264 * Do a batched query for the sizes of a set of revisions.
2266 * MCR migration note: this replaces Revision::getParentLengths
2268 * @param int[] $revIds
2269 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2270 * of the corresponding revision.
2272 public function getRevisionSizes( array $revIds ) {
2273 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
2277 * Do a batched query for the sizes of a set of revisions.
2279 * MCR migration note: this replaces Revision::getParentLengths
2281 * @deprecated use RevisionStore::getRevisionSizes instead.
2283 * @param IDatabase $db
2284 * @param int[] $revIds
2285 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2286 * of the corresponding revision.
2288 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
2289 $this->checkDatabaseWikiId( $db );
2293 return $revLens; // empty
2298 [ 'rev_id', 'rev_len' ],
2299 [ 'rev_id' => $revIds ],
2303 foreach ( $res as $row ) {
2304 $revLens[$row->rev_id
] = intval( $row->rev_len
);
2311 * Get previous revision for this title
2313 * MCR migration note: this replaces Revision::getPrevious
2315 * @param RevisionRecord $rev
2316 * @param Title $title if known (optional)
2318 * @return RevisionRecord|null
2320 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
2321 if ( $title === null ) {
2322 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2324 $prev = $title->getPreviousRevisionID( $rev->getId() );
2326 return $this->getRevisionByTitle( $title, $prev );
2332 * Get next revision for this title
2334 * MCR migration note: this replaces Revision::getNext
2336 * @param RevisionRecord $rev
2337 * @param Title $title if known (optional)
2339 * @return RevisionRecord|null
2341 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
2342 if ( $title === null ) {
2343 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2345 $next = $title->getNextRevisionID( $rev->getId() );
2347 return $this->getRevisionByTitle( $title, $next );
2353 * Get previous revision Id for this page_id
2354 * This is used to populate rev_parent_id on save
2356 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
2358 * @param IDatabase $db
2359 * @param RevisionRecord $rev
2363 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
2364 $this->checkDatabaseWikiId( $db );
2366 if ( $rev->getPageId() === null ) {
2369 # Use page_latest if ID is not given
2370 if ( !$rev->getId() ) {
2371 $prevId = $db->selectField(
2372 'page', 'page_latest',
2373 [ 'page_id' => $rev->getPageId() ],
2377 $prevId = $db->selectField(
2378 'revision', 'rev_id',
2379 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
2381 [ 'ORDER BY' => 'rev_id DESC' ]
2384 return intval( $prevId );
2388 * Get rev_timestamp from rev_id, without loading the rest of the row
2390 * MCR migration note: this replaces Revision::getTimestampFromId
2392 * @param Title $title
2395 * @return string|bool False if not found
2397 public function getTimestampFromId( $title, $id, $flags = 0 ) {
2398 $db = $this->getDBConnection(
2399 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
2402 $conds = [ 'rev_id' => $id ];
2403 $conds['rev_page'] = $title->getArticleID();
2404 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
2406 $this->releaseDBConnection( $db );
2407 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
2411 * Get count of revisions per page...not very efficient
2413 * MCR migration note: this replaces Revision::countByPageId
2415 * @param IDatabase $db
2416 * @param int $id Page id
2419 public function countRevisionsByPageId( IDatabase
$db, $id ) {
2420 $this->checkDatabaseWikiId( $db );
2422 $row = $db->selectRow( 'revision',
2423 [ 'revCount' => 'COUNT(*)' ],
2424 [ 'rev_page' => $id ],
2428 return intval( $row->revCount
);
2434 * Get count of revisions per page...not very efficient
2436 * MCR migration note: this replaces Revision::countByTitle
2438 * @param IDatabase $db
2439 * @param Title $title
2442 public function countRevisionsByTitle( IDatabase
$db, $title ) {
2443 $id = $title->getArticleID();
2445 return $this->countRevisionsByPageId( $db, $id );
2451 * Check if no edits were made by other users since
2452 * the time a user started editing the page. Limit to
2453 * 50 revisions for the sake of performance.
2455 * MCR migration note: this replaces Revision::userWasLastToEdit
2457 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
2458 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
2459 * has been deprecated since 1.24.
2461 * @param IDatabase $db The Database to perform the check on.
2462 * @param int $pageId The ID of the page in question
2463 * @param int $userId The ID of the user in question
2464 * @param string $since Look at edits since this time
2466 * @return bool True if the given user was the only one to edit since the given timestamp
2468 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
2469 $this->checkDatabaseWikiId( $db );
2475 $revQuery = $this->getQueryInfo();
2477 $revQuery['tables'],
2479 'rev_user' => $revQuery['fields']['rev_user'],
2482 'rev_page' => $pageId,
2483 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
2486 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
2489 foreach ( $res as $row ) {
2490 if ( $row->rev_user
!= $userId ) {
2498 * Load a revision based on a known page ID and current revision ID from the DB
2500 * This method allows for the use of caching, though accessing anything that normally
2501 * requires permission checks (aside from the text) will trigger a small DB lookup.
2503 * MCR migration note: this replaces Revision::newKnownCurrent
2505 * @param Title $title the associated page title
2506 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
2508 * @return RevisionRecord|bool Returns false if missing
2510 public function getKnownCurrentRevision( Title
$title, $revId ) {
2511 $db = $this->getDBConnectionRef( DB_REPLICA
);
2513 $pageId = $title->getArticleID();
2520 $revId = $title->getLatestRevID();
2525 'No latest revision known for page ' . $title->getPrefixedDBkey()
2526 . ' even though it exists with page ID ' . $pageId
2531 $row = $this->cache
->getWithSetCallback(
2532 // Page/rev IDs passed in from DB to reflect history merges
2533 $this->getRevisionRowCacheKey( $db, $pageId, $revId ),
2534 WANObjectCache
::TTL_WEEK
,
2535 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
2536 $setOpts +
= Database
::getCacheSetOptions( $db );
2539 'rev_page' => intval( $pageId ),
2540 'page_id' => intval( $pageId ),
2541 'rev_id' => intval( $revId ),
2544 $row = $this->fetchRevisionRowFromConds( $db, $conds );
2545 return $row ?
: false; // don't cache negatives
2549 // Reflect revision deletion and user renames
2551 return $this->newRevisionFromRow( $row, 0, $title );
2558 * Get a cache key for use with a row as selected with getQueryInfo( [ 'page', 'user' ] )
2559 * Caching rows without 'page' or 'user' could lead to issues.
2560 * If the format of the rows returned by the query provided by getQueryInfo changes the
2561 * cache key should be updated to avoid conflicts.
2563 * @param IDatabase $db
2564 * @param int $pageId
2568 private function getRevisionRowCacheKey( IDatabase
$db, $pageId, $revId ) {
2569 return $this->cache
->makeGlobalKey(
2570 self
::ROW_CACHE_KEY
,
2577 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.