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
;
61 use Wikimedia\Assert\Assert
;
62 use Wikimedia\Rdbms\Database
;
63 use Wikimedia\Rdbms\DBConnRef
;
64 use Wikimedia\Rdbms\IDatabase
;
65 use Wikimedia\Rdbms\ILoadBalancer
;
68 * Service for looking up page revisions.
71 * @since 1.32 Renamed from MediaWiki\Storage\RevisionStore
73 * @note This was written to act as a drop-in replacement for the corresponding
74 * static methods in Revision.
77 implements IDBAccessObject
, RevisionFactory
, RevisionLookup
, LoggerAwareInterface
{
79 const ROW_CACHE_KEY
= 'revision-row-1.29';
93 * @see $wgContentHandlerUseDB
95 private $contentHandlerUseDB = true;
100 private $loadBalancer;
103 * @var WANObjectCache
110 private $commentStore;
113 * @var ActorMigration
115 private $actorMigration;
118 * @var LoggerInterface
123 * @var NameTableStore
125 private $contentModelStore;
128 * @var NameTableStore
130 private $slotRoleStore;
132 /** @var int An appropriate combination of SCHEMA_COMPAT_XXX flags. */
133 private $mcrMigrationStage;
136 * @todo $blobStore should be allowed to be any BlobStore!
138 * @param ILoadBalancer $loadBalancer
139 * @param SqlBlobStore $blobStore
140 * @param WANObjectCache $cache A cache for caching revision rows. This can be the local
141 * wiki's default instance even if $wikiId refers to a different wiki, since
142 * makeGlobalKey() is used to constructed a key that allows cached revision rows from
143 * the same database to be re-used between wikis. For example, enwiki and frwiki will
144 * use the same cache keys for revision rows from the wikidatawiki database, regardless
145 * of the cache's default key space.
146 * @param CommentStore $commentStore
147 * @param NameTableStore $contentModelStore
148 * @param NameTableStore $slotRoleStore
149 * @param int $mcrMigrationStage An appropriate combination of SCHEMA_COMPAT_XXX flags
150 * @param ActorMigration $actorMigration
151 * @param bool|string $wikiId
153 * @throws MWException if $mcrMigrationStage or $wikiId is invalid.
155 public function __construct(
156 ILoadBalancer
$loadBalancer,
157 SqlBlobStore
$blobStore,
158 WANObjectCache
$cache,
159 CommentStore
$commentStore,
160 NameTableStore
$contentModelStore,
161 NameTableStore
$slotRoleStore,
163 ActorMigration
$actorMigration,
166 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
167 Assert
::parameterType( 'integer', $mcrMigrationStage, '$mcrMigrationStage' );
169 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== SCHEMA_COMPAT_READ_BOTH
,
170 '$mcrMigrationStage',
171 'Reading from the old and the new schema at the same time is not supported.'
174 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== 0,
175 '$mcrMigrationStage',
176 'Reading needs to be enabled for the old or the new schema.'
179 ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) !== 0,
180 '$mcrMigrationStage',
181 'Writing needs to be enabled for the old or the new schema.'
184 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_OLD
) === 0
185 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) !== 0,
186 '$mcrMigrationStage',
187 'Cannot read the old schema when not also writing it.'
190 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_NEW
) === 0
191 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) !== 0,
192 '$mcrMigrationStage',
193 'Cannot read the new schema when not also writing it.'
196 $this->loadBalancer
= $loadBalancer;
197 $this->blobStore
= $blobStore;
198 $this->cache
= $cache;
199 $this->commentStore
= $commentStore;
200 $this->contentModelStore
= $contentModelStore;
201 $this->slotRoleStore
= $slotRoleStore;
202 $this->mcrMigrationStage
= $mcrMigrationStage;
203 $this->actorMigration
= $actorMigration;
204 $this->wikiId
= $wikiId;
205 $this->logger
= new NullLogger();
209 * @param int $flags A combination of SCHEMA_COMPAT_XXX flags.
210 * @return bool True if all the given flags were set in the $mcrMigrationStage
211 * parameter passed to the constructor.
213 private function hasMcrSchemaFlags( $flags ) {
214 return ( $this->mcrMigrationStage
& $flags ) === $flags;
218 * Throws a RevisionAccessException if this RevisionStore is configured for cross-wiki loading
219 * and still reading from the old DB schema.
221 * @throws RevisionAccessException
223 private function assertCrossWikiContentLoadingIsSafe() {
224 if ( $this->wikiId
!== false && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
225 throw new RevisionAccessException(
226 "Cross-wiki content loading is not supported by the pre-MCR schema"
231 public function setLogger( LoggerInterface
$logger ) {
232 $this->logger
= $logger;
236 * @return bool Whether the store is read-only
238 public function isReadOnly() {
239 return $this->blobStore
->isReadOnly();
245 public function getContentHandlerUseDB() {
246 return $this->contentHandlerUseDB
;
250 * @see $wgContentHandlerUseDB
251 * @param bool $contentHandlerUseDB
252 * @throws MWException
254 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
255 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
)
256 ||
$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
)
258 if ( !$contentHandlerUseDB ) {
259 throw new MWException(
260 'Content model must be stored in the database for multi content revision migration.'
264 $this->contentHandlerUseDB
= $contentHandlerUseDB;
268 * @return ILoadBalancer
270 private function getDBLoadBalancer() {
271 return $this->loadBalancer
;
275 * @param int $mode DB_MASTER or DB_REPLICA
279 private function getDBConnection( $mode ) {
280 $lb = $this->getDBLoadBalancer();
281 return $lb->getConnection( $mode, [], $this->wikiId
);
285 * @param int $queryFlags a bit field composed of READ_XXX flags
289 private function getDBConnectionRefForQueryFlags( $queryFlags ) {
290 list( $mode, ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
291 return $this->getDBConnectionRef( $mode );
295 * @param IDatabase $connection
297 private function releaseDBConnection( IDatabase
$connection ) {
298 $lb = $this->getDBLoadBalancer();
299 $lb->reuseConnection( $connection );
303 * @param int $mode DB_MASTER or DB_REPLICA
307 private function getDBConnectionRef( $mode ) {
308 $lb = $this->getDBLoadBalancer();
309 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
313 * Determines the page Title based on the available information.
315 * MCR migration note: this corresponds to Revision::getTitle
317 * @note this method should be private, external use should be avoided!
319 * @param int|null $pageId
320 * @param int|null $revId
321 * @param int $queryFlags
324 * @throws RevisionAccessException
326 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
327 if ( !$pageId && !$revId ) {
328 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
331 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
332 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
333 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
334 $queryFlags = self
::READ_NORMAL
;
337 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false );
338 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
339 $titleFlags = ( $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0 );
341 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
342 if ( $canUseTitleNewFromId ) {
343 // TODO: better foreign title handling (introduce TitleFactory)
344 $title = Title
::newFromID( $pageId, $titleFlags );
350 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
351 $canUseRevId = ( $revId !== null && $revId > 0 );
353 if ( $canUseRevId ) {
354 $dbr = $this->getDBConnectionRef( $dbMode );
355 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
356 $row = $dbr->selectRow(
357 [ 'revision', 'page' ],
366 [ 'rev_id' => $revId ],
369 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
372 // TODO: better foreign title handling (introduce TitleFactory)
373 return Title
::newFromRow( $row );
377 // If we still don't have a title, fallback to master if that wasn't already happening.
378 if ( $dbMode !== DB_MASTER
) {
379 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
382 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
383 [ 'trace' => wfBacktrace() ]
389 throw new RevisionAccessException(
390 "Could not determine title for page ID $pageId and revision ID $revId"
395 * @param mixed $value
396 * @param string $name
398 * @throws IncompleteRevisionException if $value is null
399 * @return mixed $value, if $value is not null
401 private function failOnNull( $value, $name ) {
402 if ( $value === null ) {
403 throw new IncompleteRevisionException(
404 "$name must not be " . var_export( $value, true ) . "!"
412 * @param mixed $value
413 * @param string $name
415 * @throws IncompleteRevisionException if $value is empty
416 * @return mixed $value, if $value is not null
418 private function failOnEmpty( $value, $name ) {
419 if ( $value === null ||
$value === 0 ||
$value === '' ) {
420 throw new IncompleteRevisionException(
421 "$name must not be " . var_export( $value, true ) . "!"
429 * Insert a new revision into the database, returning the new revision record
430 * on success and dies horribly on failure.
432 * MCR migration note: this replaces Revision::insertOn
434 * @param RevisionRecord $rev
435 * @param IDatabase $dbw (master connection)
437 * @throws InvalidArgumentException
438 * @return RevisionRecord the new revision record.
440 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
441 // TODO: pass in a DBTransactionContext instead of a database connection.
442 $this->checkDatabaseWikiId( $dbw );
444 $slotRoles = $rev->getSlotRoles();
446 // Make sure the main slot is always provided throughout migration
447 if ( !in_array( SlotRecord
::MAIN
, $slotRoles ) ) {
448 throw new InvalidArgumentException(
449 'main slot must be provided'
453 // If we are not writing into the new schema, we can't support extra slots.
454 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
)
455 && $slotRoles !== [ SlotRecord
::MAIN
]
457 throw new InvalidArgumentException(
458 'Only the main slot is supported when not writing to the MCR enabled schema!'
462 // As long as we are not reading from the new schema, we don't want to write extra slots.
463 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
)
464 && $slotRoles !== [ SlotRecord
::MAIN
]
466 throw new InvalidArgumentException(
467 'Only the main slot is supported when not reading from the MCR enabled schema!'
472 $this->failOnNull( $rev->getSize(), 'size field' );
473 $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
474 $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
475 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
476 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
477 $this->failOnNull( $user->getId(), 'user field' );
478 $this->failOnEmpty( $user->getName(), 'user_text field' );
480 if ( !$rev->isReadyForInsertion() ) {
481 // This is here for future-proofing. At the time this check being added, it
482 // was redundant to the individual checks above.
483 throw new IncompleteRevisionException( 'Revision is incomplete' );
486 // TODO: we shouldn't need an actual Title here.
487 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
488 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
490 $parentId = $rev->getParentId() === null
491 ?
$this->getPreviousRevisionId( $dbw, $rev )
492 : $rev->getParentId();
494 /** @var RevisionRecord $rev */
495 $rev = $dbw->doAtomicSection(
497 function ( IDatabase
$dbw, $fname ) use (
505 return $this->insertRevisionInternal(
518 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
519 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
520 Assert
::postcondition(
521 $rev->getComment( RevisionRecord
::RAW
) !== null,
522 'revision must have a comment'
524 Assert
::postcondition(
525 $rev->getUser( RevisionRecord
::RAW
) !== null,
526 'revision must have a user'
529 // Trigger exception if the main slot is missing.
530 // Technically, this could go away after MCR migration: while
531 // calling code may require a main slot to exist, RevisionStore
532 // really should not know or care about that requirement.
533 $rev->getSlot( SlotRecord
::MAIN
, RevisionRecord
::RAW
);
535 foreach ( $slotRoles as $role ) {
536 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
537 Assert
::postcondition(
538 $slot->getContent() !== null,
539 $role . ' slot must have content'
541 Assert
::postcondition(
542 $slot->hasRevision(),
543 $role . ' slot must have a revision associated'
547 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
549 // TODO: deprecate in 1.32!
550 $legacyRevision = new Revision( $rev );
551 Hooks
::run( 'RevisionInsertComplete', [ &$legacyRevision, null, null ] );
556 private function insertRevisionInternal(
560 CommentStoreComment
$comment,
565 $slotRoles = $rev->getSlotRoles();
567 $revisionRow = $this->insertRevisionRowOn(
574 $revisionId = $revisionRow['rev_id'];
577 BlobStore
::PAGE_HINT
=> $pageId,
578 BlobStore
::REVISION_HINT
=> $revisionId,
579 BlobStore
::PARENT_HINT
=> $parentId,
583 foreach ( $slotRoles as $role ) {
584 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
586 // If the SlotRecord already has a revision ID set, this means it already exists
587 // in the database, and should already belong to the current revision.
588 // However, a slot may already have a revision, but no content ID, if the slot
589 // is emulated based on the archive table, because we are in SCHEMA_COMPAT_READ_OLD
590 // mode, and the respective archive row was not yet migrated to the new schema.
591 // In that case, a new slot row (and content row) must be inserted even during
593 if ( $slot->hasRevision() && $slot->hasContentId() ) {
594 // TODO: properly abort transaction if the assertion fails!
596 $slot->getRevision() === $revisionId,
597 'slot role ' . $slot->getRole(),
598 'Existing slot should belong to revision '
599 . $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
602 // Slot exists, nothing to do, move along.
603 // This happens when restoring archived revisions.
605 $newSlots[$role] = $slot;
607 // Write the main slot's text ID to the revision table for backwards compatibility
608 if ( $slot->getRole() === SlotRecord
::MAIN
609 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
611 $blobAddress = $slot->getAddress();
612 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
615 $newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $title, $blobHints );
619 $this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
621 $rev = new RevisionStoreRecord(
625 (object)$revisionRow,
626 new RevisionSlots( $newSlots ),
634 * @param IDatabase $dbw
635 * @param int $revisionId
636 * @param string &$blobAddress (may change!)
638 * @return int the text row id
640 private function updateRevisionTextId( IDatabase
$dbw, $revisionId, &$blobAddress ) {
641 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
643 throw new LogicException(
644 'Blob address not supported in 1.29 database schema: ' . $blobAddress
648 // getTextIdFromAddress() is free to insert something into the text table, so $textId
649 // may be a new value, not anything already contained in $blobAddress.
650 $blobAddress = SqlBlobStore
::makeAddressFromTextId( $textId );
654 [ 'rev_text_id' => $textId ],
655 [ 'rev_id' => $revisionId ],
663 * @param IDatabase $dbw
664 * @param int $revisionId
665 * @param SlotRecord $protoSlot
666 * @param Title $title
667 * @param array $blobHints See the BlobStore::XXX_HINT constants
670 private function insertSlotOn(
673 SlotRecord
$protoSlot,
675 array $blobHints = []
677 if ( $protoSlot->hasAddress() ) {
678 $blobAddress = $protoSlot->getAddress();
680 $blobAddress = $this->storeContentBlob( $protoSlot, $title, $blobHints );
685 // Write the main slot's text ID to the revision table for backwards compatibility
686 if ( $protoSlot->getRole() === SlotRecord
::MAIN
687 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
689 // If SCHEMA_COMPAT_WRITE_NEW is also set, the fake content ID is overwritten
690 // with the real content ID below.
691 $textId = $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
692 $contentId = $this->emulateContentId( $textId );
695 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
696 if ( $protoSlot->hasContentId() ) {
697 $contentId = $protoSlot->getContentId();
699 $contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
702 $this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
705 $savedSlot = SlotRecord
::newSaved(
716 * Insert IP revision into ip_changes for use when querying for a range.
717 * @param IDatabase $dbw
719 * @param RevisionRecord $rev
720 * @param int $revisionId
722 private function insertIpChangesRow(
728 if ( $user->getId() === 0 && IP
::isValid( $user->getName() ) ) {
730 'ipc_rev_id' => $revisionId,
731 'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
732 'ipc_hex' => IP
::toHex( $user->getName() ),
734 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
739 * @param IDatabase $dbw
740 * @param RevisionRecord $rev
741 * @param Title $title
742 * @param int $parentId
744 * @return array a revision table row
746 * @throws MWException
747 * @throws MWUnknownContentModelException
749 private function insertRevisionRowOn(
755 $revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $title, $parentId );
757 list( $commentFields, $commentCallback ) =
758 $this->commentStore
->insertWithTempTable(
761 $rev->getComment( RevisionRecord
::RAW
)
763 $revisionRow +
= $commentFields;
765 list( $actorFields, $actorCallback ) =
766 $this->actorMigration
->getInsertValuesWithTempTable(
769 $rev->getUser( RevisionRecord
::RAW
)
771 $revisionRow +
= $actorFields;
773 $dbw->insert( 'revision', $revisionRow, __METHOD__
);
775 if ( !isset( $revisionRow['rev_id'] ) ) {
776 // only if auto-increment was used
777 $revisionRow['rev_id'] = intval( $dbw->insertId() );
779 if ( $dbw->getType() === 'mysql' ) {
780 // (T202032) MySQL until 8.0 and MariaDB until some version after 10.1.34 don't save the
781 // auto-increment value to disk, so on server restart it might reuse IDs from deleted
782 // revisions. We can fix that with an insert with an explicit rev_id value, if necessary.
784 $maxRevId = intval( $dbw->selectField( 'archive', 'MAX(ar_rev_id)', '', __METHOD__
) );
786 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
787 $maxRevId2 = intval( $dbw->selectField( 'slots', 'MAX(slot_revision_id)', '', __METHOD__
) );
788 if ( $maxRevId2 >= $maxRevId ) {
789 $maxRevId = $maxRevId2;
794 if ( $maxRevId >= $revisionRow['rev_id'] ) {
795 $this->logger
->debug(
796 '__METHOD__: Inserted revision {revid} but {table} has revisions up to {maxrevid}.'
797 . ' Trying to fix it.',
799 'revid' => $revisionRow['rev_id'],
801 'maxrevid' => $maxRevId,
805 if ( !$dbw->lock( 'fix-for-T202032', __METHOD__
) ) {
806 throw new MWException( 'Failed to get database lock for T202032' );
809 $dbw->onTransactionResolution( function ( $trigger, $dbw ) use ( $fname ) {
810 $dbw->unlock( 'fix-for-T202032', $fname );
813 $dbw->delete( 'revision', [ 'rev_id' => $revisionRow['rev_id'] ], __METHOD__
);
815 // The locking here is mostly to make MySQL bypass the REPEATABLE-READ transaction
816 // isolation (weird MySQL "feature"). It does seem to block concurrent auto-incrementing
817 // inserts too, though, at least on MariaDB 10.1.29.
819 // Don't try to lock `revision` in this way, it'll deadlock if there are concurrent
820 // transactions in this code path thanks to the row lock from the original ->insert() above.
822 // And we have to use raw SQL to bypass the "aggregation used with a locking SELECT" warning
823 // that's for non-MySQL DBs.
825 $dbw->selectSqlText( 'archive', [ 'v' => "MAX(ar_rev_id)" ], '', __METHOD__
) . ' FOR UPDATE'
827 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
829 $dbw->selectSqlText( 'slots', [ 'v' => "MAX(slot_revision_id)" ], '', __METHOD__
)
837 $row1 ?
intval( $row1->v
) : 0,
838 $row2 ?
intval( $row2->v
) : 0
841 // If we don't have SCHEMA_COMPAT_WRITE_NEW, all except the first of any concurrent
842 // transactions will throw a duplicate key error here. It doesn't seem worth trying
844 $revisionRow['rev_id'] = $maxRevId +
1;
845 $dbw->insert( 'revision', $revisionRow, __METHOD__
);
850 $commentCallback( $revisionRow['rev_id'] );
851 $actorCallback( $revisionRow['rev_id'], $revisionRow );
857 * @param IDatabase $dbw
858 * @param RevisionRecord $rev
859 * @param Title $title
860 * @param int $parentId
862 * @return array [ 0 => array $revisionRow, 1 => callable ]
863 * @throws MWException
864 * @throws MWUnknownContentModelException
866 private function getBaseRevisionRow(
872 // Record the edit in revisions
874 'rev_page' => $rev->getPageId(),
875 'rev_parent_id' => $parentId,
876 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
877 'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
878 'rev_deleted' => $rev->getVisibility(),
879 'rev_len' => $rev->getSize(),
880 'rev_sha1' => $rev->getSha1(),
883 if ( $rev->getId() !== null ) {
884 // Needed to restore revisions with their original ID
885 $revisionRow['rev_id'] = $rev->getId();
888 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
889 // In non MCR mode this IF section will relate to the main slot
890 $mainSlot = $rev->getSlot( SlotRecord
::MAIN
);
891 $model = $mainSlot->getModel();
892 $format = $mainSlot->getFormat();
894 // MCR migration note: rev_content_model and rev_content_format will go away
895 if ( $this->contentHandlerUseDB
) {
896 $this->assertCrossWikiContentLoadingIsSafe();
898 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
899 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
901 $revisionRow['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
902 $revisionRow['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
910 * @param SlotRecord $slot
911 * @param Title $title
912 * @param array $blobHints See the BlobStore::XXX_HINT constants
914 * @throws MWException
915 * @return string the blob address
917 private function storeContentBlob(
920 array $blobHints = []
922 $content = $slot->getContent();
923 $format = $content->getDefaultFormat();
924 $model = $content->getModel();
926 $this->checkContent( $content, $title );
928 return $this->blobStore
->storeBlob(
929 $content->serialize( $format ),
930 // These hints "leak" some information from the higher abstraction layer to
931 // low level storage to allow for optimization.
935 BlobStore
::DESIGNATION_HINT
=> 'page-content',
936 BlobStore
::ROLE_HINT
=> $slot->getRole(),
937 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
938 BlobStore
::MODEL_HINT
=> $model,
939 BlobStore
::FORMAT_HINT
=> $format,
946 * @param SlotRecord $slot
947 * @param IDatabase $dbw
948 * @param int $revisionId
949 * @param int $contentId
951 private function insertSlotRowOn( SlotRecord
$slot, IDatabase
$dbw, $revisionId, $contentId ) {
953 'slot_revision_id' => $revisionId,
954 'slot_role_id' => $this->slotRoleStore
->acquireId( $slot->getRole() ),
955 'slot_content_id' => $contentId,
956 // If the slot has a specific origin use that ID, otherwise use the ID of the revision
957 // that we just inserted.
958 'slot_origin' => $slot->hasOrigin() ?
$slot->getOrigin() : $revisionId,
960 $dbw->insert( 'slots', $slotRow, __METHOD__
);
964 * @param SlotRecord $slot
965 * @param IDatabase $dbw
966 * @param string $blobAddress
967 * @return int content row ID
969 private function insertContentRowOn( SlotRecord
$slot, IDatabase
$dbw, $blobAddress ) {
971 'content_size' => $slot->getSize(),
972 'content_sha1' => $slot->getSha1(),
973 'content_model' => $this->contentModelStore
->acquireId( $slot->getModel() ),
974 'content_address' => $blobAddress,
976 $dbw->insert( 'content', $contentRow, __METHOD__
);
977 return intval( $dbw->insertId() );
981 * MCR migration note: this corresponds to Revision::checkContentModel
983 * @param Content $content
984 * @param Title $title
986 * @throws MWException
987 * @throws MWUnknownContentModelException
989 private function checkContent( Content
$content, Title
$title ) {
990 // Note: may return null for revisions that have not yet been inserted
992 $model = $content->getModel();
993 $format = $content->getDefaultFormat();
994 $handler = $content->getContentHandler();
998 if ( !$handler->isSupportedFormat( $format ) ) {
999 throw new MWException( "Can't use format $format with content model $model on $name" );
1002 if ( !$this->contentHandlerUseDB
) {
1003 // if $wgContentHandlerUseDB is not set,
1004 // all revisions must use the default content model and format.
1006 $this->assertCrossWikiContentLoadingIsSafe();
1008 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1009 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1010 $defaultFormat = $defaultHandler->getDefaultFormat();
1012 if ( $model != $defaultModel ) {
1013 throw new MWException( "Can't save non-default content model with "
1014 . "\$wgContentHandlerUseDB disabled: model is $model, "
1015 . "default for $name is $defaultModel"
1019 if ( $format != $defaultFormat ) {
1020 throw new MWException( "Can't use non-default content format with "
1021 . "\$wgContentHandlerUseDB disabled: format is $format, "
1022 . "default for $name is $defaultFormat"
1027 if ( !$content->isValid() ) {
1028 throw new MWException(
1029 "New content for $name is not valid! Content model is $model"
1035 * Create a new null-revision for insertion into a page's
1036 * history. This will not re-save the text, but simply refer
1037 * to the text from the previous version.
1039 * Such revisions can for instance identify page rename
1040 * operations and other such meta-modifications.
1042 * @note This method grabs a FOR UPDATE lock on the relevant row of the page table,
1043 * to prevent a new revision from being inserted before the null revision has been written
1046 * MCR migration note: this replaces Revision::newNullRevision
1048 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
1051 * @param IDatabase $dbw used for obtaining the lock on the page table row
1052 * @param Title $title Title of the page to read from
1053 * @param CommentStoreComment $comment RevisionRecord's summary
1054 * @param bool $minor Whether the revision should be considered as minor
1055 * @param User $user The user to attribute the revision to
1057 * @return RevisionRecord|null RevisionRecord or null on error
1059 public function newNullRevision(
1062 CommentStoreComment
$comment,
1066 $this->checkDatabaseWikiId( $dbw );
1068 $pageId = $title->getArticleID();
1070 // T51581: Lock the page table row to ensure no other process
1071 // is adding a revision to the page at the same time.
1072 // Avoid locking extra tables, compare T191892.
1073 $pageLatest = $dbw->selectField(
1076 [ 'page_id' => $pageId ],
1081 if ( !$pageLatest ) {
1085 // Fetch the actual revision row from master, without locking all extra tables.
1086 $oldRevision = $this->loadRevisionFromConds(
1088 [ 'rev_id' => intval( $pageLatest ) ],
1093 if ( !$oldRevision ) {
1094 $msg = "Failed to load latest revision ID $pageLatest of page ID $pageId.";
1095 $this->logger
->error(
1097 [ 'exception' => new RuntimeException( $msg ) ]
1102 // Construct the new revision
1103 $timestamp = wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1104 $newRevision = MutableRevisionRecord
::newFromParentRevision( $oldRevision );
1106 $newRevision->setComment( $comment );
1107 $newRevision->setUser( $user );
1108 $newRevision->setTimestamp( $timestamp );
1109 $newRevision->setMinorEdit( $minor );
1111 return $newRevision;
1115 * MCR migration note: this replaces Revision::isUnpatrolled
1117 * @todo This is overly specific, so move or kill this method.
1119 * @param RevisionRecord $rev
1121 * @return int Rcid of the unpatrolled row, zero if there isn't one
1123 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
1124 $rc = $this->getRecentChange( $rev );
1125 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == RecentChange
::PRC_UNPATROLLED
) {
1126 return $rc->getAttribute( 'rc_id' );
1133 * Get the RC object belonging to the current revision, if there's one
1135 * MCR migration note: this replaces Revision::getRecentChange
1137 * @todo move this somewhere else?
1139 * @param RevisionRecord $rev
1140 * @param int $flags (optional) $flags include:
1141 * IDBAccessObject::READ_LATEST: Select the data from the master
1143 * @return null|RecentChange
1145 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
1146 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
1147 $db = $this->getDBConnection( $dbType );
1149 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
1151 if ( !$userIdentity ) {
1152 // If the revision has no user identity, chances are it never went
1153 // into the database, and doesn't have an RC entry.
1157 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
1158 $actorWhere = $this->actorMigration
->getWhere( $db, 'rc_user', $rev->getUser(), false );
1159 $rc = RecentChange
::newFromConds(
1161 $actorWhere['conds'],
1162 'rc_timestamp' => $db->timestamp( $rev->getTimestamp() ),
1163 'rc_this_oldid' => $rev->getId()
1169 $this->releaseDBConnection( $db );
1171 // XXX: cache this locally? Glue it to the RevisionRecord?
1176 * Maps fields of the archive row to corresponding revision rows.
1178 * @param object $archiveRow
1180 * @return object a revision row object, corresponding to $archiveRow.
1182 private static function mapArchiveFields( $archiveRow ) {
1184 // keep with ar prefix:
1187 // not the same suffix:
1188 'ar_page_id' => 'rev_page',
1189 'ar_rev_id' => 'rev_id',
1192 'ar_text_id' => 'rev_text_id',
1193 'ar_timestamp' => 'rev_timestamp',
1194 'ar_user_text' => 'rev_user_text',
1195 'ar_user' => 'rev_user',
1196 'ar_actor' => 'rev_actor',
1197 'ar_minor_edit' => 'rev_minor_edit',
1198 'ar_deleted' => 'rev_deleted',
1199 'ar_len' => 'rev_len',
1200 'ar_parent_id' => 'rev_parent_id',
1201 'ar_sha1' => 'rev_sha1',
1202 'ar_comment' => 'rev_comment',
1203 'ar_comment_cid' => 'rev_comment_cid',
1204 'ar_comment_id' => 'rev_comment_id',
1205 'ar_comment_text' => 'rev_comment_text',
1206 'ar_comment_data' => 'rev_comment_data',
1207 'ar_comment_old' => 'rev_comment_old',
1208 'ar_content_format' => 'rev_content_format',
1209 'ar_content_model' => 'rev_content_model',
1212 $revRow = new stdClass();
1213 foreach ( $fieldMap as $arKey => $revKey ) {
1214 if ( property_exists( $archiveRow, $arKey ) ) {
1215 $revRow->$revKey = $archiveRow->$arKey;
1223 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
1225 * @param object|array $row Either a database row or an array
1226 * @param int $queryFlags for callbacks
1227 * @param Title $title
1229 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
1230 * @throws MWException
1232 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
1233 $mainSlotRow = new stdClass();
1234 $mainSlotRow->role_name
= SlotRecord
::MAIN
;
1235 $mainSlotRow->model_name
= null;
1236 $mainSlotRow->slot_revision_id
= null;
1237 $mainSlotRow->slot_content_id
= null;
1238 $mainSlotRow->content_address
= null;
1244 if ( is_object( $row ) ) {
1245 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1246 // Don't emulate from a row when using the new schema.
1247 // Emulating from an array is still OK.
1248 throw new LogicException( 'Can\'t emulate the main slot when using MCR schema.' );
1252 if ( !isset( $row->rev_id
) && ( isset( $row->ar_user
) ||
isset( $row->ar_actor
) ) ) {
1253 $row = $this->mapArchiveFields( $row );
1256 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
1257 $mainSlotRow->content_address
= SqlBlobStore
::makeAddressFromTextId(
1262 // This is used by null-revisions
1263 $mainSlotRow->slot_origin
= isset( $row->slot_origin
)
1264 ?
intval( $row->slot_origin
)
1267 if ( isset( $row->old_text
) ) {
1268 // this happens when the text-table gets joined directly, in the pre-1.30 schema
1269 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
1270 // Check against selects that might have not included old_flags
1271 if ( !property_exists( $row, 'old_flags' ) ) {
1272 throw new InvalidArgumentException( 'old_flags was not set in $row' );
1274 $blobFlags = $row->old_flags ??
'';
1277 $mainSlotRow->slot_revision_id
= intval( $row->rev_id
);
1279 $mainSlotRow->content_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
1280 $mainSlotRow->content_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
1281 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
1282 ?
strval( $row->rev_content_model
)
1284 // XXX: in the future, we'll probably always use the default format, and drop content_format
1285 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
1286 ?
strval( $row->rev_content_format
)
1289 if ( isset( $row->rev_text_id
) && intval( $row->rev_text_id
) > 0 ) {
1290 // Overwritten below for SCHEMA_COMPAT_WRITE_NEW
1291 $mainSlotRow->slot_content_id
1292 = $this->emulateContentId( intval( $row->rev_text_id
) );
1294 } elseif ( is_array( $row ) ) {
1295 $mainSlotRow->slot_revision_id
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
1297 $mainSlotRow->slot_origin
= isset( $row['slot_origin'] )
1298 ?
intval( $row['slot_origin'] )
1300 $mainSlotRow->content_address
= isset( $row['text_id'] )
1301 ? SqlBlobStore
::makeAddressFromTextId( intval( $row['text_id'] ) )
1303 $mainSlotRow->content_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
1304 $mainSlotRow->content_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
1306 $mainSlotRow->model_name
= isset( $row['content_model'] )
1307 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
1308 // XXX: in the future, we'll probably always use the default format, and drop content_format
1309 $mainSlotRow->format_name
= isset( $row['content_format'] )
1310 ?
strval( $row['content_format'] ) : null;
1311 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
1312 // XXX: If the flags field is not set then $blobFlags should be null so that no
1313 // decoding will happen. An empty string will result in default decodings.
1314 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
1316 // if we have a Content object, override mText and mContentModel
1317 if ( !empty( $row['content'] ) ) {
1318 if ( !( $row['content'] instanceof Content
) ) {
1319 throw new MWException( 'content field must contain a Content object.' );
1322 /** @var Content $content */
1323 $content = $row['content'];
1324 $handler = $content->getContentHandler();
1326 $mainSlotRow->model_name
= $content->getModel();
1328 // XXX: in the future, we'll probably always use the default format.
1329 if ( $mainSlotRow->format_name
=== null ) {
1330 $mainSlotRow->format_name
= $handler->getDefaultFormat();
1334 if ( isset( $row['text_id'] ) && intval( $row['text_id'] ) > 0 ) {
1335 // Overwritten below for SCHEMA_COMPAT_WRITE_NEW
1336 $mainSlotRow->slot_content_id
1337 = $this->emulateContentId( intval( $row['text_id'] ) );
1340 throw new MWException( 'Revision constructor passed invalid row format.' );
1343 // With the old schema, the content changes with every revision,
1344 // except for null-revisions.
1345 if ( !isset( $mainSlotRow->slot_origin
) ) {
1346 $mainSlotRow->slot_origin
= $mainSlotRow->slot_revision_id
;
1349 if ( $mainSlotRow->model_name
=== null ) {
1350 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
1351 $this->assertCrossWikiContentLoadingIsSafe();
1353 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
1354 // TODO: MCR: deprecate $title->getModel().
1355 return ContentHandler
::getDefaultModelFor( $title );
1360 // XXX: We should perhaps fail if $blobData is null and $mainSlotRow->content_address
1361 // is missing, but "empty revisions" with no content are used in some edge cases.
1363 $content = function ( SlotRecord
$slot )
1364 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
1366 return $this->loadSlotContent(
1370 $mainSlotRow->format_name
,
1376 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
1377 // NOTE: this callback will be looped through RevisionSlot::newInherited(), allowing
1378 // the inherited slot to have the same content_id as the original slot. In that case,
1379 // $slot will be the inherited slot, while $mainSlotRow still refers to the original slot.
1380 $mainSlotRow->slot_content_id
=
1381 function ( SlotRecord
$slot ) use ( $queryFlags, $mainSlotRow ) {
1382 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1383 return $this->findSlotContentId( $db, $mainSlotRow->slot_revision_id
, SlotRecord
::MAIN
);
1387 return new SlotRecord( $mainSlotRow, $content );
1391 * Provides a content ID to use with emulated SlotRecords in SCHEMA_COMPAT_OLD mode,
1392 * based on the revision's text ID (rev_text_id or ar_text_id, respectively).
1393 * Note that in SCHEMA_COMPAT_WRITE_BOTH, a callback to findSlotContentId() should be used
1394 * instead, since in that mode, some revision rows may already have a real content ID,
1395 * while other's don't - and for the ones that don't, we should indicate that it
1396 * is missing and cause SlotRecords::hasContentId() to return false.
1398 * @param int $textId
1399 * @return int The emulated content ID
1401 private function emulateContentId( $textId ) {
1402 // Return a negative number to ensure the ID is distinct from any real content IDs
1403 // that will be assigned in SCHEMA_COMPAT_WRITE_NEW mode and read in SCHEMA_COMPAT_READ_NEW
1409 * Loads a Content object based on a slot row.
1411 * This method does not call $slot->getContent(), and may be used as a callback
1412 * called by $slot->getContent().
1414 * MCR migration note: this roughly corresponds to Revision::getContentInternal
1416 * @param SlotRecord $slot The SlotRecord to load content for
1417 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
1418 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
1419 * Use null if no processing should happen. That is in constrast to the empty string,
1420 * which causes the blob to be decoded according to the configured legacy encoding.
1421 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
1422 * @param int $queryFlags
1424 * @throws RevisionAccessException
1427 private function loadSlotContent(
1434 if ( $blobData !== null ) {
1435 Assert
::parameterType( 'string', $blobData, '$blobData' );
1436 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
1438 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
1440 if ( $blobFlags === null ) {
1441 // No blob flags, so use the blob verbatim.
1444 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
1445 if ( $data === false ) {
1446 throw new RevisionAccessException(
1447 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
1453 $address = $slot->getAddress();
1455 $data = $this->blobStore
->getBlob( $address, $queryFlags );
1456 } catch ( BlobAccessException
$e ) {
1457 throw new RevisionAccessException(
1458 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
1463 // Unserialize content
1464 $handler = ContentHandler
::getForModelID( $slot->getModel() );
1466 $content = $handler->unserializeContent( $data, $blobFormat );
1471 * Load a page revision from a given revision ID number.
1472 * Returns null if no such revision can be found.
1474 * MCR migration note: this replaces Revision::newFromId
1477 * IDBAccessObject::READ_LATEST: Select the data from the master
1478 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1481 * @param int $flags (optional)
1482 * @return RevisionRecord|null
1484 public function getRevisionById( $id, $flags = 0 ) {
1485 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
1489 * Load either the current, or a specified, revision
1490 * that's attached to a given link target. If not attached
1491 * to that link target, will return null.
1493 * MCR migration note: this replaces Revision::newFromTitle
1496 * IDBAccessObject::READ_LATEST: Select the data from the master
1497 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1499 * @param LinkTarget $linkTarget
1500 * @param int $revId (optional)
1501 * @param int $flags Bitfield (optional)
1502 * @return RevisionRecord|null
1504 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
1506 'page_namespace' => $linkTarget->getNamespace(),
1507 'page_title' => $linkTarget->getDBkey()
1510 // Use the specified revision ID.
1511 // Note that we use newRevisionFromConds here because we want to retry
1512 // and fall back to master if the page is not found on a replica.
1513 // Since the caller supplied a revision ID, we are pretty sure the revision is
1514 // supposed to exist, so we should try hard to find it.
1515 $conds['rev_id'] = $revId;
1516 return $this->newRevisionFromConds( $conds, $flags );
1518 // Use a join to get the latest revision.
1519 // Note that we don't use newRevisionFromConds here because we don't want to retry
1520 // and fall back to master. The assumption is that we only want to force the fallback
1521 // if we are quite sure the revision exists because the caller supplied a revision ID.
1522 // If the page isn't found at all on a replica, it probably simply does not exist.
1523 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1525 $conds[] = 'rev_id=page_latest';
1526 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1533 * Load either the current, or a specified, revision
1534 * that's attached to a given page ID.
1535 * Returns null if no such revision can be found.
1537 * MCR migration note: this replaces Revision::newFromPageId
1540 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
1541 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1543 * @param int $pageId
1544 * @param int $revId (optional)
1545 * @param int $flags Bitfield (optional)
1546 * @return RevisionRecord|null
1548 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1549 $conds = [ 'page_id' => $pageId ];
1551 // Use the specified revision ID.
1552 // Note that we use newRevisionFromConds here because we want to retry
1553 // and fall back to master if the page is not found on a replica.
1554 // Since the caller supplied a revision ID, we are pretty sure the revision is
1555 // supposed to exist, so we should try hard to find it.
1556 $conds['rev_id'] = $revId;
1557 return $this->newRevisionFromConds( $conds, $flags );
1559 // Use a join to get the latest revision.
1560 // Note that we don't use newRevisionFromConds here because we don't want to retry
1561 // and fall back to master. The assumption is that we only want to force the fallback
1562 // if we are quite sure the revision exists because the caller supplied a revision ID.
1563 // If the page isn't found at all on a replica, it probably simply does not exist.
1564 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1566 $conds[] = 'rev_id=page_latest';
1567 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1574 * Load the revision for the given title with the given timestamp.
1575 * WARNING: Timestamps may in some circumstances not be unique,
1576 * so this isn't the best key to use.
1578 * MCR migration note: this replaces Revision::loadFromTimestamp
1580 * @param Title $title
1581 * @param string $timestamp
1582 * @return RevisionRecord|null
1584 public function getRevisionByTimestamp( $title, $timestamp ) {
1585 $db = $this->getDBConnection( DB_REPLICA
);
1586 return $this->newRevisionFromConds(
1588 'rev_timestamp' => $db->timestamp( $timestamp ),
1589 'page_namespace' => $title->getNamespace(),
1590 'page_title' => $title->getDBkey()
1598 * @param int $revId The revision to load slots for.
1599 * @param int $queryFlags
1601 * @return SlotRecord[]
1603 private function loadSlotRecords( $revId, $queryFlags ) {
1604 $revQuery = self
::getSlotsQueryInfo( [ 'content' ] );
1606 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
1607 $db = $this->getDBConnectionRef( $dbMode );
1610 $revQuery['tables'],
1611 $revQuery['fields'],
1613 'slot_revision_id' => $revId,
1622 foreach ( $res as $row ) {
1623 // resolve role names and model names from in-memory cache, instead of joining.
1624 $row->role_name
= $this->slotRoleStore
->getName( (int)$row->slot_role_id
);
1625 $row->model_name
= $this->contentModelStore
->getName( (int)$row->content_model
);
1627 $contentCallback = function ( SlotRecord
$slot ) use ( $queryFlags, $row ) {
1628 return $this->loadSlotContent( $slot, null, null, null, $queryFlags );
1631 $slots[$row->role_name
] = new SlotRecord( $row, $contentCallback );
1634 if ( !isset( $slots[SlotRecord
::MAIN
] ) ) {
1635 throw new RevisionAccessException(
1636 'Main slot of revision ' . $revId . ' not found in database!'
1644 * Factory method for RevisionSlots.
1646 * @note If other code has a need to construct RevisionSlots objects, this should be made
1647 * public, since RevisionSlots instances should not be constructed directly.
1650 * @param object $revisionRow
1651 * @param int $queryFlags
1652 * @param Title $title
1654 * @return RevisionSlots
1655 * @throws MWException
1657 private function newRevisionSlots(
1663 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1664 $mainSlot = $this->emulateMainSlot_1_29( $revisionRow, $queryFlags, $title );
1665 $slots = new RevisionSlots( [ SlotRecord
::MAIN
=> $mainSlot ] );
1667 // XXX: do we need the same kind of caching here
1668 // that getKnownCurrentRevision uses (if $revId == page_latest?)
1670 $slots = new RevisionSlots( function () use( $revId, $queryFlags ) {
1671 return $this->loadSlotRecords( $revId, $queryFlags );
1679 * Make a fake revision object from an archive table row. This is queried
1680 * for permissions or even inserted (as in Special:Undelete)
1682 * MCR migration note: this replaces Revision::newFromArchiveRow
1684 * @param object $row
1685 * @param int $queryFlags
1686 * @param Title|null $title
1687 * @param array $overrides associative array with fields of $row to override. This may be
1688 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1689 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1690 * override ar_parent_id.
1692 * @return RevisionRecord
1693 * @throws MWException
1695 public function newRevisionFromArchiveRow(
1698 Title
$title = null,
1699 array $overrides = []
1701 Assert
::parameterType( 'object', $row, '$row' );
1703 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1704 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1706 if ( !$title && isset( $overrides['title'] ) ) {
1707 if ( !( $overrides['title'] instanceof Title
) ) {
1708 throw new MWException( 'title field override must contain a Title object.' );
1711 $title = $overrides['title'];
1714 if ( !isset( $title ) ) {
1715 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1716 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1718 throw new InvalidArgumentException(
1719 'A Title or ar_namespace and ar_title must be given'
1724 foreach ( $overrides as $key => $value ) {
1726 $row->$field = $value;
1730 $user = User
::newFromAnyId(
1731 $row->ar_user ??
null,
1732 $row->ar_user_text ??
null,
1733 $row->ar_actor ??
null
1735 } catch ( InvalidArgumentException
$ex ) {
1736 wfWarn( __METHOD__
. ': ' . $title->getPrefixedDBkey() . ': ' . $ex->getMessage() );
1737 $user = new UserIdentityValue( 0, 'Unknown user', 0 );
1740 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1741 // Legacy because $row may have come from self::selectFields()
1742 $comment = $this->commentStore
->getCommentLegacy( $db, 'ar_comment', $row, true );
1744 $slots = $this->newRevisionSlots( $row->ar_rev_id
, $row, $queryFlags, $title );
1746 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1750 * @see RevisionFactory::newRevisionFromRow
1752 * MCR migration note: this replaces Revision::newFromRow
1754 * @param object $row
1755 * @param int $queryFlags
1756 * @param Title|null $title
1758 * @return RevisionRecord
1760 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1761 Assert
::parameterType( 'object', $row, '$row' );
1764 $pageId = $row->rev_page ??
0; // XXX: also check page_id?
1765 $revId = $row->rev_id ??
0;
1767 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1770 if ( !isset( $row->page_latest
) ) {
1771 $row->page_latest
= $title->getLatestRevID();
1772 if ( $row->page_latest
=== 0 && $title->exists() ) {
1773 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1778 $user = User
::newFromAnyId(
1779 $row->rev_user ??
null,
1780 $row->rev_user_text ??
null,
1781 $row->rev_actor ??
null
1783 } catch ( InvalidArgumentException
$ex ) {
1784 wfWarn( __METHOD__
. ': ' . $title->getPrefixedDBkey() . ': ' . $ex->getMessage() );
1785 $user = new UserIdentityValue( 0, 'Unknown user', 0 );
1788 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1789 // Legacy because $row may have come from self::selectFields()
1790 $comment = $this->commentStore
->getCommentLegacy( $db, 'rev_comment', $row, true );
1792 $slots = $this->newRevisionSlots( $row->rev_id
, $row, $queryFlags, $title );
1794 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1798 * Constructs a new MutableRevisionRecord based on the given associative array following
1799 * the MW1.29 convention for the Revision constructor.
1801 * MCR migration note: this replaces Revision::newFromRow
1803 * @param array $fields
1804 * @param int $queryFlags
1805 * @param Title|null $title
1807 * @return MutableRevisionRecord
1808 * @throws MWException
1809 * @throws RevisionAccessException
1811 public function newMutableRevisionFromArray(
1816 if ( !$title && isset( $fields['title'] ) ) {
1817 if ( !( $fields['title'] instanceof Title
) ) {
1818 throw new MWException( 'title field must contain a Title object.' );
1821 $title = $fields['title'];
1825 $pageId = $fields['page'] ??
0;
1826 $revId = $fields['id'] ??
0;
1828 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1831 if ( !isset( $fields['page'] ) ) {
1832 $fields['page'] = $title->getArticleID( $queryFlags );
1835 // if we have a content object, use it to set the model and type
1836 if ( !empty( $fields['content'] ) ) {
1837 if ( !( $fields['content'] instanceof Content
) && !is_array( $fields['content'] ) ) {
1838 throw new MWException(
1839 'content field must contain a Content object or an array of Content objects.'
1844 if ( !empty( $fields['text_id'] ) ) {
1845 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
1846 throw new MWException( "The text_id field is only available in the pre-MCR schema" );
1849 if ( !empty( $fields['content'] ) ) {
1850 throw new MWException(
1851 "Text already stored in external store (id {$fields['text_id']}), " .
1852 "can't specify content object"
1858 isset( $fields['comment'] )
1859 && !( $fields['comment'] instanceof CommentStoreComment
)
1861 $commentData = $fields['comment_data'] ??
null;
1863 if ( $fields['comment'] instanceof Message
) {
1864 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1869 $commentText = trim( strval( $fields['comment'] ) );
1870 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1877 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1878 $this->initializeMutableRevisionFromArray( $revision, $fields );
1880 if ( isset( $fields['content'] ) && is_array( $fields['content'] ) ) {
1881 foreach ( $fields['content'] as $role => $content ) {
1882 $revision->setContent( $role, $content );
1885 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1886 $revision->setSlot( $mainSlot );
1893 * @param MutableRevisionRecord $record
1894 * @param array $fields
1896 private function initializeMutableRevisionFromArray(
1897 MutableRevisionRecord
$record,
1900 /** @var UserIdentity $user */
1903 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1904 $user = $fields['user'];
1907 $user = User
::newFromAnyId(
1908 $fields['user'] ??
null,
1909 $fields['user_text'] ??
null,
1910 $fields['actor'] ??
null
1912 } catch ( InvalidArgumentException
$ex ) {
1918 $record->setUser( $user );
1921 $timestamp = isset( $fields['timestamp'] )
1922 ?
strval( $fields['timestamp'] )
1923 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1925 $record->setTimestamp( $timestamp );
1927 if ( isset( $fields['page'] ) ) {
1928 $record->setPageId( intval( $fields['page'] ) );
1931 if ( isset( $fields['id'] ) ) {
1932 $record->setId( intval( $fields['id'] ) );
1934 if ( isset( $fields['parent_id'] ) ) {
1935 $record->setParentId( intval( $fields['parent_id'] ) );
1938 if ( isset( $fields['sha1'] ) ) {
1939 $record->setSha1( $fields['sha1'] );
1941 if ( isset( $fields['size'] ) ) {
1942 $record->setSize( intval( $fields['size'] ) );
1945 if ( isset( $fields['minor_edit'] ) ) {
1946 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1948 if ( isset( $fields['deleted'] ) ) {
1949 $record->setVisibility( intval( $fields['deleted'] ) );
1952 if ( isset( $fields['comment'] ) ) {
1953 Assert
::parameterType(
1954 CommentStoreComment
::class,
1958 $record->setComment( $fields['comment'] );
1963 * Load a page revision from a given revision ID number.
1964 * Returns null if no such revision can be found.
1966 * MCR migration note: this corresponds to Revision::loadFromId
1968 * @note direct use is deprecated!
1969 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1971 * @param IDatabase $db
1974 * @return RevisionRecord|null
1976 public function loadRevisionFromId( IDatabase
$db, $id ) {
1977 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1981 * Load either the current, or a specified, revision
1982 * that's attached to a given page. If not attached
1983 * to that page, will return null.
1985 * MCR migration note: this replaces Revision::loadFromPageId
1987 * @note direct use is deprecated!
1988 * @todo remove when unused!
1990 * @param IDatabase $db
1991 * @param int $pageid
1993 * @return RevisionRecord|null
1995 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1996 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1998 $conds['rev_id'] = intval( $id );
2000 $conds[] = 'rev_id=page_latest';
2002 return $this->loadRevisionFromConds( $db, $conds );
2006 * Load either the current, or a specified, revision
2007 * that's attached to a given page. If not attached
2008 * to that page, will return null.
2010 * MCR migration note: this replaces Revision::loadFromTitle
2012 * @note direct use is deprecated!
2013 * @todo remove when unused!
2015 * @param IDatabase $db
2016 * @param Title $title
2019 * @return RevisionRecord|null
2021 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
2023 $matchId = intval( $id );
2025 $matchId = 'page_latest';
2028 return $this->loadRevisionFromConds(
2032 'page_namespace' => $title->getNamespace(),
2033 'page_title' => $title->getDBkey()
2041 * Load the revision for the given title with the given timestamp.
2042 * WARNING: Timestamps may in some circumstances not be unique,
2043 * so this isn't the best key to use.
2045 * MCR migration note: this replaces Revision::loadFromTimestamp
2047 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
2048 * @todo remove when unused!
2050 * @param IDatabase $db
2051 * @param Title $title
2052 * @param string $timestamp
2053 * @return RevisionRecord|null
2055 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
2056 return $this->loadRevisionFromConds( $db,
2058 'rev_timestamp' => $db->timestamp( $timestamp ),
2059 'page_namespace' => $title->getNamespace(),
2060 'page_title' => $title->getDBkey()
2068 * Given a set of conditions, fetch a revision
2070 * This method should be used if we are pretty sure the revision exists.
2071 * Unless $flags has READ_LATEST set, this method will first try to find the revision
2072 * on a replica before hitting the master database.
2074 * MCR migration note: this corresponds to Revision::newFromConds
2076 * @param array $conditions
2077 * @param int $flags (optional)
2078 * @param Title|null $title
2080 * @return RevisionRecord|null
2082 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
2083 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2084 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
2086 $lb = $this->getDBLoadBalancer();
2088 // Make sure new pending/committed revision are visibile later on
2089 // within web requests to certain avoid bugs like T93866 and T94407.
2091 && !( $flags & self
::READ_LATEST
)
2092 && $lb->getServerCount() > 1
2093 && $lb->hasOrMadeRecentMasterChanges()
2095 $flags = self
::READ_LATEST
;
2096 $dbw = $this->getDBConnection( DB_MASTER
);
2097 $rev = $this->loadRevisionFromConds( $dbw, $conditions, $flags, $title );
2098 $this->releaseDBConnection( $dbw );
2105 * Given a set of conditions, fetch a revision from
2106 * the given database connection.
2108 * MCR migration note: this corresponds to Revision::loadFromConds
2110 * @param IDatabase $db
2111 * @param array $conditions
2112 * @param int $flags (optional)
2113 * @param Title|null $title
2115 * @return RevisionRecord|null
2117 private function loadRevisionFromConds(
2123 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
2125 $rev = $this->newRevisionFromRow( $row, $flags, $title );
2134 * Throws an exception if the given database connection does not belong to the wiki this
2135 * RevisionStore is bound to.
2137 * @param IDatabase $db
2138 * @throws MWException
2140 private function checkDatabaseWikiId( IDatabase
$db ) {
2141 $storeWiki = $this->wikiId
;
2142 $dbWiki = $db->getDomainID();
2144 if ( $dbWiki === $storeWiki ) {
2148 $storeWiki = $storeWiki ?
: $this->loadBalancer
->getLocalDomainID();
2149 // @FIXME: when would getDomainID() be false here?
2150 $dbWiki = $dbWiki ?
: wfWikiID();
2152 if ( $dbWiki === $storeWiki ) {
2156 // HACK: counteract encoding imposed by DatabaseDomain
2157 $storeWiki = str_replace( '?h', '-', $storeWiki );
2158 $dbWiki = str_replace( '?h', '-', $dbWiki );
2160 if ( $dbWiki === $storeWiki ) {
2164 throw new MWException( "RevisionStore for $storeWiki "
2165 . "cannot be used with a DB connection for $dbWiki" );
2169 * Given a set of conditions, return a row with the
2170 * fields necessary to build RevisionRecord objects.
2172 * MCR migration note: this corresponds to Revision::fetchFromConds
2174 * @param IDatabase $db
2175 * @param array $conditions
2176 * @param int $flags (optional)
2178 * @return object|false data row as a raw object
2180 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
2181 $this->checkDatabaseWikiId( $db );
2183 $revQuery = $this->getQueryInfo( [ 'page', 'user' ] );
2185 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
2186 $options[] = 'FOR UPDATE';
2188 return $db->selectRow(
2189 $revQuery['tables'],
2190 $revQuery['fields'],
2199 * Finds the ID of a content row for a given revision and slot role.
2200 * This can be used to re-use content rows even while the content ID
2201 * is still missing from SlotRecords, when writing to both the old and
2202 * the new schema during MCR schema migration.
2204 * @todo remove after MCR schema migration is complete.
2206 * @param IDatabase $db
2208 * @param string $role
2212 private function findSlotContentId( IDatabase
$db, $revId, $role ) {
2213 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
2218 $roleId = $this->slotRoleStore
->getId( $role );
2220 'slot_revision_id' => $revId,
2221 'slot_role_id' => $roleId,
2224 $contentId = $db->selectField( 'slots', 'slot_content_id', $conditions, __METHOD__
);
2226 return $contentId ?
: null;
2227 } catch ( NameTableAccessException
$ex ) {
2228 // If the role is missing from the slot_roles table,
2229 // the corresponding row in slots cannot exist.
2235 * Return the tables, fields, and join conditions to be selected to create
2236 * a new RevisionStoreRecord object.
2238 * MCR migration note: this replaces Revision::getQueryInfo
2240 * If the format of fields returned changes in any way then the cache key provided by
2241 * self::getRevisionRowCacheKey should be updated.
2245 * @param array $options Any combination of the following strings
2246 * - 'page': Join with the page table, and select fields to identify the page
2247 * - 'user': Join with the user table, and select the user name
2248 * - 'text': Join with the text table, and select fields to load page text. This
2249 * option is deprecated in MW 1.32 when the MCR migration flag SCHEMA_COMPAT_WRITE_NEW
2250 * is set, and disallowed when SCHEMA_COMPAT_READ_OLD is not set.
2252 * @return array With three keys:
2253 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2254 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2255 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2257 public function getQueryInfo( $options = [] ) {
2264 $ret['tables'][] = 'revision';
2265 $ret['fields'] = array_merge( $ret['fields'], [
2276 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
2277 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
2278 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
2279 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
2281 $actorQuery = $this->actorMigration
->getJoin( 'rev_user' );
2282 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
2283 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
2284 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
2286 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2287 $ret['fields'][] = 'rev_text_id';
2289 if ( $this->contentHandlerUseDB
) {
2290 $ret['fields'][] = 'rev_content_format';
2291 $ret['fields'][] = 'rev_content_model';
2295 if ( in_array( 'page', $options, true ) ) {
2296 $ret['tables'][] = 'page';
2297 $ret['fields'] = array_merge( $ret['fields'], [
2305 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
2308 if ( in_array( 'user', $options, true ) ) {
2309 $ret['tables'][] = 'user';
2310 $ret['fields'] = array_merge( $ret['fields'], [
2313 $u = $actorQuery['fields']['rev_user'];
2314 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
2317 if ( in_array( 'text', $options, true ) ) {
2318 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
2319 throw new InvalidArgumentException( 'text table can no longer be joined directly' );
2320 } elseif ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2321 // NOTE: even when this class is set to not read from the old schema, callers
2322 // should still be able to join against the text table, as long as we are still
2323 // writing the old schema for compatibility.
2324 // TODO: This should trigger a deprecation warning eventually (T200918), but not
2325 // before all known usages are removed (see T198341 and T201164).
2326 // wfDeprecated( __METHOD__ . ' with `text` option', '1.32' );
2329 $ret['tables'][] = 'text';
2330 $ret['fields'] = array_merge( $ret['fields'], [
2334 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
2341 * Return the tables, fields, and join conditions to be selected to create
2346 * @param array $options Any combination of the following strings
2347 * - 'content': Join with the content table, and select content meta-data fields
2348 * - 'model': Join with the content_models table, and select the model_name field.
2349 * Only applicable if 'content' is also set.
2350 * - 'role': Join with the slot_roles table, and select the role_name field
2352 * @return array With three keys:
2353 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2354 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2355 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2357 public function getSlotsQueryInfo( $options = [] ) {
2364 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2365 $db = $this->getDBConnectionRef( DB_REPLICA
);
2366 $ret['tables']['slots'] = 'revision';
2368 $ret['fields']['slot_revision_id'] = 'slots.rev_id';
2369 $ret['fields']['slot_content_id'] = 'NULL';
2370 $ret['fields']['slot_origin'] = 'slots.rev_id';
2371 $ret['fields']['role_name'] = $db->addQuotes( SlotRecord
::MAIN
);
2373 if ( in_array( 'content', $options, true ) ) {
2374 $ret['fields']['content_size'] = 'slots.rev_len';
2375 $ret['fields']['content_sha1'] = 'slots.rev_sha1';
2376 $ret['fields']['content_address']
2377 = $db->buildConcat( [ $db->addQuotes( 'tt:' ), 'slots.rev_text_id' ] );
2379 if ( $this->contentHandlerUseDB
) {
2380 $ret['fields']['model_name'] = 'slots.rev_content_model';
2382 $ret['fields']['model_name'] = 'NULL';
2386 $ret['tables'][] = 'slots';
2387 $ret['fields'] = array_merge( $ret['fields'], [
2394 if ( in_array( 'role', $options, true ) ) {
2395 // Use left join to attach role name, so we still find the revision row even
2396 // if the role name is missing. This triggers a more obvious failure mode.
2397 $ret['tables'][] = 'slot_roles';
2398 $ret['joins']['slot_roles'] = [ 'LEFT JOIN', [ 'slot_role_id = role_id' ] ];
2399 $ret['fields'][] = 'role_name';
2402 if ( in_array( 'content', $options, true ) ) {
2403 $ret['tables'][] = 'content';
2404 $ret['fields'] = array_merge( $ret['fields'], [
2410 $ret['joins']['content'] = [ 'INNER JOIN', [ 'slot_content_id = content_id' ] ];
2412 if ( in_array( 'model', $options, true ) ) {
2413 // Use left join to attach model name, so we still find the revision row even
2414 // if the model name is missing. This triggers a more obvious failure mode.
2415 $ret['tables'][] = 'content_models';
2416 $ret['joins']['content_models'] = [ 'LEFT JOIN', [ 'content_model = model_id' ] ];
2417 $ret['fields'][] = 'model_name';
2427 * Return the tables, fields, and join conditions to be selected to create
2428 * a new RevisionArchiveRecord object.
2430 * MCR migration note: this replaces Revision::getArchiveQueryInfo
2434 * @return array With three keys:
2435 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2436 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2437 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2439 public function getArchiveQueryInfo() {
2440 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
2441 $actorQuery = $this->actorMigration
->getJoin( 'ar_user' );
2443 'tables' => [ 'archive' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
2456 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
2457 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
2460 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2461 $ret['fields'][] = 'ar_text_id';
2463 if ( $this->contentHandlerUseDB
) {
2464 $ret['fields'][] = 'ar_content_format';
2465 $ret['fields'][] = 'ar_content_model';
2473 * Do a batched query for the sizes of a set of revisions.
2475 * MCR migration note: this replaces Revision::getParentLengths
2477 * @param int[] $revIds
2478 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2479 * of the corresponding revision.
2481 public function getRevisionSizes( array $revIds ) {
2482 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
2486 * Do a batched query for the sizes of a set of revisions.
2488 * MCR migration note: this replaces Revision::getParentLengths
2490 * @deprecated use RevisionStore::getRevisionSizes instead.
2492 * @param IDatabase $db
2493 * @param int[] $revIds
2494 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2495 * of the corresponding revision.
2497 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
2498 $this->checkDatabaseWikiId( $db );
2502 return $revLens; // empty
2507 [ 'rev_id', 'rev_len' ],
2508 [ 'rev_id' => $revIds ],
2512 foreach ( $res as $row ) {
2513 $revLens[$row->rev_id
] = intval( $row->rev_len
);
2520 * Get the revision before $rev in the page's history, if any.
2521 * Will return null for the first revision but also for deleted or unsaved revisions.
2523 * MCR migration note: this replaces Revision::getPrevious
2525 * @see Title::getPreviousRevisionID
2526 * @see PageArchive::getPreviousRevision
2528 * @param RevisionRecord $rev
2529 * @param Title|null $title if known (optional)
2531 * @return RevisionRecord|null
2533 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
2534 if ( !$rev->getId() ||
!$rev->getPageId() ) {
2535 // revision is unsaved or otherwise incomplete
2539 if ( $rev instanceof RevisionArchiveRecord
) {
2540 // revision is deleted, so it's not part of the page history
2544 if ( $title === null ) {
2545 // this would fail for deleted revisions
2546 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2549 $prev = $title->getPreviousRevisionID( $rev->getId() );
2554 return $this->getRevisionByTitle( $title, $prev );
2558 * Get the revision after $rev in the page's history, if any.
2559 * Will return null for the latest revision but also for deleted or unsaved revisions.
2561 * MCR migration note: this replaces Revision::getNext
2563 * @see Title::getNextRevisionID
2565 * @param RevisionRecord $rev
2566 * @param Title|null $title if known (optional)
2568 * @return RevisionRecord|null
2570 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
2571 if ( !$rev->getId() ||
!$rev->getPageId() ) {
2572 // revision is unsaved or otherwise incomplete
2576 if ( $rev instanceof RevisionArchiveRecord
) {
2577 // revision is deleted, so it's not part of the page history
2581 if ( $title === null ) {
2582 // this would fail for deleted revisions
2583 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2586 $next = $title->getNextRevisionID( $rev->getId() );
2591 return $this->getRevisionByTitle( $title, $next );
2595 * Get previous revision Id for this page_id
2596 * This is used to populate rev_parent_id on save
2598 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
2600 * @param IDatabase $db
2601 * @param RevisionRecord $rev
2605 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
2606 $this->checkDatabaseWikiId( $db );
2608 if ( $rev->getPageId() === null ) {
2611 # Use page_latest if ID is not given
2612 if ( !$rev->getId() ) {
2613 $prevId = $db->selectField(
2614 'page', 'page_latest',
2615 [ 'page_id' => $rev->getPageId() ],
2619 $prevId = $db->selectField(
2620 'revision', 'rev_id',
2621 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
2623 [ 'ORDER BY' => 'rev_id DESC' ]
2626 return intval( $prevId );
2630 * Get rev_timestamp from rev_id, without loading the rest of the row
2632 * MCR migration note: this replaces Revision::getTimestampFromId
2634 * @param Title $title
2637 * @return string|bool False if not found
2639 public function getTimestampFromId( $title, $id, $flags = 0 ) {
2640 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2642 $conds = [ 'rev_id' => $id ];
2643 $conds['rev_page'] = $title->getArticleID();
2644 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
2646 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
2650 * Get count of revisions per page...not very efficient
2652 * MCR migration note: this replaces Revision::countByPageId
2654 * @param IDatabase $db
2655 * @param int $id Page id
2658 public function countRevisionsByPageId( IDatabase
$db, $id ) {
2659 $this->checkDatabaseWikiId( $db );
2661 $row = $db->selectRow( 'revision',
2662 [ 'revCount' => 'COUNT(*)' ],
2663 [ 'rev_page' => $id ],
2667 return intval( $row->revCount
);
2673 * Get count of revisions per page...not very efficient
2675 * MCR migration note: this replaces Revision::countByTitle
2677 * @param IDatabase $db
2678 * @param Title $title
2681 public function countRevisionsByTitle( IDatabase
$db, $title ) {
2682 $id = $title->getArticleID();
2684 return $this->countRevisionsByPageId( $db, $id );
2690 * Check if no edits were made by other users since
2691 * the time a user started editing the page. Limit to
2692 * 50 revisions for the sake of performance.
2694 * MCR migration note: this replaces Revision::userWasLastToEdit
2696 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
2697 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
2698 * has been deprecated since 1.24.
2700 * @param IDatabase $db The Database to perform the check on.
2701 * @param int $pageId The ID of the page in question
2702 * @param int $userId The ID of the user in question
2703 * @param string $since Look at edits since this time
2705 * @return bool True if the given user was the only one to edit since the given timestamp
2707 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
2708 $this->checkDatabaseWikiId( $db );
2714 $revQuery = $this->getQueryInfo();
2716 $revQuery['tables'],
2718 'rev_user' => $revQuery['fields']['rev_user'],
2721 'rev_page' => $pageId,
2722 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
2725 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
2728 foreach ( $res as $row ) {
2729 if ( $row->rev_user
!= $userId ) {
2737 * Load a revision based on a known page ID and current revision ID from the DB
2739 * This method allows for the use of caching, though accessing anything that normally
2740 * requires permission checks (aside from the text) will trigger a small DB lookup.
2742 * MCR migration note: this replaces Revision::newKnownCurrent
2744 * @param Title $title the associated page title
2745 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
2747 * @return RevisionRecord|bool Returns false if missing
2749 public function getKnownCurrentRevision( Title
$title, $revId ) {
2750 $db = $this->getDBConnectionRef( DB_REPLICA
);
2752 $pageId = $title->getArticleID();
2759 $revId = $title->getLatestRevID();
2764 'No latest revision known for page ' . $title->getPrefixedDBkey()
2765 . ' even though it exists with page ID ' . $pageId
2770 $row = $this->cache
->getWithSetCallback(
2771 // Page/rev IDs passed in from DB to reflect history merges
2772 $this->getRevisionRowCacheKey( $db, $pageId, $revId ),
2773 WANObjectCache
::TTL_WEEK
,
2774 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
2775 $setOpts +
= Database
::getCacheSetOptions( $db );
2778 'rev_page' => intval( $pageId ),
2779 'page_id' => intval( $pageId ),
2780 'rev_id' => intval( $revId ),
2783 $row = $this->fetchRevisionRowFromConds( $db, $conds );
2784 return $row ?
: false; // don't cache negatives
2788 // Reflect revision deletion and user renames
2790 return $this->newRevisionFromRow( $row, 0, $title );
2797 * Get a cache key for use with a row as selected with getQueryInfo( [ 'page', 'user' ] )
2798 * Caching rows without 'page' or 'user' could lead to issues.
2799 * If the format of the rows returned by the query provided by getQueryInfo changes the
2800 * cache key should be updated to avoid conflicts.
2802 * @param IDatabase $db
2803 * @param int $pageId
2807 private function getRevisionRowCacheKey( IDatabase
$db, $pageId, $revId ) {
2808 return $this->cache
->makeGlobalKey(
2809 self
::ROW_CACHE_KEY
,
2816 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.
2821 * Retain the old class name for backwards compatibility.
2822 * @deprecated since 1.32
2824 class_alias( RevisionStore
::class, 'MediaWiki\Storage\RevisionStore' );