3 * Service for looking up page revisions.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * Attribution notice: when this file was created, much of its content was taken
21 * from the Revision.php file as present in release 1.30. Refer to the history
22 * of that file for original authorship.
27 namespace MediaWiki\Storage
;
31 use CommentStoreComment
;
34 use DBAccessObjectUtils
;
37 use InvalidArgumentException
;
40 use MediaWiki\Linker\LinkTarget
;
41 use MediaWiki\User\UserIdentity
;
42 use MediaWiki\User\UserIdentityValue
;
45 use MWUnknownContentModelException
;
46 use Psr\Log\LoggerAwareInterface
;
47 use Psr\Log\LoggerInterface
;
48 use Psr\Log\NullLogger
;
55 use Wikimedia\Assert\Assert
;
56 use Wikimedia\Rdbms\Database
;
57 use Wikimedia\Rdbms\DBConnRef
;
58 use Wikimedia\Rdbms\IDatabase
;
59 use Wikimedia\Rdbms\LoadBalancer
;
62 * Service for looking up page revisions.
66 * @note This was written to act as a drop-in replacement for the corresponding
67 * static methods in Revision.
70 implements IDBAccessObject
, RevisionFactory
, RevisionLookup
, LoggerAwareInterface
{
72 const ROW_CACHE_KEY
= 'revision-row-1.29';
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 LoadBalancer $loadBalancer
132 * @param SqlBlobStore $blobStore
133 * @param WANObjectCache $cache
134 * @param CommentStore $commentStore
135 * @param NameTableStore $contentModelStore
136 * @param NameTableStore $slotRoleStore
137 * @param int $mcrMigrationStage An appropriate combination of SCHEMA_COMPAT_XXX flags
138 * @param ActorMigration $actorMigration
139 * @param bool|string $wikiId
141 * @throws MWException if $mcrMigrationStage or $wikiId is invalid.
143 public function __construct(
144 LoadBalancer
$loadBalancer,
145 SqlBlobStore
$blobStore,
146 WANObjectCache
$cache,
147 CommentStore
$commentStore,
148 NameTableStore
$contentModelStore,
149 NameTableStore
$slotRoleStore,
151 ActorMigration
$actorMigration,
154 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
155 Assert
::parameterType( 'integer', $mcrMigrationStage, '$mcrMigrationStage' );
157 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== SCHEMA_COMPAT_READ_BOTH
,
158 '$mcrMigrationStage',
159 'Reading from the old and the new schema at the same time is not supported.'
162 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH
) !== 0,
163 '$mcrMigrationStage',
164 'Reading needs to be enabled for the old or the new schema.'
167 ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) !== 0,
168 '$mcrMigrationStage',
169 'Writing needs to be enabled for the old or the new schema.'
172 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_OLD
) === 0
173 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) !== 0,
174 '$mcrMigrationStage',
175 'Cannot read the old schema when not also writing it.'
178 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_NEW
) === 0
179 ||
( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) !== 0,
180 '$mcrMigrationStage',
181 'Cannot read the new schema when not also writing it.'
184 $this->loadBalancer
= $loadBalancer;
185 $this->blobStore
= $blobStore;
186 $this->cache
= $cache;
187 $this->commentStore
= $commentStore;
188 $this->contentModelStore
= $contentModelStore;
189 $this->slotRoleStore
= $slotRoleStore;
190 $this->mcrMigrationStage
= $mcrMigrationStage;
191 $this->actorMigration
= $actorMigration;
192 $this->wikiId
= $wikiId;
193 $this->logger
= new NullLogger();
197 * @param int $flags A combination of SCHEMA_COMPAT_XXX flags.
198 * @return bool True if all the given flags were set in the $mcrMigrationStage
199 * parameter passed to the constructor.
201 private function hasMcrSchemaFlags( $flags ) {
202 return ( $this->mcrMigrationStage
& $flags ) === $flags;
205 public function setLogger( LoggerInterface
$logger ) {
206 $this->logger
= $logger;
210 * @return bool Whether the store is read-only
212 public function isReadOnly() {
213 return $this->blobStore
->isReadOnly();
219 public function getContentHandlerUseDB() {
220 return $this->contentHandlerUseDB
;
224 * @see $wgContentHandlerUseDB
225 * @param bool $contentHandlerUseDB
226 * @throws MWException
228 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
229 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
)
230 ||
$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
)
232 if ( !$contentHandlerUseDB ) {
233 throw new MWException(
234 'Content model must be stored in the database for multi content revision migration.'
238 $this->contentHandlerUseDB
= $contentHandlerUseDB;
242 * @return LoadBalancer
244 private function getDBLoadBalancer() {
245 return $this->loadBalancer
;
249 * @param int $mode DB_MASTER or DB_REPLICA
253 private function getDBConnection( $mode ) {
254 $lb = $this->getDBLoadBalancer();
255 return $lb->getConnection( $mode, [], $this->wikiId
);
259 * @param int $queryFlags a bit field composed of READ_XXX flags
263 private function getDBConnectionRefForQueryFlags( $queryFlags ) {
264 list( $mode, ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
265 return $this->getDBConnectionRef( $mode );
269 * @param IDatabase $connection
271 private function releaseDBConnection( IDatabase
$connection ) {
272 $lb = $this->getDBLoadBalancer();
273 $lb->reuseConnection( $connection );
277 * @param int $mode DB_MASTER or DB_REPLICA
281 private function getDBConnectionRef( $mode ) {
282 $lb = $this->getDBLoadBalancer();
283 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
287 * Determines the page Title based on the available information.
289 * MCR migration note: this corresponds to Revision::getTitle
291 * @note this method should be private, external use should be avoided!
293 * @param int|null $pageId
294 * @param int|null $revId
295 * @param int $queryFlags
298 * @throws RevisionAccessException
300 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
301 if ( !$pageId && !$revId ) {
302 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
305 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
306 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
307 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
308 $queryFlags = self
::READ_NORMAL
;
311 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false );
312 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
313 $titleFlags = ( $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0 );
315 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
316 if ( $canUseTitleNewFromId ) {
317 // TODO: better foreign title handling (introduce TitleFactory)
318 $title = Title
::newFromID( $pageId, $titleFlags );
324 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
325 $canUseRevId = ( $revId !== null && $revId > 0 );
327 if ( $canUseRevId ) {
328 $dbr = $this->getDBConnectionRef( $dbMode );
329 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
330 $row = $dbr->selectRow(
331 [ 'revision', 'page' ],
340 [ 'rev_id' => $revId ],
343 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
346 // TODO: better foreign title handling (introduce TitleFactory)
347 return Title
::newFromRow( $row );
351 // If we still don't have a title, fallback to master if that wasn't already happening.
352 if ( $dbMode !== DB_MASTER
) {
353 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
356 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
357 [ 'trace' => wfBacktrace() ]
363 throw new RevisionAccessException(
364 "Could not determine title for page ID $pageId and revision ID $revId"
369 * @param mixed $value
370 * @param string $name
372 * @throws IncompleteRevisionException if $value is null
373 * @return mixed $value, if $value is not null
375 private function failOnNull( $value, $name ) {
376 if ( $value === null ) {
377 throw new IncompleteRevisionException(
378 "$name must not be " . var_export( $value, true ) . "!"
386 * @param mixed $value
387 * @param string $name
389 * @throws IncompleteRevisionException if $value is empty
390 * @return mixed $value, if $value is not null
392 private function failOnEmpty( $value, $name ) {
393 if ( $value === null ||
$value === 0 ||
$value === '' ) {
394 throw new IncompleteRevisionException(
395 "$name must not be " . var_export( $value, true ) . "!"
403 * Insert a new revision into the database, returning the new revision record
404 * on success and dies horribly on failure.
406 * MCR migration note: this replaces Revision::insertOn
408 * @param RevisionRecord $rev
409 * @param IDatabase $dbw (master connection)
411 * @throws InvalidArgumentException
412 * @return RevisionRecord the new revision record.
414 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
415 // TODO: pass in a DBTransactionContext instead of a database connection.
416 $this->checkDatabaseWikiId( $dbw );
418 $slotRoles = $rev->getSlotRoles();
420 // Make sure the main slot is always provided throughout migration
421 if ( !in_array( 'main', $slotRoles ) ) {
422 throw new InvalidArgumentException(
423 'main slot must be provided'
427 // If we are not writing into the new schema, we can't support extra slots.
428 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) && $slotRoles !== [ 'main' ] ) {
429 throw new InvalidArgumentException(
430 'Only the main slot is supported when not writing to the MCR enabled schema!'
434 // As long as we are not reading from the new schema, we don't want to write extra slots.
435 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) && $slotRoles !== [ 'main' ] ) {
436 throw new InvalidArgumentException(
437 'Only the main slot is supported when not reading from the MCR enabled schema!'
442 $this->failOnNull( $rev->getSize(), 'size field' );
443 $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
444 $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
445 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
446 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
447 $this->failOnNull( $user->getId(), 'user field' );
448 $this->failOnEmpty( $user->getName(), 'user_text field' );
450 // TODO: we shouldn't need an actual Title here.
451 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
452 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
454 $parentId = $rev->getParentId() === null
455 ?
$this->getPreviousRevisionId( $dbw, $rev )
456 : $rev->getParentId();
458 /** @var RevisionRecord $rev */
459 $rev = $dbw->doAtomicSection(
461 function ( IDatabase
$dbw, $fname ) use (
469 return $this->insertRevisionInternal(
482 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
483 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
484 Assert
::postcondition(
485 $rev->getComment( RevisionRecord
::RAW
) !== null,
486 'revision must have a comment'
488 Assert
::postcondition(
489 $rev->getUser( RevisionRecord
::RAW
) !== null,
490 'revision must have a user'
493 // Trigger exception if the main slot is missing.
494 // Technically, this could go away after MCR migration: while
495 // calling code may require a main slot to exist, RevisionStore
496 // really should not know or care about that requirement.
497 $rev->getSlot( 'main', RevisionRecord
::RAW
);
499 foreach ( $slotRoles as $role ) {
500 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
501 Assert
::postcondition(
502 $slot->getContent() !== null,
503 $role . ' slot must have content'
505 Assert
::postcondition(
506 $slot->hasRevision(),
507 $role . ' slot must have a revision associated'
511 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
513 // TODO: deprecate in 1.32!
514 $legacyRevision = new Revision( $rev );
515 Hooks
::run( 'RevisionInsertComplete', [ &$legacyRevision, null, null ] );
520 private function insertRevisionInternal(
524 CommentStoreComment
$comment,
529 $slotRoles = $rev->getSlotRoles();
531 $revisionRow = $this->insertRevisionRowOn(
538 $revisionId = $revisionRow['rev_id'];
541 BlobStore
::PAGE_HINT
=> $pageId,
542 BlobStore
::REVISION_HINT
=> $revisionId,
543 BlobStore
::PARENT_HINT
=> $parentId,
547 foreach ( $slotRoles as $role ) {
548 $slot = $rev->getSlot( $role, RevisionRecord
::RAW
);
550 if ( $slot->hasRevision() ) {
551 // If the SlotRecord already has a revision ID set, this means it already exists
552 // in the database, and should already belong to the current revision.
553 // TODO: properly abort transaction if the assertion fails!
555 $slot->getRevision() === $revisionId,
556 'slot role ' . $slot->getRole(),
557 'Existing slot should belong to revision '
558 . $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
561 // Slot exists, nothing to do, move along.
562 // This happens when restoring archived revisions.
564 $newSlots[$role] = $slot;
566 // Write the main slot's text ID to the revision table for backwards compatibility
567 if ( $slot->getRole() === 'main'
568 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
570 $blobAddress = $slot->getAddress();
571 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
574 $newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $title, $blobHints );
578 $this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
580 $rev = new RevisionStoreRecord(
584 (object)$revisionRow,
585 new RevisionSlots( $newSlots ),
593 * @param IDatabase $dbw
594 * @param int $revisionId
595 * @param string &$blobAddress (may change!)
597 private function updateRevisionTextId( IDatabase
$dbw, $revisionId, &$blobAddress ) {
598 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
600 throw new LogicException(
601 'Blob address not supported in 1.29 database schema: ' . $blobAddress
605 // getTextIdFromAddress() is free to insert something into the text table, so $textId
606 // may be a new value, not anything already contained in $blobAddress.
607 $blobAddress = SqlBlobStore
::makeAddressFromTextId( $textId );
611 [ 'rev_text_id' => $textId ],
612 [ 'rev_id' => $revisionId ],
618 * @param IDatabase $dbw
619 * @param int $revisionId
620 * @param SlotRecord $protoSlot
621 * @param Title $title
622 * @param array $blobHints See the BlobStore::XXX_HINT constants
625 private function insertSlotOn(
628 SlotRecord
$protoSlot,
630 array $blobHints = []
632 if ( $protoSlot->hasAddress() ) {
633 $blobAddress = $protoSlot->getAddress();
635 $blobAddress = $this->storeContentBlob( $protoSlot, $title, $blobHints );
638 // Write the main slot's text ID to the revision table for backwards compatibility
639 if ( $protoSlot->getRole() === 'main'
640 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
)
642 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
645 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
646 if ( $protoSlot->hasContentId() ) {
647 $contentId = $protoSlot->getContentId();
649 $contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
652 $this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
657 $savedSlot = SlotRecord
::newSaved(
668 * Insert IP revision into ip_changes for use when querying for a range.
669 * @param IDatabase $dbw
671 * @param RevisionRecord $rev
672 * @param int $revisionId
674 private function insertIpChangesRow(
680 if ( $user->getId() === 0 && IP
::isValid( $user->getName() ) ) {
682 'ipc_rev_id' => $revisionId,
683 'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
684 'ipc_hex' => IP
::toHex( $user->getName() ),
686 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
691 * @param IDatabase $dbw
692 * @param RevisionRecord $rev
693 * @param Title $title
694 * @param int $parentId
696 * @return array a revision table row
698 * @throws MWException
699 * @throws MWUnknownContentModelException
701 private function insertRevisionRowOn(
707 $revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $title, $parentId );
709 list( $commentFields, $commentCallback ) =
710 $this->commentStore
->insertWithTempTable(
713 $rev->getComment( RevisionRecord
::RAW
)
715 $revisionRow +
= $commentFields;
717 list( $actorFields, $actorCallback ) =
718 $this->actorMigration
->getInsertValuesWithTempTable(
721 $rev->getUser( RevisionRecord
::RAW
)
723 $revisionRow +
= $actorFields;
725 $dbw->insert( 'revision', $revisionRow, __METHOD__
);
727 if ( !isset( $revisionRow['rev_id'] ) ) {
728 // only if auto-increment was used
729 $revisionRow['rev_id'] = intval( $dbw->insertId() );
732 $commentCallback( $revisionRow['rev_id'] );
733 $actorCallback( $revisionRow['rev_id'], $revisionRow );
739 * @param IDatabase $dbw
740 * @param RevisionRecord $rev
741 * @param Title $title
742 * @param int $parentId
744 * @return array [ 0 => array $revisionRow, 1 => callable ]
745 * @throws MWException
746 * @throws MWUnknownContentModelException
748 private function getBaseRevisionRow(
754 // Record the edit in revisions
756 'rev_page' => $rev->getPageId(),
757 'rev_parent_id' => $parentId,
758 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
759 'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
760 'rev_deleted' => $rev->getVisibility(),
761 'rev_len' => $rev->getSize(),
762 'rev_sha1' => $rev->getSha1(),
765 if ( $rev->getId() !== null ) {
766 // Needed to restore revisions with their original ID
767 $revisionRow['rev_id'] = $rev->getId();
770 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
771 // In non MCR mode this IF section will relate to the main slot
772 $mainSlot = $rev->getSlot( 'main' );
773 $model = $mainSlot->getModel();
774 $format = $mainSlot->getFormat();
776 // MCR migration note: rev_content_model and rev_content_format will go away
777 if ( $this->contentHandlerUseDB
) {
778 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
779 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
781 $revisionRow['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
782 $revisionRow['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
790 * @param SlotRecord $slot
791 * @param Title $title
792 * @param array $blobHints See the BlobStore::XXX_HINT constants
794 * @throws MWException
795 * @return string the blob address
797 private function storeContentBlob(
800 array $blobHints = []
802 $content = $slot->getContent();
803 $format = $content->getDefaultFormat();
804 $model = $content->getModel();
806 $this->checkContent( $content, $title );
808 return $this->blobStore
->storeBlob(
809 $content->serialize( $format ),
810 // These hints "leak" some information from the higher abstraction layer to
811 // low level storage to allow for optimization.
815 BlobStore
::DESIGNATION_HINT
=> 'page-content',
816 BlobStore
::ROLE_HINT
=> $slot->getRole(),
817 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
818 BlobStore
::MODEL_HINT
=> $model,
819 BlobStore
::FORMAT_HINT
=> $format,
826 * @param SlotRecord $slot
827 * @param IDatabase $dbw
828 * @param int $revisionId
829 * @param int $contentId
831 private function insertSlotRowOn( SlotRecord
$slot, IDatabase
$dbw, $revisionId, $contentId ) {
833 'slot_revision_id' => $revisionId,
834 'slot_role_id' => $this->slotRoleStore
->acquireId( $slot->getRole() ),
835 'slot_content_id' => $contentId,
836 // If the slot has a specific origin use that ID, otherwise use the ID of the revision
837 // that we just inserted.
838 'slot_origin' => $slot->hasOrigin() ?
$slot->getOrigin() : $revisionId,
840 $dbw->insert( 'slots', $slotRow, __METHOD__
);
844 * @param SlotRecord $slot
845 * @param IDatabase $dbw
846 * @param string $blobAddress
847 * @return int content row ID
849 private function insertContentRowOn( SlotRecord
$slot, IDatabase
$dbw, $blobAddress ) {
851 'content_size' => $slot->getSize(),
852 'content_sha1' => $slot->getSha1(),
853 'content_model' => $this->contentModelStore
->acquireId( $slot->getModel() ),
854 'content_address' => $blobAddress,
856 $dbw->insert( 'content', $contentRow, __METHOD__
);
857 return intval( $dbw->insertId() );
861 * MCR migration note: this corresponds to Revision::checkContentModel
863 * @param Content $content
864 * @param Title $title
866 * @throws MWException
867 * @throws MWUnknownContentModelException
869 private function checkContent( Content
$content, Title
$title ) {
870 // Note: may return null for revisions that have not yet been inserted
872 $model = $content->getModel();
873 $format = $content->getDefaultFormat();
874 $handler = $content->getContentHandler();
878 if ( !$handler->isSupportedFormat( $format ) ) {
879 throw new MWException( "Can't use format $format with content model $model on $name" );
882 if ( !$this->contentHandlerUseDB
) {
883 // if $wgContentHandlerUseDB is not set,
884 // all revisions must use the default content model and format.
886 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
887 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
888 $defaultFormat = $defaultHandler->getDefaultFormat();
890 if ( $model != $defaultModel ) {
891 throw new MWException( "Can't save non-default content model with "
892 . "\$wgContentHandlerUseDB disabled: model is $model, "
893 . "default for $name is $defaultModel"
897 if ( $format != $defaultFormat ) {
898 throw new MWException( "Can't use non-default content format with "
899 . "\$wgContentHandlerUseDB disabled: format is $format, "
900 . "default for $name is $defaultFormat"
905 if ( !$content->isValid() ) {
906 throw new MWException(
907 "New content for $name is not valid! Content model is $model"
913 * Create a new null-revision for insertion into a page's
914 * history. This will not re-save the text, but simply refer
915 * to the text from the previous version.
917 * Such revisions can for instance identify page rename
918 * operations and other such meta-modifications.
920 * @note: This method grabs a FOR UPDATE lock on the relevant row of the page table,
921 * to prevent a new revision from being inserted before the null revision has been written
924 * MCR migration note: this replaces Revision::newNullRevision
926 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
929 * @param IDatabase $dbw used for obtaining the lock on the page table row
930 * @param Title $title Title of the page to read from
931 * @param CommentStoreComment $comment RevisionRecord's summary
932 * @param bool $minor Whether the revision should be considered as minor
933 * @param User $user The user to attribute the revision to
935 * @return RevisionRecord|null RevisionRecord or null on error
937 public function newNullRevision(
940 CommentStoreComment
$comment,
944 $this->checkDatabaseWikiId( $dbw );
946 // T51581: Lock the page table row to ensure no other process
947 // is adding a revision to the page at the same time.
948 // Avoid locking extra tables, compare T191892.
949 $pageLatest = $dbw->selectField(
952 [ 'page_id' => $title->getArticleID() ],
957 if ( !$pageLatest ) {
961 // Fetch the actual revision row from master, without locking all extra tables.
962 $oldRevision = $this->loadRevisionFromConds(
964 [ 'rev_id' => intval( $pageLatest ) ],
969 // Construct the new revision
970 $timestamp = wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
971 $newRevision = MutableRevisionRecord
::newFromParentRevision( $oldRevision );
973 $newRevision->setComment( $comment );
974 $newRevision->setUser( $user );
975 $newRevision->setTimestamp( $timestamp );
976 $newRevision->setMinorEdit( $minor );
982 * MCR migration note: this replaces Revision::isUnpatrolled
984 * @todo This is overly specific, so move or kill this method.
986 * @param RevisionRecord $rev
988 * @return int Rcid of the unpatrolled row, zero if there isn't one
990 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
991 $rc = $this->getRecentChange( $rev );
992 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == RecentChange
::PRC_UNPATROLLED
) {
993 return $rc->getAttribute( 'rc_id' );
1000 * Get the RC object belonging to the current revision, if there's one
1002 * MCR migration note: this replaces Revision::getRecentChange
1004 * @todo move this somewhere else?
1006 * @param RevisionRecord $rev
1007 * @param int $flags (optional) $flags include:
1008 * IDBAccessObject::READ_LATEST: Select the data from the master
1010 * @return null|RecentChange
1012 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
1013 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
1014 $db = $this->getDBConnection( $dbType );
1016 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
1018 if ( !$userIdentity ) {
1019 // If the revision has no user identity, chances are it never went
1020 // into the database, and doesn't have an RC entry.
1024 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
1025 $actorWhere = $this->actorMigration
->getWhere( $db, 'rc_user', $rev->getUser(), false );
1026 $rc = RecentChange
::newFromConds(
1028 $actorWhere['conds'],
1029 'rc_timestamp' => $db->timestamp( $rev->getTimestamp() ),
1030 'rc_this_oldid' => $rev->getId()
1036 $this->releaseDBConnection( $db );
1038 // XXX: cache this locally? Glue it to the RevisionRecord?
1043 * Maps fields of the archive row to corresponding revision rows.
1045 * @param object $archiveRow
1047 * @return object a revision row object, corresponding to $archiveRow.
1049 private static function mapArchiveFields( $archiveRow ) {
1051 // keep with ar prefix:
1054 // not the same suffix:
1055 'ar_page_id' => 'rev_page',
1056 'ar_rev_id' => 'rev_id',
1059 'ar_text_id' => 'rev_text_id',
1060 'ar_timestamp' => 'rev_timestamp',
1061 'ar_user_text' => 'rev_user_text',
1062 'ar_user' => 'rev_user',
1063 'ar_actor' => 'rev_actor',
1064 'ar_minor_edit' => 'rev_minor_edit',
1065 'ar_deleted' => 'rev_deleted',
1066 'ar_len' => 'rev_len',
1067 'ar_parent_id' => 'rev_parent_id',
1068 'ar_sha1' => 'rev_sha1',
1069 'ar_comment' => 'rev_comment',
1070 'ar_comment_cid' => 'rev_comment_cid',
1071 'ar_comment_id' => 'rev_comment_id',
1072 'ar_comment_text' => 'rev_comment_text',
1073 'ar_comment_data' => 'rev_comment_data',
1074 'ar_comment_old' => 'rev_comment_old',
1075 'ar_content_format' => 'rev_content_format',
1076 'ar_content_model' => 'rev_content_model',
1079 $revRow = new stdClass();
1080 foreach ( $fieldMap as $arKey => $revKey ) {
1081 if ( property_exists( $archiveRow, $arKey ) ) {
1082 $revRow->$revKey = $archiveRow->$arKey;
1090 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
1092 * @param object|array $row Either a database row or an array
1093 * @param int $queryFlags for callbacks
1094 * @param Title $title
1096 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
1097 * @throws MWException
1099 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
1100 $mainSlotRow = new stdClass();
1101 $mainSlotRow->role_name
= 'main';
1102 $mainSlotRow->model_name
= null;
1103 $mainSlotRow->slot_revision_id
= null;
1104 $mainSlotRow->content_address
= null;
1110 if ( is_object( $row ) ) {
1111 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1112 // Don't emulate from a row when using the new schema.
1113 // Emulating from an array is still OK.
1114 throw new LogicException( 'Can\'t emulate the main slot when using MCR schema.' );
1118 if ( !isset( $row->rev_id
) && ( isset( $row->ar_user
) ||
isset( $row->ar_actor
) ) ) {
1119 $row = $this->mapArchiveFields( $row );
1122 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
1123 $mainSlotRow->content_address
= SqlBlobStore
::makeAddressFromTextId(
1128 // This is used by null-revisions
1129 $mainSlotRow->slot_origin
= isset( $row->slot_origin
)
1130 ?
intval( $row->slot_origin
)
1133 if ( isset( $row->old_text
) ) {
1134 // this happens when the text-table gets joined directly, in the pre-1.30 schema
1135 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
1136 // Check against selects that might have not included old_flags
1137 if ( !property_exists( $row, 'old_flags' ) ) {
1138 throw new InvalidArgumentException( 'old_flags was not set in $row' );
1140 $blobFlags = $row->old_flags ??
'';
1143 $mainSlotRow->slot_revision_id
= intval( $row->rev_id
);
1145 $mainSlotRow->content_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
1146 $mainSlotRow->content_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
1147 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
1148 ?
strval( $row->rev_content_model
)
1150 // XXX: in the future, we'll probably always use the default format, and drop content_format
1151 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
1152 ?
strval( $row->rev_content_format
)
1154 } elseif ( is_array( $row ) ) {
1155 $mainSlotRow->slot_revision_id
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
1157 $mainSlotRow->slot_origin
= isset( $row['slot_origin'] )
1158 ?
intval( $row['slot_origin'] )
1160 $mainSlotRow->content_address
= isset( $row['text_id'] )
1161 ? SqlBlobStore
::makeAddressFromTextId( intval( $row['text_id'] ) )
1163 $mainSlotRow->content_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
1164 $mainSlotRow->content_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
1166 $mainSlotRow->model_name
= isset( $row['content_model'] )
1167 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
1168 // XXX: in the future, we'll probably always use the default format, and drop content_format
1169 $mainSlotRow->format_name
= isset( $row['content_format'] )
1170 ?
strval( $row['content_format'] ) : null;
1171 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
1172 // XXX: If the flags field is not set then $blobFlags should be null so that no
1173 // decoding will happen. An empty string will result in default decodings.
1174 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
1176 // if we have a Content object, override mText and mContentModel
1177 if ( !empty( $row['content'] ) ) {
1178 if ( !( $row['content'] instanceof Content
) ) {
1179 throw new MWException( 'content field must contain a Content object.' );
1182 /** @var Content $content */
1183 $content = $row['content'];
1184 $handler = $content->getContentHandler();
1186 $mainSlotRow->model_name
= $content->getModel();
1188 // XXX: in the future, we'll probably always use the default format.
1189 if ( $mainSlotRow->format_name
=== null ) {
1190 $mainSlotRow->format_name
= $handler->getDefaultFormat();
1194 throw new MWException( 'Revision constructor passed invalid row format.' );
1197 // With the old schema, the content changes with every revision,
1198 // except for null-revisions.
1199 if ( !isset( $mainSlotRow->slot_origin
) ) {
1200 $mainSlotRow->slot_origin
= $mainSlotRow->slot_revision_id
;
1203 if ( $mainSlotRow->model_name
=== null ) {
1204 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
1205 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
1206 // TODO: MCR: deprecate $title->getModel().
1207 return ContentHandler
::getDefaultModelFor( $title );
1212 // XXX: We should perhaps fail if $blobData is null and $mainSlotRow->content_address
1213 // is missing, but "empty revisions" with no content are used in some edge cases.
1215 $content = function ( SlotRecord
$slot )
1216 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
1218 return $this->loadSlotContent(
1222 $mainSlotRow->format_name
,
1228 // NOTE: this callback will be looped through RevisionSlot::newInherited(), allowing
1229 // the inherited slot to have the same content_id as the original slot. In that case,
1230 // $slot will be the inherited slot, while $mainSlotRow still refers to the original slot.
1231 $mainSlotRow->slot_content_id
=
1232 function ( SlotRecord
$slot ) use ( $queryFlags, $mainSlotRow ) {
1233 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1234 return $this->findSlotContentId( $db, $mainSlotRow->slot_revision_id
, 'main' );
1237 return new SlotRecord( $mainSlotRow, $content );
1241 * Loads a Content object based on a slot row.
1243 * This method does not call $slot->getContent(), and may be used as a callback
1244 * called by $slot->getContent().
1246 * MCR migration note: this roughly corresponds to Revision::getContentInternal
1248 * @param SlotRecord $slot The SlotRecord to load content for
1249 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
1250 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
1251 * Use null if no processing should happen. That is in constrast to the empty string,
1252 * which causes the blob to be decoded according to the configured legacy encoding.
1253 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
1254 * @param int $queryFlags
1256 * @throws RevisionAccessException
1259 private function loadSlotContent(
1266 if ( $blobData !== null ) {
1267 Assert
::parameterType( 'string', $blobData, '$blobData' );
1268 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
1270 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
1272 if ( $blobFlags === null ) {
1273 // No blob flags, so use the blob verbatim.
1276 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
1277 if ( $data === false ) {
1278 throw new RevisionAccessException(
1279 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
1285 $address = $slot->getAddress();
1287 $data = $this->blobStore
->getBlob( $address, $queryFlags );
1288 } catch ( BlobAccessException
$e ) {
1289 throw new RevisionAccessException(
1290 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
1295 // Unserialize content
1296 $handler = ContentHandler
::getForModelID( $slot->getModel() );
1298 $content = $handler->unserializeContent( $data, $blobFormat );
1303 * Load a page revision from a given revision ID number.
1304 * Returns null if no such revision can be found.
1306 * MCR migration note: this replaces Revision::newFromId
1309 * IDBAccessObject::READ_LATEST: Select the data from the master
1310 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1313 * @param int $flags (optional)
1314 * @return RevisionRecord|null
1316 public function getRevisionById( $id, $flags = 0 ) {
1317 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
1321 * Load either the current, or a specified, revision
1322 * that's attached to a given link target. If not attached
1323 * to that link target, will return null.
1325 * MCR migration note: this replaces Revision::newFromTitle
1328 * IDBAccessObject::READ_LATEST: Select the data from the master
1329 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1331 * @param LinkTarget $linkTarget
1332 * @param int $revId (optional)
1333 * @param int $flags Bitfield (optional)
1334 * @return RevisionRecord|null
1336 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
1338 'page_namespace' => $linkTarget->getNamespace(),
1339 'page_title' => $linkTarget->getDBkey()
1342 // Use the specified revision ID.
1343 // Note that we use newRevisionFromConds here because we want to retry
1344 // and fall back to master if the page is not found on a replica.
1345 // Since the caller supplied a revision ID, we are pretty sure the revision is
1346 // supposed to exist, so we should try hard to find it.
1347 $conds['rev_id'] = $revId;
1348 return $this->newRevisionFromConds( $conds, $flags );
1350 // Use a join to get the latest revision.
1351 // Note that we don't use newRevisionFromConds here because we don't want to retry
1352 // and fall back to master. The assumption is that we only want to force the fallback
1353 // if we are quite sure the revision exists because the caller supplied a revision ID.
1354 // If the page isn't found at all on a replica, it probably simply does not exist.
1355 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1357 $conds[] = 'rev_id=page_latest';
1358 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1365 * Load either the current, or a specified, revision
1366 * that's attached to a given page ID.
1367 * Returns null if no such revision can be found.
1369 * MCR migration note: this replaces Revision::newFromPageId
1372 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
1373 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1375 * @param int $pageId
1376 * @param int $revId (optional)
1377 * @param int $flags Bitfield (optional)
1378 * @return RevisionRecord|null
1380 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1381 $conds = [ 'page_id' => $pageId ];
1383 // Use the specified revision ID.
1384 // Note that we use newRevisionFromConds here because we want to retry
1385 // and fall back to master if the page is not found on a replica.
1386 // Since the caller supplied a revision ID, we are pretty sure the revision is
1387 // supposed to exist, so we should try hard to find it.
1388 $conds['rev_id'] = $revId;
1389 return $this->newRevisionFromConds( $conds, $flags );
1391 // Use a join to get the latest revision.
1392 // Note that we don't use newRevisionFromConds here because we don't want to retry
1393 // and fall back to master. The assumption is that we only want to force the fallback
1394 // if we are quite sure the revision exists because the caller supplied a revision ID.
1395 // If the page isn't found at all on a replica, it probably simply does not exist.
1396 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1398 $conds[] = 'rev_id=page_latest';
1399 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1406 * Load the revision for the given title with the given timestamp.
1407 * WARNING: Timestamps may in some circumstances not be unique,
1408 * so this isn't the best key to use.
1410 * MCR migration note: this replaces Revision::loadFromTimestamp
1412 * @param Title $title
1413 * @param string $timestamp
1414 * @return RevisionRecord|null
1416 public function getRevisionByTimestamp( $title, $timestamp ) {
1417 $db = $this->getDBConnection( DB_REPLICA
);
1418 return $this->newRevisionFromConds(
1420 'rev_timestamp' => $db->timestamp( $timestamp ),
1421 'page_namespace' => $title->getNamespace(),
1422 'page_title' => $title->getDBkey()
1430 * @param int $revId The revision to load slots for.
1431 * @param int $queryFlags
1433 * @return SlotRecord[]
1435 private function loadSlotRecords( $revId, $queryFlags ) {
1436 $revQuery = self
::getSlotsQueryInfo( [ 'content' ] );
1438 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
1439 $db = $this->getDBConnectionRef( $dbMode );
1442 $revQuery['tables'],
1443 $revQuery['fields'],
1445 'slot_revision_id' => $revId,
1454 foreach ( $res as $row ) {
1455 $contentCallback = function ( SlotRecord
$slot ) use ( $queryFlags, $row ) {
1456 return $this->loadSlotContent( $slot, null, null, null, $queryFlags );
1459 $slots[$row->role_name
] = new SlotRecord( $row, $contentCallback );
1462 if ( !isset( $slots['main'] ) ) {
1463 throw new RevisionAccessException(
1464 'Main slot of revision ' . $revId . ' not found in database!'
1472 * Factory method for RevisionSlots.
1474 * @note If other code has a need to construct RevisionSlots objects, this should be made
1475 * public, since RevisionSlots instances should not be constructed directly.
1478 * @param object $revisionRow
1479 * @param int $queryFlags
1480 * @param Title $title
1482 * @return RevisionSlots
1483 * @throws MWException
1485 private function newRevisionSlots(
1491 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW
) ) {
1492 $mainSlot = $this->emulateMainSlot_1_29( $revisionRow, $queryFlags, $title );
1493 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1495 // XXX: do we need the same kind of caching here
1496 // that getKnownCurrentRevision uses (if $revId == page_latest?)
1498 $slots = new RevisionSlots( function () use( $revId, $queryFlags ) {
1499 return $this->loadSlotRecords( $revId, $queryFlags );
1507 * Make a fake revision object from an archive table row. This is queried
1508 * for permissions or even inserted (as in Special:Undelete)
1510 * MCR migration note: this replaces Revision::newFromArchiveRow
1512 * @param object $row
1513 * @param int $queryFlags
1514 * @param Title|null $title
1515 * @param array $overrides associative array with fields of $row to override. This may be
1516 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1517 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1518 * override ar_parent_id.
1520 * @return RevisionRecord
1521 * @throws MWException
1523 public function newRevisionFromArchiveRow(
1526 Title
$title = null,
1527 array $overrides = []
1529 Assert
::parameterType( 'object', $row, '$row' );
1531 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1532 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1534 if ( !$title && isset( $overrides['title'] ) ) {
1535 if ( !( $overrides['title'] instanceof Title
) ) {
1536 throw new MWException( 'title field override must contain a Title object.' );
1539 $title = $overrides['title'];
1542 if ( !isset( $title ) ) {
1543 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1544 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1546 throw new InvalidArgumentException(
1547 'A Title or ar_namespace and ar_title must be given'
1552 foreach ( $overrides as $key => $value ) {
1554 $row->$field = $value;
1558 $user = User
::newFromAnyId(
1559 $row->ar_user ??
null,
1560 $row->ar_user_text ??
null,
1561 $row->ar_actor ??
null
1563 } catch ( InvalidArgumentException
$ex ) {
1564 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1565 $user = new UserIdentityValue( 0, '', 0 );
1568 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1569 // Legacy because $row may have come from self::selectFields()
1570 $comment = $this->commentStore
->getCommentLegacy( $db, 'ar_comment', $row, true );
1572 $slots = $this->newRevisionSlots( $row->ar_rev_id
, $row, $queryFlags, $title );
1574 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1578 * @see RevisionFactory::newRevisionFromRow
1580 * MCR migration note: this replaces Revision::newFromRow
1582 * @param object $row
1583 * @param int $queryFlags
1584 * @param Title|null $title
1586 * @return RevisionRecord
1588 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1589 Assert
::parameterType( 'object', $row, '$row' );
1592 $pageId = $row->rev_page ??
0; // XXX: also check page_id?
1593 $revId = $row->rev_id ??
0;
1595 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1598 if ( !isset( $row->page_latest
) ) {
1599 $row->page_latest
= $title->getLatestRevID();
1600 if ( $row->page_latest
=== 0 && $title->exists() ) {
1601 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1606 $user = User
::newFromAnyId(
1607 $row->rev_user ??
null,
1608 $row->rev_user_text ??
null,
1609 $row->rev_actor ??
null
1611 } catch ( InvalidArgumentException
$ex ) {
1612 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1613 $user = new UserIdentityValue( 0, '', 0 );
1616 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1617 // Legacy because $row may have come from self::selectFields()
1618 $comment = $this->commentStore
->getCommentLegacy( $db, 'rev_comment', $row, true );
1620 $slots = $this->newRevisionSlots( $row->rev_id
, $row, $queryFlags, $title );
1622 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1626 * Constructs a new MutableRevisionRecord based on the given associative array following
1627 * the MW1.29 convention for the Revision constructor.
1629 * MCR migration note: this replaces Revision::newFromRow
1631 * @param array $fields
1632 * @param int $queryFlags
1633 * @param Title|null $title
1635 * @return MutableRevisionRecord
1636 * @throws MWException
1637 * @throws RevisionAccessException
1639 public function newMutableRevisionFromArray(
1644 if ( !$title && isset( $fields['title'] ) ) {
1645 if ( !( $fields['title'] instanceof Title
) ) {
1646 throw new MWException( 'title field must contain a Title object.' );
1649 $title = $fields['title'];
1653 $pageId = $fields['page'] ??
0;
1654 $revId = $fields['id'] ??
0;
1656 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1659 if ( !isset( $fields['page'] ) ) {
1660 $fields['page'] = $title->getArticleID( $queryFlags );
1663 // if we have a content object, use it to set the model and type
1664 if ( !empty( $fields['content'] ) ) {
1665 if ( !( $fields['content'] instanceof Content
) && !is_array( $fields['content'] ) ) {
1666 throw new MWException(
1667 'content field must contain a Content object or an array of Content objects.'
1672 if ( !empty( $fields['text_id'] ) ) {
1673 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
1674 throw new MWException( "The text_id field is only available in the pre-MCR schema" );
1677 if ( !empty( $fields['content'] ) ) {
1678 throw new MWException(
1679 "Text already stored in external store (id {$fields['text_id']}), " .
1680 "can't specify content object"
1686 isset( $fields['comment'] )
1687 && !( $fields['comment'] instanceof CommentStoreComment
)
1689 $commentData = $fields['comment_data'] ??
null;
1691 if ( $fields['comment'] instanceof Message
) {
1692 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1697 $commentText = trim( strval( $fields['comment'] ) );
1698 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1705 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1706 $this->initializeMutableRevisionFromArray( $revision, $fields );
1708 if ( isset( $fields['content'] ) && is_array( $fields['content'] ) ) {
1709 foreach ( $fields['content'] as $role => $content ) {
1710 $revision->setContent( $role, $content );
1713 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1714 $revision->setSlot( $mainSlot );
1721 * @param MutableRevisionRecord $record
1722 * @param array $fields
1724 private function initializeMutableRevisionFromArray(
1725 MutableRevisionRecord
$record,
1728 /** @var UserIdentity $user */
1731 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1732 $user = $fields['user'];
1735 $user = User
::newFromAnyId(
1736 $fields['user'] ??
null,
1737 $fields['user_text'] ??
null,
1738 $fields['actor'] ??
null
1740 } catch ( InvalidArgumentException
$ex ) {
1746 $record->setUser( $user );
1749 $timestamp = isset( $fields['timestamp'] )
1750 ?
strval( $fields['timestamp'] )
1751 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1753 $record->setTimestamp( $timestamp );
1755 if ( isset( $fields['page'] ) ) {
1756 $record->setPageId( intval( $fields['page'] ) );
1759 if ( isset( $fields['id'] ) ) {
1760 $record->setId( intval( $fields['id'] ) );
1762 if ( isset( $fields['parent_id'] ) ) {
1763 $record->setParentId( intval( $fields['parent_id'] ) );
1766 if ( isset( $fields['sha1'] ) ) {
1767 $record->setSha1( $fields['sha1'] );
1769 if ( isset( $fields['size'] ) ) {
1770 $record->setSize( intval( $fields['size'] ) );
1773 if ( isset( $fields['minor_edit'] ) ) {
1774 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1776 if ( isset( $fields['deleted'] ) ) {
1777 $record->setVisibility( intval( $fields['deleted'] ) );
1780 if ( isset( $fields['comment'] ) ) {
1781 Assert
::parameterType(
1782 CommentStoreComment
::class,
1786 $record->setComment( $fields['comment'] );
1791 * Load a page revision from a given revision ID number.
1792 * Returns null if no such revision can be found.
1794 * MCR migration note: this corresponds to Revision::loadFromId
1796 * @note direct use is deprecated!
1797 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1799 * @param IDatabase $db
1802 * @return RevisionRecord|null
1804 public function loadRevisionFromId( IDatabase
$db, $id ) {
1805 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1809 * Load either the current, or a specified, revision
1810 * that's attached to a given page. If not attached
1811 * to that page, will return null.
1813 * MCR migration note: this replaces Revision::loadFromPageId
1815 * @note direct use is deprecated!
1816 * @todo remove when unused!
1818 * @param IDatabase $db
1819 * @param int $pageid
1821 * @return RevisionRecord|null
1823 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1824 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1826 $conds['rev_id'] = intval( $id );
1828 $conds[] = 'rev_id=page_latest';
1830 return $this->loadRevisionFromConds( $db, $conds );
1834 * Load either the current, or a specified, revision
1835 * that's attached to a given page. If not attached
1836 * to that page, will return null.
1838 * MCR migration note: this replaces Revision::loadFromTitle
1840 * @note direct use is deprecated!
1841 * @todo remove when unused!
1843 * @param IDatabase $db
1844 * @param Title $title
1847 * @return RevisionRecord|null
1849 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1851 $matchId = intval( $id );
1853 $matchId = 'page_latest';
1856 return $this->loadRevisionFromConds(
1860 'page_namespace' => $title->getNamespace(),
1861 'page_title' => $title->getDBkey()
1869 * Load the revision for the given title with the given timestamp.
1870 * WARNING: Timestamps may in some circumstances not be unique,
1871 * so this isn't the best key to use.
1873 * MCR migration note: this replaces Revision::loadFromTimestamp
1875 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1876 * @todo remove when unused!
1878 * @param IDatabase $db
1879 * @param Title $title
1880 * @param string $timestamp
1881 * @return RevisionRecord|null
1883 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1884 return $this->loadRevisionFromConds( $db,
1886 'rev_timestamp' => $db->timestamp( $timestamp ),
1887 'page_namespace' => $title->getNamespace(),
1888 'page_title' => $title->getDBkey()
1896 * Given a set of conditions, fetch a revision
1898 * This method should be used if we are pretty sure the revision exists.
1899 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1900 * on a replica before hitting the master database.
1902 * MCR migration note: this corresponds to Revision::newFromConds
1904 * @param array $conditions
1905 * @param int $flags (optional)
1906 * @param Title|null $title
1908 * @return RevisionRecord|null
1910 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1911 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1912 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1914 $lb = $this->getDBLoadBalancer();
1916 // Make sure new pending/committed revision are visibile later on
1917 // within web requests to certain avoid bugs like T93866 and T94407.
1919 && !( $flags & self
::READ_LATEST
)
1920 && $lb->getServerCount() > 1
1921 && $lb->hasOrMadeRecentMasterChanges()
1923 $flags = self
::READ_LATEST
;
1924 $dbw = $this->getDBConnection( DB_MASTER
);
1925 $rev = $this->loadRevisionFromConds( $dbw, $conditions, $flags, $title );
1926 $this->releaseDBConnection( $dbw );
1933 * Given a set of conditions, fetch a revision from
1934 * the given database connection.
1936 * MCR migration note: this corresponds to Revision::loadFromConds
1938 * @param IDatabase $db
1939 * @param array $conditions
1940 * @param int $flags (optional)
1941 * @param Title|null $title
1943 * @return RevisionRecord|null
1945 private function loadRevisionFromConds(
1951 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1953 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1962 * Throws an exception if the given database connection does not belong to the wiki this
1963 * RevisionStore is bound to.
1965 * @param IDatabase $db
1966 * @throws MWException
1968 private function checkDatabaseWikiId( IDatabase
$db ) {
1969 $storeWiki = $this->wikiId
;
1970 $dbWiki = $db->getDomainID();
1972 if ( $dbWiki === $storeWiki ) {
1976 // XXX: we really want the default database ID...
1977 $storeWiki = $storeWiki ?
: wfWikiID();
1978 $dbWiki = $dbWiki ?
: wfWikiID();
1980 if ( $dbWiki === $storeWiki ) {
1984 // HACK: counteract encoding imposed by DatabaseDomain
1985 $storeWiki = str_replace( '?h', '-', $storeWiki );
1986 $dbWiki = str_replace( '?h', '-', $dbWiki );
1988 if ( $dbWiki === $storeWiki ) {
1992 throw new MWException( "RevisionStore for $storeWiki "
1993 . "cannot be used with a DB connection for $dbWiki" );
1997 * Given a set of conditions, return a row with the
1998 * fields necessary to build RevisionRecord objects.
2000 * MCR migration note: this corresponds to Revision::fetchFromConds
2002 * @param IDatabase $db
2003 * @param array $conditions
2004 * @param int $flags (optional)
2006 * @return object|false data row as a raw object
2008 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
2009 $this->checkDatabaseWikiId( $db );
2011 $revQuery = $this->getQueryInfo( [ 'page', 'user' ] );
2013 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
2014 $options[] = 'FOR UPDATE';
2016 return $db->selectRow(
2017 $revQuery['tables'],
2018 $revQuery['fields'],
2027 * Finds the ID of a content row for a given revision and slot role.
2028 * This can be used to re-use content rows even while the content ID
2029 * is still missing from SlotRecords, when writing to both the old and
2030 * the new schema during MCR schema migration.
2032 * @todo remove after MCR schema migration is complete.
2034 * @param IDatabase $db
2036 * @param string $role
2040 private function findSlotContentId( IDatabase
$db, $revId, $role ) {
2041 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW
) ) {
2046 $roleId = $this->slotRoleStore
->getId( $role );
2048 'slot_revision_id' => $revId,
2049 'slot_role_id' => $roleId,
2052 $contentId = $db->selectField( 'slots', 'slot_content_id', $conditions, __METHOD__
);
2054 return $contentId ?
: null;
2055 } catch ( NameTableAccessException
$ex ) {
2056 // If the role is missing from the slot_roles table,
2057 // the corresponding row in slots cannot exist.
2063 * Return the tables, fields, and join conditions to be selected to create
2064 * a new RevisionStoreRecord object.
2066 * MCR migration note: this replaces Revision::getQueryInfo
2068 * If the format of fields returned changes in any way then the cache key provided by
2069 * self::getRevisionRowCacheKey should be updated.
2073 * @param array $options Any combination of the following strings
2074 * - 'page': Join with the page table, and select fields to identify the page
2075 * - 'user': Join with the user table, and select the user name
2076 * - 'text': Join with the text table, and select fields to load page text. This
2077 * option is deprecated in MW 1.32 when the MCR migration flag SCHEMA_COMPAT_WRITE_NEW
2078 * is set, and disallowed when SCHEMA_COMPAT_READ_OLD is not set.
2080 * @return array With three keys:
2081 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2082 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2083 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2085 public function getQueryInfo( $options = [] ) {
2092 $ret['tables'][] = 'revision';
2093 $ret['fields'] = array_merge( $ret['fields'], [
2104 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
2105 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
2106 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
2107 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
2109 $actorQuery = $this->actorMigration
->getJoin( 'rev_user' );
2110 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
2111 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
2112 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
2114 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2115 $ret['fields'][] = 'rev_text_id';
2117 if ( $this->contentHandlerUseDB
) {
2118 $ret['fields'][] = 'rev_content_format';
2119 $ret['fields'][] = 'rev_content_model';
2123 if ( in_array( 'page', $options, true ) ) {
2124 $ret['tables'][] = 'page';
2125 $ret['fields'] = array_merge( $ret['fields'], [
2133 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
2136 if ( in_array( 'user', $options, true ) ) {
2137 $ret['tables'][] = 'user';
2138 $ret['fields'] = array_merge( $ret['fields'], [
2141 $u = $actorQuery['fields']['rev_user'];
2142 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
2145 if ( in_array( 'text', $options, true ) ) {
2146 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD
) ) {
2147 throw new InvalidArgumentException( 'text table can no longer be joined directly' );
2148 } elseif ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2149 // NOTE: even when this class is set to not read from the old schema, callers
2150 // should still be able to join against the text table, as long as we are still
2151 // writing the old schema for compatibility.
2152 wfDeprecated( __METHOD__
. ' with `text` option', '1.32' );
2155 $ret['tables'][] = 'text';
2156 $ret['fields'] = array_merge( $ret['fields'], [
2160 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
2167 * Return the tables, fields, and join conditions to be selected to create
2172 * @param array $options Any combination of the following strings
2173 * - 'content': Join with the content table, and select content meta-data fields
2175 * @return array With three keys:
2176 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2177 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2178 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2180 public function getSlotsQueryInfo( $options = [] ) {
2187 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2188 $db = $this->getDBConnectionRef( DB_REPLICA
);
2189 $ret['tables']['slots'] = 'revision';
2191 $ret['fields']['slot_revision_id'] = 'slots.rev_id';
2192 $ret['fields']['slot_content_id'] = 'NULL';
2193 $ret['fields']['slot_origin'] = 'slots.rev_id';
2194 $ret['fields']['role_name'] = $db->addQuotes( 'main' );
2196 if ( in_array( 'content', $options, true ) ) {
2197 $ret['fields']['content_size'] = 'slots.rev_len';
2198 $ret['fields']['content_sha1'] = 'slots.rev_sha1';
2199 $ret['fields']['content_address']
2200 = $db->buildConcat( [ $db->addQuotes( 'tt:' ), 'slots.rev_text_id' ] );
2202 if ( $this->contentHandlerUseDB
) {
2203 $ret['fields']['model_name'] = 'slots.rev_content_model';
2205 $ret['fields']['model_name'] = 'NULL';
2209 $ret['tables'][] = 'slots';
2210 $ret['tables'][] = 'slot_roles';
2211 $ret['fields'] = array_merge( $ret['fields'], [
2217 $ret['joins']['slot_roles'] = [ 'INNER JOIN', [ 'slot_role_id = role_id' ] ];
2219 if ( in_array( 'content', $options, true ) ) {
2220 $ret['tables'][] = 'content';
2221 $ret['tables'][] = 'content_models';
2222 $ret['fields'] = array_merge( $ret['fields'], [
2228 $ret['joins']['content'] = [ 'INNER JOIN', [ 'slot_content_id = content_id' ] ];
2229 $ret['joins']['content_models'] = [ 'INNER JOIN', [ 'content_model = model_id' ] ];
2237 * Return the tables, fields, and join conditions to be selected to create
2238 * a new RevisionArchiveRecord object.
2240 * MCR migration note: this replaces Revision::getArchiveQueryInfo
2244 * @return array With three keys:
2245 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2246 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2247 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2249 public function getArchiveQueryInfo() {
2250 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
2251 $actorQuery = $this->actorMigration
->getJoin( 'ar_user' );
2253 'tables' => [ 'archive' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
2266 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
2267 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
2270 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD
) ) {
2271 $ret['fields'][] = 'ar_text_id';
2273 if ( $this->contentHandlerUseDB
) {
2274 $ret['fields'][] = 'ar_content_format';
2275 $ret['fields'][] = 'ar_content_model';
2283 * Do a batched query for the sizes of a set of revisions.
2285 * MCR migration note: this replaces Revision::getParentLengths
2287 * @param int[] $revIds
2288 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2289 * of the corresponding revision.
2291 public function getRevisionSizes( array $revIds ) {
2292 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
2296 * Do a batched query for the sizes of a set of revisions.
2298 * MCR migration note: this replaces Revision::getParentLengths
2300 * @deprecated use RevisionStore::getRevisionSizes instead.
2302 * @param IDatabase $db
2303 * @param int[] $revIds
2304 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2305 * of the corresponding revision.
2307 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
2308 $this->checkDatabaseWikiId( $db );
2312 return $revLens; // empty
2317 [ 'rev_id', 'rev_len' ],
2318 [ 'rev_id' => $revIds ],
2322 foreach ( $res as $row ) {
2323 $revLens[$row->rev_id
] = intval( $row->rev_len
);
2330 * Get previous revision for this title
2332 * MCR migration note: this replaces Revision::getPrevious
2334 * @param RevisionRecord $rev
2335 * @param Title|null $title if known (optional)
2337 * @return RevisionRecord|null
2339 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
2340 if ( $title === null ) {
2341 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2343 $prev = $title->getPreviousRevisionID( $rev->getId() );
2345 return $this->getRevisionByTitle( $title, $prev );
2351 * Get next revision for this title
2353 * MCR migration note: this replaces Revision::getNext
2355 * @param RevisionRecord $rev
2356 * @param Title|null $title if known (optional)
2358 * @return RevisionRecord|null
2360 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
2361 if ( $title === null ) {
2362 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2364 $next = $title->getNextRevisionID( $rev->getId() );
2366 return $this->getRevisionByTitle( $title, $next );
2372 * Get previous revision Id for this page_id
2373 * This is used to populate rev_parent_id on save
2375 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
2377 * @param IDatabase $db
2378 * @param RevisionRecord $rev
2382 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
2383 $this->checkDatabaseWikiId( $db );
2385 if ( $rev->getPageId() === null ) {
2388 # Use page_latest if ID is not given
2389 if ( !$rev->getId() ) {
2390 $prevId = $db->selectField(
2391 'page', 'page_latest',
2392 [ 'page_id' => $rev->getPageId() ],
2396 $prevId = $db->selectField(
2397 'revision', 'rev_id',
2398 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
2400 [ 'ORDER BY' => 'rev_id DESC' ]
2403 return intval( $prevId );
2407 * Get rev_timestamp from rev_id, without loading the rest of the row
2409 * MCR migration note: this replaces Revision::getTimestampFromId
2411 * @param Title $title
2414 * @return string|bool False if not found
2416 public function getTimestampFromId( $title, $id, $flags = 0 ) {
2417 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2419 $conds = [ 'rev_id' => $id ];
2420 $conds['rev_page'] = $title->getArticleID();
2421 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
2423 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
2427 * Get count of revisions per page...not very efficient
2429 * MCR migration note: this replaces Revision::countByPageId
2431 * @param IDatabase $db
2432 * @param int $id Page id
2435 public function countRevisionsByPageId( IDatabase
$db, $id ) {
2436 $this->checkDatabaseWikiId( $db );
2438 $row = $db->selectRow( 'revision',
2439 [ 'revCount' => 'COUNT(*)' ],
2440 [ 'rev_page' => $id ],
2444 return intval( $row->revCount
);
2450 * Get count of revisions per page...not very efficient
2452 * MCR migration note: this replaces Revision::countByTitle
2454 * @param IDatabase $db
2455 * @param Title $title
2458 public function countRevisionsByTitle( IDatabase
$db, $title ) {
2459 $id = $title->getArticleID();
2461 return $this->countRevisionsByPageId( $db, $id );
2467 * Check if no edits were made by other users since
2468 * the time a user started editing the page. Limit to
2469 * 50 revisions for the sake of performance.
2471 * MCR migration note: this replaces Revision::userWasLastToEdit
2473 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
2474 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
2475 * has been deprecated since 1.24.
2477 * @param IDatabase $db The Database to perform the check on.
2478 * @param int $pageId The ID of the page in question
2479 * @param int $userId The ID of the user in question
2480 * @param string $since Look at edits since this time
2482 * @return bool True if the given user was the only one to edit since the given timestamp
2484 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
2485 $this->checkDatabaseWikiId( $db );
2491 $revQuery = $this->getQueryInfo();
2493 $revQuery['tables'],
2495 'rev_user' => $revQuery['fields']['rev_user'],
2498 'rev_page' => $pageId,
2499 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
2502 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
2505 foreach ( $res as $row ) {
2506 if ( $row->rev_user
!= $userId ) {
2514 * Load a revision based on a known page ID and current revision ID from the DB
2516 * This method allows for the use of caching, though accessing anything that normally
2517 * requires permission checks (aside from the text) will trigger a small DB lookup.
2519 * MCR migration note: this replaces Revision::newKnownCurrent
2521 * @param Title $title the associated page title
2522 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
2524 * @return RevisionRecord|bool Returns false if missing
2526 public function getKnownCurrentRevision( Title
$title, $revId ) {
2527 $db = $this->getDBConnectionRef( DB_REPLICA
);
2529 $pageId = $title->getArticleID();
2536 $revId = $title->getLatestRevID();
2541 'No latest revision known for page ' . $title->getPrefixedDBkey()
2542 . ' even though it exists with page ID ' . $pageId
2547 $row = $this->cache
->getWithSetCallback(
2548 // Page/rev IDs passed in from DB to reflect history merges
2549 $this->getRevisionRowCacheKey( $db, $pageId, $revId ),
2550 WANObjectCache
::TTL_WEEK
,
2551 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
2552 $setOpts +
= Database
::getCacheSetOptions( $db );
2555 'rev_page' => intval( $pageId ),
2556 'page_id' => intval( $pageId ),
2557 'rev_id' => intval( $revId ),
2560 $row = $this->fetchRevisionRowFromConds( $db, $conds );
2561 return $row ?
: false; // don't cache negatives
2565 // Reflect revision deletion and user renames
2567 return $this->newRevisionFromRow( $row, 0, $title );
2574 * Get a cache key for use with a row as selected with getQueryInfo( [ 'page', 'user' ] )
2575 * Caching rows without 'page' or 'user' could lead to issues.
2576 * If the format of the rows returned by the query provided by getQueryInfo changes the
2577 * cache key should be updated to avoid conflicts.
2579 * @param IDatabase $db
2580 * @param int $pageId
2584 private function getRevisionRowCacheKey( IDatabase
$db, $pageId, $revId ) {
2585 return $this->cache
->makeGlobalKey(
2586 self
::ROW_CACHE_KEY
,
2593 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.