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
;
30 use CommentStoreComment
;
33 use DBAccessObjectUtils
;
36 use InvalidArgumentException
;
39 use MediaWiki\Linker\LinkTarget
;
40 use MediaWiki\User\UserIdentity
;
41 use MediaWiki\User\UserIdentityValue
;
44 use MWUnknownContentModelException
;
50 use Wikimedia\Assert\Assert
;
51 use Wikimedia\Rdbms\Database
;
52 use Wikimedia\Rdbms\DBConnRef
;
53 use Wikimedia\Rdbms\IDatabase
;
54 use Wikimedia\Rdbms\LoadBalancer
;
57 * Service for looking up page revisions.
61 * @note This was written to act as a drop-in replacement for the corresponding
62 * static methods in Revision.
64 class RevisionStore
implements IDBAccessObject
, RevisionFactory
, RevisionLookup
{
79 private $contentHandlerUseDB = true;
84 private $loadBalancer;
92 * @todo $blobStore should be allowed to be any BlobStore!
94 * @param LoadBalancer $loadBalancer
95 * @param SqlBlobStore $blobStore
96 * @param WANObjectCache $cache
97 * @param bool|string $wikiId
99 public function __construct(
100 LoadBalancer
$loadBalancer,
101 SqlBlobStore
$blobStore,
102 WANObjectCache
$cache,
105 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
107 $this->loadBalancer
= $loadBalancer;
108 $this->blobStore
= $blobStore;
109 $this->cache
= $cache;
110 $this->wikiId
= $wikiId;
116 public function getContentHandlerUseDB() {
117 return $this->contentHandlerUseDB
;
121 * @param bool $contentHandlerUseDB
123 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
124 $this->contentHandlerUseDB
= $contentHandlerUseDB;
128 * @return LoadBalancer
130 private function getDBLoadBalancer() {
131 return $this->loadBalancer
;
135 * @param int $mode DB_MASTER or DB_REPLICA
139 private function getDBConnection( $mode ) {
140 $lb = $this->getDBLoadBalancer();
141 return $lb->getConnection( $mode, [], $this->wikiId
);
145 * @param IDatabase $connection
147 private function releaseDBConnection( IDatabase
$connection ) {
148 $lb = $this->getDBLoadBalancer();
149 $lb->reuseConnection( $connection );
153 * @param int $mode DB_MASTER or DB_REPLICA
157 private function getDBConnectionRef( $mode ) {
158 $lb = $this->getDBLoadBalancer();
159 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
163 * Determines the page Title based on the available information.
165 * MCR migration note: this corresponds to Revision::getTitle
167 * @param int|null $pageId
168 * @param int|null $revId
169 * @param int $queryFlags
172 * @throws RevisionAccessException
174 private function getTitle( $pageId, $revId, $queryFlags = 0 ) {
175 if ( !$pageId && !$revId ) {
176 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
181 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
182 if ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false ) {
183 // TODO: better foreign title handling (introduce TitleFactory)
184 $title = Title
::newFromID( $pageId, $queryFlags );
187 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
188 if ( !$title && $revId !== null && $revId > 0 ) {
189 list( $dbMode, $dbOptions, , ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
191 $dbr = $this->getDbConnectionRef( $dbMode );
192 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
193 $row = $dbr->selectRow(
194 [ 'revision', 'page' ],
203 [ 'rev_id' => $revId ],
206 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
209 // TODO: better foreign title handling (introduce TitleFactory)
210 $title = Title
::newFromRow( $row );
215 throw new RevisionAccessException(
216 "Could not determine title for page ID $pageId and revision ID $revId"
224 * @param mixed $value
225 * @param string $name
227 * @throw IncompleteRevisionException if $value is null
228 * @return mixed $value, if $value is not null
230 private function failOnNull( $value, $name ) {
231 if ( $value === null ) {
232 throw new IncompleteRevisionException(
233 "$name must not be " . var_export( $value, true ) . "!"
241 * @param mixed $value
242 * @param string $name
244 * @throw IncompleteRevisionException if $value is empty
245 * @return mixed $value, if $value is not null
247 private function failOnEmpty( $value, $name ) {
248 if ( $value === null ||
$value === 0 ||
$value === '' ) {
249 throw new IncompleteRevisionException(
250 "$name must not be " . var_export( $value, true ) . "!"
258 * Insert a new revision into the database, returning the new revision ID
259 * number on success and dies horribly on failure.
261 * MCR migration note: this replaces Revision::insertOn
263 * @param RevisionRecord $rev
264 * @param IDatabase $dbw (master connection)
266 * @throws InvalidArgumentException
267 * @return RevisionRecord the new revision record.
269 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
270 // TODO: pass in a DBTransactionContext instead of a database connection.
271 $this->checkDatabaseWikiId( $dbw );
273 if ( !$rev->getSlotRoles() ) {
274 throw new InvalidArgumentException( 'At least one slot needs to be defined!' );
277 if ( $rev->getSlotRoles() !== [ 'main' ] ) {
278 throw new InvalidArgumentException( 'Only the main slot is supported for now!' );
281 // TODO: we shouldn't need an actual Title here.
282 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
283 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
285 $parentId = $rev->getParentId() === null
286 ?
$this->getPreviousRevisionId( $dbw, $rev )
287 : $rev->getParentId();
289 // Record the text (or external storage URL) to the blob store
290 $slot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
292 $size = $this->failOnNull( $rev->getSize(), 'size field' );
293 $sha1 = $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
295 if ( !$slot->hasAddress() ) {
296 $content = $slot->getContent();
297 $format = $content->getDefaultFormat();
298 $model = $content->getModel();
300 $this->checkContentModel( $content, $title );
302 $data = $content->serialize( $format );
304 // Hints allow the blob store to optimize by "leaking" application level information to it.
305 // TODO: with the new MCR storage schema, we rev_id have this before storing the blobs.
306 // When we have it, add rev_id as a hint. Can be used with rev_parent_id for
307 // differential storage or compression of subsequent revisions.
309 BlobStore
::DESIGNATION_HINT
=> 'page-content', // BlobStore may be used for other things too.
310 BlobStore
::PAGE_HINT
=> $pageId,
311 BlobStore
::ROLE_HINT
=> $slot->getRole(),
312 BlobStore
::PARENT_HINT
=> $parentId,
313 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
314 BlobStore
::MODEL_HINT
=> $model,
315 BlobStore
::FORMAT_HINT
=> $format,
318 $blobAddress = $this->blobStore
->storeBlob( $data, $blobHints );
320 $blobAddress = $slot->getAddress();
321 $model = $slot->getModel();
322 $format = $slot->getFormat();
325 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
328 throw new LogicException(
329 'Blob address not supported in 1.29 database schema: ' . $blobAddress
333 // getTextIdFromAddress() is free to insert something into the text table, so $textId
334 // may be a new value, not anything already contained in $blobAddress.
335 $blobAddress = 'tt:' . $textId;
337 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
338 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
339 $timestamp = $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
341 # Record the edit in revisions
343 'rev_page' => $pageId,
344 'rev_parent_id' => $parentId,
345 'rev_text_id' => $textId,
346 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
347 'rev_user' => $this->failOnNull( $user->getId(), 'user field' ),
348 'rev_user_text' => $this->failOnEmpty( $user->getName(), 'user_text field' ),
349 'rev_timestamp' => $dbw->timestamp( $timestamp ),
350 'rev_deleted' => $rev->getVisibility(),
355 if ( $rev->getId() !== null ) {
356 // Needed to restore revisions with their original ID
357 $row['rev_id'] = $rev->getId();
360 list( $commentFields, $commentCallback ) =
361 CommentStore
::newKey( 'rev_comment' )->insertWithTempTable( $dbw, $comment );
362 $row +
= $commentFields;
364 if ( $this->contentHandlerUseDB
) {
365 // MCR migration note: rev_content_model and rev_content_format will go away
367 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
368 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
370 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
371 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
374 $dbw->insert( 'revision', $row, __METHOD__
);
376 if ( !isset( $row['rev_id'] ) ) {
377 // only if auto-increment was used
378 $row['rev_id'] = intval( $dbw->insertId() );
380 $commentCallback( $row['rev_id'] );
382 // Insert IP revision into ip_changes for use when querying for a range.
383 if ( $row['rev_user'] === 0 && IP
::isValid( $row['rev_user_text'] ) ) {
385 'ipc_rev_id' => $row['rev_id'],
386 'ipc_rev_timestamp' => $row['rev_timestamp'],
387 'ipc_hex' => IP
::toHex( $row['rev_user_text'] ),
389 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
392 $newSlot = SlotRecord
::newSaved( $row['rev_id'], $blobAddress, $slot );
393 $slots = new RevisionSlots( [ 'main' => $newSlot ] );
395 $user = new UserIdentityValue( intval( $row['rev_user'] ), $row['rev_user_text'] );
397 $rev = new RevisionStoreRecord(
406 $newSlot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
409 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
410 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
411 Assert
::postcondition(
412 $rev->getComment( RevisionRecord
::RAW
) !== null,
413 'revision must have a comment'
415 Assert
::postcondition(
416 $rev->getUser( RevisionRecord
::RAW
) !== null,
417 'revision must have a user'
420 Assert
::postcondition( $newSlot !== null, 'revision must have a main slot' );
421 Assert
::postcondition(
422 $newSlot->getAddress() !== null,
423 'main slot must have an addess'
426 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
432 * MCR migration note: this corresponds to Revision::checkContentModel
434 * @param Content $content
435 * @param Title $title
437 * @throws MWException
438 * @throws MWUnknownContentModelException
440 private function checkContentModel( Content
$content, Title
$title ) {
441 // Note: may return null for revisions that have not yet been inserted
443 $model = $content->getModel();
444 $format = $content->getDefaultFormat();
445 $handler = $content->getContentHandler();
449 if ( !$handler->isSupportedFormat( $format ) ) {
450 throw new MWException( "Can't use format $format with content model $model on $name" );
453 if ( !$this->contentHandlerUseDB
) {
454 // if $wgContentHandlerUseDB is not set,
455 // all revisions must use the default content model and format.
457 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
458 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
459 $defaultFormat = $defaultHandler->getDefaultFormat();
461 if ( $model != $defaultModel ) {
462 throw new MWException( "Can't save non-default content model with "
463 . "\$wgContentHandlerUseDB disabled: model is $model, "
464 . "default for $name is $defaultModel"
468 if ( $format != $defaultFormat ) {
469 throw new MWException( "Can't use non-default content format with "
470 . "\$wgContentHandlerUseDB disabled: format is $format, "
471 . "default for $name is $defaultFormat"
476 if ( !$content->isValid() ) {
477 throw new MWException(
478 "New content for $name is not valid! Content model is $model"
484 * Create a new null-revision for insertion into a page's
485 * history. This will not re-save the text, but simply refer
486 * to the text from the previous version.
488 * Such revisions can for instance identify page rename
489 * operations and other such meta-modifications.
491 * MCR migration note: this replaces Revision::newNullRevision
493 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
496 * @param IDatabase $dbw
497 * @param Title $title Title of the page to read from
498 * @param CommentStoreComment $comment RevisionRecord's summary
499 * @param bool $minor Whether the revision should be considered as minor
500 * @param User $user The user to attribute the revision to
501 * @return RevisionRecord|null RevisionRecord or null on error
503 public function newNullRevision(
506 CommentStoreComment
$comment,
510 $this->checkDatabaseWikiId( $dbw );
512 $fields = [ 'page_latest', 'page_namespace', 'page_title',
513 'rev_id', 'rev_text_id', 'rev_len', 'rev_sha1' ];
515 if ( $this->contentHandlerUseDB
) {
516 $fields[] = 'rev_content_model';
517 $fields[] = 'rev_content_format';
520 $current = $dbw->selectRow(
521 [ 'page', 'revision' ],
524 'page_id' => $title->getArticleID(),
525 'page_latest=rev_id',
528 [ 'FOR UPDATE' ] // T51581
533 'page' => $title->getArticleID(),
534 'user_text' => $user->getName(),
535 'user' => $user->getId(),
536 'comment' => $comment,
537 'minor_edit' => $minor,
538 'text_id' => $current->rev_text_id
,
539 'parent_id' => $current->page_latest
,
540 'len' => $current->rev_len
,
541 'sha1' => $current->rev_sha1
544 if ( $this->contentHandlerUseDB
) {
545 $fields['content_model'] = $current->rev_content_model
;
546 $fields['content_format'] = $current->rev_content_format
;
549 $fields['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
551 $mainSlot = $this->emulateMainSlot_1_29( $fields, 0, $title );
552 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
553 $this->initializeMutableRevisionFromArray( $revision, $fields );
554 $revision->setSlot( $mainSlot );
563 * MCR migration note: this replaces Revision::isUnpatrolled
565 * @return int Rcid of the unpatrolled row, zero if there isn't one
567 public function isUnpatrolled( RevisionRecord
$rev ) {
568 $rc = $this->getRecentChange( $rev );
569 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
570 return $rc->getAttribute( 'rc_id' );
577 * Get the RC object belonging to the current revision, if there's one
579 * MCR migration note: this replaces Revision::getRecentChange
581 * @todo move this somewhere else?
583 * @param RevisionRecord $rev
584 * @param int $flags (optional) $flags include:
585 * IDBAccessObject::READ_LATEST: Select the data from the master
587 * @return null|RecentChange
589 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
590 $dbr = $this->getDBConnection( DB_REPLICA
);
592 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
594 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
596 if ( !$userIdentity ) {
597 // If the revision has no user identity, chances are it never went
598 // into the database, and doesn't have an RC entry.
602 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
603 $rc = RecentChange
::newFromConds(
605 'rc_user_text' => $userIdentity->getName(),
606 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
607 'rc_this_oldid' => $rev->getId()
613 $this->releaseDBConnection( $dbr );
615 // XXX: cache this locally? Glue it to the RevisionRecord?
620 * Maps fields of the archive row to corresponding revision rows.
622 * @param object $archiveRow
624 * @return object a revision row object, corresponding to $archiveRow.
626 private static function mapArchiveFields( $archiveRow ) {
628 // keep with ar prefix:
631 // not the same suffix:
632 'ar_page_id' => 'rev_page',
633 'ar_rev_id' => 'rev_id',
636 'ar_text_id' => 'rev_text_id',
637 'ar_timestamp' => 'rev_timestamp',
638 'ar_user_text' => 'rev_user_text',
639 'ar_user' => 'rev_user',
640 'ar_minor_edit' => 'rev_minor_edit',
641 'ar_deleted' => 'rev_deleted',
642 'ar_len' => 'rev_len',
643 'ar_parent_id' => 'rev_parent_id',
644 'ar_sha1' => 'rev_sha1',
645 'ar_comment' => 'rev_comment',
646 'ar_comment_cid' => 'rev_comment_cid',
647 'ar_comment_id' => 'rev_comment_id',
648 'ar_comment_text' => 'rev_comment_text',
649 'ar_comment_data' => 'rev_comment_data',
650 'ar_comment_old' => 'rev_comment_old',
651 'ar_content_format' => 'rev_content_format',
652 'ar_content_model' => 'rev_content_model',
655 if ( empty( $archiveRow->ar_text_id
) ) {
656 $fieldMap['ar_text'] = 'old_text';
657 $fieldMap['ar_flags'] = 'old_flags';
660 $revRow = new stdClass();
661 foreach ( $fieldMap as $arKey => $revKey ) {
662 if ( property_exists( $archiveRow, $arKey ) ) {
663 $revRow->$revKey = $archiveRow->$arKey;
671 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
673 * @param object|array $row Either a database row or an array
674 * @param int $queryFlags for callbacks
675 * @param Title $title
677 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
678 * @throws MWException
680 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
681 $mainSlotRow = new stdClass();
682 $mainSlotRow->role_name
= 'main';
688 if ( is_object( $row ) ) {
690 if ( !isset( $row->rev_id
) && isset( $row->ar_user
) ) {
691 $row = $this->mapArchiveFields( $row );
694 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
695 $mainSlotRow->cont_address
= 'tt:' . $row->rev_text_id
;
696 } elseif ( isset( $row->ar_id
) ) {
697 $mainSlotRow->cont_address
= 'ar:' . $row->ar_id
;
700 if ( isset( $row->old_text
) ) {
701 // this happens when the text-table gets joined directly, in the pre-1.30 schema
702 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
703 $blobFlags = isset( $row->old_flags
) ?
strval( $row->old_flags
) : '';
706 $mainSlotRow->slot_revision
= intval( $row->rev_id
);
708 $mainSlotRow->cont_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
709 $mainSlotRow->cont_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
710 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
711 ?
strval( $row->rev_content_model
)
713 // XXX: in the future, we'll probably always use the default format, and drop content_format
714 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
715 ?
strval( $row->rev_content_format
)
717 } elseif ( is_array( $row ) ) {
718 $mainSlotRow->slot_revision
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
720 $mainSlotRow->cont_address
= isset( $row['text_id'] )
721 ?
'tt:' . intval( $row['text_id'] )
723 $mainSlotRow->cont_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
724 $mainSlotRow->cont_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
726 $mainSlotRow->model_name
= isset( $row['content_model'] )
727 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
728 // XXX: in the future, we'll probably always use the default format, and drop content_format
729 $mainSlotRow->format_name
= isset( $row['content_format'] )
730 ?
strval( $row['content_format'] ) : null;
731 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
732 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : '';
734 // if we have a Content object, override mText and mContentModel
735 if ( !empty( $row['content'] ) ) {
736 if ( !( $row['content'] instanceof Content
) ) {
737 throw new MWException( 'content field must contain a Content object.' );
740 /** @var Content $content */
741 $content = $row['content'];
742 $handler = $content->getContentHandler();
744 $mainSlotRow->model_name
= $content->getModel();
746 // XXX: in the future, we'll probably always use the default format.
747 if ( $mainSlotRow->format_name
=== null ) {
748 $mainSlotRow->format_name
= $handler->getDefaultFormat();
752 throw new MWException( 'Revision constructor passed invalid row format.' );
755 // With the old schema, the content changes with every revision.
756 // ...except for null-revisions. Would be nice if we could detect them.
757 $mainSlotRow->slot_inherited
= 0;
759 if ( $mainSlotRow->model_name
=== null ) {
760 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
761 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
762 // TODO: MCR: deprecate $title->getModel().
763 return ContentHandler
::getDefaultModelFor( $title );
768 $content = function ( SlotRecord
$slot )
769 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
771 return $this->loadSlotContent(
775 $mainSlotRow->format_name
,
781 return new SlotRecord( $mainSlotRow, $content );
785 * Loads a Content object based on a slot row.
787 * This method does not call $slot->getContent(), and may be used as a callback
788 * called by $slot->getContent().
790 * MCR migration note: this roughly corresponds to Revision::getContentInternal
792 * @param SlotRecord $slot The SlotRecord to load content for
793 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
794 * @param string $blobFlags Flags indicating how $blobData needs to be processed
795 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
796 * @param int $queryFlags
798 * @throw RevisionAccessException
801 private function loadSlotContent(
808 if ( $blobData !== null ) {
809 Assert
::parameterType( 'string', $blobData, '$blobData' );
810 Assert
::parameterType( 'string', $blobFlags, '$blobFlags' );
812 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
814 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
816 if ( $data === false ) {
817 throw new RevisionAccessException(
818 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
822 $address = $slot->getAddress();
824 $data = $this->blobStore
->getBlob( $address, $queryFlags );
825 } catch ( BlobAccessException
$e ) {
826 throw new RevisionAccessException(
827 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
832 // Unserialize content
833 $handler = ContentHandler
::getForModelID( $slot->getModel() );
835 $content = $handler->unserializeContent( $data, $blobFormat );
840 * Load a page revision from a given revision ID number.
841 * Returns null if no such revision can be found.
843 * MCR migration note: this replaces Revision::newFromId
846 * IDBAccessObject::READ_LATEST: Select the data from the master
847 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
850 * @param int $flags (optional)
851 * @param Title $title (optional)
852 * @return RevisionRecord|null
854 public function getRevisionById( $id, $flags = 0, Title
$title = null ) {
855 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags, $title );
859 * Load either the current, or a specified, revision
860 * that's attached to a given link target. If not attached
861 * to that link target, will return null.
863 * MCR migration note: this replaces Revision::newFromTitle
866 * IDBAccessObject::READ_LATEST: Select the data from the master
867 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
869 * @param LinkTarget $linkTarget
870 * @param int $revId (optional)
871 * @param int $flags Bitfield (optional)
872 * @return RevisionRecord|null
874 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
876 'page_namespace' => $linkTarget->getNamespace(),
877 'page_title' => $linkTarget->getDBkey()
880 // Use the specified revision ID.
881 // Note that we use newRevisionFromConds here because we want to retry
882 // and fall back to master if the page is not found on a replica.
883 // Since the caller supplied a revision ID, we are pretty sure the revision is
884 // supposed to exist, so we should try hard to find it.
885 $conds['rev_id'] = $revId;
886 return $this->newRevisionFromConds( $conds, $flags );
888 // Use a join to get the latest revision.
889 // Note that we don't use newRevisionFromConds here because we don't want to retry
890 // and fall back to master. The assumption is that we only want to force the fallback
891 // if we are quite sure the revision exists because the caller supplied a revision ID.
892 // If the page isn't found at all on a replica, it probably simply does not exist.
893 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
895 $conds[] = 'rev_id=page_latest';
896 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
898 $this->releaseDBConnection( $db );
904 * Load either the current, or a specified, revision
905 * that's attached to a given page ID.
906 * Returns null if no such revision can be found.
908 * MCR migration note: this replaces Revision::newFromPageId
911 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
912 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
915 * @param int $revId (optional)
916 * @param int $flags Bitfield (optional)
917 * @return RevisionRecord|null
919 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
920 $conds = [ 'page_id' => $pageId ];
922 // Use the specified revision ID.
923 // Note that we use newRevisionFromConds here because we want to retry
924 // and fall back to master if the page is not found on a replica.
925 // Since the caller supplied a revision ID, we are pretty sure the revision is
926 // supposed to exist, so we should try hard to find it.
927 $conds['rev_id'] = $revId;
928 return $this->newRevisionFromConds( $conds, $flags );
930 // Use a join to get the latest revision.
931 // Note that we don't use newRevisionFromConds here because we don't want to retry
932 // and fall back to master. The assumption is that we only want to force the fallback
933 // if we are quite sure the revision exists because the caller supplied a revision ID.
934 // If the page isn't found at all on a replica, it probably simply does not exist.
935 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
937 $conds[] = 'rev_id=page_latest';
938 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
940 $this->releaseDBConnection( $db );
946 * Load the revision for the given title with the given timestamp.
947 * WARNING: Timestamps may in some circumstances not be unique,
948 * so this isn't the best key to use.
950 * MCR migration note: this replaces Revision::loadFromTimestamp
952 * @param Title $title
953 * @param string $timestamp
954 * @return RevisionRecord|null
956 public function getRevisionFromTimestamp( $title, $timestamp ) {
957 return $this->newRevisionFromConds(
959 'rev_timestamp' => $timestamp,
960 'page_namespace' => $title->getNamespace(),
961 'page_title' => $title->getDBkey()
969 * Make a fake revision object from an archive table row. This is queried
970 * for permissions or even inserted (as in Special:Undelete)
972 * MCR migration note: this replaces Revision::newFromArchiveRow
975 * @param int $queryFlags
976 * @param Title|null $title
977 * @param array $overrides associative array with fields of $row to override. This may be
978 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
979 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
980 * override ar_parent_id.
982 * @return RevisionRecord
983 * @throws MWException
985 public function newRevisionFromArchiveRow(
989 array $overrides = []
991 Assert
::parameterType( 'object', $row, '$row' );
993 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
994 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
996 if ( !$title && isset( $overrides['title'] ) ) {
997 if ( !( $overrides['title'] instanceof Title
) ) {
998 throw new MWException( 'title field override must contain a Title object.' );
1001 $title = $overrides['title'];
1004 if ( !isset( $title ) ) {
1005 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1006 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1008 throw new InvalidArgumentException(
1009 'A Title or ar_namespace and ar_title must be given'
1014 foreach ( $overrides as $key => $value ) {
1016 $row->$field = $value;
1019 $user = $this->getUserIdentityFromRowObject( $row, 'ar_' );
1021 $comment = CommentStore
::newKey( 'ar_comment' )
1022 // Legacy because $row may have come from self::selectFields()
1023 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1025 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1026 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1028 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1032 * @param object $row
1033 * @param string $prefix Field prefix, such as 'rev_' or 'ar_'.
1035 * @return UserIdentityValue
1037 private function getUserIdentityFromRowObject( $row, $prefix = 'rev_' ) {
1038 $idField = "{$prefix}user";
1039 $nameField = "{$prefix}user_text";
1041 $userId = intval( $row->$idField );
1043 if ( isset( $row->user_name
) ) {
1044 $userName = $row->user_name
;
1045 } elseif ( isset( $row->$nameField ) ) {
1046 $userName = $row->$nameField;
1048 $userName = User
::whoIs( $userId );
1051 if ( $userName === false ) {
1052 wfWarn( __METHOD__
. ': Cannot determine user name for user ID ' . $userId );
1056 return new UserIdentityValue( $userId, $userName );
1060 * @see RevisionFactory::newRevisionFromRow_1_29
1062 * MCR migration note: this replaces Revision::newFromRow
1064 * @param object $row
1065 * @param int $queryFlags
1066 * @param Title|null $title
1068 * @return RevisionRecord
1069 * @throws MWException
1070 * @throws RevisionAccessException
1072 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title
$title = null ) {
1073 Assert
::parameterType( 'object', $row, '$row' );
1076 $pageId = isset( $row->rev_page
) ?
$row->rev_page
: 0; // XXX: also check page_id?
1077 $revId = isset( $row->rev_id
) ?
$row->rev_id
: 0;
1079 $title = $this->getTitle( $pageId, $revId );
1082 if ( !isset( $row->page_latest
) ) {
1083 $row->page_latest
= $title->getLatestRevID();
1084 if ( $row->page_latest
=== 0 && $title->exists() ) {
1085 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1089 $user = $this->getUserIdentityFromRowObject( $row );
1091 $comment = CommentStore
::newKey( 'rev_comment' )
1092 // Legacy because $row may have come from self::selectFields()
1093 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1095 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1096 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1098 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1102 * @see RevisionFactory::newRevisionFromRow
1104 * MCR migration note: this replaces Revision::newFromRow
1106 * @param object $row
1107 * @param int $queryFlags
1108 * @param Title|null $title
1110 * @return RevisionRecord
1112 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1113 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1117 * Constructs a new MutableRevisionRecord based on the given associative array following
1118 * the MW1.29 convention for the Revision constructor.
1120 * MCR migration note: this replaces Revision::newFromRow
1122 * @param array $fields
1123 * @param int $queryFlags
1124 * @param Title|null $title
1126 * @return MutableRevisionRecord
1127 * @throws MWException
1128 * @throws RevisionAccessException
1130 public function newMutableRevisionFromArray(
1135 if ( !$title && isset( $fields['title'] ) ) {
1136 if ( !( $fields['title'] instanceof Title
) ) {
1137 throw new MWException( 'title field must contain a Title object.' );
1140 $title = $fields['title'];
1144 $pageId = isset( $fields['page'] ) ?
$fields['page'] : 0;
1145 $revId = isset( $fields['id'] ) ?
$fields['id'] : 0;
1147 $title = $this->getTitle( $pageId, $revId );
1150 if ( !isset( $fields['page'] ) ) {
1151 $fields['page'] = $title->getArticleID( $queryFlags );
1154 // if we have a content object, use it to set the model and type
1155 if ( !empty( $fields['content'] ) ) {
1156 if ( !( $fields['content'] instanceof Content
) ) {
1157 throw new MWException( 'content field must contain a Content object.' );
1160 if ( !empty( $fields['text_id'] ) ) {
1161 throw new MWException(
1162 "Text already stored in external store (id {$fields['text_id']}), " .
1163 "can't serialize content object"
1168 // Replaces old lazy loading logic in Revision::getUserText.
1169 if ( !isset( $fields['user_text'] ) && isset( $fields['user'] ) ) {
1170 if ( $fields['user'] instanceof UserIdentity
) {
1171 /** @var User $user */
1172 $user = $fields['user'];
1173 $fields['user_text'] = $user->getName();
1174 $fields['user'] = $user->getId();
1176 // TODO: wrap this in a callback to make it lazy again.
1177 $name = $fields['user'] === 0 ?
false : User
::whoIs( $fields['user'] );
1179 if ( $name === false ) {
1180 throw new MWException(
1181 'user_text not given, and unknown user ID ' . $fields['user']
1185 $fields['user_text'] = $name;
1190 isset( $fields['comment'] )
1191 && !( $fields['comment'] instanceof CommentStoreComment
)
1193 $commentData = isset( $fields['comment_data'] ) ?
$fields['comment_data'] : null;
1195 if ( $fields['comment'] instanceof Message
) {
1196 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1201 $commentText = trim( strval( $fields['comment'] ) );
1202 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1209 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1211 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1212 $this->initializeMutableRevisionFromArray( $revision, $fields );
1213 $revision->setSlot( $mainSlot );
1219 * @param MutableRevisionRecord $record
1220 * @param array $fields
1222 private function initializeMutableRevisionFromArray(
1223 MutableRevisionRecord
$record,
1226 /** @var UserIdentity $user */
1229 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1230 $user = $fields['user'];
1231 } elseif ( isset( $fields['user'] ) && isset( $fields['user_text'] ) ) {
1232 $user = new UserIdentityValue( intval( $fields['user'] ), $fields['user_text'] );
1233 } elseif ( isset( $fields['user'] ) ) {
1234 $user = User
::newFromId( intval( $fields['user'] ) );
1235 } elseif ( isset( $fields['user_text'] ) ) {
1236 $user = User
::newFromName( $fields['user_text'] );
1238 // User::newFromName will return false for IP addresses (and invalid names)
1239 if ( $user == false ) {
1240 $user = new UserIdentityValue( 0, $fields['user_text'] );
1245 $record->setUser( $user );
1248 $timestamp = isset( $fields['timestamp'] )
1249 ?
strval( $fields['timestamp'] )
1250 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1252 $record->setTimestamp( $timestamp );
1254 if ( isset( $fields['page'] ) ) {
1255 $record->setPageId( intval( $fields['page'] ) );
1258 if ( isset( $fields['id'] ) ) {
1259 $record->setId( intval( $fields['id'] ) );
1261 if ( isset( $fields['parent_id'] ) ) {
1262 $record->setParentId( intval( $fields['parent_id'] ) );
1265 if ( isset( $fields['sha1'] ) ) {
1266 $record->setSha1( $fields['sha1'] );
1268 if ( isset( $fields['size'] ) ) {
1269 $record->setSize( intval( $fields['size'] ) );
1272 if ( isset( $fields['minor_edit'] ) ) {
1273 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1275 if ( isset( $fields['deleted'] ) ) {
1276 $record->setVisibility( intval( $fields['deleted'] ) );
1279 if ( isset( $fields['comment'] ) ) {
1280 Assert
::parameterType(
1281 CommentStoreComment
::class,
1285 $record->setComment( $fields['comment'] );
1290 * Load a page revision from a given revision ID number.
1291 * Returns null if no such revision can be found.
1293 * MCR migration note: this corresponds to Revision::loadFromId
1295 * @note direct use is deprecated!
1296 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1298 * @param IDatabase $db
1301 * @return RevisionRecord|null
1303 public function loadRevisionFromId( IDatabase
$db, $id ) {
1304 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1308 * Load either the current, or a specified, revision
1309 * that's attached to a given page. If not attached
1310 * to that page, will return null.
1312 * MCR migration note: this replaces Revision::loadFromPageId
1314 * @note direct use is deprecated!
1315 * @todo remove when unused!
1317 * @param IDatabase $db
1318 * @param int $pageid
1320 * @return RevisionRecord|null
1322 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1323 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1325 $conds['rev_id'] = intval( $id );
1327 $conds[] = 'rev_id=page_latest';
1329 return $this->loadRevisionFromConds( $db, $conds );
1333 * Load either the current, or a specified, revision
1334 * that's attached to a given page. If not attached
1335 * to that page, will return null.
1337 * MCR migration note: this replaces Revision::loadFromTitle
1339 * @note direct use is deprecated!
1340 * @todo remove when unused!
1342 * @param IDatabase $db
1343 * @param Title $title
1346 * @return RevisionRecord|null
1348 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1350 $matchId = intval( $id );
1352 $matchId = 'page_latest';
1355 return $this->loadRevisionFromConds(
1359 'page_namespace' => $title->getNamespace(),
1360 'page_title' => $title->getDBkey()
1368 * Load the revision for the given title with the given timestamp.
1369 * WARNING: Timestamps may in some circumstances not be unique,
1370 * so this isn't the best key to use.
1372 * MCR migration note: this replaces Revision::loadFromTimestamp
1374 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1375 * @todo remove when unused!
1377 * @param IDatabase $db
1378 * @param Title $title
1379 * @param string $timestamp
1380 * @return RevisionRecord|null
1382 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1383 return $this->loadRevisionFromConds( $db,
1385 'rev_timestamp' => $db->timestamp( $timestamp ),
1386 'page_namespace' => $title->getNamespace(),
1387 'page_title' => $title->getDBkey()
1395 * Given a set of conditions, fetch a revision
1397 * This method should be used if we are pretty sure the revision exists.
1398 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1399 * on a replica before hitting the master database.
1401 * MCR migration note: this corresponds to Revision::newFromConds
1403 * @param array $conditions
1404 * @param int $flags (optional)
1405 * @param Title $title
1407 * @return RevisionRecord|null
1409 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1410 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1411 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1412 $this->releaseDBConnection( $db );
1414 $lb = $this->getDBLoadBalancer();
1416 // Make sure new pending/committed revision are visibile later on
1417 // within web requests to certain avoid bugs like T93866 and T94407.
1419 && !( $flags & self
::READ_LATEST
)
1420 && $lb->getServerCount() > 1
1421 && $lb->hasOrMadeRecentMasterChanges()
1423 $flags = self
::READ_LATEST
;
1424 $db = $this->getDBConnection( DB_MASTER
);
1425 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1426 $this->releaseDBConnection( $db );
1433 * Given a set of conditions, fetch a revision from
1434 * the given database connection.
1436 * MCR migration note: this corresponds to Revision::loadFromConds
1438 * @param IDatabase $db
1439 * @param array $conditions
1440 * @param int $flags (optional)
1441 * @param Title $title
1443 * @return RevisionRecord|null
1445 private function loadRevisionFromConds(
1451 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1453 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1462 * Throws an exception if the given database connection does not belong to the wiki this
1463 * RevisionStore is bound to.
1465 * @param IDatabase $db
1466 * @throws MWException
1468 private function checkDatabaseWikiId( IDatabase
$db ) {
1469 $storeWiki = $this->wikiId
;
1470 $dbWiki = $db->getDomainID();
1472 if ( $dbWiki === $storeWiki ) {
1476 // XXX: we really want the default database ID...
1477 $storeWiki = $storeWiki ?
: wfWikiID();
1478 $dbWiki = $dbWiki ?
: wfWikiID();
1480 if ( $dbWiki !== $storeWiki ) {
1481 throw new MWException( "RevisionStore for $storeWiki "
1482 . "cannot be used with a DB connection for $dbWiki" );
1487 * Given a set of conditions, return a row with the
1488 * fields necessary to build RevisionRecord objects.
1490 * MCR migration note: this corresponds to Revision::fetchFromConds
1492 * @param IDatabase $db
1493 * @param array $conditions
1494 * @param int $flags (optional)
1496 * @return object|false data row as a raw object
1498 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1499 $this->checkDatabaseWikiId( $db );
1501 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
1503 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1504 $options[] = 'FOR UPDATE';
1506 return $db->selectRow(
1507 $revQuery['tables'],
1508 $revQuery['fields'],
1517 * Return the tables, fields, and join conditions to be selected to create
1518 * a new revision object.
1520 * MCR migration note: this replaces Revision::getQueryInfo
1524 * @param array $options Any combination of the following strings
1525 * - 'page': Join with the page table, and select fields to identify the page
1526 * - 'user': Join with the user table, and select the user name
1527 * - 'text': Join with the text table, and select fields to load page text
1529 * @return array With three keys:
1530 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1531 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1532 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1534 public function getQueryInfo( $options = [] ) {
1541 $ret['tables'][] = 'revision';
1542 $ret['fields'] = array_merge( $ret['fields'], [
1556 $commentQuery = CommentStore
::newKey( 'rev_comment' )->getJoin();
1557 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1558 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1559 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1561 if ( $this->contentHandlerUseDB
) {
1562 $ret['fields'][] = 'rev_content_format';
1563 $ret['fields'][] = 'rev_content_model';
1566 if ( in_array( 'page', $options, true ) ) {
1567 $ret['tables'][] = 'page';
1568 $ret['fields'] = array_merge( $ret['fields'], [
1576 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1579 if ( in_array( 'user', $options, true ) ) {
1580 $ret['tables'][] = 'user';
1581 $ret['fields'] = array_merge( $ret['fields'], [
1584 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
1587 if ( in_array( 'text', $options, true ) ) {
1588 $ret['tables'][] = 'text';
1589 $ret['fields'] = array_merge( $ret['fields'], [
1593 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1600 * Return the tables, fields, and join conditions to be selected to create
1601 * a new archived revision object.
1603 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1607 * @return array With three keys:
1608 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1609 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1610 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1612 public function getArchiveQueryInfo() {
1613 $commentQuery = CommentStore
::newKey( 'ar_comment' )->getJoin();
1615 'tables' => [ 'archive' ] +
$commentQuery['tables'],
1632 ] +
$commentQuery['fields'],
1633 'joins' => $commentQuery['joins'],
1636 if ( $this->contentHandlerUseDB
) {
1637 $ret['fields'][] = 'ar_content_format';
1638 $ret['fields'][] = 'ar_content_model';
1645 * Do a batched query for the sizes of a set of revisions.
1647 * MCR migration note: this replaces Revision::getParentLengths
1649 * @param IDatabase $db
1650 * @param int[] $revIds
1651 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1652 * of the corresponding revision.
1654 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
1655 $this->checkDatabaseWikiId( $db );
1659 return $revLens; // empty
1664 [ 'rev_id', 'rev_len' ],
1665 [ 'rev_id' => $revIds ],
1669 foreach ( $res as $row ) {
1670 $revLens[$row->rev_id
] = intval( $row->rev_len
);
1677 * Get previous revision for this title
1679 * MCR migration note: this replaces Revision::getPrevious
1681 * @param RevisionRecord $rev
1683 * @return RevisionRecord|null
1685 public function getPreviousRevision( RevisionRecord
$rev ) {
1686 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1687 $prev = $title->getPreviousRevisionID( $rev->getId() );
1689 return $this->getRevisionByTitle( $title, $prev );
1695 * Get next revision for this title
1697 * MCR migration note: this replaces Revision::getNext
1699 * @param RevisionRecord $rev
1701 * @return RevisionRecord|null
1703 public function getNextRevision( RevisionRecord
$rev ) {
1704 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1705 $next = $title->getNextRevisionID( $rev->getId() );
1707 return $this->getRevisionByTitle( $title, $next );
1713 * Get previous revision Id for this page_id
1714 * This is used to populate rev_parent_id on save
1716 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1718 * @param IDatabase $db
1719 * @param RevisionRecord $rev
1723 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
1724 $this->checkDatabaseWikiId( $db );
1726 if ( $rev->getPageId() === null ) {
1729 # Use page_latest if ID is not given
1730 if ( !$rev->getId() ) {
1731 $prevId = $db->selectField(
1732 'page', 'page_latest',
1733 [ 'page_id' => $rev->getPageId() ],
1737 $prevId = $db->selectField(
1738 'revision', 'rev_id',
1739 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1741 [ 'ORDER BY' => 'rev_id DESC' ]
1744 return intval( $prevId );
1748 * Get rev_timestamp from rev_id, without loading the rest of the row
1750 * MCR migration note: this replaces Revision::getTimestampFromId
1752 * @param Title $title
1755 * @return string|bool False if not found
1757 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1758 $db = $this->getDBConnection(
1759 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
1762 $conds = [ 'rev_id' => $id ];
1763 $conds['rev_page'] = $title->getArticleID();
1764 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1766 $this->releaseDBConnection( $db );
1767 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1771 * Get count of revisions per page...not very efficient
1773 * MCR migration note: this replaces Revision::countByPageId
1775 * @param IDatabase $db
1776 * @param int $id Page id
1779 public function countRevisionsByPageId( IDatabase
$db, $id ) {
1780 $this->checkDatabaseWikiId( $db );
1782 $row = $db->selectRow( 'revision',
1783 [ 'revCount' => 'COUNT(*)' ],
1784 [ 'rev_page' => $id ],
1788 return intval( $row->revCount
);
1794 * Get count of revisions per page...not very efficient
1796 * MCR migration note: this replaces Revision::countByTitle
1798 * @param IDatabase $db
1799 * @param Title $title
1802 public function countRevisionsByTitle( IDatabase
$db, $title ) {
1803 $id = $title->getArticleID();
1805 return $this->countRevisionsByPageId( $db, $id );
1811 * Check if no edits were made by other users since
1812 * the time a user started editing the page. Limit to
1813 * 50 revisions for the sake of performance.
1815 * MCR migration note: this replaces Revision::userWasLastToEdit
1817 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1818 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1819 * has been deprecated since 1.24.
1821 * @param IDatabase $db The Database to perform the check on.
1822 * @param int $pageId The ID of the page in question
1823 * @param int $userId The ID of the user in question
1824 * @param string $since Look at edits since this time
1826 * @return bool True if the given user was the only one to edit since the given timestamp
1828 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
1829 $this->checkDatabaseWikiId( $db );
1839 'rev_page' => $pageId,
1840 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1843 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ]
1845 foreach ( $res as $row ) {
1846 if ( $row->rev_user
!= $userId ) {
1854 * Load a revision based on a known page ID and current revision ID from the DB
1856 * This method allows for the use of caching, though accessing anything that normally
1857 * requires permission checks (aside from the text) will trigger a small DB lookup.
1859 * MCR migration note: this replaces Revision::newKnownCurrent
1861 * @param Title $title the associated page title
1862 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1864 * @return RevisionRecord|bool Returns false if missing
1866 public function getKnownCurrentRevision( Title
$title, $revId ) {
1867 $db = $this->getDBConnectionRef( DB_REPLICA
);
1869 $pageId = $title->getArticleID();
1876 $revId = $title->getLatestRevID();
1881 'No latest revision known for page ' . $title->getPrefixedDBkey()
1882 . ' even though it exists with page ID ' . $pageId
1887 $row = $this->cache
->getWithSetCallback(
1888 // Page/rev IDs passed in from DB to reflect history merges
1889 $this->cache
->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1890 WANObjectCache
::TTL_WEEK
,
1891 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1892 $setOpts +
= Database
::getCacheSetOptions( $db );
1895 'rev_page' => intval( $pageId ),
1896 'page_id' => intval( $pageId ),
1897 'rev_id' => intval( $revId ),
1900 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1901 return $row ?
: false; // don't cache negatives
1905 // Reflect revision deletion and user renames
1907 return $this->newRevisionFromRow( $row, 0, $title );
1913 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.