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\Revision
;
31 use CommentStoreComment
;
34 use DBAccessObjectUtils
;
37 use InvalidArgumentException
;
40 use MediaWiki\Linker\LinkTarget
;
41 use MediaWiki\Storage\BlobAccessException
;
42 use MediaWiki\Storage\BlobStore
;
43 use MediaWiki\Storage\NameTableAccessException
;
44 use MediaWiki\Storage\NameTableStore
;
45 use MediaWiki\Storage\SqlBlobStore
;
46 use MediaWiki\User\UserIdentity
;
47 use MediaWiki\User\UserIdentityValue
;
50 use MWUnknownContentModelException
;
51 use Psr\Log\LoggerAwareInterface
;
52 use Psr\Log\LoggerInterface
;
53 use Psr\Log\NullLogger
;
63 use Wikimedia\Assert\Assert
;
64 use Wikimedia\Rdbms\Database
;
65 use Wikimedia\Rdbms\DBConnRef
;
66 use Wikimedia\Rdbms\IDatabase
;
67 use Wikimedia\Rdbms\ILoadBalancer
;
68 use Wikimedia\Rdbms\IResultWrapper
;
71 * Service for looking up page revisions.
74 * @since 1.32 Renamed from MediaWiki\Storage\RevisionStore
76 * @note This was written to act as a drop-in replacement for the corresponding
77 * static methods in Revision.
80 implements IDBAccessObject
, RevisionFactory
, RevisionLookup
, LoggerAwareInterface
{
82 const ROW_CACHE_KEY
= 'revision-row-1.29';
96 * @see $wgContentHandlerUseDB
98 private $contentHandlerUseDB = true;
103 private $loadBalancer;
106 * @var WANObjectCache
113 private $commentStore;
116 * @var ActorMigration
118 private $actorMigration;
121 * @var LoggerInterface
126 * @var NameTableStore
128 private $contentModelStore;
131 * @var NameTableStore
133 private $slotRoleStore;
135 /** @var int An appropriate combination of SCHEMA_COMPAT_XXX flags. */
136 private $mcrMigrationStage;
138 /** @var SlotRoleRegistry */
139 private $slotRoleRegistry;
142 * @todo $blobStore should be allowed to be any BlobStore!
144 * @param ILoadBalancer $loadBalancer
145 * @param SqlBlobStore $blobStore
146 * @param WANObjectCache $cache A cache for caching revision rows. This can be the local
147 * wiki's default instance even if $dbDomain refers to a different wiki, since
148 * makeGlobalKey() is used to constructed a key that allows cached revision rows from
149 * the same database to be re-used between wikis. For example, enwiki and frwiki will
150 * use the same cache keys for revision rows from the wikidatawiki database, regardless
151 * of the cache's default key space.
152 * @param CommentStore $commentStore
153 * @param NameTableStore $contentModelStore
154 * @param NameTableStore $slotRoleStore
155 * @param SlotRoleRegistry $slotRoleRegistry
156 * @param int $mcrMigrationStage An appropriate combination of SCHEMA_COMPAT_XXX flags
157 * @param ActorMigration $actorMigration
158 * @param bool|string $dbDomain DB domain of the relevant wiki or false for the current one
160 public function __construct(
161 ILoadBalancer
$loadBalancer,
162 SqlBlobStore
$blobStore,
163 WANObjectCache
$cache,
164 CommentStore
$commentStore,
165 NameTableStore
$contentModelStore,
166 NameTableStore
$slotRoleStore,
167 SlotRoleRegistry
$slotRoleRegistry,
169 ActorMigration
$actorMigration,
172 Assert
::parameterType( 'string|boolean', $dbDomain, '$dbDomain' );
173 Assert
::parameterType( 'integer', $mcrMigrationStage, '$mcrMigrationStage' );
175 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== SCHEMA_COMPAT_READ_BOTH
,
176 '$mcrMigrationStage',
177 'Reading from the old and the new schema at the same time is not supported.'
180 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== 0,
181 '$mcrMigrationStage',
182 'Reading needs to be enabled for the old or the new schema.'
185 ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) !== 0,
186 '$mcrMigrationStage',
187 'Writing needs to be enabled for the old or the new schema.'
190 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_OLD
) === 0
191 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) !== 0,
192 '$mcrMigrationStage',
193 'Cannot read the old schema when not also writing it.'
196 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_NEW
) === 0
197 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) !== 0,
198 '$mcrMigrationStage',
199 'Cannot read the new schema when not also writing it.'
202 $this->loadBalancer
= $loadBalancer;
203 $this->blobStore
= $blobStore;
204 $this->cache
= $cache;
205 $this->commentStore
= $commentStore;
206 $this->contentModelStore
= $contentModelStore;
207 $this->slotRoleStore
= $slotRoleStore;
208 $this->slotRoleRegistry
= $slotRoleRegistry;
209 $this->mcrMigrationStage
= $mcrMigrationStage;
210 $this->actorMigration
= $actorMigration;
211 $this->dbDomain
= $dbDomain;
212 $this->logger
= new NullLogger();
216 * @param int $flags A combination of SCHEMA_COMPAT_XXX flags.
217 * @return bool True if all the given flags were set in the $mcrMigrationStage
218 * parameter passed to the constructor.
220 private function hasMcrSchemaFlags( $flags ) {
221 return ( $this->mcrMigrationStage
& $flags ) === $flags;
225 * Throws a RevisionAccessException if this RevisionStore is configured for cross-wiki loading
226 * and still reading from the old DB schema.
228 * @throws RevisionAccessException
230 private function assertCrossWikiContentLoadingIsSafe() {
231 if ( $this->dbDomain
!== false && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
232 throw new RevisionAccessException(
233 "Cross-wiki content loading is not supported by the pre-MCR schema"
238 public function setLogger( LoggerInterface
$logger ) {
239 $this->logger
= $logger;
243 * @return bool Whether the store is read-only
245 public function isReadOnly() {
246 return $this->blobStore
->isReadOnly();
252 public function getContentHandlerUseDB() {
253 return $this->contentHandlerUseDB
;
257 * @see $wgContentHandlerUseDB
258 * @param bool $contentHandlerUseDB
259 * @throws MWException
261 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
262 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
)
263 ||
$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
)
265 if ( !$contentHandlerUseDB ) {
266 throw new MWException(
267 'Content model must be stored in the database for multi content revision migration.'
271 $this->contentHandlerUseDB
= $contentHandlerUseDB;
275 * @return ILoadBalancer
277 private function getDBLoadBalancer() {
278 return $this->loadBalancer
;
282 * @param int $queryFlags a bit field composed of READ_XXX flags
286 private function getDBConnectionRefForQueryFlags( $queryFlags ) {
287 list( $mode, ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
288 return $this->getDBConnectionRef( $mode );
292 * @param int $mode DB_MASTER or DB_REPLICA
294 * @param array $groups
297 private function getDBConnectionRef( $mode, $groups = [] ) {
298 $lb = $this->getDBLoadBalancer();
299 return $lb->getConnectionRef( $mode, $groups, $this->dbDomain
);
303 * Determines the page Title based on the available information.
305 * MCR migration note: this corresponds to Revision::getTitle
307 * @note this method should be private, external use should be avoided!
309 * @param int|null $pageId
310 * @param int|null $revId
311 * @param int $queryFlags
314 * @throws RevisionAccessException
316 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
317 if ( !$pageId && !$revId ) {
318 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
321 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
322 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
323 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
324 $queryFlags = self
::READ_NORMAL
;
327 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->dbDomain
=== false );
328 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
330 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
331 if ( $canUseTitleNewFromId ) {
332 $titleFlags = ( $dbMode == DB_MASTER ? Title
::READ_LATEST
: 0 );
333 // TODO: better foreign title handling (introduce TitleFactory)
334 $title = Title
::newFromID( $pageId, $titleFlags );
340 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
341 $canUseRevId = ( $revId !== null && $revId > 0 );
343 if ( $canUseRevId ) {
344 $dbr = $this->getDBConnectionRef( $dbMode );
345 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
346 $row = $dbr->selectRow(
347 [ 'revision', 'page' ],
356 [ 'rev_id' => $revId ],
359 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
362 // TODO: better foreign title handling (introduce TitleFactory)
363 return Title
::newFromRow( $row );
367 // If we still don't have a title, fallback to master if that wasn't already happening.
368 if ( $dbMode !== DB_MASTER
) {
369 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
372 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
373 [ 'trace' => wfBacktrace() ]
379 throw new RevisionAccessException(
380 "Could not determine title for page ID $pageId and revision ID $revId"
385 * @param mixed $value
386 * @param string $name
388 * @throws IncompleteRevisionException if $value is null
389 * @return mixed $value, if $value is not null
391 private function failOnNull( $value, $name ) {
392 if ( $value === null ) {
393 throw new IncompleteRevisionException(
394 "$name must not be " . var_export( $value, true ) . "!"
402 * @param mixed $value
403 * @param string $name
405 * @throws IncompleteRevisionException if $value is empty
406 * @return mixed $value, if $value is not null
408 private function failOnEmpty( $value, $name ) {
409 if ( $value === null ||
$value === 0 ||
$value === '' ) {
410 throw new IncompleteRevisionException(
411 "$name must not be " . var_export( $value, true ) . "!"
419 * Insert a new revision into the database, returning the new revision record
420 * on success and dies horribly on failure.
422 * MCR migration note: this replaces Revision::insertOn
424 * @param RevisionRecord $rev
425 * @param IDatabase $dbw (master connection)
427 * @throws InvalidArgumentException
428 * @return RevisionRecord the new revision record.
430 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
431 // TODO: pass in a DBTransactionContext instead of a database connection.
432 $this->checkDatabaseDomain( $dbw );
434 $slotRoles = $rev->getSlotRoles();
436 // Make sure the main slot is always provided throughout migration
437 if ( !in_array( SlotRecord
::MAIN
, $slotRoles ) ) {
438 throw new InvalidArgumentException(
439 'main slot must be provided'
443 // If we are not writing into the new schema, we can't support extra slots.
444 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
)
445 && $slotRoles !== [ SlotRecord
::MAIN
]
447 throw new InvalidArgumentException(
448 'Only the main slot is supported when not writing to the MCR enabled schema!'
452 // As long as we are not reading from the new schema, we don't want to write extra slots.
453 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
)
454 && $slotRoles !== [ SlotRecord
::MAIN
]
456 throw new InvalidArgumentException(
457 'Only the main slot is supported when not reading from the MCR enabled schema!'
462 $this->failOnNull( $rev->getSize(), 'size field' );
463 $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
464 $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
465 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
466 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
467 $this->failOnNull( $user->getId(), 'user field' );
468 $this->failOnEmpty( $user->getName(), 'user_text field' );
470 if ( !$rev->isReadyForInsertion() ) {
471 // This is here for future-proofing. At the time this check being added, it
472 // was redundant to the individual checks above.
473 throw new IncompleteRevisionException( 'Revision is incomplete' );
476 // TODO: we shouldn't need an actual Title here.
477 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
478 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
480 $parentId = $rev->getParentId() === null
481 ?
$this->getPreviousRevisionId( $dbw, $rev )
482 : $rev->getParentId();
484 /** @var RevisionRecord $rev */
485 $rev = $dbw->doAtomicSection(
487 function ( IDatabase
$dbw, $fname ) use (
495 return $this->insertRevisionInternal(
508 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
509 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
510 Assert
::postcondition(
511 $rev->getComment( RevisionRecord
::RAW
) !== null,
512 'revision must have a comment'
514 Assert
::postcondition(
515 $rev->getUser( RevisionRecord
::RAW
) !== null,
516 'revision must have a user'
519 // Trigger exception if the main slot is missing.
520 // Technically, this could go away after MCR migration: while
521 // calling code may require a main slot to exist, RevisionStore
522 // really should not know or care about that requirement.
523 $rev->getSlot( SlotRecord
::MAIN
, RevisionRecord
::RAW
);
525 foreach ( $slotRoles as $role ) {
526 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
527 Assert
::postcondition(
528 $slot->getContent() !== null,
529 $role . ' slot must have content'
531 Assert
::postcondition(
532 $slot->hasRevision(),
533 $role . ' slot must have a revision associated'
537 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
539 // TODO: deprecate in 1.32!
540 $legacyRevision = new Revision( $rev );
541 Hooks
::run( 'RevisionInsertComplete', [ &$legacyRevision, null, null ] );
546 private function insertRevisionInternal(
550 CommentStoreComment
$comment,
555 $slotRoles = $rev->getSlotRoles();
557 $revisionRow = $this->insertRevisionRowOn(
564 $revisionId = $revisionRow['rev_id'];
567 BlobStore
::PAGE_HINT
=> $pageId,
568 BlobStore
::REVISION_HINT
=> $revisionId,
569 BlobStore
::PARENT_HINT
=> $parentId,
573 foreach ( $slotRoles as $role ) {
574 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
576 // If the SlotRecord already has a revision ID set, this means it already exists
577 // in the database, and should already belong to the current revision.
578 // However, a slot may already have a revision, but no content ID, if the slot
579 // is emulated based on the archive table, because we are in SCHEMA_COMPAT_READ_OLD
580 // mode, and the respective archive row was not yet migrated to the new schema.
581 // In that case, a new slot row (and content row) must be inserted even during
583 if ( $slot->hasRevision() && $slot->hasContentId() ) {
584 // TODO: properly abort transaction if the assertion fails!
586 $slot->getRevision() === $revisionId,
587 'slot role ' . $slot->getRole(),
588 'Existing slot should belong to revision '
589 . $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
592 // Slot exists, nothing to do, move along.
593 // This happens when restoring archived revisions.
595 $newSlots[$role] = $slot;
597 // Write the main slot's text ID to the revision table for backwards compatibility
598 if ( $slot->getRole() === SlotRecord
::MAIN
599 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
601 $blobAddress = $slot->getAddress();
602 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
605 $newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $title, $blobHints );
609 $this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
611 $rev = new RevisionStoreRecord(
615 (object)$revisionRow,
616 new RevisionSlots( $newSlots ),
624 * @param IDatabase $dbw
625 * @param int $revisionId
626 * @param string &$blobAddress (may change!)
628 * @return int the text row id
630 private function updateRevisionTextId( IDatabase
$dbw, $revisionId, &$blobAddress ) {
631 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
633 throw new LogicException(
634 'Blob address not supported in 1.29 database schema: ' . $blobAddress
638 // getTextIdFromAddress() is free to insert something into the text table, so $textId
639 // may be a new value, not anything already contained in $blobAddress.
640 $blobAddress = SqlBlobStore
::makeAddressFromTextId( $textId );
644 [ 'rev_text_id' => $textId ],
645 [ 'rev_id' => $revisionId ],
653 * @param IDatabase $dbw
654 * @param int $revisionId
655 * @param SlotRecord $protoSlot
656 * @param Title $title
657 * @param array $blobHints See the BlobStore::XXX_HINT constants
660 private function insertSlotOn(
663 SlotRecord
$protoSlot,
665 array $blobHints = []
667 if ( $protoSlot->hasAddress() ) {
668 $blobAddress = $protoSlot->getAddress();
670 $blobAddress = $this->storeContentBlob( $protoSlot, $title, $blobHints );
675 // Write the main slot's text ID to the revision table for backwards compatibility
676 if ( $protoSlot->getRole() === SlotRecord
::MAIN
677 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
679 // If SCHEMA_COMPAT_WRITE_NEW is also set, the fake content ID is overwritten
680 // with the real content ID below.
681 $textId = $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
682 $contentId = $this->emulateContentId( $textId );
685 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
686 if ( $protoSlot->hasContentId() ) {
687 $contentId = $protoSlot->getContentId();
689 $contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
692 $this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
695 $savedSlot = SlotRecord
::newSaved(
706 * Insert IP revision into ip_changes for use when querying for a range.
707 * @param IDatabase $dbw
709 * @param RevisionRecord $rev
710 * @param int $revisionId
712 private function insertIpChangesRow(
718 if ( $user->getId() === 0 && IP
::isValid( $user->getName() ) ) {
720 'ipc_rev_id' => $revisionId,
721 'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
722 'ipc_hex' => IP
::toHex( $user->getName() ),
724 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
729 * @param IDatabase $dbw
730 * @param RevisionRecord $rev
731 * @param Title $title
732 * @param int $parentId
734 * @return array a revision table row
736 * @throws MWException
737 * @throws MWUnknownContentModelException
739 private function insertRevisionRowOn(
745 $revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $title, $parentId );
747 list( $commentFields, $commentCallback ) =
748 $this->commentStore
->insertWithTempTable(
751 $rev->getComment( RevisionRecord
::RAW
)
753 $revisionRow +
= $commentFields;
755 list( $actorFields, $actorCallback ) =
756 $this->actorMigration
->getInsertValuesWithTempTable(
759 $rev->getUser( RevisionRecord
::RAW
)
761 $revisionRow +
= $actorFields;
763 $dbw->insert( 'revision', $revisionRow, __METHOD__
);
765 if ( !isset( $revisionRow['rev_id'] ) ) {
766 // only if auto-increment was used
767 $revisionRow['rev_id'] = intval( $dbw->insertId() );
769 if ( $dbw->getType() === 'mysql' ) {
770 // (T202032) MySQL until 8.0 and MariaDB until some version after 10.1.34 don't save the
771 // auto-increment value to disk, so on server restart it might reuse IDs from deleted
772 // revisions. We can fix that with an insert with an explicit rev_id value, if necessary.
774 $maxRevId = intval( $dbw->selectField( 'archive', 'MAX(ar_rev_id)', '', __METHOD__
) );
776 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
777 $maxRevId2 = intval( $dbw->selectField( 'slots', 'MAX(slot_revision_id)', '', __METHOD__
) );
778 if ( $maxRevId2 >= $maxRevId ) {
779 $maxRevId = $maxRevId2;
784 if ( $maxRevId >= $revisionRow['rev_id'] ) {
785 $this->logger
->debug(
786 '__METHOD__: Inserted revision {revid} but {table} has revisions up to {maxrevid}.'
787 . ' Trying to fix it.',
789 'revid' => $revisionRow['rev_id'],
791 'maxrevid' => $maxRevId,
795 if ( !$dbw->lock( 'fix-for-T202032', __METHOD__
) ) {
796 throw new MWException( 'Failed to get database lock for T202032' );
799 $dbw->onTransactionResolution(
800 function ( $trigger, IDatabase
$dbw ) use ( $fname ) {
801 $dbw->unlock( 'fix-for-T202032', $fname );
805 $dbw->delete( 'revision', [ 'rev_id' => $revisionRow['rev_id'] ], __METHOD__
);
807 // The locking here is mostly to make MySQL bypass the REPEATABLE-READ transaction
808 // isolation (weird MySQL "feature"). It does seem to block concurrent auto-incrementing
809 // inserts too, though, at least on MariaDB 10.1.29.
811 // Don't try to lock `revision` in this way, it'll deadlock if there are concurrent
812 // transactions in this code path thanks to the row lock from the original ->insert() above.
814 // And we have to use raw SQL to bypass the "aggregation used with a locking SELECT" warning
815 // that's for non-MySQL DBs.
817 $dbw->selectSQLText( 'archive', [ 'v' => "MAX(ar_rev_id)" ], '', __METHOD__
) . ' FOR UPDATE'
819 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
821 $dbw->selectSQLText( 'slots', [ 'v' => "MAX(slot_revision_id)" ], '', __METHOD__
)
829 $row1 ?
intval( $row1->v
) : 0,
830 $row2 ?
intval( $row2->v
) : 0
833 // If we don't have SCHEMA_COMPAT_WRITE_NEW, all except the first of any concurrent
834 // transactions will throw a duplicate key error here. It doesn't seem worth trying
836 $revisionRow['rev_id'] = $maxRevId +
1;
837 $dbw->insert( 'revision', $revisionRow, __METHOD__
);
842 $commentCallback( $revisionRow['rev_id'] );
843 $actorCallback( $revisionRow['rev_id'], $revisionRow );
849 * @param IDatabase $dbw
850 * @param RevisionRecord $rev
851 * @param Title $title
852 * @param int $parentId
854 * @return array [ 0 => array $revisionRow, 1 => callable ]
855 * @throws MWException
856 * @throws MWUnknownContentModelException
858 private function getBaseRevisionRow(
864 // Record the edit in revisions
866 'rev_page' => $rev->getPageId(),
867 'rev_parent_id' => $parentId,
868 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
869 'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
870 'rev_deleted' => $rev->getVisibility(),
871 'rev_len' => $rev->getSize(),
872 'rev_sha1' => $rev->getSha1(),
875 if ( $rev->getId() !== null ) {
876 // Needed to restore revisions with their original ID
877 $revisionRow['rev_id'] = $rev->getId();
880 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
881 // In non MCR mode this IF section will relate to the main slot
882 $mainSlot = $rev->getSlot( SlotRecord
::MAIN
);
883 $model = $mainSlot->getModel();
884 $format = $mainSlot->getFormat();
886 // MCR migration note: rev_content_model and rev_content_format will go away
887 if ( $this->contentHandlerUseDB
) {
888 $this->assertCrossWikiContentLoadingIsSafe();
890 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
891 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
893 $revisionRow['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
894 $revisionRow['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
902 * @param SlotRecord $slot
903 * @param Title $title
904 * @param array $blobHints See the BlobStore::XXX_HINT constants
906 * @throws MWException
907 * @return string the blob address
909 private function storeContentBlob(
912 array $blobHints = []
914 $content = $slot->getContent();
915 $format = $content->getDefaultFormat();
916 $model = $content->getModel();
918 $this->checkContent( $content, $title, $slot->getRole() );
920 return $this->blobStore
->storeBlob(
921 $content->serialize( $format ),
922 // These hints "leak" some information from the higher abstraction layer to
923 // low level storage to allow for optimization.
927 BlobStore
::DESIGNATION_HINT
=> 'page-content',
928 BlobStore
::ROLE_HINT
=> $slot->getRole(),
929 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
930 BlobStore
::MODEL_HINT
=> $model,
931 BlobStore
::FORMAT_HINT
=> $format,
938 * @param SlotRecord $slot
939 * @param IDatabase $dbw
940 * @param int $revisionId
941 * @param int $contentId
943 private function insertSlotRowOn( SlotRecord
$slot, IDatabase
$dbw, $revisionId, $contentId ) {
945 'slot_revision_id' => $revisionId,
946 'slot_role_id' => $this->slotRoleStore
->acquireId( $slot->getRole() ),
947 'slot_content_id' => $contentId,
948 // If the slot has a specific origin use that ID, otherwise use the ID of the revision
949 // that we just inserted.
950 'slot_origin' => $slot->hasOrigin() ?
$slot->getOrigin() : $revisionId,
952 $dbw->insert( 'slots', $slotRow, __METHOD__
);
956 * @param SlotRecord $slot
957 * @param IDatabase $dbw
958 * @param string $blobAddress
959 * @return int content row ID
961 private function insertContentRowOn( SlotRecord
$slot, IDatabase
$dbw, $blobAddress ) {
963 'content_size' => $slot->getSize(),
964 'content_sha1' => $slot->getSha1(),
965 'content_model' => $this->contentModelStore
->acquireId( $slot->getModel() ),
966 'content_address' => $blobAddress,
968 $dbw->insert( 'content', $contentRow, __METHOD__
);
969 return intval( $dbw->insertId() );
973 * MCR migration note: this corresponds to Revision::checkContentModel
975 * @param Content $content
976 * @param Title $title
977 * @param string $role
979 * @throws MWException
980 * @throws MWUnknownContentModelException
982 private function checkContent( Content
$content, Title
$title, $role ) {
983 // Note: may return null for revisions that have not yet been inserted
985 $model = $content->getModel();
986 $format = $content->getDefaultFormat();
987 $handler = $content->getContentHandler();
991 if ( !$handler->isSupportedFormat( $format ) ) {
992 throw new MWException( "Can't use format $format with content model $model on $name" );
995 if ( !$this->contentHandlerUseDB
) {
996 // if $wgContentHandlerUseDB is not set,
997 // all revisions must use the default content model and format.
999 $this->assertCrossWikiContentLoadingIsSafe();
1001 $roleHandler = $this->slotRoleRegistry
->getRoleHandler( $role );
1002 $defaultModel = $roleHandler->getDefaultModel( $title );
1003 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1004 $defaultFormat = $defaultHandler->getDefaultFormat();
1006 if ( $model != $defaultModel ) {
1007 throw new MWException( "Can't save non-default content model with "
1008 . "\$wgContentHandlerUseDB disabled: model is $model, "
1009 . "default for $name is $defaultModel"
1013 if ( $format != $defaultFormat ) {
1014 throw new MWException( "Can't use non-default content format with "
1015 . "\$wgContentHandlerUseDB disabled: format is $format, "
1016 . "default for $name is $defaultFormat"
1021 if ( !$content->isValid() ) {
1022 throw new MWException(
1023 "New content for $name is not valid! Content model is $model"
1029 * Create a new null-revision for insertion into a page's
1030 * history. This will not re-save the text, but simply refer
1031 * to the text from the previous version.
1033 * Such revisions can for instance identify page rename
1034 * operations and other such meta-modifications.
1036 * @note This method grabs a FOR UPDATE lock on the relevant row of the page table,
1037 * to prevent a new revision from being inserted before the null revision has been written
1040 * MCR migration note: this replaces Revision::newNullRevision
1042 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
1045 * @param IDatabase $dbw used for obtaining the lock on the page table row
1046 * @param Title $title Title of the page to read from
1047 * @param CommentStoreComment $comment RevisionRecord's summary
1048 * @param bool $minor Whether the revision should be considered as minor
1049 * @param User $user The user to attribute the revision to
1051 * @return RevisionRecord|null RevisionRecord or null on error
1053 public function newNullRevision(
1056 CommentStoreComment
$comment,
1060 $this->checkDatabaseDomain( $dbw );
1062 $pageId = $title->getArticleID();
1064 // T51581: Lock the page table row to ensure no other process
1065 // is adding a revision to the page at the same time.
1066 // Avoid locking extra tables, compare T191892.
1067 $pageLatest = $dbw->selectField(
1070 [ 'page_id' => $pageId ],
1075 if ( !$pageLatest ) {
1079 // Fetch the actual revision row from master, without locking all extra tables.
1080 $oldRevision = $this->loadRevisionFromConds(
1082 [ 'rev_id' => intval( $pageLatest ) ],
1087 if ( !$oldRevision ) {
1088 $msg = "Failed to load latest revision ID $pageLatest of page ID $pageId.";
1089 $this->logger
->error(
1091 [ 'exception' => new RuntimeException( $msg ) ]
1096 // Construct the new revision
1097 $timestamp = wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1098 $newRevision = MutableRevisionRecord
::newFromParentRevision( $oldRevision );
1100 $newRevision->setComment( $comment );
1101 $newRevision->setUser( $user );
1102 $newRevision->setTimestamp( $timestamp );
1103 $newRevision->setMinorEdit( $minor );
1105 return $newRevision;
1109 * MCR migration note: this replaces Revision::isUnpatrolled
1111 * @todo This is overly specific, so move or kill this method.
1113 * @param RevisionRecord $rev
1115 * @return int Rcid of the unpatrolled row, zero if there isn't one
1117 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
1118 $rc = $this->getRecentChange( $rev );
1119 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == RecentChange
::PRC_UNPATROLLED
) {
1120 return $rc->getAttribute( 'rc_id' );
1127 * Get the RC object belonging to the current revision, if there's one
1129 * MCR migration note: this replaces Revision::getRecentChange
1131 * @todo move this somewhere else?
1133 * @param RevisionRecord $rev
1134 * @param int $flags (optional) $flags include:
1135 * IDBAccessObject::READ_LATEST: Select the data from the master
1137 * @return null|RecentChange
1139 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
1140 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
1141 $db = $this->getDBConnectionRef( $dbType );
1143 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
1145 if ( !$userIdentity ) {
1146 // If the revision has no user identity, chances are it never went
1147 // into the database, and doesn't have an RC entry.
1151 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
1152 $actorWhere = $this->actorMigration
->getWhere( $db, 'rc_user', $rev->getUser(), false );
1153 $rc = RecentChange
::newFromConds(
1155 $actorWhere['conds'],
1156 'rc_timestamp' => $db->timestamp( $rev->getTimestamp() ),
1157 'rc_this_oldid' => $rev->getId()
1163 // XXX: cache this locally? Glue it to the RevisionRecord?
1168 * Maps fields of the archive row to corresponding revision rows.
1170 * @param object $archiveRow
1172 * @return object a revision row object, corresponding to $archiveRow.
1174 private static function mapArchiveFields( $archiveRow ) {
1176 // keep with ar prefix:
1179 // not the same suffix:
1180 'ar_page_id' => 'rev_page',
1181 'ar_rev_id' => 'rev_id',
1184 'ar_text_id' => 'rev_text_id',
1185 'ar_timestamp' => 'rev_timestamp',
1186 'ar_user_text' => 'rev_user_text',
1187 'ar_user' => 'rev_user',
1188 'ar_actor' => 'rev_actor',
1189 'ar_minor_edit' => 'rev_minor_edit',
1190 'ar_deleted' => 'rev_deleted',
1191 'ar_len' => 'rev_len',
1192 'ar_parent_id' => 'rev_parent_id',
1193 'ar_sha1' => 'rev_sha1',
1194 'ar_comment' => 'rev_comment',
1195 'ar_comment_cid' => 'rev_comment_cid',
1196 'ar_comment_id' => 'rev_comment_id',
1197 'ar_comment_text' => 'rev_comment_text',
1198 'ar_comment_data' => 'rev_comment_data',
1199 'ar_comment_old' => 'rev_comment_old',
1200 'ar_content_format' => 'rev_content_format',
1201 'ar_content_model' => 'rev_content_model',
1204 $revRow = new stdClass();
1205 foreach ( $fieldMap as $arKey => $revKey ) {
1206 if ( property_exists( $archiveRow, $arKey ) ) {
1207 $revRow->$revKey = $archiveRow->$arKey;
1215 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
1217 * @param object|array $row Either a database row or an array
1218 * @param int $queryFlags for callbacks
1219 * @param Title $title
1221 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
1222 * @throws MWException
1224 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
1225 $mainSlotRow = new stdClass();
1226 $mainSlotRow->role_name
= SlotRecord
::MAIN
;
1227 $mainSlotRow->model_name
= null;
1228 $mainSlotRow->slot_revision_id
= null;
1229 $mainSlotRow->slot_content_id
= null;
1230 $mainSlotRow->content_address
= null;
1236 if ( is_object( $row ) ) {
1237 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1238 // Don't emulate from a row when using the new schema.
1239 // Emulating from an array is still OK.
1240 throw new LogicException( 'Can\'t emulate the main slot when using MCR schema.' );
1244 if ( !isset( $row->rev_id
) && ( isset( $row->ar_user
) ||
isset( $row->ar_actor
) ) ) {
1245 $row = $this->mapArchiveFields( $row );
1248 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
1249 $mainSlotRow->content_address
= SqlBlobStore
::makeAddressFromTextId(
1254 // This is used by null-revisions
1255 $mainSlotRow->slot_origin
= isset( $row->slot_origin
)
1256 ?
intval( $row->slot_origin
)
1259 if ( isset( $row->old_text
) ) {
1260 // this happens when the text-table gets joined directly, in the pre-1.30 schema
1261 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
1262 // Check against selects that might have not included old_flags
1263 if ( !property_exists( $row, 'old_flags' ) ) {
1264 throw new InvalidArgumentException( 'old_flags was not set in $row' );
1266 $blobFlags = $row->old_flags ??
'';
1269 $mainSlotRow->slot_revision_id
= intval( $row->rev_id
);
1271 $mainSlotRow->content_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
1272 $mainSlotRow->content_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
1273 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
1274 ?
strval( $row->rev_content_model
)
1276 // XXX: in the future, we'll probably always use the default format, and drop content_format
1277 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
1278 ?
strval( $row->rev_content_format
)
1281 if ( isset( $row->rev_text_id
) && intval( $row->rev_text_id
) > 0 ) {
1282 // Overwritten below for SCHEMA_COMPAT_WRITE_NEW
1283 $mainSlotRow->slot_content_id
1284 = $this->emulateContentId( intval( $row->rev_text_id
) );
1286 } elseif ( is_array( $row ) ) {
1287 $mainSlotRow->slot_revision_id
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
1289 $mainSlotRow->slot_origin
= isset( $row['slot_origin'] )
1290 ?
intval( $row['slot_origin'] )
1292 $mainSlotRow->content_address
= isset( $row['text_id'] )
1293 ? SqlBlobStore
::makeAddressFromTextId( intval( $row['text_id'] ) )
1295 $mainSlotRow->content_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
1296 $mainSlotRow->content_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
1298 $mainSlotRow->model_name
= isset( $row['content_model'] )
1299 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
1300 // XXX: in the future, we'll probably always use the default format, and drop content_format
1301 $mainSlotRow->format_name
= isset( $row['content_format'] )
1302 ?
strval( $row['content_format'] ) : null;
1303 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
1304 // XXX: If the flags field is not set then $blobFlags should be null so that no
1305 // decoding will happen. An empty string will result in default decodings.
1306 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
1308 // if we have a Content object, override mText and mContentModel
1309 if ( !empty( $row['content'] ) ) {
1310 if ( !( $row['content'] instanceof Content
) ) {
1311 throw new MWException( 'content field must contain a Content object.' );
1314 /** @var Content $content */
1315 $content = $row['content'];
1316 $handler = $content->getContentHandler();
1318 $mainSlotRow->model_name
= $content->getModel();
1320 // XXX: in the future, we'll probably always use the default format.
1321 if ( $mainSlotRow->format_name
=== null ) {
1322 $mainSlotRow->format_name
= $handler->getDefaultFormat();
1326 if ( isset( $row['text_id'] ) && intval( $row['text_id'] ) > 0 ) {
1327 // Overwritten below for SCHEMA_COMPAT_WRITE_NEW
1328 $mainSlotRow->slot_content_id
1329 = $this->emulateContentId( intval( $row['text_id'] ) );
1332 throw new MWException( 'Revision constructor passed invalid row format.' );
1335 // With the old schema, the content changes with every revision,
1336 // except for null-revisions.
1337 if ( !isset( $mainSlotRow->slot_origin
) ) {
1338 $mainSlotRow->slot_origin
= $mainSlotRow->slot_revision_id
;
1341 if ( $mainSlotRow->model_name
=== null ) {
1342 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
1343 $this->assertCrossWikiContentLoadingIsSafe();
1345 return $this->slotRoleRegistry
->getRoleHandler( $slot->getRole() )
1346 ->getDefaultModel( $title );
1351 // XXX: We should perhaps fail if $blobData is null and $mainSlotRow->content_address
1352 // is missing, but "empty revisions" with no content are used in some edge cases.
1354 $content = function ( SlotRecord
$slot )
1355 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
1357 return $this->loadSlotContent(
1361 $mainSlotRow->format_name
,
1367 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
1368 // NOTE: this callback will be looped through RevisionSlot::newInherited(), allowing
1369 // the inherited slot to have the same content_id as the original slot. In that case,
1370 // $slot will be the inherited slot, while $mainSlotRow still refers to the original slot.
1371 $mainSlotRow->slot_content_id
=
1372 function ( SlotRecord
$slot ) use ( $queryFlags, $mainSlotRow ) {
1373 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1374 return $this->findSlotContentId( $db, $mainSlotRow->slot_revision_id
, SlotRecord
::MAIN
);
1378 return new SlotRecord( $mainSlotRow, $content );
1382 * Provides a content ID to use with emulated SlotRecords in SCHEMA_COMPAT_OLD mode,
1383 * based on the revision's text ID (rev_text_id or ar_text_id, respectively).
1384 * Note that in SCHEMA_COMPAT_WRITE_BOTH, a callback to findSlotContentId() should be used
1385 * instead, since in that mode, some revision rows may already have a real content ID,
1386 * while other's don't - and for the ones that don't, we should indicate that it
1387 * is missing and cause SlotRecords::hasContentId() to return false.
1389 * @param int $textId
1390 * @return int The emulated content ID
1392 private function emulateContentId( $textId ) {
1393 // Return a negative number to ensure the ID is distinct from any real content IDs
1394 // that will be assigned in SCHEMA_COMPAT_WRITE_NEW mode and read in SCHEMA_COMPAT_READ_NEW
1400 * Loads a Content object based on a slot row.
1402 * This method does not call $slot->getContent(), and may be used as a callback
1403 * called by $slot->getContent().
1405 * MCR migration note: this roughly corresponds to Revision::getContentInternal
1407 * @param SlotRecord $slot The SlotRecord to load content for
1408 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
1409 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
1410 * Use null if no processing should happen. That is in constrast to the empty string,
1411 * which causes the blob to be decoded according to the configured legacy encoding.
1412 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
1413 * @param int $queryFlags
1415 * @throws RevisionAccessException
1418 private function loadSlotContent(
1425 if ( $blobData !== null ) {
1426 Assert
::parameterType( 'string', $blobData, '$blobData' );
1427 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
1429 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
1431 if ( $blobFlags === null ) {
1432 // No blob flags, so use the blob verbatim.
1435 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
1436 if ( $data === false ) {
1437 throw new RevisionAccessException(
1438 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
1444 $address = $slot->getAddress();
1446 $data = $this->blobStore
->getBlob( $address, $queryFlags );
1447 } catch ( BlobAccessException
$e ) {
1448 throw new RevisionAccessException(
1449 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
1454 // Unserialize content
1455 $handler = ContentHandler
::getForModelID( $slot->getModel() );
1457 $content = $handler->unserializeContent( $data, $blobFormat );
1462 * Load a page revision from a given revision ID number.
1463 * Returns null if no such revision can be found.
1465 * MCR migration note: this replaces Revision::newFromId
1468 * IDBAccessObject::READ_LATEST: Select the data from the master
1469 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1472 * @param int $flags (optional)
1473 * @return RevisionRecord|null
1475 public function getRevisionById( $id, $flags = 0 ) {
1476 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
1480 * Load either the current, or a specified, revision
1481 * that's attached to a given link target. If not attached
1482 * to that link target, will return null.
1484 * MCR migration note: this replaces Revision::newFromTitle
1487 * IDBAccessObject::READ_LATEST: Select the data from the master
1488 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1490 * @param LinkTarget $linkTarget
1491 * @param int $revId (optional)
1492 * @param int $flags Bitfield (optional)
1493 * @return RevisionRecord|null
1495 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
1496 // TODO should not require Title in future (T206498)
1497 $title = Title
::newFromLinkTarget( $linkTarget );
1499 'page_namespace' => $title->getNamespace(),
1500 'page_title' => $title->getDBkey()
1503 // Use the specified revision ID.
1504 // Note that we use newRevisionFromConds here because we want to retry
1505 // and fall back to master if the page is not found on a replica.
1506 // Since the caller supplied a revision ID, we are pretty sure the revision is
1507 // supposed to exist, so we should try hard to find it.
1508 $conds['rev_id'] = $revId;
1509 return $this->newRevisionFromConds( $conds, $flags, $title );
1511 // Use a join to get the latest revision.
1512 // Note that we don't use newRevisionFromConds here because we don't want to retry
1513 // and fall back to master. The assumption is that we only want to force the fallback
1514 // if we are quite sure the revision exists because the caller supplied a revision ID.
1515 // If the page isn't found at all on a replica, it probably simply does not exist.
1516 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1518 $conds[] = 'rev_id=page_latest';
1519 $rev = $this->loadRevisionFromConds( $db, $conds, $flags, $title );
1526 * Load either the current, or a specified, revision
1527 * that's attached to a given page ID.
1528 * Returns null if no such revision can be found.
1530 * MCR migration note: this replaces Revision::newFromPageId
1533 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
1534 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1536 * @param int $pageId
1537 * @param int $revId (optional)
1538 * @param int $flags Bitfield (optional)
1539 * @return RevisionRecord|null
1541 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1542 $conds = [ 'page_id' => $pageId ];
1544 // Use the specified revision ID.
1545 // Note that we use newRevisionFromConds here because we want to retry
1546 // and fall back to master if the page is not found on a replica.
1547 // Since the caller supplied a revision ID, we are pretty sure the revision is
1548 // supposed to exist, so we should try hard to find it.
1549 $conds['rev_id'] = $revId;
1550 return $this->newRevisionFromConds( $conds, $flags );
1552 // Use a join to get the latest revision.
1553 // Note that we don't use newRevisionFromConds here because we don't want to retry
1554 // and fall back to master. The assumption is that we only want to force the fallback
1555 // if we are quite sure the revision exists because the caller supplied a revision ID.
1556 // If the page isn't found at all on a replica, it probably simply does not exist.
1557 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1559 $conds[] = 'rev_id=page_latest';
1560 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1567 * Load the revision for the given title with the given timestamp.
1568 * WARNING: Timestamps may in some circumstances not be unique,
1569 * so this isn't the best key to use.
1571 * MCR migration note: this replaces Revision::loadFromTimestamp
1573 * @param Title $title
1574 * @param string $timestamp
1575 * @return RevisionRecord|null
1577 public function getRevisionByTimestamp( $title, $timestamp ) {
1578 $db = $this->getDBConnectionRef( DB_REPLICA
);
1579 return $this->newRevisionFromConds(
1581 'rev_timestamp' => $db->timestamp( $timestamp ),
1582 'page_namespace' => $title->getNamespace(),
1583 'page_title' => $title->getDBkey()
1591 * @param int $revId The revision to load slots for.
1592 * @param int $queryFlags
1593 * @param Title $title
1595 * @return SlotRecord[]
1597 private function loadSlotRecords( $revId, $queryFlags, Title
$title ) {
1598 $revQuery = self
::getSlotsQueryInfo( [ 'content' ] );
1600 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
1601 $db = $this->getDBConnectionRef( $dbMode );
1604 $revQuery['tables'],
1605 $revQuery['fields'],
1607 'slot_revision_id' => $revId,
1614 $slots = $this->constructSlotRecords( $revId, $res, $queryFlags, $title );
1620 * Factory method for SlotRecords based on known slot rows.
1622 * @param int $revId The revision to load slots for.
1623 * @param object[]|IResultWrapper $slotRows
1624 * @param int $queryFlags
1625 * @param Title $title
1627 * @return SlotRecord[]
1629 private function constructSlotRecords( $revId, $slotRows, $queryFlags, Title
$title ) {
1632 foreach ( $slotRows as $row ) {
1633 // Resolve role names and model names from in-memory cache, if they were not joined in.
1634 if ( !isset( $row->role_name
) ) {
1635 $row->role_name
= $this->slotRoleStore
->getName( (int)$row->slot_role_id
);
1638 if ( !isset( $row->model_name
) ) {
1639 if ( isset( $row->content_model
) ) {
1640 $row->model_name
= $this->contentModelStore
->getName( (int)$row->content_model
);
1642 // We may get here if $row->model_name is set but null, perhaps because it
1643 // came from rev_content_model, which is NULL for the default model.
1644 $slotRoleHandler = $this->slotRoleRegistry
->getRoleHandler( $row->role_name
);
1645 $row->model_name
= $slotRoleHandler->getDefaultModel( $title );
1649 if ( !isset( $row->content_id
) && isset( $row->rev_text_id
) ) {
1650 $row->slot_content_id
1651 = $this->emulateContentId( intval( $row->rev_text_id
) );
1654 $contentCallback = function ( SlotRecord
$slot ) use ( $queryFlags ) {
1655 return $this->loadSlotContent( $slot, null, null, null, $queryFlags );
1658 $slots[$row->role_name
] = new SlotRecord( $row, $contentCallback );
1661 if ( !isset( $slots[SlotRecord
::MAIN
] ) ) {
1662 throw new RevisionAccessException(
1663 'Main slot of revision ' . $revId . ' not found in database!'
1671 * Factory method for RevisionSlots based on a revision ID.
1673 * @note If other code has a need to construct RevisionSlots objects, this should be made
1674 * public, since RevisionSlots instances should not be constructed directly.
1677 * @param object $revisionRow
1678 * @param object[]|null $slotRows
1679 * @param int $queryFlags
1680 * @param Title $title
1682 * @return RevisionSlots
1683 * @throws MWException
1685 private function newRevisionSlots(
1693 $slots = new RevisionSlots(
1694 $this->constructSlotRecords( $revId, $slotRows, $queryFlags, $title )
1696 } elseif ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1697 $mainSlot = $this->emulateMainSlot_1_29( $revisionRow, $queryFlags, $title );
1698 // @phan-suppress-next-line PhanTypeInvalidCallableArraySize false positive
1699 $slots = new RevisionSlots( [ SlotRecord
::MAIN
=> $mainSlot ] );
1701 // XXX: do we need the same kind of caching here
1702 // that getKnownCurrentRevision uses (if $revId == page_latest?)
1704 $slots = new RevisionSlots( function () use( $revId, $queryFlags, $title ) {
1705 return $this->loadSlotRecords( $revId, $queryFlags, $title );
1713 * Make a fake revision object from an archive table row. This is queried
1714 * for permissions or even inserted (as in Special:Undelete)
1716 * MCR migration note: this replaces Revision::newFromArchiveRow
1718 * @param object $row
1719 * @param int $queryFlags
1720 * @param Title|null $title
1721 * @param array $overrides associative array with fields of $row to override. This may be
1722 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1723 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1724 * override ar_parent_id.
1726 * @return RevisionRecord
1727 * @throws MWException
1729 public function newRevisionFromArchiveRow(
1732 Title
$title = null,
1733 array $overrides = []
1735 Assert
::parameterType( 'object', $row, '$row' );
1737 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1738 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1740 if ( !$title && isset( $overrides['title'] ) ) {
1741 if ( !( $overrides['title'] instanceof Title
) ) {
1742 throw new MWException( 'title field override must contain a Title object.' );
1745 $title = $overrides['title'];
1748 if ( !isset( $title ) ) {
1749 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1750 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1752 throw new InvalidArgumentException(
1753 'A Title or ar_namespace and ar_title must be given'
1758 foreach ( $overrides as $key => $value ) {
1760 $row->$field = $value;
1764 $user = User
::newFromAnyId(
1765 $row->ar_user ??
null,
1766 $row->ar_user_text ??
null,
1767 $row->ar_actor ??
null,
1770 } catch ( InvalidArgumentException
$ex ) {
1771 wfWarn( __METHOD__
. ': ' . $title->getPrefixedDBkey() . ': ' . $ex->getMessage() );
1772 $user = new UserIdentityValue( 0, 'Unknown user', 0 );
1775 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1776 // Legacy because $row may have come from self::selectFields()
1777 $comment = $this->commentStore
->getCommentLegacy( $db, 'ar_comment', $row, true );
1779 $slots = $this->newRevisionSlots( $row->ar_rev_id
, $row, null, $queryFlags, $title );
1781 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->dbDomain
);
1785 * @see RevisionFactory::newRevisionFromRow
1787 * MCR migration note: this replaces Revision::newFromRow
1789 * @param object $row A database row generated from a query based on getQueryInfo()
1790 * @param int $queryFlags
1791 * @param Title|null $title
1792 * @param bool $fromCache if true, the returned RevisionRecord will ensure that no stale
1793 * data is returned from getters, by querying the database as needed
1794 * @return RevisionRecord
1796 public function newRevisionFromRow(
1799 Title
$title = null,
1802 return $this->newRevisionFromRowAndSlots( $row, null, $queryFlags, $title, $fromCache );
1806 * @param object $row A database row generated from a query based on getQueryInfo()
1807 * @param null|object[] $slotRows Database rows generated from a query based on
1808 * getSlotsQueryInfo with the 'content' flag set.
1809 * @param int $queryFlags
1810 * @param Title|null $title
1811 * @param bool $fromCache if true, the returned RevisionRecord will ensure that no stale
1812 * data is returned from getters, by querying the database as needed
1814 * @return RevisionRecord
1815 * @throws MWException
1816 * @see RevisionFactory::newRevisionFromRow
1818 * MCR migration note: this replaces Revision::newFromRow
1821 public function newRevisionFromRowAndSlots(
1825 Title
$title = null,
1828 Assert
::parameterType( 'object', $row, '$row' );
1831 $pageId = $row->rev_page ??
0; // XXX: also check page_id?
1832 $revId = $row->rev_id ??
0;
1834 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1837 if ( !isset( $row->page_latest
) ) {
1838 $row->page_latest
= $title->getLatestRevID();
1839 if ( $row->page_latest
=== 0 && $title->exists() ) {
1840 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1845 $user = User
::newFromAnyId(
1846 $row->rev_user ??
null,
1847 $row->rev_user_text ??
null,
1848 $row->rev_actor ??
null,
1851 } catch ( InvalidArgumentException
$ex ) {
1852 wfWarn( __METHOD__
. ': ' . $title->getPrefixedDBkey() . ': ' . $ex->getMessage() );
1853 $user = new UserIdentityValue( 0, 'Unknown user', 0 );
1856 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1857 // Legacy because $row may have come from self::selectFields()
1858 $comment = $this->commentStore
->getCommentLegacy( $db, 'rev_comment', $row, true );
1860 $slots = $this->newRevisionSlots( $row->rev_id
, $row, $slotRows, $queryFlags, $title );
1862 // If this is a cached row, instantiate a cache-aware revision class to avoid stale data.
1864 $rev = new RevisionStoreCacheRecord(
1865 function ( $revId ) use ( $queryFlags ) {
1866 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1867 return $this->fetchRevisionRowFromConds(
1869 [ 'rev_id' => intval( $revId ) ]
1872 $title, $user, $comment, $row, $slots, $this->dbDomain
1875 $rev = new RevisionStoreRecord(
1876 $title, $user, $comment, $row, $slots, $this->dbDomain
);
1882 * Construct a RevisionRecord instance for each row in $rows,
1883 * and return them as an associative array indexed by revision ID.
1884 * @param Traversable|array $rows the rows to construct revision records from
1885 * @param array $options Supports the following options:
1886 * 'slots' - whether metadata about revision slots should be
1887 * loaded immediately. Supports falsy or truthy value as well
1888 * as an explicit list of slot role names.
1889 * 'content'- whether the actual content of the slots should be
1890 * preloaded. TODO: no supported yet.
1891 * @param int $queryFlags
1892 * @param Title|null $title
1893 * @return StatusValue a status with a RevisionRecord[] of successfully fetched revisions
1894 * and an array of errors for the revisions failed to fetch.
1896 public function newRevisionsFromBatch(
1898 array $options = [],
1902 $result = new StatusValue();
1906 $titlesByPageId = [];
1907 foreach ( $rows as $row ) {
1908 if ( isset( $rowsByRevId[$row->rev_id
] ) ) {
1909 throw new InvalidArgumentException( "Duplicate rows in newRevisionsFromBatch {$row->rev_id}" );
1911 if ( $title && $row->rev_page
!= $title->getArticleID() ) {
1912 throw new InvalidArgumentException(
1913 "Revision {$row->rev_id} doesn't belong to page {$title->getArticleID()}"
1916 $pageIds[] = $row->rev_page
;
1917 $rowsByRevId[$row->rev_id
] = $row;
1920 if ( empty( $rowsByRevId ) ) {
1921 $result->setResult( true, [] );
1925 // If the title is not supplied, batch-fetch Title objects.
1927 $titlesByPageId[$title->getArticleID()] = $title;
1929 $pageIds = array_unique( $pageIds );
1930 foreach ( Title
::newFromIDs( $pageIds ) as $t ) {
1931 $titlesByPageId[$t->getArticleID()] = $t;
1935 if ( !isset( $options['slots'] ) ||
$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
1936 $result->setResult( true,
1937 array_map( function ( $row ) use ( $queryFlags, $titlesByPageId, $result ) {
1939 return $this->newRevisionFromRow(
1942 $titlesByPageId[$row->rev_page
]
1944 } catch ( MWException
$e ) {
1945 $result->warning( 'internalerror', $e->getMessage() );
1953 $slotQueryConds = [ 'slot_revision_id' => array_keys( $rowsByRevId ) ];
1954 if ( is_array( $options['slots'] ) ) {
1955 $slotQueryConds['slot_role_id'] = array_map( function ( $slot_name ) {
1956 return $this->slotRoleStore
->getId( $slot_name );
1957 }, $options['slots'] );
1960 // TODO: Support optional fetching of the content
1961 $queryInfo = self
::getSlotsQueryInfo( [ 'content' ] );
1962 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1963 $slotRows = $db->select(
1964 $queryInfo['tables'],
1965 $queryInfo['fields'],
1972 $slotRowsByRevId = [];
1973 foreach ( $slotRows as $slotRow ) {
1974 $slotRowsByRevId[$slotRow->slot_revision_id
][] = $slotRow;
1976 $result->setResult( true, array_map( function ( $row ) use
1977 ( $slotRowsByRevId, $queryFlags, $titlesByPageId, $result ) {
1978 if ( !isset( $slotRowsByRevId[$row->rev_id
] ) ) {
1981 "Couldn't find slots for rev {$row->rev_id}"
1986 return $this->newRevisionFromRowAndSlots(
1988 $slotRowsByRevId[$row->rev_id
],
1990 $titlesByPageId[$row->rev_page
]
1992 } catch ( MWException
$e ) {
1993 $result->warning( 'internalerror', $e->getMessage() );
1996 }, $rowsByRevId ) );
2001 * Constructs a new MutableRevisionRecord based on the given associative array following
2002 * the MW1.29 convention for the Revision constructor.
2004 * MCR migration note: this replaces Revision::newFromRow
2006 * @param array $fields
2007 * @param int $queryFlags
2008 * @param Title|null $title
2010 * @return MutableRevisionRecord
2011 * @throws MWException
2012 * @throws RevisionAccessException
2014 public function newMutableRevisionFromArray(
2019 if ( !$title && isset( $fields['title'] ) ) {
2020 if ( !( $fields['title'] instanceof Title
) ) {
2021 throw new MWException( 'title field must contain a Title object.' );
2024 $title = $fields['title'];
2028 $pageId = $fields['page'] ??
0;
2029 $revId = $fields['id'] ??
0;
2031 $title = $this->getTitle( $pageId, $revId, $queryFlags );
2034 if ( !isset( $fields['page'] ) ) {
2035 $fields['page'] = $title->getArticleID( $queryFlags );
2038 // if we have a content object, use it to set the model and type
2039 if ( !empty( $fields['content'] ) && !( $fields['content'] instanceof Content
)
2040 && !is_array( $fields['content'] )
2042 throw new MWException(
2043 'content field must contain a Content object or an array of Content objects.'
2047 if ( !empty( $fields['text_id'] ) ) {
2048 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2049 throw new MWException( "The text_id field is only available in the pre-MCR schema" );
2052 if ( !empty( $fields['content'] ) ) {
2053 throw new MWException(
2054 "Text already stored in external store (id {$fields['text_id']}), " .
2055 "can't specify content object"
2061 isset( $fields['comment'] )
2062 && !( $fields['comment'] instanceof CommentStoreComment
)
2064 $commentData = $fields['comment_data'] ??
null;
2066 if ( $fields['comment'] instanceof Message
) {
2067 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
2072 $commentText = trim( strval( $fields['comment'] ) );
2073 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
2080 $revision = new MutableRevisionRecord( $title, $this->dbDomain
);
2081 $this->initializeMutableRevisionFromArray( $revision, $fields );
2083 if ( isset( $fields['content'] ) && is_array( $fields['content'] ) ) {
2084 // @phan-suppress-next-line PhanTypeNoPropertiesForeach
2085 foreach ( $fields['content'] as $role => $content ) {
2086 $revision->setContent( $role, $content );
2089 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
2090 $revision->setSlot( $mainSlot );
2097 * @param MutableRevisionRecord $record
2098 * @param array $fields
2100 private function initializeMutableRevisionFromArray(
2101 MutableRevisionRecord
$record,
2104 /** @var UserIdentity $user */
2107 // If a user is passed in, use it if possible. We cannot use a user from a
2108 // remote wiki with unsuppressed ids, due to issues described in T222212.
2109 if ( isset( $fields['user'] ) &&
2110 ( $fields['user'] instanceof UserIdentity
) &&
2111 ( $this->dbDomain
=== false ||
2112 ( !$fields['user']->getId() && !$fields['user']->getActorId() ) )
2114 $user = $fields['user'];
2117 $user = User
::newFromAnyId(
2118 $fields['user'] ??
null,
2119 $fields['user_text'] ??
null,
2120 $fields['actor'] ??
null,
2123 } catch ( InvalidArgumentException
$ex ) {
2129 $record->setUser( $user );
2132 $timestamp = isset( $fields['timestamp'] )
2133 ?
strval( $fields['timestamp'] )
2134 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
2136 $record->setTimestamp( $timestamp );
2138 if ( isset( $fields['page'] ) ) {
2139 $record->setPageId( intval( $fields['page'] ) );
2142 if ( isset( $fields['id'] ) ) {
2143 $record->setId( intval( $fields['id'] ) );
2145 if ( isset( $fields['parent_id'] ) ) {
2146 $record->setParentId( intval( $fields['parent_id'] ) );
2149 if ( isset( $fields['sha1'] ) ) {
2150 $record->setSha1( $fields['sha1'] );
2152 if ( isset( $fields['size'] ) ) {
2153 $record->setSize( intval( $fields['size'] ) );
2156 if ( isset( $fields['minor_edit'] ) ) {
2157 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
2159 if ( isset( $fields['deleted'] ) ) {
2160 $record->setVisibility( intval( $fields['deleted'] ) );
2163 if ( isset( $fields['comment'] ) ) {
2164 Assert
::parameterType(
2165 CommentStoreComment
::class,
2169 $record->setComment( $fields['comment'] );
2174 * Load a page revision from a given revision ID number.
2175 * Returns null if no such revision can be found.
2177 * MCR migration note: this corresponds to Revision::loadFromId
2179 * @note direct use is deprecated!
2180 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
2182 * @param IDatabase $db
2185 * @return RevisionRecord|null
2187 public function loadRevisionFromId( IDatabase
$db, $id ) {
2188 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
2192 * Load either the current, or a specified, revision
2193 * that's attached to a given page. If not attached
2194 * to that page, will return null.
2196 * MCR migration note: this replaces Revision::loadFromPageId
2198 * @note direct use is deprecated!
2199 * @todo remove when unused!
2201 * @param IDatabase $db
2202 * @param int $pageid
2204 * @return RevisionRecord|null
2206 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
2207 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
2209 $conds['rev_id'] = intval( $id );
2211 $conds[] = 'rev_id=page_latest';
2213 return $this->loadRevisionFromConds( $db, $conds );
2217 * Load either the current, or a specified, revision
2218 * that's attached to a given page. If not attached
2219 * to that page, will return null.
2221 * MCR migration note: this replaces Revision::loadFromTitle
2223 * @note direct use is deprecated!
2224 * @todo remove when unused!
2226 * @param IDatabase $db
2227 * @param Title $title
2230 * @return RevisionRecord|null
2232 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
2234 $matchId = intval( $id );
2236 $matchId = 'page_latest';
2239 return $this->loadRevisionFromConds(
2243 'page_namespace' => $title->getNamespace(),
2244 'page_title' => $title->getDBkey()
2252 * Load the revision for the given title with the given timestamp.
2253 * WARNING: Timestamps may in some circumstances not be unique,
2254 * so this isn't the best key to use.
2256 * MCR migration note: this replaces Revision::loadFromTimestamp
2258 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
2259 * @todo remove when unused!
2261 * @param IDatabase $db
2262 * @param Title $title
2263 * @param string $timestamp
2264 * @return RevisionRecord|null
2266 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
2267 return $this->loadRevisionFromConds( $db,
2269 'rev_timestamp' => $db->timestamp( $timestamp ),
2270 'page_namespace' => $title->getNamespace(),
2271 'page_title' => $title->getDBkey()
2279 * Given a set of conditions, fetch a revision
2281 * This method should be used if we are pretty sure the revision exists.
2282 * Unless $flags has READ_LATEST set, this method will first try to find the revision
2283 * on a replica before hitting the master database.
2285 * MCR migration note: this corresponds to Revision::newFromConds
2287 * @param array $conditions
2288 * @param int $flags (optional)
2289 * @param Title|null $title
2291 * @return RevisionRecord|null
2293 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
2294 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2295 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
2297 $lb = $this->getDBLoadBalancer();
2299 // Make sure new pending/committed revision are visibile later on
2300 // within web requests to certain avoid bugs like T93866 and T94407.
2302 && !( $flags & self
::READ_LATEST
)
2303 && $lb->hasStreamingReplicaServers()
2304 && $lb->hasOrMadeRecentMasterChanges()
2306 $flags = self
::READ_LATEST
;
2307 $dbw = $this->getDBConnectionRef( DB_MASTER
);
2308 $rev = $this->loadRevisionFromConds( $dbw, $conditions, $flags, $title );
2315 * Given a set of conditions, fetch a revision from
2316 * the given database connection.
2318 * MCR migration note: this corresponds to Revision::loadFromConds
2320 * @param IDatabase $db
2321 * @param array $conditions
2322 * @param int $flags (optional)
2323 * @param Title|null $title
2325 * @return RevisionRecord|null
2327 private function loadRevisionFromConds(
2333 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
2335 $rev = $this->newRevisionFromRow( $row, $flags, $title );
2344 * Throws an exception if the given database connection does not belong to the wiki this
2345 * RevisionStore is bound to.
2347 * @param IDatabase $db
2348 * @throws MWException
2350 private function checkDatabaseDomain( IDatabase
$db ) {
2351 $dbDomain = $db->getDomainID();
2352 $storeDomain = $this->loadBalancer
->resolveDomainID( $this->dbDomain
);
2353 if ( $dbDomain === $storeDomain ) {
2357 throw new MWException( "DB connection domain '$dbDomain' does not match '$storeDomain'" );
2361 * Given a set of conditions, return a row with the
2362 * fields necessary to build RevisionRecord objects.
2364 * MCR migration note: this corresponds to Revision::fetchFromConds
2366 * @param IDatabase $db
2367 * @param array $conditions
2368 * @param int $flags (optional)
2370 * @return object|false data row as a raw object
2372 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
2373 $this->checkDatabaseDomain( $db );
2375 $revQuery = $this->getQueryInfo( [ 'page', 'user' ] );
2377 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
2378 $options[] = 'FOR UPDATE';
2380 return $db->selectRow(
2381 $revQuery['tables'],
2382 $revQuery['fields'],
2391 * Finds the ID of a content row for a given revision and slot role.
2392 * This can be used to re-use content rows even while the content ID
2393 * is still missing from SlotRecords, when writing to both the old and
2394 * the new schema during MCR schema migration.
2396 * @todo remove after MCR schema migration is complete.
2398 * @param IDatabase $db
2400 * @param string $role
2404 private function findSlotContentId( IDatabase
$db, $revId, $role ) {
2405 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
2410 $roleId = $this->slotRoleStore
->getId( $role );
2412 'slot_revision_id' => $revId,
2413 'slot_role_id' => $roleId,
2416 $contentId = $db->selectField( 'slots', 'slot_content_id', $conditions, __METHOD__
);
2418 return $contentId ?
: null;
2419 } catch ( NameTableAccessException
$ex ) {
2420 // If the role is missing from the slot_roles table,
2421 // the corresponding row in slots cannot exist.
2427 * Return the tables, fields, and join conditions to be selected to create
2428 * a new RevisionStoreRecord object.
2430 * MCR migration note: this replaces Revision::getQueryInfo
2432 * If the format of fields returned changes in any way then the cache key provided by
2433 * self::getRevisionRowCacheKey should be updated.
2437 * @param array $options Any combination of the following strings
2438 * - 'page': Join with the page table, and select fields to identify the page
2439 * - 'user': Join with the user table, and select the user name
2440 * - 'text': Join with the text table, and select fields to load page text. This
2441 * option is deprecated in MW 1.32 when the MCR migration flag SCHEMA_COMPAT_WRITE_NEW
2442 * is set, and disallowed when SCHEMA_COMPAT_READ_OLD is not set.
2444 * @return array With three keys:
2445 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2446 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2447 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2448 * @phan-return array{tables:string[],fields:string[],joins:array}
2450 public function getQueryInfo( $options = [] ) {
2457 $ret['tables'][] = 'revision';
2458 $ret['fields'] = array_merge( $ret['fields'], [
2469 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
2470 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
2471 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
2472 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
2474 $actorQuery = $this->actorMigration
->getJoin( 'rev_user' );
2475 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
2476 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
2477 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
2479 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2480 $ret['fields'][] = 'rev_text_id';
2482 if ( $this->contentHandlerUseDB
) {
2483 $ret['fields'][] = 'rev_content_format';
2484 $ret['fields'][] = 'rev_content_model';
2488 if ( in_array( 'page', $options, true ) ) {
2489 $ret['tables'][] = 'page';
2490 $ret['fields'] = array_merge( $ret['fields'], [
2498 $ret['joins']['page'] = [ 'JOIN', [ 'page_id = rev_page' ] ];
2501 if ( in_array( 'user', $options, true ) ) {
2502 $ret['tables'][] = 'user';
2503 $ret['fields'] = array_merge( $ret['fields'], [
2506 $u = $actorQuery['fields']['rev_user'];
2507 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
2510 if ( in_array( 'text', $options, true ) ) {
2511 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
2512 throw new InvalidArgumentException( 'text table can no longer be joined directly' );
2513 } elseif ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2514 // NOTE: even when this class is set to not read from the old schema, callers
2515 // should still be able to join against the text table, as long as we are still
2516 // writing the old schema for compatibility.
2517 // TODO: This should trigger a deprecation warning eventually (T200918), but not
2518 // before all known usages are removed (see T198341 and T201164).
2519 // wfDeprecated( __METHOD__ . ' with `text` option', '1.32' );
2522 $ret['tables'][] = 'text';
2523 $ret['fields'] = array_merge( $ret['fields'], [
2527 $ret['joins']['text'] = [ 'JOIN', [ 'rev_text_id=old_id' ] ];
2534 * Return the tables, fields, and join conditions to be selected to create
2539 * @param array $options Any combination of the following strings
2540 * - 'content': Join with the content table, and select content meta-data fields
2541 * - 'model': Join with the content_models table, and select the model_name field.
2542 * Only applicable if 'content' is also set.
2543 * - 'role': Join with the slot_roles table, and select the role_name field
2545 * @return array With three keys:
2546 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2547 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2548 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2550 public function getSlotsQueryInfo( $options = [] ) {
2557 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2558 $db = $this->getDBConnectionRef( DB_REPLICA
);
2559 $ret['tables'][] = 'revision';
2561 $ret['fields']['slot_revision_id'] = 'rev_id';
2562 $ret['fields']['slot_content_id'] = 'NULL';
2563 $ret['fields']['slot_origin'] = 'rev_id';
2564 $ret['fields']['role_name'] = $db->addQuotes( SlotRecord
::MAIN
);
2566 if ( in_array( 'content', $options, true ) ) {
2567 $ret['fields']['content_size'] = 'rev_len';
2568 $ret['fields']['content_sha1'] = 'rev_sha1';
2569 $ret['fields']['content_address']
2570 = $db->buildConcat( [ $db->addQuotes( 'tt:' ), 'rev_text_id' ] );
2572 // Allow the content_id field to be emulated later
2573 $ret['fields']['rev_text_id'] = 'rev_text_id';
2575 if ( $this->contentHandlerUseDB
) {
2576 $ret['fields']['model_name'] = 'rev_content_model';
2578 $ret['fields']['model_name'] = 'NULL';
2582 $ret['tables'][] = 'slots';
2583 $ret['fields'] = array_merge( $ret['fields'], [
2590 if ( in_array( 'role', $options, true ) ) {
2591 // Use left join to attach role name, so we still find the revision row even
2592 // if the role name is missing. This triggers a more obvious failure mode.
2593 $ret['tables'][] = 'slot_roles';
2594 $ret['joins']['slot_roles'] = [ 'LEFT JOIN', [ 'slot_role_id = role_id' ] ];
2595 $ret['fields'][] = 'role_name';
2598 if ( in_array( 'content', $options, true ) ) {
2599 $ret['tables'][] = 'content';
2600 $ret['fields'] = array_merge( $ret['fields'], [
2606 $ret['joins']['content'] = [ 'JOIN', [ 'slot_content_id = content_id' ] ];
2608 if ( in_array( 'model', $options, true ) ) {
2609 // Use left join to attach model name, so we still find the revision row even
2610 // if the model name is missing. This triggers a more obvious failure mode.
2611 $ret['tables'][] = 'content_models';
2612 $ret['joins']['content_models'] = [ 'LEFT JOIN', [ 'content_model = model_id' ] ];
2613 $ret['fields'][] = 'model_name';
2623 * Return the tables, fields, and join conditions to be selected to create
2624 * a new RevisionArchiveRecord object.
2626 * MCR migration note: this replaces Revision::getArchiveQueryInfo
2630 * @return array With three keys:
2631 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2632 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2633 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2635 public function getArchiveQueryInfo() {
2636 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
2637 $actorQuery = $this->actorMigration
->getJoin( 'ar_user' );
2639 'tables' => [ 'archive' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
2652 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
2653 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
2656 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2657 $ret['fields'][] = 'ar_text_id';
2659 if ( $this->contentHandlerUseDB
) {
2660 $ret['fields'][] = 'ar_content_format';
2661 $ret['fields'][] = 'ar_content_model';
2669 * Do a batched query for the sizes of a set of revisions.
2671 * MCR migration note: this replaces Revision::getParentLengths
2673 * @param int[] $revIds
2674 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2675 * of the corresponding revision.
2677 public function getRevisionSizes( array $revIds ) {
2678 return $this->listRevisionSizes( $this->getDBConnectionRef( DB_REPLICA
), $revIds );
2682 * Do a batched query for the sizes of a set of revisions.
2684 * MCR migration note: this replaces Revision::getParentLengths
2686 * @deprecated use RevisionStore::getRevisionSizes instead.
2688 * @param IDatabase $db
2689 * @param int[] $revIds
2690 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2691 * of the corresponding revision.
2693 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
2694 $this->checkDatabaseDomain( $db );
2698 return $revLens; // empty
2703 [ 'rev_id', 'rev_len' ],
2704 [ 'rev_id' => $revIds ],
2708 foreach ( $res as $row ) {
2709 $revLens[$row->rev_id
] = intval( $row->rev_len
);
2716 * Implementation of getPreviousRevision and getNextRevision.
2718 * @param RevisionRecord $rev
2720 * @param string $dir 'next' or 'prev'
2721 * @return RevisionRecord|null
2723 private function getRelativeRevision( RevisionRecord
$rev, $flags, $dir ) {
2724 $op = $dir === 'next' ?
'>' : '<';
2725 $sort = $dir === 'next' ?
'ASC' : 'DESC';
2727 if ( !$rev->getId() ||
!$rev->getPageId() ) {
2728 // revision is unsaved or otherwise incomplete
2732 if ( $rev instanceof RevisionArchiveRecord
) {
2733 // revision is deleted, so it's not part of the page history
2737 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
2738 $db = $this->getDBConnectionRef( $dbType, [ 'contributions' ] );
2740 $ts = $this->getTimestampFromId( $rev->getId(), $flags );
2741 if ( $ts === false ) {
2742 // XXX Should this be moved into getTimestampFromId?
2743 $ts = $db->selectField( 'archive', 'ar_timestamp',
2744 [ 'ar_rev_id' => $rev->getId() ], __METHOD__
);
2745 if ( $ts === false ) {
2746 // XXX Is this reachable? How can we have a page id but no timestamp?
2750 $ts = $db->addQuotes( $db->timestamp( $ts ) );
2752 $revId = $db->selectField( 'revision', 'rev_id',
2754 'rev_page' => $rev->getPageId(),
2755 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op {$rev->getId()})"
2759 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
2760 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
2764 if ( $revId === false ) {
2768 return $this->getRevisionById( intval( $revId ) );
2772 * Get the revision before $rev in the page's history, if any.
2773 * Will return null for the first revision but also for deleted or unsaved revisions.
2775 * MCR migration note: this replaces Revision::getPrevious
2777 * @see Title::getPreviousRevisionID
2778 * @see PageArchive::getPreviousRevision
2780 * @param RevisionRecord $rev
2781 * @param int $flags (optional) $flags include:
2782 * IDBAccessObject::READ_LATEST: Select the data from the master
2784 * @return RevisionRecord|null
2786 public function getPreviousRevision( RevisionRecord
$rev, $flags = 0 ) {
2787 if ( $flags instanceof Title
) {
2788 // Old calling convention, we don't use Title here anymore
2789 wfDeprecated( __METHOD__
. ' with Title', '1.34' );
2793 return $this->getRelativeRevision( $rev, $flags, 'prev' );
2797 * Get the revision after $rev in the page's history, if any.
2798 * Will return null for the latest revision but also for deleted or unsaved revisions.
2800 * MCR migration note: this replaces Revision::getNext
2802 * @see Title::getNextRevisionID
2804 * @param RevisionRecord $rev
2805 * @param int $flags (optional) $flags include:
2806 * IDBAccessObject::READ_LATEST: Select the data from the master
2807 * @return RevisionRecord|null
2809 public function getNextRevision( RevisionRecord
$rev, $flags = 0 ) {
2810 if ( $flags instanceof Title
) {
2811 // Old calling convention, we don't use Title here anymore
2812 wfDeprecated( __METHOD__
. ' with Title', '1.34' );
2816 return $this->getRelativeRevision( $rev, $flags, 'next' );
2820 * Get previous revision Id for this page_id
2821 * This is used to populate rev_parent_id on save
2823 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
2825 * @param IDatabase $db
2826 * @param RevisionRecord $rev
2830 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
2831 $this->checkDatabaseDomain( $db );
2833 if ( $rev->getPageId() === null ) {
2836 # Use page_latest if ID is not given
2837 if ( !$rev->getId() ) {
2838 $prevId = $db->selectField(
2839 'page', 'page_latest',
2840 [ 'page_id' => $rev->getPageId() ],
2844 $prevId = $db->selectField(
2845 'revision', 'rev_id',
2846 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
2848 [ 'ORDER BY' => 'rev_id DESC' ]
2851 return intval( $prevId );
2855 * Get rev_timestamp from rev_id, without loading the rest of the row.
2857 * Historically, there was an extra Title parameter that was passed before $id. This is no
2858 * longer needed and is deprecated in 1.34.
2860 * MCR migration note: this replaces Revision::getTimestampFromId
2864 * @return string|bool False if not found
2866 public function getTimestampFromId( $id, $flags = 0 ) {
2867 if ( $id instanceof Title
) {
2868 // Old deprecated calling convention supported for backwards compatibility
2870 $flags = func_num_args() > 2 ?
func_get_arg( 2 ) : 0;
2872 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2875 $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $id ], __METHOD__
);
2877 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
2881 * Get count of revisions per page...not very efficient
2883 * MCR migration note: this replaces Revision::countByPageId
2885 * @param IDatabase $db
2886 * @param int $id Page id
2889 public function countRevisionsByPageId( IDatabase
$db, $id ) {
2890 $this->checkDatabaseDomain( $db );
2892 $row = $db->selectRow( 'revision',
2893 [ 'revCount' => 'COUNT(*)' ],
2894 [ 'rev_page' => $id ],
2898 return intval( $row->revCount
);
2904 * Get count of revisions per page...not very efficient
2906 * MCR migration note: this replaces Revision::countByTitle
2908 * @param IDatabase $db
2909 * @param Title $title
2912 public function countRevisionsByTitle( IDatabase
$db, $title ) {
2913 $id = $title->getArticleID();
2915 return $this->countRevisionsByPageId( $db, $id );
2921 * Check if no edits were made by other users since
2922 * the time a user started editing the page. Limit to
2923 * 50 revisions for the sake of performance.
2925 * MCR migration note: this replaces Revision::userWasLastToEdit
2927 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
2928 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
2929 * has been deprecated since 1.24.
2931 * @param IDatabase $db The Database to perform the check on.
2932 * @param int $pageId The ID of the page in question
2933 * @param int $userId The ID of the user in question
2934 * @param string $since Look at edits since this time
2936 * @return bool True if the given user was the only one to edit since the given timestamp
2938 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
2939 $this->checkDatabaseDomain( $db );
2945 $revQuery = $this->getQueryInfo();
2947 $revQuery['tables'],
2949 'rev_user' => $revQuery['fields']['rev_user'],
2952 'rev_page' => $pageId,
2953 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
2956 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
2959 foreach ( $res as $row ) {
2960 if ( $row->rev_user
!= $userId ) {
2968 * Load a revision based on a known page ID and current revision ID from the DB
2970 * This method allows for the use of caching, though accessing anything that normally
2971 * requires permission checks (aside from the text) will trigger a small DB lookup.
2973 * MCR migration note: this replaces Revision::newKnownCurrent
2975 * @param Title $title the associated page title
2976 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
2978 * @return RevisionRecord|bool Returns false if missing
2980 public function getKnownCurrentRevision( Title
$title, $revId ) {
2981 $db = $this->getDBConnectionRef( DB_REPLICA
);
2983 $pageId = $title->getArticleID();
2990 $revId = $title->getLatestRevID();
2995 'No latest revision known for page ' . $title->getPrefixedDBkey()
2996 . ' even though it exists with page ID ' . $pageId
3001 // Load the row from cache if possible. If not possible, populate the cache.
3002 // As a minor optimization, remember if this was a cache hit or miss.
3003 // We can sometimes avoid a database query later if this is a cache miss.
3005 $row = $this->cache
->getWithSetCallback(
3006 // Page/rev IDs passed in from DB to reflect history merges
3007 $this->getRevisionRowCacheKey( $db, $pageId, $revId ),
3008 WANObjectCache
::TTL_WEEK
,
3009 function ( $curValue, &$ttl, array &$setOpts ) use (
3010 $db, $pageId, $revId, &$fromCache
3012 $setOpts +
= Database
::getCacheSetOptions( $db );
3013 $row = $this->fetchRevisionRowFromConds( $db, [ 'rev_id' => intval( $revId ) ] );
3017 return $row; // don't cache negatives
3021 // Reflect revision deletion and user renames.
3023 return $this->newRevisionFromRow( $row, 0, $title, $fromCache );
3030 * Get a cache key for use with a row as selected with getQueryInfo( [ 'page', 'user' ] )
3031 * Caching rows without 'page' or 'user' could lead to issues.
3032 * If the format of the rows returned by the query provided by getQueryInfo changes the
3033 * cache key should be updated to avoid conflicts.
3035 * @param IDatabase $db
3036 * @param int $pageId
3040 private function getRevisionRowCacheKey( IDatabase
$db, $pageId, $revId ) {
3041 return $this->cache
->makeGlobalKey(
3042 self
::ROW_CACHE_KEY
,
3049 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.
3054 * Retain the old class name for backwards compatibility.
3055 * @deprecated since 1.32
3057 class_alias( RevisionStore
::class, 'MediaWiki\Storage\RevisionStore' );