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 * @return RevisionRecord|null
853 public function getRevisionById( $id, $flags = 0 ) {
854 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
858 * Load either the current, or a specified, revision
859 * that's attached to a given link target. If not attached
860 * to that link target, will return null.
862 * MCR migration note: this replaces Revision::newFromTitle
865 * IDBAccessObject::READ_LATEST: Select the data from the master
866 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
868 * @param LinkTarget $linkTarget
869 * @param int $revId (optional)
870 * @param int $flags Bitfield (optional)
871 * @return RevisionRecord|null
873 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
875 'page_namespace' => $linkTarget->getNamespace(),
876 'page_title' => $linkTarget->getDBkey()
879 // Use the specified revision ID.
880 // Note that we use newRevisionFromConds here because we want to retry
881 // and fall back to master if the page is not found on a replica.
882 // Since the caller supplied a revision ID, we are pretty sure the revision is
883 // supposed to exist, so we should try hard to find it.
884 $conds['rev_id'] = $revId;
885 return $this->newRevisionFromConds( $conds, $flags );
887 // Use a join to get the latest revision.
888 // Note that we don't use newRevisionFromConds here because we don't want to retry
889 // and fall back to master. The assumption is that we only want to force the fallback
890 // if we are quite sure the revision exists because the caller supplied a revision ID.
891 // If the page isn't found at all on a replica, it probably simply does not exist.
892 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
894 $conds[] = 'rev_id=page_latest';
895 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
897 $this->releaseDBConnection( $db );
903 * Load either the current, or a specified, revision
904 * that's attached to a given page ID.
905 * Returns null if no such revision can be found.
907 * MCR migration note: this replaces Revision::newFromPageId
910 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
911 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
914 * @param int $revId (optional)
915 * @param int $flags Bitfield (optional)
916 * @return RevisionRecord|null
918 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
919 $conds = [ 'page_id' => $pageId ];
921 // Use the specified revision ID.
922 // Note that we use newRevisionFromConds here because we want to retry
923 // and fall back to master if the page is not found on a replica.
924 // Since the caller supplied a revision ID, we are pretty sure the revision is
925 // supposed to exist, so we should try hard to find it.
926 $conds['rev_id'] = $revId;
927 return $this->newRevisionFromConds( $conds, $flags );
929 // Use a join to get the latest revision.
930 // Note that we don't use newRevisionFromConds here because we don't want to retry
931 // and fall back to master. The assumption is that we only want to force the fallback
932 // if we are quite sure the revision exists because the caller supplied a revision ID.
933 // If the page isn't found at all on a replica, it probably simply does not exist.
934 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
936 $conds[] = 'rev_id=page_latest';
937 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
939 $this->releaseDBConnection( $db );
945 * Load the revision for the given title with the given timestamp.
946 * WARNING: Timestamps may in some circumstances not be unique,
947 * so this isn't the best key to use.
949 * MCR migration note: this replaces Revision::loadFromTimestamp
951 * @param Title $title
952 * @param string $timestamp
953 * @return RevisionRecord|null
955 public function getRevisionFromTimestamp( $title, $timestamp ) {
956 return $this->newRevisionFromConds(
958 'rev_timestamp' => $timestamp,
959 'page_namespace' => $title->getNamespace(),
960 'page_title' => $title->getDBkey()
968 * Make a fake revision object from an archive table row. This is queried
969 * for permissions or even inserted (as in Special:Undelete)
971 * MCR migration note: this replaces Revision::newFromArchiveRow
974 * @param int $queryFlags
975 * @param Title|null $title
976 * @param array $overrides associative array with fields of $row to override. This may be
977 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
978 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
979 * override ar_parent_id.
981 * @return RevisionRecord
982 * @throws MWException
984 public function newRevisionFromArchiveRow(
988 array $overrides = []
990 Assert
::parameterType( 'object', $row, '$row' );
992 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
993 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
995 if ( !$title && isset( $overrides['title'] ) ) {
996 if ( !( $overrides['title'] instanceof Title
) ) {
997 throw new MWException( 'title field override must contain a Title object.' );
1000 $title = $overrides['title'];
1003 if ( !isset( $title ) ) {
1004 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1005 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1007 throw new InvalidArgumentException(
1008 'A Title or ar_namespace and ar_title must be given'
1013 foreach ( $overrides as $key => $value ) {
1015 $row->$field = $value;
1018 $user = $this->getUserIdentityFromRowObject( $row, 'ar_' );
1020 $comment = CommentStore
::newKey( 'ar_comment' )
1021 // Legacy because $row may have come from self::selectFields()
1022 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1024 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1025 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1027 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1031 * @param object $row
1032 * @param string $prefix Field prefix, such as 'rev_' or 'ar_'.
1034 * @return UserIdentityValue
1036 private function getUserIdentityFromRowObject( $row, $prefix = 'rev_' ) {
1037 $idField = "{$prefix}user";
1038 $nameField = "{$prefix}user_text";
1040 $userId = intval( $row->$idField );
1042 if ( isset( $row->user_name
) ) {
1043 $userName = $row->user_name
;
1044 } elseif ( isset( $row->$nameField ) ) {
1045 $userName = $row->$nameField;
1047 $userName = User
::whoIs( $userId );
1050 if ( $userName === false ) {
1051 wfWarn( __METHOD__
. ': Cannot determine user name for user ID ' . $userId );
1055 return new UserIdentityValue( $userId, $userName );
1059 * @see RevisionFactory::newRevisionFromRow_1_29
1061 * MCR migration note: this replaces Revision::newFromRow
1063 * @param object $row
1064 * @param int $queryFlags
1065 * @param Title|null $title
1067 * @return RevisionRecord
1068 * @throws MWException
1069 * @throws RevisionAccessException
1071 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title
$title = null ) {
1072 Assert
::parameterType( 'object', $row, '$row' );
1075 $pageId = isset( $row->rev_page
) ?
$row->rev_page
: 0; // XXX: also check page_id?
1076 $revId = isset( $row->rev_id
) ?
$row->rev_id
: 0;
1078 $title = $this->getTitle( $pageId, $revId );
1081 if ( !isset( $row->page_latest
) ) {
1082 $row->page_latest
= $title->getLatestRevID();
1083 if ( $row->page_latest
=== 0 && $title->exists() ) {
1084 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1088 $user = $this->getUserIdentityFromRowObject( $row );
1090 $comment = CommentStore
::newKey( 'rev_comment' )
1091 // Legacy because $row may have come from self::selectFields()
1092 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1094 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1095 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1097 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1101 * @see RevisionFactory::newRevisionFromRow
1103 * MCR migration note: this replaces Revision::newFromRow
1105 * @param object $row
1106 * @param int $queryFlags
1107 * @param Title|null $title
1109 * @return RevisionRecord
1111 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1112 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1116 * Constructs a new MutableRevisionRecord based on the given associative array following
1117 * the MW1.29 convention for the Revision constructor.
1119 * MCR migration note: this replaces Revision::newFromRow
1121 * @param array $fields
1122 * @param int $queryFlags
1123 * @param Title|null $title
1125 * @return MutableRevisionRecord
1126 * @throws MWException
1127 * @throws RevisionAccessException
1129 public function newMutableRevisionFromArray(
1134 if ( !$title && isset( $fields['title'] ) ) {
1135 if ( !( $fields['title'] instanceof Title
) ) {
1136 throw new MWException( 'title field must contain a Title object.' );
1139 $title = $fields['title'];
1143 $pageId = isset( $fields['page'] ) ?
$fields['page'] : 0;
1144 $revId = isset( $fields['id'] ) ?
$fields['id'] : 0;
1146 $title = $this->getTitle( $pageId, $revId );
1149 if ( !isset( $fields['page'] ) ) {
1150 $fields['page'] = $title->getArticleID( $queryFlags );
1153 // if we have a content object, use it to set the model and type
1154 if ( !empty( $fields['content'] ) ) {
1155 if ( !( $fields['content'] instanceof Content
) ) {
1156 throw new MWException( 'content field must contain a Content object.' );
1159 if ( !empty( $fields['text_id'] ) ) {
1160 throw new MWException(
1161 "Text already stored in external store (id {$fields['text_id']}), " .
1162 "can't serialize content object"
1167 // Replaces old lazy loading logic in Revision::getUserText.
1168 if ( !isset( $fields['user_text'] ) && isset( $fields['user'] ) ) {
1169 if ( $fields['user'] instanceof UserIdentity
) {
1170 /** @var User $user */
1171 $user = $fields['user'];
1172 $fields['user_text'] = $user->getName();
1173 $fields['user'] = $user->getId();
1175 // TODO: wrap this in a callback to make it lazy again.
1176 $name = $fields['user'] === 0 ?
false : User
::whoIs( $fields['user'] );
1178 if ( $name === false ) {
1179 throw new MWException(
1180 'user_text not given, and unknown user ID ' . $fields['user']
1184 $fields['user_text'] = $name;
1189 isset( $fields['comment'] )
1190 && !( $fields['comment'] instanceof CommentStoreComment
)
1192 $commentData = isset( $fields['comment_data'] ) ?
$fields['comment_data'] : null;
1194 if ( $fields['comment'] instanceof Message
) {
1195 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1200 $commentText = trim( strval( $fields['comment'] ) );
1201 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1208 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1210 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1211 $this->initializeMutableRevisionFromArray( $revision, $fields );
1212 $revision->setSlot( $mainSlot );
1218 * @param MutableRevisionRecord $record
1219 * @param array $fields
1221 private function initializeMutableRevisionFromArray(
1222 MutableRevisionRecord
$record,
1225 /** @var UserIdentity $user */
1228 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1229 $user = $fields['user'];
1230 } elseif ( isset( $fields['user'] ) && isset( $fields['user_text'] ) ) {
1231 $user = new UserIdentityValue( intval( $fields['user'] ), $fields['user_text'] );
1232 } elseif ( isset( $fields['user'] ) ) {
1233 $user = User
::newFromId( intval( $fields['user'] ) );
1234 } elseif ( isset( $fields['user_text'] ) ) {
1235 $user = User
::newFromName( $fields['user_text'] );
1237 // User::newFromName will return false for IP addresses (and invalid names)
1238 if ( $user == false ) {
1239 $user = new UserIdentityValue( 0, $fields['user_text'] );
1244 $record->setUser( $user );
1247 $timestamp = isset( $fields['timestamp'] )
1248 ?
strval( $fields['timestamp'] )
1249 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1251 $record->setTimestamp( $timestamp );
1253 if ( isset( $fields['page'] ) ) {
1254 $record->setPageId( intval( $fields['page'] ) );
1257 if ( isset( $fields['id'] ) ) {
1258 $record->setId( intval( $fields['id'] ) );
1260 if ( isset( $fields['parent_id'] ) ) {
1261 $record->setParentId( intval( $fields['parent_id'] ) );
1264 if ( isset( $fields['sha1'] ) ) {
1265 $record->setSha1( $fields['sha1'] );
1267 if ( isset( $fields['size'] ) ) {
1268 $record->setSize( intval( $fields['size'] ) );
1271 if ( isset( $fields['minor_edit'] ) ) {
1272 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1274 if ( isset( $fields['deleted'] ) ) {
1275 $record->setVisibility( intval( $fields['deleted'] ) );
1278 if ( isset( $fields['comment'] ) ) {
1279 Assert
::parameterType(
1280 CommentStoreComment
::class,
1284 $record->setComment( $fields['comment'] );
1289 * Load a page revision from a given revision ID number.
1290 * Returns null if no such revision can be found.
1292 * MCR migration note: this corresponds to Revision::loadFromId
1294 * @note direct use is deprecated!
1295 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1297 * @param IDatabase $db
1300 * @return RevisionRecord|null
1302 public function loadRevisionFromId( IDatabase
$db, $id ) {
1303 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1307 * Load either the current, or a specified, revision
1308 * that's attached to a given page. If not attached
1309 * to that page, will return null.
1311 * MCR migration note: this replaces Revision::loadFromPageId
1313 * @note direct use is deprecated!
1314 * @todo remove when unused!
1316 * @param IDatabase $db
1317 * @param int $pageid
1319 * @return RevisionRecord|null
1321 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1322 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1324 $conds['rev_id'] = intval( $id );
1326 $conds[] = 'rev_id=page_latest';
1328 return $this->loadRevisionFromConds( $db, $conds );
1332 * Load either the current, or a specified, revision
1333 * that's attached to a given page. If not attached
1334 * to that page, will return null.
1336 * MCR migration note: this replaces Revision::loadFromTitle
1338 * @note direct use is deprecated!
1339 * @todo remove when unused!
1341 * @param IDatabase $db
1342 * @param Title $title
1345 * @return RevisionRecord|null
1347 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1349 $matchId = intval( $id );
1351 $matchId = 'page_latest';
1354 return $this->loadRevisionFromConds(
1358 'page_namespace' => $title->getNamespace(),
1359 'page_title' => $title->getDBkey()
1367 * Load the revision for the given title with the given timestamp.
1368 * WARNING: Timestamps may in some circumstances not be unique,
1369 * so this isn't the best key to use.
1371 * MCR migration note: this replaces Revision::loadFromTimestamp
1373 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1374 * @todo remove when unused!
1376 * @param IDatabase $db
1377 * @param Title $title
1378 * @param string $timestamp
1379 * @return RevisionRecord|null
1381 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1382 return $this->loadRevisionFromConds( $db,
1384 'rev_timestamp' => $db->timestamp( $timestamp ),
1385 'page_namespace' => $title->getNamespace(),
1386 'page_title' => $title->getDBkey()
1394 * Given a set of conditions, fetch a revision
1396 * This method should be used if we are pretty sure the revision exists.
1397 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1398 * on a replica before hitting the master database.
1400 * MCR migration note: this corresponds to Revision::newFromConds
1402 * @param array $conditions
1403 * @param int $flags (optional)
1404 * @param Title $title
1406 * @return RevisionRecord|null
1408 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1409 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1410 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1411 $this->releaseDBConnection( $db );
1413 $lb = $this->getDBLoadBalancer();
1415 // Make sure new pending/committed revision are visibile later on
1416 // within web requests to certain avoid bugs like T93866 and T94407.
1418 && !( $flags & self
::READ_LATEST
)
1419 && $lb->getServerCount() > 1
1420 && $lb->hasOrMadeRecentMasterChanges()
1422 $flags = self
::READ_LATEST
;
1423 $db = $this->getDBConnection( DB_MASTER
);
1424 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1425 $this->releaseDBConnection( $db );
1432 * Given a set of conditions, fetch a revision from
1433 * the given database connection.
1435 * MCR migration note: this corresponds to Revision::loadFromConds
1437 * @param IDatabase $db
1438 * @param array $conditions
1439 * @param int $flags (optional)
1440 * @param Title $title
1442 * @return RevisionRecord|null
1444 private function loadRevisionFromConds(
1450 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1452 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1461 * Throws an exception if the given database connection does not belong to the wiki this
1462 * RevisionStore is bound to.
1464 * @param IDatabase $db
1465 * @throws MWException
1467 private function checkDatabaseWikiId( IDatabase
$db ) {
1468 $storeWiki = $this->wikiId
;
1469 $dbWiki = $db->getDomainID();
1471 if ( $dbWiki === $storeWiki ) {
1475 // XXX: we really want the default database ID...
1476 $storeWiki = $storeWiki ?
: wfWikiID();
1477 $dbWiki = $dbWiki ?
: wfWikiID();
1479 if ( $dbWiki !== $storeWiki ) {
1480 throw new MWException( "RevisionStore for $storeWiki "
1481 . "cannot be used with a DB connection for $dbWiki" );
1486 * Given a set of conditions, return a row with the
1487 * fields necessary to build RevisionRecord objects.
1489 * MCR migration note: this corresponds to Revision::fetchFromConds
1491 * @param IDatabase $db
1492 * @param array $conditions
1493 * @param int $flags (optional)
1495 * @return object|false data row as a raw object
1497 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1498 $this->checkDatabaseWikiId( $db );
1500 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
1502 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1503 $options[] = 'FOR UPDATE';
1505 return $db->selectRow(
1506 $revQuery['tables'],
1507 $revQuery['fields'],
1516 * Return the tables, fields, and join conditions to be selected to create
1517 * a new revision object.
1519 * MCR migration note: this replaces Revision::getQueryInfo
1523 * @param array $options Any combination of the following strings
1524 * - 'page': Join with the page table, and select fields to identify the page
1525 * - 'user': Join with the user table, and select the user name
1526 * - 'text': Join with the text table, and select fields to load page text
1528 * @return array With three keys:
1529 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1530 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1531 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1533 public function getQueryInfo( $options = [] ) {
1540 $ret['tables'][] = 'revision';
1541 $ret['fields'] = array_merge( $ret['fields'], [
1555 $commentQuery = CommentStore
::newKey( 'rev_comment' )->getJoin();
1556 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1557 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1558 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1560 if ( $this->contentHandlerUseDB
) {
1561 $ret['fields'][] = 'rev_content_format';
1562 $ret['fields'][] = 'rev_content_model';
1565 if ( in_array( 'page', $options, true ) ) {
1566 $ret['tables'][] = 'page';
1567 $ret['fields'] = array_merge( $ret['fields'], [
1575 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1578 if ( in_array( 'user', $options, true ) ) {
1579 $ret['tables'][] = 'user';
1580 $ret['fields'] = array_merge( $ret['fields'], [
1583 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
1586 if ( in_array( 'text', $options, true ) ) {
1587 $ret['tables'][] = 'text';
1588 $ret['fields'] = array_merge( $ret['fields'], [
1592 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1599 * Return the tables, fields, and join conditions to be selected to create
1600 * a new archived revision object.
1602 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1606 * @return array With three keys:
1607 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1608 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1609 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1611 public function getArchiveQueryInfo() {
1612 $commentQuery = CommentStore
::newKey( 'ar_comment' )->getJoin();
1614 'tables' => [ 'archive' ] +
$commentQuery['tables'],
1631 ] +
$commentQuery['fields'],
1632 'joins' => $commentQuery['joins'],
1635 if ( $this->contentHandlerUseDB
) {
1636 $ret['fields'][] = 'ar_content_format';
1637 $ret['fields'][] = 'ar_content_model';
1644 * Do a batched query for the sizes of a set of revisions.
1646 * MCR migration note: this replaces Revision::getParentLengths
1648 * @param IDatabase $db
1649 * @param int[] $revIds
1650 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1651 * of the corresponding revision.
1653 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
1654 $this->checkDatabaseWikiId( $db );
1658 return $revLens; // empty
1663 [ 'rev_id', 'rev_len' ],
1664 [ 'rev_id' => $revIds ],
1668 foreach ( $res as $row ) {
1669 $revLens[$row->rev_id
] = intval( $row->rev_len
);
1676 * Get previous revision for this title
1678 * MCR migration note: this replaces Revision::getPrevious
1680 * @param RevisionRecord $rev
1682 * @return RevisionRecord|null
1684 public function getPreviousRevision( RevisionRecord
$rev ) {
1685 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1686 $prev = $title->getPreviousRevisionID( $rev->getId() );
1688 return $this->getRevisionByTitle( $title, $prev );
1694 * Get next revision for this title
1696 * MCR migration note: this replaces Revision::getNext
1698 * @param RevisionRecord $rev
1700 * @return RevisionRecord|null
1702 public function getNextRevision( RevisionRecord
$rev ) {
1703 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1704 $next = $title->getNextRevisionID( $rev->getId() );
1706 return $this->getRevisionByTitle( $title, $next );
1712 * Get previous revision Id for this page_id
1713 * This is used to populate rev_parent_id on save
1715 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1717 * @param IDatabase $db
1718 * @param RevisionRecord $rev
1722 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
1723 $this->checkDatabaseWikiId( $db );
1725 if ( $rev->getPageId() === null ) {
1728 # Use page_latest if ID is not given
1729 if ( !$rev->getId() ) {
1730 $prevId = $db->selectField(
1731 'page', 'page_latest',
1732 [ 'page_id' => $rev->getPageId() ],
1736 $prevId = $db->selectField(
1737 'revision', 'rev_id',
1738 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1740 [ 'ORDER BY' => 'rev_id DESC' ]
1743 return intval( $prevId );
1747 * Get rev_timestamp from rev_id, without loading the rest of the row
1749 * MCR migration note: this replaces Revision::getTimestampFromId
1751 * @param Title $title
1754 * @return string|bool False if not found
1756 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1757 $db = $this->getDBConnection(
1758 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
1761 $conds = [ 'rev_id' => $id ];
1762 $conds['rev_page'] = $title->getArticleID();
1763 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1765 $this->releaseDBConnection( $db );
1766 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1770 * Get count of revisions per page...not very efficient
1772 * MCR migration note: this replaces Revision::countByPageId
1774 * @param IDatabase $db
1775 * @param int $id Page id
1778 public function countRevisionsByPageId( IDatabase
$db, $id ) {
1779 $this->checkDatabaseWikiId( $db );
1781 $row = $db->selectRow( 'revision',
1782 [ 'revCount' => 'COUNT(*)' ],
1783 [ 'rev_page' => $id ],
1787 return intval( $row->revCount
);
1793 * Get count of revisions per page...not very efficient
1795 * MCR migration note: this replaces Revision::countByTitle
1797 * @param IDatabase $db
1798 * @param Title $title
1801 public function countRevisionsByTitle( IDatabase
$db, $title ) {
1802 $id = $title->getArticleID();
1804 return $this->countRevisionsByPageId( $db, $id );
1810 * Check if no edits were made by other users since
1811 * the time a user started editing the page. Limit to
1812 * 50 revisions for the sake of performance.
1814 * MCR migration note: this replaces Revision::userWasLastToEdit
1816 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1817 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1818 * has been deprecated since 1.24.
1820 * @param IDatabase $db The Database to perform the check on.
1821 * @param int $pageId The ID of the page in question
1822 * @param int $userId The ID of the user in question
1823 * @param string $since Look at edits since this time
1825 * @return bool True if the given user was the only one to edit since the given timestamp
1827 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
1828 $this->checkDatabaseWikiId( $db );
1838 'rev_page' => $pageId,
1839 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1842 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ]
1844 foreach ( $res as $row ) {
1845 if ( $row->rev_user
!= $userId ) {
1853 * Load a revision based on a known page ID and current revision ID from the DB
1855 * This method allows for the use of caching, though accessing anything that normally
1856 * requires permission checks (aside from the text) will trigger a small DB lookup.
1858 * MCR migration note: this replaces Revision::newKnownCurrent
1860 * @param Title $title the associated page title
1861 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1863 * @return RevisionRecord|bool Returns false if missing
1865 public function getKnownCurrentRevision( Title
$title, $revId ) {
1866 $db = $this->getDBConnectionRef( DB_REPLICA
);
1868 $pageId = $title->getArticleID();
1875 $revId = $title->getLatestRevID();
1880 'No latest revision known for page ' . $title->getPrefixedDBkey()
1881 . ' even though it exists with page ID ' . $pageId
1886 $row = $this->cache
->getWithSetCallback(
1887 // Page/rev IDs passed in from DB to reflect history merges
1888 $this->cache
->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1889 WANObjectCache
::TTL_WEEK
,
1890 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1891 $setOpts +
= Database
::getCacheSetOptions( $db );
1894 'rev_page' => intval( $pageId ),
1895 'page_id' => intval( $pageId ),
1896 'rev_id' => intval( $revId ),
1899 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1900 return $row ?
: false; // don't cache negatives
1904 // Reflect revision deletion and user renames
1906 return $this->newRevisionFromRow( $row, 0, $title );
1912 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.