3 * Service for looking up page revisions.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * Attribution notice: when this file was created, much of its content was taken
21 * from the Revision.php file as present in release 1.30. Refer to the history
22 * of that file for original authorship.
27 namespace MediaWiki\Storage
;
31 use CommentStoreComment
;
34 use DBAccessObjectUtils
;
37 use InvalidArgumentException
;
40 use MediaWiki\Linker\LinkTarget
;
41 use MediaWiki\User\UserIdentity
;
42 use MediaWiki\User\UserIdentityValue
;
45 use MWUnknownContentModelException
;
46 use Psr\Log\LoggerAwareInterface
;
47 use Psr\Log\LoggerInterface
;
48 use Psr\Log\NullLogger
;
55 use Wikimedia\Assert\Assert
;
56 use Wikimedia\Rdbms\Database
;
57 use Wikimedia\Rdbms\DBConnRef
;
58 use Wikimedia\Rdbms\IDatabase
;
59 use Wikimedia\Rdbms\ILoadBalancer
;
62 * Service for looking up page revisions.
66 * @note This was written to act as a drop-in replacement for the corresponding
67 * static methods in Revision.
70 implements IDBAccessObject
, RevisionFactory
, RevisionLookup
, LoggerAwareInterface
{
72 const ROW_CACHE_KEY
= 'revision-row-1.29';
86 * @see $wgContentHandlerUseDB
88 private $contentHandlerUseDB = true;
93 private $loadBalancer;
103 private $commentStore;
106 * @var ActorMigration
108 private $actorMigration;
111 * @var LoggerInterface
116 * @var NameTableStore
118 private $contentModelStore;
121 * @var NameTableStore
123 private $slotRoleStore;
125 /** @var int An appropriate combination of SCHEMA_COMPAT_XXX flags. */
126 private $mcrMigrationStage;
129 * @todo $blobStore should be allowed to be any BlobStore!
131 * @param ILoadBalancer $loadBalancer
132 * @param SqlBlobStore $blobStore
133 * @param WANObjectCache $cache A cache for caching revision rows. This can be the local
134 * wiki's default instance even if $wikiId refers to a different wiki, since
135 * makeGlobalKey() is used to constructed a key that allows cached revision rows from
136 * the same database to be re-used between wikis. For example, enwiki and frwiki will
137 * use the same cache keys for revision rows from the wikidatawiki database, regardless
138 * of the cache's default key space.
139 * @param CommentStore $commentStore
140 * @param NameTableStore $contentModelStore
141 * @param NameTableStore $slotRoleStore
142 * @param int $mcrMigrationStage An appropriate combination of SCHEMA_COMPAT_XXX flags
143 * @param ActorMigration $actorMigration
144 * @param bool|string $wikiId
146 * @throws MWException if $mcrMigrationStage or $wikiId is invalid.
148 public function __construct(
149 ILoadBalancer
$loadBalancer,
150 SqlBlobStore
$blobStore,
151 WANObjectCache
$cache,
152 CommentStore
$commentStore,
153 NameTableStore
$contentModelStore,
154 NameTableStore
$slotRoleStore,
156 ActorMigration
$actorMigration,
159 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
160 Assert
::parameterType( 'integer', $mcrMigrationStage, '$mcrMigrationStage' );
162 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== SCHEMA_COMPAT_READ_BOTH
,
163 '$mcrMigrationStage',
164 'Reading from the old and the new schema at the same time is not supported.'
167 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== 0,
168 '$mcrMigrationStage',
169 'Reading needs to be enabled for the old or the new schema.'
172 ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) !== 0,
173 '$mcrMigrationStage',
174 'Writing needs to be enabled for the old or the new schema.'
177 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_OLD
) === 0
178 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) !== 0,
179 '$mcrMigrationStage',
180 'Cannot read the old schema when not also writing it.'
183 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_NEW
) === 0
184 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) !== 0,
185 '$mcrMigrationStage',
186 'Cannot read the new schema when not also writing it.'
189 $this->loadBalancer
= $loadBalancer;
190 $this->blobStore
= $blobStore;
191 $this->cache
= $cache;
192 $this->commentStore
= $commentStore;
193 $this->contentModelStore
= $contentModelStore;
194 $this->slotRoleStore
= $slotRoleStore;
195 $this->mcrMigrationStage
= $mcrMigrationStage;
196 $this->actorMigration
= $actorMigration;
197 $this->wikiId
= $wikiId;
198 $this->logger
= new NullLogger();
202 * @param int $flags A combination of SCHEMA_COMPAT_XXX flags.
203 * @return bool True if all the given flags were set in the $mcrMigrationStage
204 * parameter passed to the constructor.
206 private function hasMcrSchemaFlags( $flags ) {
207 return ( $this->mcrMigrationStage
& $flags ) === $flags;
210 public function setLogger( LoggerInterface
$logger ) {
211 $this->logger
= $logger;
215 * @return bool Whether the store is read-only
217 public function isReadOnly() {
218 return $this->blobStore
->isReadOnly();
224 public function getContentHandlerUseDB() {
225 return $this->contentHandlerUseDB
;
229 * @see $wgContentHandlerUseDB
230 * @param bool $contentHandlerUseDB
231 * @throws MWException
233 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
234 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
)
235 ||
$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
)
237 if ( !$contentHandlerUseDB ) {
238 throw new MWException(
239 'Content model must be stored in the database for multi content revision migration.'
243 $this->contentHandlerUseDB
= $contentHandlerUseDB;
247 * @return ILoadBalancer
249 private function getDBLoadBalancer() {
250 return $this->loadBalancer
;
254 * @param int $mode DB_MASTER or DB_REPLICA
258 private function getDBConnection( $mode ) {
259 $lb = $this->getDBLoadBalancer();
260 return $lb->getConnection( $mode, [], $this->wikiId
);
264 * @param int $queryFlags a bit field composed of READ_XXX flags
268 private function getDBConnectionRefForQueryFlags( $queryFlags ) {
269 list( $mode, ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
270 return $this->getDBConnectionRef( $mode );
274 * @param IDatabase $connection
276 private function releaseDBConnection( IDatabase
$connection ) {
277 $lb = $this->getDBLoadBalancer();
278 $lb->reuseConnection( $connection );
282 * @param int $mode DB_MASTER or DB_REPLICA
286 private function getDBConnectionRef( $mode ) {
287 $lb = $this->getDBLoadBalancer();
288 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
292 * Determines the page Title based on the available information.
294 * MCR migration note: this corresponds to Revision::getTitle
296 * @note this method should be private, external use should be avoided!
298 * @param int|null $pageId
299 * @param int|null $revId
300 * @param int $queryFlags
303 * @throws RevisionAccessException
305 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
306 if ( !$pageId && !$revId ) {
307 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
310 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
311 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
312 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
313 $queryFlags = self
::READ_NORMAL
;
316 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false );
317 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
318 $titleFlags = ( $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0 );
320 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
321 if ( $canUseTitleNewFromId ) {
322 // TODO: better foreign title handling (introduce TitleFactory)
323 $title = Title
::newFromID( $pageId, $titleFlags );
329 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
330 $canUseRevId = ( $revId !== null && $revId > 0 );
332 if ( $canUseRevId ) {
333 $dbr = $this->getDBConnectionRef( $dbMode );
334 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
335 $row = $dbr->selectRow(
336 [ 'revision', 'page' ],
345 [ 'rev_id' => $revId ],
348 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
351 // TODO: better foreign title handling (introduce TitleFactory)
352 return Title
::newFromRow( $row );
356 // If we still don't have a title, fallback to master if that wasn't already happening.
357 if ( $dbMode !== DB_MASTER
) {
358 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
361 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
362 [ 'trace' => wfBacktrace() ]
368 throw new RevisionAccessException(
369 "Could not determine title for page ID $pageId and revision ID $revId"
374 * @param mixed $value
375 * @param string $name
377 * @throws IncompleteRevisionException if $value is null
378 * @return mixed $value, if $value is not null
380 private function failOnNull( $value, $name ) {
381 if ( $value === null ) {
382 throw new IncompleteRevisionException(
383 "$name must not be " . var_export( $value, true ) . "!"
391 * @param mixed $value
392 * @param string $name
394 * @throws IncompleteRevisionException if $value is empty
395 * @return mixed $value, if $value is not null
397 private function failOnEmpty( $value, $name ) {
398 if ( $value === null ||
$value === 0 ||
$value === '' ) {
399 throw new IncompleteRevisionException(
400 "$name must not be " . var_export( $value, true ) . "!"
408 * Insert a new revision into the database, returning the new revision record
409 * on success and dies horribly on failure.
411 * MCR migration note: this replaces Revision::insertOn
413 * @param RevisionRecord $rev
414 * @param IDatabase $dbw (master connection)
416 * @throws InvalidArgumentException
417 * @return RevisionRecord the new revision record.
419 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
420 // TODO: pass in a DBTransactionContext instead of a database connection.
421 $this->checkDatabaseWikiId( $dbw );
423 $slotRoles = $rev->getSlotRoles();
425 // Make sure the main slot is always provided throughout migration
426 if ( !in_array( 'main', $slotRoles ) ) {
427 throw new InvalidArgumentException(
428 'main slot must be provided'
432 // If we are not writing into the new schema, we can't support extra slots.
433 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) && $slotRoles !== [ 'main' ] ) {
434 throw new InvalidArgumentException(
435 'Only the main slot is supported when not writing to the MCR enabled schema!'
439 // As long as we are not reading from the new schema, we don't want to write extra slots.
440 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) && $slotRoles !== [ 'main' ] ) {
441 throw new InvalidArgumentException(
442 'Only the main slot is supported when not reading from the MCR enabled schema!'
447 $this->failOnNull( $rev->getSize(), 'size field' );
448 $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
449 $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
450 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
451 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
452 $this->failOnNull( $user->getId(), 'user field' );
453 $this->failOnEmpty( $user->getName(), 'user_text field' );
455 // TODO: we shouldn't need an actual Title here.
456 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
457 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
459 $parentId = $rev->getParentId() === null
460 ?
$this->getPreviousRevisionId( $dbw, $rev )
461 : $rev->getParentId();
463 /** @var RevisionRecord $rev */
464 $rev = $dbw->doAtomicSection(
466 function ( IDatabase
$dbw, $fname ) use (
474 return $this->insertRevisionInternal(
487 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
488 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
489 Assert
::postcondition(
490 $rev->getComment( RevisionRecord
::RAW
) !== null,
491 'revision must have a comment'
493 Assert
::postcondition(
494 $rev->getUser( RevisionRecord
::RAW
) !== null,
495 'revision must have a user'
498 // Trigger exception if the main slot is missing.
499 // Technically, this could go away after MCR migration: while
500 // calling code may require a main slot to exist, RevisionStore
501 // really should not know or care about that requirement.
502 $rev->getSlot( 'main', RevisionRecord
::RAW
);
504 foreach ( $slotRoles as $role ) {
505 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
506 Assert
::postcondition(
507 $slot->getContent() !== null,
508 $role . ' slot must have content'
510 Assert
::postcondition(
511 $slot->hasRevision(),
512 $role . ' slot must have a revision associated'
516 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
518 // TODO: deprecate in 1.32!
519 $legacyRevision = new Revision( $rev );
520 Hooks
::run( 'RevisionInsertComplete', [ &$legacyRevision, null, null ] );
525 private function insertRevisionInternal(
529 CommentStoreComment
$comment,
534 $slotRoles = $rev->getSlotRoles();
536 $revisionRow = $this->insertRevisionRowOn(
543 $revisionId = $revisionRow['rev_id'];
546 BlobStore
::PAGE_HINT
=> $pageId,
547 BlobStore
::REVISION_HINT
=> $revisionId,
548 BlobStore
::PARENT_HINT
=> $parentId,
552 foreach ( $slotRoles as $role ) {
553 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
555 if ( $slot->hasRevision() ) {
556 // If the SlotRecord already has a revision ID set, this means it already exists
557 // in the database, and should already belong to the current revision.
558 // TODO: properly abort transaction if the assertion fails!
560 $slot->getRevision() === $revisionId,
561 'slot role ' . $slot->getRole(),
562 'Existing slot should belong to revision '
563 . $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
566 // Slot exists, nothing to do, move along.
567 // This happens when restoring archived revisions.
569 $newSlots[$role] = $slot;
571 // Write the main slot's text ID to the revision table for backwards compatibility
572 if ( $slot->getRole() === 'main'
573 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
575 $blobAddress = $slot->getAddress();
576 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
579 $newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $title, $blobHints );
583 $this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
585 $rev = new RevisionStoreRecord(
589 (object)$revisionRow,
590 new RevisionSlots( $newSlots ),
598 * @param IDatabase $dbw
599 * @param int $revisionId
600 * @param string &$blobAddress (may change!)
602 private function updateRevisionTextId( IDatabase
$dbw, $revisionId, &$blobAddress ) {
603 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
605 throw new LogicException(
606 'Blob address not supported in 1.29 database schema: ' . $blobAddress
610 // getTextIdFromAddress() is free to insert something into the text table, so $textId
611 // may be a new value, not anything already contained in $blobAddress.
612 $blobAddress = SqlBlobStore
::makeAddressFromTextId( $textId );
616 [ 'rev_text_id' => $textId ],
617 [ 'rev_id' => $revisionId ],
623 * @param IDatabase $dbw
624 * @param int $revisionId
625 * @param SlotRecord $protoSlot
626 * @param Title $title
627 * @param array $blobHints See the BlobStore::XXX_HINT constants
630 private function insertSlotOn(
633 SlotRecord
$protoSlot,
635 array $blobHints = []
637 if ( $protoSlot->hasAddress() ) {
638 $blobAddress = $protoSlot->getAddress();
640 $blobAddress = $this->storeContentBlob( $protoSlot, $title, $blobHints );
643 // Write the main slot's text ID to the revision table for backwards compatibility
644 if ( $protoSlot->getRole() === 'main'
645 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
647 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
650 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
651 if ( $protoSlot->hasContentId() ) {
652 $contentId = $protoSlot->getContentId();
654 $contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
657 $this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
662 $savedSlot = SlotRecord
::newSaved(
673 * Insert IP revision into ip_changes for use when querying for a range.
674 * @param IDatabase $dbw
676 * @param RevisionRecord $rev
677 * @param int $revisionId
679 private function insertIpChangesRow(
685 if ( $user->getId() === 0 && IP
::isValid( $user->getName() ) ) {
687 'ipc_rev_id' => $revisionId,
688 'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
689 'ipc_hex' => IP
::toHex( $user->getName() ),
691 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
696 * @param IDatabase $dbw
697 * @param RevisionRecord $rev
698 * @param Title $title
699 * @param int $parentId
701 * @return array a revision table row
703 * @throws MWException
704 * @throws MWUnknownContentModelException
706 private function insertRevisionRowOn(
712 $revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $title, $parentId );
714 list( $commentFields, $commentCallback ) =
715 $this->commentStore
->insertWithTempTable(
718 $rev->getComment( RevisionRecord
::RAW
)
720 $revisionRow +
= $commentFields;
722 list( $actorFields, $actorCallback ) =
723 $this->actorMigration
->getInsertValuesWithTempTable(
726 $rev->getUser( RevisionRecord
::RAW
)
728 $revisionRow +
= $actorFields;
730 $dbw->insert( 'revision', $revisionRow, __METHOD__
);
732 if ( !isset( $revisionRow['rev_id'] ) ) {
733 // only if auto-increment was used
734 $revisionRow['rev_id'] = intval( $dbw->insertId() );
737 $commentCallback( $revisionRow['rev_id'] );
738 $actorCallback( $revisionRow['rev_id'], $revisionRow );
744 * @param IDatabase $dbw
745 * @param RevisionRecord $rev
746 * @param Title $title
747 * @param int $parentId
749 * @return array [ 0 => array $revisionRow, 1 => callable ]
750 * @throws MWException
751 * @throws MWUnknownContentModelException
753 private function getBaseRevisionRow(
759 // Record the edit in revisions
761 'rev_page' => $rev->getPageId(),
762 'rev_parent_id' => $parentId,
763 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
764 'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
765 'rev_deleted' => $rev->getVisibility(),
766 'rev_len' => $rev->getSize(),
767 'rev_sha1' => $rev->getSha1(),
770 if ( $rev->getId() !== null ) {
771 // Needed to restore revisions with their original ID
772 $revisionRow['rev_id'] = $rev->getId();
775 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
776 // In non MCR mode this IF section will relate to the main slot
777 $mainSlot = $rev->getSlot( 'main' );
778 $model = $mainSlot->getModel();
779 $format = $mainSlot->getFormat();
781 // MCR migration note: rev_content_model and rev_content_format will go away
782 if ( $this->contentHandlerUseDB
) {
783 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
784 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
786 $revisionRow['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
787 $revisionRow['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
795 * @param SlotRecord $slot
796 * @param Title $title
797 * @param array $blobHints See the BlobStore::XXX_HINT constants
799 * @throws MWException
800 * @return string the blob address
802 private function storeContentBlob(
805 array $blobHints = []
807 $content = $slot->getContent();
808 $format = $content->getDefaultFormat();
809 $model = $content->getModel();
811 $this->checkContent( $content, $title );
813 return $this->blobStore
->storeBlob(
814 $content->serialize( $format ),
815 // These hints "leak" some information from the higher abstraction layer to
816 // low level storage to allow for optimization.
820 BlobStore
::DESIGNATION_HINT
=> 'page-content',
821 BlobStore
::ROLE_HINT
=> $slot->getRole(),
822 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
823 BlobStore
::MODEL_HINT
=> $model,
824 BlobStore
::FORMAT_HINT
=> $format,
831 * @param SlotRecord $slot
832 * @param IDatabase $dbw
833 * @param int $revisionId
834 * @param int $contentId
836 private function insertSlotRowOn( SlotRecord
$slot, IDatabase
$dbw, $revisionId, $contentId ) {
838 'slot_revision_id' => $revisionId,
839 'slot_role_id' => $this->slotRoleStore
->acquireId( $slot->getRole() ),
840 'slot_content_id' => $contentId,
841 // If the slot has a specific origin use that ID, otherwise use the ID of the revision
842 // that we just inserted.
843 'slot_origin' => $slot->hasOrigin() ?
$slot->getOrigin() : $revisionId,
845 $dbw->insert( 'slots', $slotRow, __METHOD__
);
849 * @param SlotRecord $slot
850 * @param IDatabase $dbw
851 * @param string $blobAddress
852 * @return int content row ID
854 private function insertContentRowOn( SlotRecord
$slot, IDatabase
$dbw, $blobAddress ) {
856 'content_size' => $slot->getSize(),
857 'content_sha1' => $slot->getSha1(),
858 'content_model' => $this->contentModelStore
->acquireId( $slot->getModel() ),
859 'content_address' => $blobAddress,
861 $dbw->insert( 'content', $contentRow, __METHOD__
);
862 return intval( $dbw->insertId() );
866 * MCR migration note: this corresponds to Revision::checkContentModel
868 * @param Content $content
869 * @param Title $title
871 * @throws MWException
872 * @throws MWUnknownContentModelException
874 private function checkContent( Content
$content, Title
$title ) {
875 // Note: may return null for revisions that have not yet been inserted
877 $model = $content->getModel();
878 $format = $content->getDefaultFormat();
879 $handler = $content->getContentHandler();
883 if ( !$handler->isSupportedFormat( $format ) ) {
884 throw new MWException( "Can't use format $format with content model $model on $name" );
887 if ( !$this->contentHandlerUseDB
) {
888 // if $wgContentHandlerUseDB is not set,
889 // all revisions must use the default content model and format.
891 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
892 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
893 $defaultFormat = $defaultHandler->getDefaultFormat();
895 if ( $model != $defaultModel ) {
896 throw new MWException( "Can't save non-default content model with "
897 . "\$wgContentHandlerUseDB disabled: model is $model, "
898 . "default for $name is $defaultModel"
902 if ( $format != $defaultFormat ) {
903 throw new MWException( "Can't use non-default content format with "
904 . "\$wgContentHandlerUseDB disabled: format is $format, "
905 . "default for $name is $defaultFormat"
910 if ( !$content->isValid() ) {
911 throw new MWException(
912 "New content for $name is not valid! Content model is $model"
918 * Create a new null-revision for insertion into a page's
919 * history. This will not re-save the text, but simply refer
920 * to the text from the previous version.
922 * Such revisions can for instance identify page rename
923 * operations and other such meta-modifications.
925 * @note This method grabs a FOR UPDATE lock on the relevant row of the page table,
926 * to prevent a new revision from being inserted before the null revision has been written
929 * MCR migration note: this replaces Revision::newNullRevision
931 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
934 * @param IDatabase $dbw used for obtaining the lock on the page table row
935 * @param Title $title Title of the page to read from
936 * @param CommentStoreComment $comment RevisionRecord's summary
937 * @param bool $minor Whether the revision should be considered as minor
938 * @param User $user The user to attribute the revision to
940 * @return RevisionRecord|null RevisionRecord or null on error
942 public function newNullRevision(
945 CommentStoreComment
$comment,
949 $this->checkDatabaseWikiId( $dbw );
951 // T51581: Lock the page table row to ensure no other process
952 // is adding a revision to the page at the same time.
953 // Avoid locking extra tables, compare T191892.
954 $pageLatest = $dbw->selectField(
957 [ 'page_id' => $title->getArticleID() ],
962 if ( !$pageLatest ) {
966 // Fetch the actual revision row from master, without locking all extra tables.
967 $oldRevision = $this->loadRevisionFromConds(
969 [ 'rev_id' => intval( $pageLatest ) ],
974 // Construct the new revision
975 $timestamp = wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
976 $newRevision = MutableRevisionRecord
::newFromParentRevision( $oldRevision );
978 $newRevision->setComment( $comment );
979 $newRevision->setUser( $user );
980 $newRevision->setTimestamp( $timestamp );
981 $newRevision->setMinorEdit( $minor );
987 * MCR migration note: this replaces Revision::isUnpatrolled
989 * @todo This is overly specific, so move or kill this method.
991 * @param RevisionRecord $rev
993 * @return int Rcid of the unpatrolled row, zero if there isn't one
995 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
996 $rc = $this->getRecentChange( $rev );
997 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == RecentChange
::PRC_UNPATROLLED
) {
998 return $rc->getAttribute( 'rc_id' );
1005 * Get the RC object belonging to the current revision, if there's one
1007 * MCR migration note: this replaces Revision::getRecentChange
1009 * @todo move this somewhere else?
1011 * @param RevisionRecord $rev
1012 * @param int $flags (optional) $flags include:
1013 * IDBAccessObject::READ_LATEST: Select the data from the master
1015 * @return null|RecentChange
1017 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
1018 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
1019 $db = $this->getDBConnection( $dbType );
1021 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
1023 if ( !$userIdentity ) {
1024 // If the revision has no user identity, chances are it never went
1025 // into the database, and doesn't have an RC entry.
1029 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
1030 $actorWhere = $this->actorMigration
->getWhere( $db, 'rc_user', $rev->getUser(), false );
1031 $rc = RecentChange
::newFromConds(
1033 $actorWhere['conds'],
1034 'rc_timestamp' => $db->timestamp( $rev->getTimestamp() ),
1035 'rc_this_oldid' => $rev->getId()
1041 $this->releaseDBConnection( $db );
1043 // XXX: cache this locally? Glue it to the RevisionRecord?
1048 * Maps fields of the archive row to corresponding revision rows.
1050 * @param object $archiveRow
1052 * @return object a revision row object, corresponding to $archiveRow.
1054 private static function mapArchiveFields( $archiveRow ) {
1056 // keep with ar prefix:
1059 // not the same suffix:
1060 'ar_page_id' => 'rev_page',
1061 'ar_rev_id' => 'rev_id',
1064 'ar_text_id' => 'rev_text_id',
1065 'ar_timestamp' => 'rev_timestamp',
1066 'ar_user_text' => 'rev_user_text',
1067 'ar_user' => 'rev_user',
1068 'ar_actor' => 'rev_actor',
1069 'ar_minor_edit' => 'rev_minor_edit',
1070 'ar_deleted' => 'rev_deleted',
1071 'ar_len' => 'rev_len',
1072 'ar_parent_id' => 'rev_parent_id',
1073 'ar_sha1' => 'rev_sha1',
1074 'ar_comment' => 'rev_comment',
1075 'ar_comment_cid' => 'rev_comment_cid',
1076 'ar_comment_id' => 'rev_comment_id',
1077 'ar_comment_text' => 'rev_comment_text',
1078 'ar_comment_data' => 'rev_comment_data',
1079 'ar_comment_old' => 'rev_comment_old',
1080 'ar_content_format' => 'rev_content_format',
1081 'ar_content_model' => 'rev_content_model',
1084 $revRow = new stdClass();
1085 foreach ( $fieldMap as $arKey => $revKey ) {
1086 if ( property_exists( $archiveRow, $arKey ) ) {
1087 $revRow->$revKey = $archiveRow->$arKey;
1095 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
1097 * @param object|array $row Either a database row or an array
1098 * @param int $queryFlags for callbacks
1099 * @param Title $title
1101 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
1102 * @throws MWException
1104 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
1105 $mainSlotRow = new stdClass();
1106 $mainSlotRow->role_name
= 'main';
1107 $mainSlotRow->model_name
= null;
1108 $mainSlotRow->slot_revision_id
= null;
1109 $mainSlotRow->content_address
= null;
1115 if ( is_object( $row ) ) {
1116 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1117 // Don't emulate from a row when using the new schema.
1118 // Emulating from an array is still OK.
1119 throw new LogicException( 'Can\'t emulate the main slot when using MCR schema.' );
1123 if ( !isset( $row->rev_id
) && ( isset( $row->ar_user
) ||
isset( $row->ar_actor
) ) ) {
1124 $row = $this->mapArchiveFields( $row );
1127 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
1128 $mainSlotRow->content_address
= SqlBlobStore
::makeAddressFromTextId(
1133 // This is used by null-revisions
1134 $mainSlotRow->slot_origin
= isset( $row->slot_origin
)
1135 ?
intval( $row->slot_origin
)
1138 if ( isset( $row->old_text
) ) {
1139 // this happens when the text-table gets joined directly, in the pre-1.30 schema
1140 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
1141 // Check against selects that might have not included old_flags
1142 if ( !property_exists( $row, 'old_flags' ) ) {
1143 throw new InvalidArgumentException( 'old_flags was not set in $row' );
1145 $blobFlags = $row->old_flags ??
'';
1148 $mainSlotRow->slot_revision_id
= intval( $row->rev_id
);
1150 $mainSlotRow->content_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
1151 $mainSlotRow->content_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
1152 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
1153 ?
strval( $row->rev_content_model
)
1155 // XXX: in the future, we'll probably always use the default format, and drop content_format
1156 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
1157 ?
strval( $row->rev_content_format
)
1159 } elseif ( is_array( $row ) ) {
1160 $mainSlotRow->slot_revision_id
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
1162 $mainSlotRow->slot_origin
= isset( $row['slot_origin'] )
1163 ?
intval( $row['slot_origin'] )
1165 $mainSlotRow->content_address
= isset( $row['text_id'] )
1166 ? SqlBlobStore
::makeAddressFromTextId( intval( $row['text_id'] ) )
1168 $mainSlotRow->content_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
1169 $mainSlotRow->content_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
1171 $mainSlotRow->model_name
= isset( $row['content_model'] )
1172 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
1173 // XXX: in the future, we'll probably always use the default format, and drop content_format
1174 $mainSlotRow->format_name
= isset( $row['content_format'] )
1175 ?
strval( $row['content_format'] ) : null;
1176 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
1177 // XXX: If the flags field is not set then $blobFlags should be null so that no
1178 // decoding will happen. An empty string will result in default decodings.
1179 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
1181 // if we have a Content object, override mText and mContentModel
1182 if ( !empty( $row['content'] ) ) {
1183 if ( !( $row['content'] instanceof Content
) ) {
1184 throw new MWException( 'content field must contain a Content object.' );
1187 /** @var Content $content */
1188 $content = $row['content'];
1189 $handler = $content->getContentHandler();
1191 $mainSlotRow->model_name
= $content->getModel();
1193 // XXX: in the future, we'll probably always use the default format.
1194 if ( $mainSlotRow->format_name
=== null ) {
1195 $mainSlotRow->format_name
= $handler->getDefaultFormat();
1199 throw new MWException( 'Revision constructor passed invalid row format.' );
1202 // With the old schema, the content changes with every revision,
1203 // except for null-revisions.
1204 if ( !isset( $mainSlotRow->slot_origin
) ) {
1205 $mainSlotRow->slot_origin
= $mainSlotRow->slot_revision_id
;
1208 if ( $mainSlotRow->model_name
=== null ) {
1209 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
1210 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
1211 // TODO: MCR: deprecate $title->getModel().
1212 return ContentHandler
::getDefaultModelFor( $title );
1217 // XXX: We should perhaps fail if $blobData is null and $mainSlotRow->content_address
1218 // is missing, but "empty revisions" with no content are used in some edge cases.
1220 $content = function ( SlotRecord
$slot )
1221 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
1223 return $this->loadSlotContent(
1227 $mainSlotRow->format_name
,
1233 // NOTE: this callback will be looped through RevisionSlot::newInherited(), allowing
1234 // the inherited slot to have the same content_id as the original slot. In that case,
1235 // $slot will be the inherited slot, while $mainSlotRow still refers to the original slot.
1236 $mainSlotRow->slot_content_id
=
1237 function ( SlotRecord
$slot ) use ( $queryFlags, $mainSlotRow ) {
1238 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1239 return $this->findSlotContentId( $db, $mainSlotRow->slot_revision_id
, 'main' );
1242 return new SlotRecord( $mainSlotRow, $content );
1246 * Loads a Content object based on a slot row.
1248 * This method does not call $slot->getContent(), and may be used as a callback
1249 * called by $slot->getContent().
1251 * MCR migration note: this roughly corresponds to Revision::getContentInternal
1253 * @param SlotRecord $slot The SlotRecord to load content for
1254 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
1255 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
1256 * Use null if no processing should happen. That is in constrast to the empty string,
1257 * which causes the blob to be decoded according to the configured legacy encoding.
1258 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
1259 * @param int $queryFlags
1261 * @throws RevisionAccessException
1264 private function loadSlotContent(
1271 if ( $blobData !== null ) {
1272 Assert
::parameterType( 'string', $blobData, '$blobData' );
1273 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
1275 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
1277 if ( $blobFlags === null ) {
1278 // No blob flags, so use the blob verbatim.
1281 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
1282 if ( $data === false ) {
1283 throw new RevisionAccessException(
1284 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
1290 $address = $slot->getAddress();
1292 $data = $this->blobStore
->getBlob( $address, $queryFlags );
1293 } catch ( BlobAccessException
$e ) {
1294 throw new RevisionAccessException(
1295 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
1300 // Unserialize content
1301 $handler = ContentHandler
::getForModelID( $slot->getModel() );
1303 $content = $handler->unserializeContent( $data, $blobFormat );
1308 * Load a page revision from a given revision ID number.
1309 * Returns null if no such revision can be found.
1311 * MCR migration note: this replaces Revision::newFromId
1314 * IDBAccessObject::READ_LATEST: Select the data from the master
1315 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1318 * @param int $flags (optional)
1319 * @return RevisionRecord|null
1321 public function getRevisionById( $id, $flags = 0 ) {
1322 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
1326 * Load either the current, or a specified, revision
1327 * that's attached to a given link target. If not attached
1328 * to that link target, will return null.
1330 * MCR migration note: this replaces Revision::newFromTitle
1333 * IDBAccessObject::READ_LATEST: Select the data from the master
1334 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1336 * @param LinkTarget $linkTarget
1337 * @param int $revId (optional)
1338 * @param int $flags Bitfield (optional)
1339 * @return RevisionRecord|null
1341 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
1343 'page_namespace' => $linkTarget->getNamespace(),
1344 'page_title' => $linkTarget->getDBkey()
1347 // Use the specified revision ID.
1348 // Note that we use newRevisionFromConds here because we want to retry
1349 // and fall back to master if the page is not found on a replica.
1350 // Since the caller supplied a revision ID, we are pretty sure the revision is
1351 // supposed to exist, so we should try hard to find it.
1352 $conds['rev_id'] = $revId;
1353 return $this->newRevisionFromConds( $conds, $flags );
1355 // Use a join to get the latest revision.
1356 // Note that we don't use newRevisionFromConds here because we don't want to retry
1357 // and fall back to master. The assumption is that we only want to force the fallback
1358 // if we are quite sure the revision exists because the caller supplied a revision ID.
1359 // If the page isn't found at all on a replica, it probably simply does not exist.
1360 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1362 $conds[] = 'rev_id=page_latest';
1363 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1370 * Load either the current, or a specified, revision
1371 * that's attached to a given page ID.
1372 * Returns null if no such revision can be found.
1374 * MCR migration note: this replaces Revision::newFromPageId
1377 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
1378 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1380 * @param int $pageId
1381 * @param int $revId (optional)
1382 * @param int $flags Bitfield (optional)
1383 * @return RevisionRecord|null
1385 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1386 $conds = [ 'page_id' => $pageId ];
1388 // Use the specified revision ID.
1389 // Note that we use newRevisionFromConds here because we want to retry
1390 // and fall back to master if the page is not found on a replica.
1391 // Since the caller supplied a revision ID, we are pretty sure the revision is
1392 // supposed to exist, so we should try hard to find it.
1393 $conds['rev_id'] = $revId;
1394 return $this->newRevisionFromConds( $conds, $flags );
1396 // Use a join to get the latest revision.
1397 // Note that we don't use newRevisionFromConds here because we don't want to retry
1398 // and fall back to master. The assumption is that we only want to force the fallback
1399 // if we are quite sure the revision exists because the caller supplied a revision ID.
1400 // If the page isn't found at all on a replica, it probably simply does not exist.
1401 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1403 $conds[] = 'rev_id=page_latest';
1404 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1411 * Load the revision for the given title with the given timestamp.
1412 * WARNING: Timestamps may in some circumstances not be unique,
1413 * so this isn't the best key to use.
1415 * MCR migration note: this replaces Revision::loadFromTimestamp
1417 * @param Title $title
1418 * @param string $timestamp
1419 * @return RevisionRecord|null
1421 public function getRevisionByTimestamp( $title, $timestamp ) {
1422 $db = $this->getDBConnection( DB_REPLICA
);
1423 return $this->newRevisionFromConds(
1425 'rev_timestamp' => $db->timestamp( $timestamp ),
1426 'page_namespace' => $title->getNamespace(),
1427 'page_title' => $title->getDBkey()
1435 * @param int $revId The revision to load slots for.
1436 * @param int $queryFlags
1438 * @return SlotRecord[]
1440 private function loadSlotRecords( $revId, $queryFlags ) {
1441 $revQuery = self
::getSlotsQueryInfo( [ 'content' ] );
1443 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
1444 $db = $this->getDBConnectionRef( $dbMode );
1447 $revQuery['tables'],
1448 $revQuery['fields'],
1450 'slot_revision_id' => $revId,
1459 foreach ( $res as $row ) {
1460 $contentCallback = function ( SlotRecord
$slot ) use ( $queryFlags, $row ) {
1461 return $this->loadSlotContent( $slot, null, null, null, $queryFlags );
1464 $slots[$row->role_name
] = new SlotRecord( $row, $contentCallback );
1467 if ( !isset( $slots['main'] ) ) {
1468 throw new RevisionAccessException(
1469 'Main slot of revision ' . $revId . ' not found in database!'
1477 * Factory method for RevisionSlots.
1479 * @note If other code has a need to construct RevisionSlots objects, this should be made
1480 * public, since RevisionSlots instances should not be constructed directly.
1483 * @param object $revisionRow
1484 * @param int $queryFlags
1485 * @param Title $title
1487 * @return RevisionSlots
1488 * @throws MWException
1490 private function newRevisionSlots(
1496 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1497 $mainSlot = $this->emulateMainSlot_1_29( $revisionRow, $queryFlags, $title );
1498 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1500 // XXX: do we need the same kind of caching here
1501 // that getKnownCurrentRevision uses (if $revId == page_latest?)
1503 $slots = new RevisionSlots( function () use( $revId, $queryFlags ) {
1504 return $this->loadSlotRecords( $revId, $queryFlags );
1512 * Make a fake revision object from an archive table row. This is queried
1513 * for permissions or even inserted (as in Special:Undelete)
1515 * MCR migration note: this replaces Revision::newFromArchiveRow
1517 * @param object $row
1518 * @param int $queryFlags
1519 * @param Title|null $title
1520 * @param array $overrides associative array with fields of $row to override. This may be
1521 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1522 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1523 * override ar_parent_id.
1525 * @return RevisionRecord
1526 * @throws MWException
1528 public function newRevisionFromArchiveRow(
1531 Title
$title = null,
1532 array $overrides = []
1534 Assert
::parameterType( 'object', $row, '$row' );
1536 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1537 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1539 if ( !$title && isset( $overrides['title'] ) ) {
1540 if ( !( $overrides['title'] instanceof Title
) ) {
1541 throw new MWException( 'title field override must contain a Title object.' );
1544 $title = $overrides['title'];
1547 if ( !isset( $title ) ) {
1548 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1549 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1551 throw new InvalidArgumentException(
1552 'A Title or ar_namespace and ar_title must be given'
1557 foreach ( $overrides as $key => $value ) {
1559 $row->$field = $value;
1563 $user = User
::newFromAnyId(
1564 $row->ar_user ??
null,
1565 $row->ar_user_text ??
null,
1566 $row->ar_actor ??
null
1568 } catch ( InvalidArgumentException
$ex ) {
1569 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1570 $user = new UserIdentityValue( 0, '', 0 );
1573 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1574 // Legacy because $row may have come from self::selectFields()
1575 $comment = $this->commentStore
->getCommentLegacy( $db, 'ar_comment', $row, true );
1577 $slots = $this->newRevisionSlots( $row->ar_rev_id
, $row, $queryFlags, $title );
1579 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1583 * @see RevisionFactory::newRevisionFromRow
1585 * MCR migration note: this replaces Revision::newFromRow
1587 * @param object $row
1588 * @param int $queryFlags
1589 * @param Title|null $title
1591 * @return RevisionRecord
1593 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1594 Assert
::parameterType( 'object', $row, '$row' );
1597 $pageId = $row->rev_page ??
0; // XXX: also check page_id?
1598 $revId = $row->rev_id ??
0;
1600 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1603 if ( !isset( $row->page_latest
) ) {
1604 $row->page_latest
= $title->getLatestRevID();
1605 if ( $row->page_latest
=== 0 && $title->exists() ) {
1606 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1611 $user = User
::newFromAnyId(
1612 $row->rev_user ??
null,
1613 $row->rev_user_text ??
null,
1614 $row->rev_actor ??
null
1616 } catch ( InvalidArgumentException
$ex ) {
1617 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1618 $user = new UserIdentityValue( 0, '', 0 );
1621 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1622 // Legacy because $row may have come from self::selectFields()
1623 $comment = $this->commentStore
->getCommentLegacy( $db, 'rev_comment', $row, true );
1625 $slots = $this->newRevisionSlots( $row->rev_id
, $row, $queryFlags, $title );
1627 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1631 * Constructs a new MutableRevisionRecord based on the given associative array following
1632 * the MW1.29 convention for the Revision constructor.
1634 * MCR migration note: this replaces Revision::newFromRow
1636 * @param array $fields
1637 * @param int $queryFlags
1638 * @param Title|null $title
1640 * @return MutableRevisionRecord
1641 * @throws MWException
1642 * @throws RevisionAccessException
1644 public function newMutableRevisionFromArray(
1649 if ( !$title && isset( $fields['title'] ) ) {
1650 if ( !( $fields['title'] instanceof Title
) ) {
1651 throw new MWException( 'title field must contain a Title object.' );
1654 $title = $fields['title'];
1658 $pageId = $fields['page'] ??
0;
1659 $revId = $fields['id'] ??
0;
1661 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1664 if ( !isset( $fields['page'] ) ) {
1665 $fields['page'] = $title->getArticleID( $queryFlags );
1668 // if we have a content object, use it to set the model and type
1669 if ( !empty( $fields['content'] ) ) {
1670 if ( !( $fields['content'] instanceof Content
) && !is_array( $fields['content'] ) ) {
1671 throw new MWException(
1672 'content field must contain a Content object or an array of Content objects.'
1677 if ( !empty( $fields['text_id'] ) ) {
1678 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
1679 throw new MWException( "The text_id field is only available in the pre-MCR schema" );
1682 if ( !empty( $fields['content'] ) ) {
1683 throw new MWException(
1684 "Text already stored in external store (id {$fields['text_id']}), " .
1685 "can't specify content object"
1691 isset( $fields['comment'] )
1692 && !( $fields['comment'] instanceof CommentStoreComment
)
1694 $commentData = $fields['comment_data'] ??
null;
1696 if ( $fields['comment'] instanceof Message
) {
1697 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1702 $commentText = trim( strval( $fields['comment'] ) );
1703 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1710 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1711 $this->initializeMutableRevisionFromArray( $revision, $fields );
1713 if ( isset( $fields['content'] ) && is_array( $fields['content'] ) ) {
1714 foreach ( $fields['content'] as $role => $content ) {
1715 $revision->setContent( $role, $content );
1718 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1719 $revision->setSlot( $mainSlot );
1726 * @param MutableRevisionRecord $record
1727 * @param array $fields
1729 private function initializeMutableRevisionFromArray(
1730 MutableRevisionRecord
$record,
1733 /** @var UserIdentity $user */
1736 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1737 $user = $fields['user'];
1740 $user = User
::newFromAnyId(
1741 $fields['user'] ??
null,
1742 $fields['user_text'] ??
null,
1743 $fields['actor'] ??
null
1745 } catch ( InvalidArgumentException
$ex ) {
1751 $record->setUser( $user );
1754 $timestamp = isset( $fields['timestamp'] )
1755 ?
strval( $fields['timestamp'] )
1756 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1758 $record->setTimestamp( $timestamp );
1760 if ( isset( $fields['page'] ) ) {
1761 $record->setPageId( intval( $fields['page'] ) );
1764 if ( isset( $fields['id'] ) ) {
1765 $record->setId( intval( $fields['id'] ) );
1767 if ( isset( $fields['parent_id'] ) ) {
1768 $record->setParentId( intval( $fields['parent_id'] ) );
1771 if ( isset( $fields['sha1'] ) ) {
1772 $record->setSha1( $fields['sha1'] );
1774 if ( isset( $fields['size'] ) ) {
1775 $record->setSize( intval( $fields['size'] ) );
1778 if ( isset( $fields['minor_edit'] ) ) {
1779 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1781 if ( isset( $fields['deleted'] ) ) {
1782 $record->setVisibility( intval( $fields['deleted'] ) );
1785 if ( isset( $fields['comment'] ) ) {
1786 Assert
::parameterType(
1787 CommentStoreComment
::class,
1791 $record->setComment( $fields['comment'] );
1796 * Load a page revision from a given revision ID number.
1797 * Returns null if no such revision can be found.
1799 * MCR migration note: this corresponds to Revision::loadFromId
1801 * @note direct use is deprecated!
1802 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1804 * @param IDatabase $db
1807 * @return RevisionRecord|null
1809 public function loadRevisionFromId( IDatabase
$db, $id ) {
1810 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1814 * Load either the current, or a specified, revision
1815 * that's attached to a given page. If not attached
1816 * to that page, will return null.
1818 * MCR migration note: this replaces Revision::loadFromPageId
1820 * @note direct use is deprecated!
1821 * @todo remove when unused!
1823 * @param IDatabase $db
1824 * @param int $pageid
1826 * @return RevisionRecord|null
1828 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1829 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1831 $conds['rev_id'] = intval( $id );
1833 $conds[] = 'rev_id=page_latest';
1835 return $this->loadRevisionFromConds( $db, $conds );
1839 * Load either the current, or a specified, revision
1840 * that's attached to a given page. If not attached
1841 * to that page, will return null.
1843 * MCR migration note: this replaces Revision::loadFromTitle
1845 * @note direct use is deprecated!
1846 * @todo remove when unused!
1848 * @param IDatabase $db
1849 * @param Title $title
1852 * @return RevisionRecord|null
1854 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1856 $matchId = intval( $id );
1858 $matchId = 'page_latest';
1861 return $this->loadRevisionFromConds(
1865 'page_namespace' => $title->getNamespace(),
1866 'page_title' => $title->getDBkey()
1874 * Load the revision for the given title with the given timestamp.
1875 * WARNING: Timestamps may in some circumstances not be unique,
1876 * so this isn't the best key to use.
1878 * MCR migration note: this replaces Revision::loadFromTimestamp
1880 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1881 * @todo remove when unused!
1883 * @param IDatabase $db
1884 * @param Title $title
1885 * @param string $timestamp
1886 * @return RevisionRecord|null
1888 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1889 return $this->loadRevisionFromConds( $db,
1891 'rev_timestamp' => $db->timestamp( $timestamp ),
1892 'page_namespace' => $title->getNamespace(),
1893 'page_title' => $title->getDBkey()
1901 * Given a set of conditions, fetch a revision
1903 * This method should be used if we are pretty sure the revision exists.
1904 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1905 * on a replica before hitting the master database.
1907 * MCR migration note: this corresponds to Revision::newFromConds
1909 * @param array $conditions
1910 * @param int $flags (optional)
1911 * @param Title|null $title
1913 * @return RevisionRecord|null
1915 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1916 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1917 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1919 $lb = $this->getDBLoadBalancer();
1921 // Make sure new pending/committed revision are visibile later on
1922 // within web requests to certain avoid bugs like T93866 and T94407.
1924 && !( $flags & self
::READ_LATEST
)
1925 && $lb->getServerCount() > 1
1926 && $lb->hasOrMadeRecentMasterChanges()
1928 $flags = self
::READ_LATEST
;
1929 $dbw = $this->getDBConnection( DB_MASTER
);
1930 $rev = $this->loadRevisionFromConds( $dbw, $conditions, $flags, $title );
1931 $this->releaseDBConnection( $dbw );
1938 * Given a set of conditions, fetch a revision from
1939 * the given database connection.
1941 * MCR migration note: this corresponds to Revision::loadFromConds
1943 * @param IDatabase $db
1944 * @param array $conditions
1945 * @param int $flags (optional)
1946 * @param Title|null $title
1948 * @return RevisionRecord|null
1950 private function loadRevisionFromConds(
1956 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1958 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1967 * Throws an exception if the given database connection does not belong to the wiki this
1968 * RevisionStore is bound to.
1970 * @param IDatabase $db
1971 * @throws MWException
1973 private function checkDatabaseWikiId( IDatabase
$db ) {
1974 $storeWiki = $this->wikiId
;
1975 $dbWiki = $db->getDomainID();
1977 if ( $dbWiki === $storeWiki ) {
1981 // XXX: we really want the default database ID...
1982 $storeWiki = $storeWiki ?
: wfWikiID();
1983 $dbWiki = $dbWiki ?
: wfWikiID();
1985 if ( $dbWiki === $storeWiki ) {
1989 // HACK: counteract encoding imposed by DatabaseDomain
1990 $storeWiki = str_replace( '?h', '-', $storeWiki );
1991 $dbWiki = str_replace( '?h', '-', $dbWiki );
1993 if ( $dbWiki === $storeWiki ) {
1997 throw new MWException( "RevisionStore for $storeWiki "
1998 . "cannot be used with a DB connection for $dbWiki" );
2002 * Given a set of conditions, return a row with the
2003 * fields necessary to build RevisionRecord objects.
2005 * MCR migration note: this corresponds to Revision::fetchFromConds
2007 * @param IDatabase $db
2008 * @param array $conditions
2009 * @param int $flags (optional)
2011 * @return object|false data row as a raw object
2013 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
2014 $this->checkDatabaseWikiId( $db );
2016 $revQuery = $this->getQueryInfo( [ 'page', 'user' ] );
2018 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
2019 $options[] = 'FOR UPDATE';
2021 return $db->selectRow(
2022 $revQuery['tables'],
2023 $revQuery['fields'],
2032 * Finds the ID of a content row for a given revision and slot role.
2033 * This can be used to re-use content rows even while the content ID
2034 * is still missing from SlotRecords, when writing to both the old and
2035 * the new schema during MCR schema migration.
2037 * @todo remove after MCR schema migration is complete.
2039 * @param IDatabase $db
2041 * @param string $role
2045 private function findSlotContentId( IDatabase
$db, $revId, $role ) {
2046 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
2051 $roleId = $this->slotRoleStore
->getId( $role );
2053 'slot_revision_id' => $revId,
2054 'slot_role_id' => $roleId,
2057 $contentId = $db->selectField( 'slots', 'slot_content_id', $conditions, __METHOD__
);
2059 return $contentId ?
: null;
2060 } catch ( NameTableAccessException
$ex ) {
2061 // If the role is missing from the slot_roles table,
2062 // the corresponding row in slots cannot exist.
2068 * Return the tables, fields, and join conditions to be selected to create
2069 * a new RevisionStoreRecord object.
2071 * MCR migration note: this replaces Revision::getQueryInfo
2073 * If the format of fields returned changes in any way then the cache key provided by
2074 * self::getRevisionRowCacheKey should be updated.
2078 * @param array $options Any combination of the following strings
2079 * - 'page': Join with the page table, and select fields to identify the page
2080 * - 'user': Join with the user table, and select the user name
2081 * - 'text': Join with the text table, and select fields to load page text. This
2082 * option is deprecated in MW 1.32 when the MCR migration flag SCHEMA_COMPAT_WRITE_NEW
2083 * is set, and disallowed when SCHEMA_COMPAT_READ_OLD is not set.
2085 * @return array With three keys:
2086 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2087 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2088 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2090 public function getQueryInfo( $options = [] ) {
2097 $ret['tables'][] = 'revision';
2098 $ret['fields'] = array_merge( $ret['fields'], [
2109 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
2110 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
2111 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
2112 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
2114 $actorQuery = $this->actorMigration
->getJoin( 'rev_user' );
2115 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
2116 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
2117 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
2119 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2120 $ret['fields'][] = 'rev_text_id';
2122 if ( $this->contentHandlerUseDB
) {
2123 $ret['fields'][] = 'rev_content_format';
2124 $ret['fields'][] = 'rev_content_model';
2128 if ( in_array( 'page', $options, true ) ) {
2129 $ret['tables'][] = 'page';
2130 $ret['fields'] = array_merge( $ret['fields'], [
2138 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
2141 if ( in_array( 'user', $options, true ) ) {
2142 $ret['tables'][] = 'user';
2143 $ret['fields'] = array_merge( $ret['fields'], [
2146 $u = $actorQuery['fields']['rev_user'];
2147 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
2150 if ( in_array( 'text', $options, true ) ) {
2151 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
2152 throw new InvalidArgumentException( 'text table can no longer be joined directly' );
2153 } elseif ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2154 // NOTE: even when this class is set to not read from the old schema, callers
2155 // should still be able to join against the text table, as long as we are still
2156 // writing the old schema for compatibility.
2157 wfDeprecated( __METHOD__
. ' with `text` option', '1.32' );
2160 $ret['tables'][] = 'text';
2161 $ret['fields'] = array_merge( $ret['fields'], [
2165 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
2172 * Return the tables, fields, and join conditions to be selected to create
2177 * @param array $options Any combination of the following strings
2178 * - 'content': Join with the content table, and select content meta-data fields
2180 * @return array With three keys:
2181 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2182 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2183 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2185 public function getSlotsQueryInfo( $options = [] ) {
2192 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2193 $db = $this->getDBConnectionRef( DB_REPLICA
);
2194 $ret['tables']['slots'] = 'revision';
2196 $ret['fields']['slot_revision_id'] = 'slots.rev_id';
2197 $ret['fields']['slot_content_id'] = 'NULL';
2198 $ret['fields']['slot_origin'] = 'slots.rev_id';
2199 $ret['fields']['role_name'] = $db->addQuotes( 'main' );
2201 if ( in_array( 'content', $options, true ) ) {
2202 $ret['fields']['content_size'] = 'slots.rev_len';
2203 $ret['fields']['content_sha1'] = 'slots.rev_sha1';
2204 $ret['fields']['content_address']
2205 = $db->buildConcat( [ $db->addQuotes( 'tt:' ), 'slots.rev_text_id' ] );
2207 if ( $this->contentHandlerUseDB
) {
2208 $ret['fields']['model_name'] = 'slots.rev_content_model';
2210 $ret['fields']['model_name'] = 'NULL';
2214 $ret['tables'][] = 'slots';
2215 $ret['tables'][] = 'slot_roles';
2216 $ret['fields'] = array_merge( $ret['fields'], [
2222 $ret['joins']['slot_roles'] = [ 'INNER JOIN', [ 'slot_role_id = role_id' ] ];
2224 if ( in_array( 'content', $options, true ) ) {
2225 $ret['tables'][] = 'content';
2226 $ret['tables'][] = 'content_models';
2227 $ret['fields'] = array_merge( $ret['fields'], [
2233 $ret['joins']['content'] = [ 'INNER JOIN', [ 'slot_content_id = content_id' ] ];
2234 $ret['joins']['content_models'] = [ 'INNER JOIN', [ 'content_model = model_id' ] ];
2242 * Return the tables, fields, and join conditions to be selected to create
2243 * a new RevisionArchiveRecord object.
2245 * MCR migration note: this replaces Revision::getArchiveQueryInfo
2249 * @return array With three keys:
2250 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2251 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2252 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2254 public function getArchiveQueryInfo() {
2255 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
2256 $actorQuery = $this->actorMigration
->getJoin( 'ar_user' );
2258 'tables' => [ 'archive' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
2271 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
2272 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
2275 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2276 $ret['fields'][] = 'ar_text_id';
2278 if ( $this->contentHandlerUseDB
) {
2279 $ret['fields'][] = 'ar_content_format';
2280 $ret['fields'][] = 'ar_content_model';
2288 * Do a batched query for the sizes of a set of revisions.
2290 * MCR migration note: this replaces Revision::getParentLengths
2292 * @param int[] $revIds
2293 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2294 * of the corresponding revision.
2296 public function getRevisionSizes( array $revIds ) {
2297 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
2301 * Do a batched query for the sizes of a set of revisions.
2303 * MCR migration note: this replaces Revision::getParentLengths
2305 * @deprecated use RevisionStore::getRevisionSizes instead.
2307 * @param IDatabase $db
2308 * @param int[] $revIds
2309 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2310 * of the corresponding revision.
2312 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
2313 $this->checkDatabaseWikiId( $db );
2317 return $revLens; // empty
2322 [ 'rev_id', 'rev_len' ],
2323 [ 'rev_id' => $revIds ],
2327 foreach ( $res as $row ) {
2328 $revLens[$row->rev_id
] = intval( $row->rev_len
);
2335 * Get previous revision for this title
2337 * MCR migration note: this replaces Revision::getPrevious
2339 * @param RevisionRecord $rev
2340 * @param Title|null $title if known (optional)
2342 * @return RevisionRecord|null
2344 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
2345 if ( $title === null ) {
2346 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2348 $prev = $title->getPreviousRevisionID( $rev->getId() );
2350 return $this->getRevisionByTitle( $title, $prev );
2356 * Get next revision for this title
2358 * MCR migration note: this replaces Revision::getNext
2360 * @param RevisionRecord $rev
2361 * @param Title|null $title if known (optional)
2363 * @return RevisionRecord|null
2365 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
2366 if ( $title === null ) {
2367 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2369 $next = $title->getNextRevisionID( $rev->getId() );
2371 return $this->getRevisionByTitle( $title, $next );
2377 * Get previous revision Id for this page_id
2378 * This is used to populate rev_parent_id on save
2380 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
2382 * @param IDatabase $db
2383 * @param RevisionRecord $rev
2387 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
2388 $this->checkDatabaseWikiId( $db );
2390 if ( $rev->getPageId() === null ) {
2393 # Use page_latest if ID is not given
2394 if ( !$rev->getId() ) {
2395 $prevId = $db->selectField(
2396 'page', 'page_latest',
2397 [ 'page_id' => $rev->getPageId() ],
2401 $prevId = $db->selectField(
2402 'revision', 'rev_id',
2403 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
2405 [ 'ORDER BY' => 'rev_id DESC' ]
2408 return intval( $prevId );
2412 * Get rev_timestamp from rev_id, without loading the rest of the row
2414 * MCR migration note: this replaces Revision::getTimestampFromId
2416 * @param Title $title
2419 * @return string|bool False if not found
2421 public function getTimestampFromId( $title, $id, $flags = 0 ) {
2422 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2424 $conds = [ 'rev_id' => $id ];
2425 $conds['rev_page'] = $title->getArticleID();
2426 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
2428 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
2432 * Get count of revisions per page...not very efficient
2434 * MCR migration note: this replaces Revision::countByPageId
2436 * @param IDatabase $db
2437 * @param int $id Page id
2440 public function countRevisionsByPageId( IDatabase
$db, $id ) {
2441 $this->checkDatabaseWikiId( $db );
2443 $row = $db->selectRow( 'revision',
2444 [ 'revCount' => 'COUNT(*)' ],
2445 [ 'rev_page' => $id ],
2449 return intval( $row->revCount
);
2455 * Get count of revisions per page...not very efficient
2457 * MCR migration note: this replaces Revision::countByTitle
2459 * @param IDatabase $db
2460 * @param Title $title
2463 public function countRevisionsByTitle( IDatabase
$db, $title ) {
2464 $id = $title->getArticleID();
2466 return $this->countRevisionsByPageId( $db, $id );
2472 * Check if no edits were made by other users since
2473 * the time a user started editing the page. Limit to
2474 * 50 revisions for the sake of performance.
2476 * MCR migration note: this replaces Revision::userWasLastToEdit
2478 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
2479 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
2480 * has been deprecated since 1.24.
2482 * @param IDatabase $db The Database to perform the check on.
2483 * @param int $pageId The ID of the page in question
2484 * @param int $userId The ID of the user in question
2485 * @param string $since Look at edits since this time
2487 * @return bool True if the given user was the only one to edit since the given timestamp
2489 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
2490 $this->checkDatabaseWikiId( $db );
2496 $revQuery = $this->getQueryInfo();
2498 $revQuery['tables'],
2500 'rev_user' => $revQuery['fields']['rev_user'],
2503 'rev_page' => $pageId,
2504 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
2507 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
2510 foreach ( $res as $row ) {
2511 if ( $row->rev_user
!= $userId ) {
2519 * Load a revision based on a known page ID and current revision ID from the DB
2521 * This method allows for the use of caching, though accessing anything that normally
2522 * requires permission checks (aside from the text) will trigger a small DB lookup.
2524 * MCR migration note: this replaces Revision::newKnownCurrent
2526 * @param Title $title the associated page title
2527 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
2529 * @return RevisionRecord|bool Returns false if missing
2531 public function getKnownCurrentRevision( Title
$title, $revId ) {
2532 $db = $this->getDBConnectionRef( DB_REPLICA
);
2534 $pageId = $title->getArticleID();
2541 $revId = $title->getLatestRevID();
2546 'No latest revision known for page ' . $title->getPrefixedDBkey()
2547 . ' even though it exists with page ID ' . $pageId
2552 $row = $this->cache
->getWithSetCallback(
2553 // Page/rev IDs passed in from DB to reflect history merges
2554 $this->getRevisionRowCacheKey( $db, $pageId, $revId ),
2555 WANObjectCache
::TTL_WEEK
,
2556 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
2557 $setOpts +
= Database
::getCacheSetOptions( $db );
2560 'rev_page' => intval( $pageId ),
2561 'page_id' => intval( $pageId ),
2562 'rev_id' => intval( $revId ),
2565 $row = $this->fetchRevisionRowFromConds( $db, $conds );
2566 return $row ?
: false; // don't cache negatives
2570 // Reflect revision deletion and user renames
2572 return $this->newRevisionFromRow( $row, 0, $title );
2579 * Get a cache key for use with a row as selected with getQueryInfo( [ 'page', 'user' ] )
2580 * Caching rows without 'page' or 'user' could lead to issues.
2581 * If the format of the rows returned by the query provided by getQueryInfo changes the
2582 * cache key should be updated to avoid conflicts.
2584 * @param IDatabase $db
2585 * @param int $pageId
2589 private function getRevisionRowCacheKey( IDatabase
$db, $pageId, $revId ) {
2590 return $this->cache
->makeGlobalKey(
2591 self
::ROW_CACHE_KEY
,
2598 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.