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 * @note this method should be private, external use should be avoided!
169 * @param int|null $pageId
170 * @param int|null $revId
171 * @param int $queryFlags
174 * @throws RevisionAccessException
176 public function getTitle( $pageId, $revId, $queryFlags = 0 ) {
177 if ( !$pageId && !$revId ) {
178 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
181 list( $dbMode, $dbOptions, , ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
182 $titleFlags = $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0;
185 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
186 if ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false ) {
187 // TODO: better foreign title handling (introduce TitleFactory)
188 $title = Title
::newFromID( $pageId, $titleFlags );
191 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
192 if ( !$title && $revId !== null && $revId > 0 ) {
193 $dbr = $this->getDbConnectionRef( $dbMode );
194 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
195 $row = $dbr->selectRow(
196 [ 'revision', 'page' ],
205 [ 'rev_id' => $revId ],
208 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
211 // TODO: better foreign title handling (introduce TitleFactory)
212 $title = Title
::newFromRow( $row );
217 throw new RevisionAccessException(
218 "Could not determine title for page ID $pageId and revision ID $revId"
226 * @param mixed $value
227 * @param string $name
229 * @throw IncompleteRevisionException if $value is null
230 * @return mixed $value, if $value is not null
232 private function failOnNull( $value, $name ) {
233 if ( $value === null ) {
234 throw new IncompleteRevisionException(
235 "$name must not be " . var_export( $value, true ) . "!"
243 * @param mixed $value
244 * @param string $name
246 * @throw IncompleteRevisionException if $value is empty
247 * @return mixed $value, if $value is not null
249 private function failOnEmpty( $value, $name ) {
250 if ( $value === null ||
$value === 0 ||
$value === '' ) {
251 throw new IncompleteRevisionException(
252 "$name must not be " . var_export( $value, true ) . "!"
260 * Insert a new revision into the database, returning the new revision ID
261 * number on success and dies horribly on failure.
263 * MCR migration note: this replaces Revision::insertOn
265 * @param RevisionRecord $rev
266 * @param IDatabase $dbw (master connection)
268 * @throws InvalidArgumentException
269 * @return RevisionRecord the new revision record.
271 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
272 // TODO: pass in a DBTransactionContext instead of a database connection.
273 $this->checkDatabaseWikiId( $dbw );
275 if ( !$rev->getSlotRoles() ) {
276 throw new InvalidArgumentException( 'At least one slot needs to be defined!' );
279 if ( $rev->getSlotRoles() !== [ 'main' ] ) {
280 throw new InvalidArgumentException( 'Only the main slot is supported for now!' );
283 // TODO: we shouldn't need an actual Title here.
284 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
285 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
287 $parentId = $rev->getParentId() === null
288 ?
$this->getPreviousRevisionId( $dbw, $rev )
289 : $rev->getParentId();
291 // Record the text (or external storage URL) to the blob store
292 $slot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
294 $size = $this->failOnNull( $rev->getSize(), 'size field' );
295 $sha1 = $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
297 if ( !$slot->hasAddress() ) {
298 $content = $slot->getContent();
299 $format = $content->getDefaultFormat();
300 $model = $content->getModel();
302 $this->checkContentModel( $content, $title );
304 $data = $content->serialize( $format );
306 // Hints allow the blob store to optimize by "leaking" application level information to it.
307 // TODO: with the new MCR storage schema, we rev_id have this before storing the blobs.
308 // When we have it, add rev_id as a hint. Can be used with rev_parent_id for
309 // differential storage or compression of subsequent revisions.
311 BlobStore
::DESIGNATION_HINT
=> 'page-content', // BlobStore may be used for other things too.
312 BlobStore
::PAGE_HINT
=> $pageId,
313 BlobStore
::ROLE_HINT
=> $slot->getRole(),
314 BlobStore
::PARENT_HINT
=> $parentId,
315 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
316 BlobStore
::MODEL_HINT
=> $model,
317 BlobStore
::FORMAT_HINT
=> $format,
320 $blobAddress = $this->blobStore
->storeBlob( $data, $blobHints );
322 $blobAddress = $slot->getAddress();
323 $model = $slot->getModel();
324 $format = $slot->getFormat();
327 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
330 throw new LogicException(
331 'Blob address not supported in 1.29 database schema: ' . $blobAddress
335 // getTextIdFromAddress() is free to insert something into the text table, so $textId
336 // may be a new value, not anything already contained in $blobAddress.
337 $blobAddress = 'tt:' . $textId;
339 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
340 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
341 $timestamp = $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
343 # Record the edit in revisions
345 'rev_page' => $pageId,
346 'rev_parent_id' => $parentId,
347 'rev_text_id' => $textId,
348 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
349 'rev_user' => $this->failOnNull( $user->getId(), 'user field' ),
350 'rev_user_text' => $this->failOnEmpty( $user->getName(), 'user_text field' ),
351 'rev_timestamp' => $dbw->timestamp( $timestamp ),
352 'rev_deleted' => $rev->getVisibility(),
357 if ( $rev->getId() !== null ) {
358 // Needed to restore revisions with their original ID
359 $row['rev_id'] = $rev->getId();
362 list( $commentFields, $commentCallback ) =
363 CommentStore
::newKey( 'rev_comment' )->insertWithTempTable( $dbw, $comment );
364 $row +
= $commentFields;
366 if ( $this->contentHandlerUseDB
) {
367 // MCR migration note: rev_content_model and rev_content_format will go away
369 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
370 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
372 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
373 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
376 $dbw->insert( 'revision', $row, __METHOD__
);
378 if ( !isset( $row['rev_id'] ) ) {
379 // only if auto-increment was used
380 $row['rev_id'] = intval( $dbw->insertId() );
382 $commentCallback( $row['rev_id'] );
384 // Insert IP revision into ip_changes for use when querying for a range.
385 if ( $row['rev_user'] === 0 && IP
::isValid( $row['rev_user_text'] ) ) {
387 'ipc_rev_id' => $row['rev_id'],
388 'ipc_rev_timestamp' => $row['rev_timestamp'],
389 'ipc_hex' => IP
::toHex( $row['rev_user_text'] ),
391 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
394 $newSlot = SlotRecord
::newSaved( $row['rev_id'], $blobAddress, $slot );
395 $slots = new RevisionSlots( [ 'main' => $newSlot ] );
397 $user = new UserIdentityValue( intval( $row['rev_user'] ), $row['rev_user_text'] );
399 $rev = new RevisionStoreRecord(
408 $newSlot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
411 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
412 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
413 Assert
::postcondition(
414 $rev->getComment( RevisionRecord
::RAW
) !== null,
415 'revision must have a comment'
417 Assert
::postcondition(
418 $rev->getUser( RevisionRecord
::RAW
) !== null,
419 'revision must have a user'
422 Assert
::postcondition( $newSlot !== null, 'revision must have a main slot' );
423 Assert
::postcondition(
424 $newSlot->getAddress() !== null,
425 'main slot must have an addess'
428 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
434 * MCR migration note: this corresponds to Revision::checkContentModel
436 * @param Content $content
437 * @param Title $title
439 * @throws MWException
440 * @throws MWUnknownContentModelException
442 private function checkContentModel( Content
$content, Title
$title ) {
443 // Note: may return null for revisions that have not yet been inserted
445 $model = $content->getModel();
446 $format = $content->getDefaultFormat();
447 $handler = $content->getContentHandler();
451 if ( !$handler->isSupportedFormat( $format ) ) {
452 throw new MWException( "Can't use format $format with content model $model on $name" );
455 if ( !$this->contentHandlerUseDB
) {
456 // if $wgContentHandlerUseDB is not set,
457 // all revisions must use the default content model and format.
459 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
460 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
461 $defaultFormat = $defaultHandler->getDefaultFormat();
463 if ( $model != $defaultModel ) {
464 throw new MWException( "Can't save non-default content model with "
465 . "\$wgContentHandlerUseDB disabled: model is $model, "
466 . "default for $name is $defaultModel"
470 if ( $format != $defaultFormat ) {
471 throw new MWException( "Can't use non-default content format with "
472 . "\$wgContentHandlerUseDB disabled: format is $format, "
473 . "default for $name is $defaultFormat"
478 if ( !$content->isValid() ) {
479 throw new MWException(
480 "New content for $name is not valid! Content model is $model"
486 * Create a new null-revision for insertion into a page's
487 * history. This will not re-save the text, but simply refer
488 * to the text from the previous version.
490 * Such revisions can for instance identify page rename
491 * operations and other such meta-modifications.
493 * MCR migration note: this replaces Revision::newNullRevision
495 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
498 * @param IDatabase $dbw
499 * @param Title $title Title of the page to read from
500 * @param CommentStoreComment $comment RevisionRecord's summary
501 * @param bool $minor Whether the revision should be considered as minor
502 * @param User $user The user to attribute the revision to
503 * @return RevisionRecord|null RevisionRecord or null on error
505 public function newNullRevision(
508 CommentStoreComment
$comment,
512 $this->checkDatabaseWikiId( $dbw );
514 $fields = [ 'page_latest', 'page_namespace', 'page_title',
515 'rev_id', 'rev_text_id', 'rev_len', 'rev_sha1' ];
517 if ( $this->contentHandlerUseDB
) {
518 $fields[] = 'rev_content_model';
519 $fields[] = 'rev_content_format';
522 $current = $dbw->selectRow(
523 [ 'page', 'revision' ],
526 'page_id' => $title->getArticleID(),
527 'page_latest=rev_id',
530 [ 'FOR UPDATE' ] // T51581
535 'page' => $title->getArticleID(),
536 'user_text' => $user->getName(),
537 'user' => $user->getId(),
538 'comment' => $comment,
539 'minor_edit' => $minor,
540 'text_id' => $current->rev_text_id
,
541 'parent_id' => $current->page_latest
,
542 'len' => $current->rev_len
,
543 'sha1' => $current->rev_sha1
546 if ( $this->contentHandlerUseDB
) {
547 $fields['content_model'] = $current->rev_content_model
;
548 $fields['content_format'] = $current->rev_content_format
;
551 $fields['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
553 $mainSlot = $this->emulateMainSlot_1_29( $fields, 0, $title );
554 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
555 $this->initializeMutableRevisionFromArray( $revision, $fields );
556 $revision->setSlot( $mainSlot );
565 * MCR migration note: this replaces Revision::isUnpatrolled
567 * @todo This is overly specific, so move or kill this method.
569 * @param RevisionRecord $rev
571 * @return int Rcid of the unpatrolled row, zero if there isn't one
573 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
574 $rc = $this->getRecentChange( $rev );
575 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
576 return $rc->getAttribute( 'rc_id' );
583 * Get the RC object belonging to the current revision, if there's one
585 * MCR migration note: this replaces Revision::getRecentChange
587 * @todo move this somewhere else?
589 * @param RevisionRecord $rev
590 * @param int $flags (optional) $flags include:
591 * IDBAccessObject::READ_LATEST: Select the data from the master
593 * @return null|RecentChange
595 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
596 $dbr = $this->getDBConnection( DB_REPLICA
);
598 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
600 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
602 if ( !$userIdentity ) {
603 // If the revision has no user identity, chances are it never went
604 // into the database, and doesn't have an RC entry.
608 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
609 $rc = RecentChange
::newFromConds(
611 'rc_user_text' => $userIdentity->getName(),
612 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
613 'rc_this_oldid' => $rev->getId()
619 $this->releaseDBConnection( $dbr );
621 // XXX: cache this locally? Glue it to the RevisionRecord?
626 * Maps fields of the archive row to corresponding revision rows.
628 * @param object $archiveRow
630 * @return object a revision row object, corresponding to $archiveRow.
632 private static function mapArchiveFields( $archiveRow ) {
634 // keep with ar prefix:
637 // not the same suffix:
638 'ar_page_id' => 'rev_page',
639 'ar_rev_id' => 'rev_id',
642 'ar_text_id' => 'rev_text_id',
643 'ar_timestamp' => 'rev_timestamp',
644 'ar_user_text' => 'rev_user_text',
645 'ar_user' => 'rev_user',
646 'ar_minor_edit' => 'rev_minor_edit',
647 'ar_deleted' => 'rev_deleted',
648 'ar_len' => 'rev_len',
649 'ar_parent_id' => 'rev_parent_id',
650 'ar_sha1' => 'rev_sha1',
651 'ar_comment' => 'rev_comment',
652 'ar_comment_cid' => 'rev_comment_cid',
653 'ar_comment_id' => 'rev_comment_id',
654 'ar_comment_text' => 'rev_comment_text',
655 'ar_comment_data' => 'rev_comment_data',
656 'ar_comment_old' => 'rev_comment_old',
657 'ar_content_format' => 'rev_content_format',
658 'ar_content_model' => 'rev_content_model',
661 if ( empty( $archiveRow->ar_text_id
) ) {
662 $fieldMap['ar_text'] = 'old_text';
663 $fieldMap['ar_flags'] = 'old_flags';
666 $revRow = new stdClass();
667 foreach ( $fieldMap as $arKey => $revKey ) {
668 if ( property_exists( $archiveRow, $arKey ) ) {
669 $revRow->$revKey = $archiveRow->$arKey;
677 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
679 * @param object|array $row Either a database row or an array
680 * @param int $queryFlags for callbacks
681 * @param Title $title
683 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
684 * @throws MWException
686 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
687 $mainSlotRow = new stdClass();
688 $mainSlotRow->role_name
= 'main';
694 if ( is_object( $row ) ) {
696 if ( !isset( $row->rev_id
) && isset( $row->ar_user
) ) {
697 $row = $this->mapArchiveFields( $row );
700 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
701 $mainSlotRow->cont_address
= 'tt:' . $row->rev_text_id
;
702 } elseif ( isset( $row->ar_id
) ) {
703 $mainSlotRow->cont_address
= 'ar:' . $row->ar_id
;
706 if ( isset( $row->old_text
) ) {
707 // this happens when the text-table gets joined directly, in the pre-1.30 schema
708 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
709 $blobFlags = isset( $row->old_flags
) ?
strval( $row->old_flags
) : '';
712 $mainSlotRow->slot_revision
= intval( $row->rev_id
);
714 $mainSlotRow->cont_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
715 $mainSlotRow->cont_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
716 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
717 ?
strval( $row->rev_content_model
)
719 // XXX: in the future, we'll probably always use the default format, and drop content_format
720 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
721 ?
strval( $row->rev_content_format
)
723 } elseif ( is_array( $row ) ) {
724 $mainSlotRow->slot_revision
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
726 $mainSlotRow->cont_address
= isset( $row['text_id'] )
727 ?
'tt:' . intval( $row['text_id'] )
729 $mainSlotRow->cont_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
730 $mainSlotRow->cont_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
732 $mainSlotRow->model_name
= isset( $row['content_model'] )
733 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
734 // XXX: in the future, we'll probably always use the default format, and drop content_format
735 $mainSlotRow->format_name
= isset( $row['content_format'] )
736 ?
strval( $row['content_format'] ) : null;
737 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
738 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : '';
740 // if we have a Content object, override mText and mContentModel
741 if ( !empty( $row['content'] ) ) {
742 if ( !( $row['content'] instanceof Content
) ) {
743 throw new MWException( 'content field must contain a Content object.' );
746 /** @var Content $content */
747 $content = $row['content'];
748 $handler = $content->getContentHandler();
750 $mainSlotRow->model_name
= $content->getModel();
752 // XXX: in the future, we'll probably always use the default format.
753 if ( $mainSlotRow->format_name
=== null ) {
754 $mainSlotRow->format_name
= $handler->getDefaultFormat();
758 throw new MWException( 'Revision constructor passed invalid row format.' );
761 // With the old schema, the content changes with every revision.
762 // ...except for null-revisions. Would be nice if we could detect them.
763 $mainSlotRow->slot_inherited
= 0;
765 if ( $mainSlotRow->model_name
=== null ) {
766 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
767 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
768 // TODO: MCR: deprecate $title->getModel().
769 return ContentHandler
::getDefaultModelFor( $title );
774 $content = function ( SlotRecord
$slot )
775 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
777 return $this->loadSlotContent(
781 $mainSlotRow->format_name
,
787 return new SlotRecord( $mainSlotRow, $content );
791 * Loads a Content object based on a slot row.
793 * This method does not call $slot->getContent(), and may be used as a callback
794 * called by $slot->getContent().
796 * MCR migration note: this roughly corresponds to Revision::getContentInternal
798 * @param SlotRecord $slot The SlotRecord to load content for
799 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
800 * @param string $blobFlags Flags indicating how $blobData needs to be processed
801 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
802 * @param int $queryFlags
804 * @throw RevisionAccessException
807 private function loadSlotContent(
814 if ( $blobData !== null ) {
815 Assert
::parameterType( 'string', $blobData, '$blobData' );
816 Assert
::parameterType( 'string', $blobFlags, '$blobFlags' );
818 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
820 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
822 if ( $data === false ) {
823 throw new RevisionAccessException(
824 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
828 $address = $slot->getAddress();
830 $data = $this->blobStore
->getBlob( $address, $queryFlags );
831 } catch ( BlobAccessException
$e ) {
832 throw new RevisionAccessException(
833 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
838 // Unserialize content
839 $handler = ContentHandler
::getForModelID( $slot->getModel() );
841 $content = $handler->unserializeContent( $data, $blobFormat );
846 * Load a page revision from a given revision ID number.
847 * Returns null if no such revision can be found.
849 * MCR migration note: this replaces Revision::newFromId
852 * IDBAccessObject::READ_LATEST: Select the data from the master
853 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
856 * @param int $flags (optional)
857 * @return RevisionRecord|null
859 public function getRevisionById( $id, $flags = 0 ) {
860 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
864 * Load either the current, or a specified, revision
865 * that's attached to a given link target. If not attached
866 * to that link target, will return null.
868 * MCR migration note: this replaces Revision::newFromTitle
871 * IDBAccessObject::READ_LATEST: Select the data from the master
872 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
874 * @param LinkTarget $linkTarget
875 * @param int $revId (optional)
876 * @param int $flags Bitfield (optional)
877 * @return RevisionRecord|null
879 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
881 'page_namespace' => $linkTarget->getNamespace(),
882 'page_title' => $linkTarget->getDBkey()
885 // Use the specified revision ID.
886 // Note that we use newRevisionFromConds here because we want to retry
887 // and fall back to master if the page is not found on a replica.
888 // Since the caller supplied a revision ID, we are pretty sure the revision is
889 // supposed to exist, so we should try hard to find it.
890 $conds['rev_id'] = $revId;
891 return $this->newRevisionFromConds( $conds, $flags );
893 // Use a join to get the latest revision.
894 // Note that we don't use newRevisionFromConds here because we don't want to retry
895 // and fall back to master. The assumption is that we only want to force the fallback
896 // if we are quite sure the revision exists because the caller supplied a revision ID.
897 // If the page isn't found at all on a replica, it probably simply does not exist.
898 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
900 $conds[] = 'rev_id=page_latest';
901 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
903 $this->releaseDBConnection( $db );
909 * Load either the current, or a specified, revision
910 * that's attached to a given page ID.
911 * Returns null if no such revision can be found.
913 * MCR migration note: this replaces Revision::newFromPageId
916 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
917 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
920 * @param int $revId (optional)
921 * @param int $flags Bitfield (optional)
922 * @return RevisionRecord|null
924 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
925 $conds = [ 'page_id' => $pageId ];
927 // Use the specified revision ID.
928 // Note that we use newRevisionFromConds here because we want to retry
929 // and fall back to master if the page is not found on a replica.
930 // Since the caller supplied a revision ID, we are pretty sure the revision is
931 // supposed to exist, so we should try hard to find it.
932 $conds['rev_id'] = $revId;
933 return $this->newRevisionFromConds( $conds, $flags );
935 // Use a join to get the latest revision.
936 // Note that we don't use newRevisionFromConds here because we don't want to retry
937 // and fall back to master. The assumption is that we only want to force the fallback
938 // if we are quite sure the revision exists because the caller supplied a revision ID.
939 // If the page isn't found at all on a replica, it probably simply does not exist.
940 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
942 $conds[] = 'rev_id=page_latest';
943 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
945 $this->releaseDBConnection( $db );
951 * Load the revision for the given title with the given timestamp.
952 * WARNING: Timestamps may in some circumstances not be unique,
953 * so this isn't the best key to use.
955 * MCR migration note: this replaces Revision::loadFromTimestamp
957 * @param Title $title
958 * @param string $timestamp
959 * @return RevisionRecord|null
961 public function getRevisionByTimestamp( $title, $timestamp ) {
962 return $this->newRevisionFromConds(
964 'rev_timestamp' => $timestamp,
965 'page_namespace' => $title->getNamespace(),
966 'page_title' => $title->getDBkey()
974 * Make a fake revision object from an archive table row. This is queried
975 * for permissions or even inserted (as in Special:Undelete)
977 * MCR migration note: this replaces Revision::newFromArchiveRow
980 * @param int $queryFlags
981 * @param Title|null $title
982 * @param array $overrides associative array with fields of $row to override. This may be
983 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
984 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
985 * override ar_parent_id.
987 * @return RevisionRecord
988 * @throws MWException
990 public function newRevisionFromArchiveRow(
994 array $overrides = []
996 Assert
::parameterType( 'object', $row, '$row' );
998 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
999 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1001 if ( !$title && isset( $overrides['title'] ) ) {
1002 if ( !( $overrides['title'] instanceof Title
) ) {
1003 throw new MWException( 'title field override must contain a Title object.' );
1006 $title = $overrides['title'];
1009 if ( !isset( $title ) ) {
1010 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1011 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1013 throw new InvalidArgumentException(
1014 'A Title or ar_namespace and ar_title must be given'
1019 foreach ( $overrides as $key => $value ) {
1021 $row->$field = $value;
1024 $user = $this->getUserIdentityFromRowObject( $row, 'ar_' );
1026 $comment = CommentStore
::newKey( 'ar_comment' )
1027 // Legacy because $row may have come from self::selectFields()
1028 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1030 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1031 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1033 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1037 * @param object $row
1038 * @param string $prefix Field prefix, such as 'rev_' or 'ar_'.
1040 * @return UserIdentityValue
1042 private function getUserIdentityFromRowObject( $row, $prefix = 'rev_' ) {
1043 $idField = "{$prefix}user";
1044 $nameField = "{$prefix}user_text";
1046 $userId = intval( $row->$idField );
1048 if ( isset( $row->user_name
) ) {
1049 $userName = $row->user_name
;
1050 } elseif ( isset( $row->$nameField ) ) {
1051 $userName = $row->$nameField;
1053 $userName = User
::whoIs( $userId );
1056 if ( $userName === false ) {
1057 wfWarn( __METHOD__
. ': Cannot determine user name for user ID ' . $userId );
1061 return new UserIdentityValue( $userId, $userName );
1065 * @see RevisionFactory::newRevisionFromRow_1_29
1067 * MCR migration note: this replaces Revision::newFromRow
1069 * @param object $row
1070 * @param int $queryFlags
1071 * @param Title|null $title
1073 * @return RevisionRecord
1074 * @throws MWException
1075 * @throws RevisionAccessException
1077 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title
$title = null ) {
1078 Assert
::parameterType( 'object', $row, '$row' );
1081 $pageId = isset( $row->rev_page
) ?
$row->rev_page
: 0; // XXX: also check page_id?
1082 $revId = isset( $row->rev_id
) ?
$row->rev_id
: 0;
1084 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1087 if ( !isset( $row->page_latest
) ) {
1088 $row->page_latest
= $title->getLatestRevID();
1089 if ( $row->page_latest
=== 0 && $title->exists() ) {
1090 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1094 $user = $this->getUserIdentityFromRowObject( $row );
1096 $comment = CommentStore
::newKey( 'rev_comment' )
1097 // Legacy because $row may have come from self::selectFields()
1098 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1100 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1101 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1103 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1107 * @see RevisionFactory::newRevisionFromRow
1109 * MCR migration note: this replaces Revision::newFromRow
1111 * @param object $row
1112 * @param int $queryFlags
1113 * @param Title|null $title
1115 * @return RevisionRecord
1117 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1118 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1122 * Constructs a new MutableRevisionRecord based on the given associative array following
1123 * the MW1.29 convention for the Revision constructor.
1125 * MCR migration note: this replaces Revision::newFromRow
1127 * @param array $fields
1128 * @param int $queryFlags
1129 * @param Title|null $title
1131 * @return MutableRevisionRecord
1132 * @throws MWException
1133 * @throws RevisionAccessException
1135 public function newMutableRevisionFromArray(
1140 if ( !$title && isset( $fields['title'] ) ) {
1141 if ( !( $fields['title'] instanceof Title
) ) {
1142 throw new MWException( 'title field must contain a Title object.' );
1145 $title = $fields['title'];
1149 $pageId = isset( $fields['page'] ) ?
$fields['page'] : 0;
1150 $revId = isset( $fields['id'] ) ?
$fields['id'] : 0;
1152 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1155 if ( !isset( $fields['page'] ) ) {
1156 $fields['page'] = $title->getArticleID( $queryFlags );
1159 // if we have a content object, use it to set the model and type
1160 if ( !empty( $fields['content'] ) ) {
1161 if ( !( $fields['content'] instanceof Content
) ) {
1162 throw new MWException( 'content field must contain a Content object.' );
1165 if ( !empty( $fields['text_id'] ) ) {
1166 throw new MWException(
1167 "Text already stored in external store (id {$fields['text_id']}), " .
1168 "can't serialize content object"
1173 // Replaces old lazy loading logic in Revision::getUserText.
1174 if ( !isset( $fields['user_text'] ) && isset( $fields['user'] ) ) {
1175 if ( $fields['user'] instanceof UserIdentity
) {
1176 /** @var User $user */
1177 $user = $fields['user'];
1178 $fields['user_text'] = $user->getName();
1179 $fields['user'] = $user->getId();
1181 // TODO: wrap this in a callback to make it lazy again.
1182 $name = $fields['user'] === 0 ?
false : User
::whoIs( $fields['user'] );
1184 if ( $name === false ) {
1185 throw new MWException(
1186 'user_text not given, and unknown user ID ' . $fields['user']
1190 $fields['user_text'] = $name;
1195 isset( $fields['comment'] )
1196 && !( $fields['comment'] instanceof CommentStoreComment
)
1198 $commentData = isset( $fields['comment_data'] ) ?
$fields['comment_data'] : null;
1200 if ( $fields['comment'] instanceof Message
) {
1201 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1206 $commentText = trim( strval( $fields['comment'] ) );
1207 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1214 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1216 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1217 $this->initializeMutableRevisionFromArray( $revision, $fields );
1218 $revision->setSlot( $mainSlot );
1224 * @param MutableRevisionRecord $record
1225 * @param array $fields
1227 private function initializeMutableRevisionFromArray(
1228 MutableRevisionRecord
$record,
1231 /** @var UserIdentity $user */
1234 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1235 $user = $fields['user'];
1236 } elseif ( isset( $fields['user'] ) && isset( $fields['user_text'] ) ) {
1237 $user = new UserIdentityValue( intval( $fields['user'] ), $fields['user_text'] );
1238 } elseif ( isset( $fields['user'] ) ) {
1239 $user = User
::newFromId( intval( $fields['user'] ) );
1240 } elseif ( isset( $fields['user_text'] ) ) {
1241 $user = User
::newFromName( $fields['user_text'] );
1243 // User::newFromName will return false for IP addresses (and invalid names)
1244 if ( $user == false ) {
1245 $user = new UserIdentityValue( 0, $fields['user_text'] );
1250 $record->setUser( $user );
1253 $timestamp = isset( $fields['timestamp'] )
1254 ?
strval( $fields['timestamp'] )
1255 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1257 $record->setTimestamp( $timestamp );
1259 if ( isset( $fields['page'] ) ) {
1260 $record->setPageId( intval( $fields['page'] ) );
1263 if ( isset( $fields['id'] ) ) {
1264 $record->setId( intval( $fields['id'] ) );
1266 if ( isset( $fields['parent_id'] ) ) {
1267 $record->setParentId( intval( $fields['parent_id'] ) );
1270 if ( isset( $fields['sha1'] ) ) {
1271 $record->setSha1( $fields['sha1'] );
1273 if ( isset( $fields['size'] ) ) {
1274 $record->setSize( intval( $fields['size'] ) );
1277 if ( isset( $fields['minor_edit'] ) ) {
1278 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1280 if ( isset( $fields['deleted'] ) ) {
1281 $record->setVisibility( intval( $fields['deleted'] ) );
1284 if ( isset( $fields['comment'] ) ) {
1285 Assert
::parameterType(
1286 CommentStoreComment
::class,
1290 $record->setComment( $fields['comment'] );
1295 * Load a page revision from a given revision ID number.
1296 * Returns null if no such revision can be found.
1298 * MCR migration note: this corresponds to Revision::loadFromId
1300 * @note direct use is deprecated!
1301 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1303 * @param IDatabase $db
1306 * @return RevisionRecord|null
1308 public function loadRevisionFromId( IDatabase
$db, $id ) {
1309 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1313 * Load either the current, or a specified, revision
1314 * that's attached to a given page. If not attached
1315 * to that page, will return null.
1317 * MCR migration note: this replaces Revision::loadFromPageId
1319 * @note direct use is deprecated!
1320 * @todo remove when unused!
1322 * @param IDatabase $db
1323 * @param int $pageid
1325 * @return RevisionRecord|null
1327 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1328 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1330 $conds['rev_id'] = intval( $id );
1332 $conds[] = 'rev_id=page_latest';
1334 return $this->loadRevisionFromConds( $db, $conds );
1338 * Load either the current, or a specified, revision
1339 * that's attached to a given page. If not attached
1340 * to that page, will return null.
1342 * MCR migration note: this replaces Revision::loadFromTitle
1344 * @note direct use is deprecated!
1345 * @todo remove when unused!
1347 * @param IDatabase $db
1348 * @param Title $title
1351 * @return RevisionRecord|null
1353 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1355 $matchId = intval( $id );
1357 $matchId = 'page_latest';
1360 return $this->loadRevisionFromConds(
1364 'page_namespace' => $title->getNamespace(),
1365 'page_title' => $title->getDBkey()
1373 * Load the revision for the given title with the given timestamp.
1374 * WARNING: Timestamps may in some circumstances not be unique,
1375 * so this isn't the best key to use.
1377 * MCR migration note: this replaces Revision::loadFromTimestamp
1379 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1380 * @todo remove when unused!
1382 * @param IDatabase $db
1383 * @param Title $title
1384 * @param string $timestamp
1385 * @return RevisionRecord|null
1387 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1388 return $this->loadRevisionFromConds( $db,
1390 'rev_timestamp' => $db->timestamp( $timestamp ),
1391 'page_namespace' => $title->getNamespace(),
1392 'page_title' => $title->getDBkey()
1400 * Given a set of conditions, fetch a revision
1402 * This method should be used if we are pretty sure the revision exists.
1403 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1404 * on a replica before hitting the master database.
1406 * MCR migration note: this corresponds to Revision::newFromConds
1408 * @param array $conditions
1409 * @param int $flags (optional)
1410 * @param Title $title
1412 * @return RevisionRecord|null
1414 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1415 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1416 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1417 $this->releaseDBConnection( $db );
1419 $lb = $this->getDBLoadBalancer();
1421 // Make sure new pending/committed revision are visibile later on
1422 // within web requests to certain avoid bugs like T93866 and T94407.
1424 && !( $flags & self
::READ_LATEST
)
1425 && $lb->getServerCount() > 1
1426 && $lb->hasOrMadeRecentMasterChanges()
1428 $flags = self
::READ_LATEST
;
1429 $db = $this->getDBConnection( DB_MASTER
);
1430 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1431 $this->releaseDBConnection( $db );
1438 * Given a set of conditions, fetch a revision from
1439 * the given database connection.
1441 * MCR migration note: this corresponds to Revision::loadFromConds
1443 * @param IDatabase $db
1444 * @param array $conditions
1445 * @param int $flags (optional)
1446 * @param Title $title
1448 * @return RevisionRecord|null
1450 private function loadRevisionFromConds(
1456 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1458 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1467 * Throws an exception if the given database connection does not belong to the wiki this
1468 * RevisionStore is bound to.
1470 * @param IDatabase $db
1471 * @throws MWException
1473 private function checkDatabaseWikiId( IDatabase
$db ) {
1474 $storeWiki = $this->wikiId
;
1475 $dbWiki = $db->getDomainID();
1477 if ( $dbWiki === $storeWiki ) {
1481 // XXX: we really want the default database ID...
1482 $storeWiki = $storeWiki ?
: wfWikiID();
1483 $dbWiki = $dbWiki ?
: wfWikiID();
1485 if ( $dbWiki === $storeWiki ) {
1489 // HACK: counteract encoding imposed by DatabaseDomain
1490 $storeWiki = str_replace( '?h', '-', $storeWiki );
1491 $dbWiki = str_replace( '?h', '-', $dbWiki );
1493 if ( $dbWiki === $storeWiki ) {
1497 throw new MWException( "RevisionStore for $storeWiki "
1498 . "cannot be used with a DB connection for $dbWiki" );
1502 * Given a set of conditions, return a row with the
1503 * fields necessary to build RevisionRecord objects.
1505 * MCR migration note: this corresponds to Revision::fetchFromConds
1507 * @param IDatabase $db
1508 * @param array $conditions
1509 * @param int $flags (optional)
1511 * @return object|false data row as a raw object
1513 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1514 $this->checkDatabaseWikiId( $db );
1516 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
1518 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1519 $options[] = 'FOR UPDATE';
1521 return $db->selectRow(
1522 $revQuery['tables'],
1523 $revQuery['fields'],
1532 * Return the tables, fields, and join conditions to be selected to create
1533 * a new revision object.
1535 * MCR migration note: this replaces Revision::getQueryInfo
1539 * @param array $options Any combination of the following strings
1540 * - 'page': Join with the page table, and select fields to identify the page
1541 * - 'user': Join with the user table, and select the user name
1542 * - 'text': Join with the text table, and select fields to load page text
1544 * @return array With three keys:
1545 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1546 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1547 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1549 public function getQueryInfo( $options = [] ) {
1556 $ret['tables'][] = 'revision';
1557 $ret['fields'] = array_merge( $ret['fields'], [
1571 $commentQuery = CommentStore
::newKey( 'rev_comment' )->getJoin();
1572 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1573 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1574 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1576 if ( $this->contentHandlerUseDB
) {
1577 $ret['fields'][] = 'rev_content_format';
1578 $ret['fields'][] = 'rev_content_model';
1581 if ( in_array( 'page', $options, true ) ) {
1582 $ret['tables'][] = 'page';
1583 $ret['fields'] = array_merge( $ret['fields'], [
1591 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1594 if ( in_array( 'user', $options, true ) ) {
1595 $ret['tables'][] = 'user';
1596 $ret['fields'] = array_merge( $ret['fields'], [
1599 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
1602 if ( in_array( 'text', $options, true ) ) {
1603 $ret['tables'][] = 'text';
1604 $ret['fields'] = array_merge( $ret['fields'], [
1608 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1615 * Return the tables, fields, and join conditions to be selected to create
1616 * a new archived revision object.
1618 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1622 * @return array With three keys:
1623 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1624 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1625 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1627 public function getArchiveQueryInfo() {
1628 $commentQuery = CommentStore
::newKey( 'ar_comment' )->getJoin();
1630 'tables' => [ 'archive' ] +
$commentQuery['tables'],
1647 ] +
$commentQuery['fields'],
1648 'joins' => $commentQuery['joins'],
1651 if ( $this->contentHandlerUseDB
) {
1652 $ret['fields'][] = 'ar_content_format';
1653 $ret['fields'][] = 'ar_content_model';
1660 * Do a batched query for the sizes of a set of revisions.
1662 * MCR migration note: this replaces Revision::getParentLengths
1664 * @param int[] $revIds
1665 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1666 * of the corresponding revision.
1668 public function getRevisionSizes( array $revIds ) {
1669 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
1673 * Do a batched query for the sizes of a set of revisions.
1675 * MCR migration note: this replaces Revision::getParentLengths
1677 * @deprecated use RevisionStore::getRevisionSizes instead.
1679 * @param IDatabase $db
1680 * @param int[] $revIds
1681 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1682 * of the corresponding revision.
1684 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
1685 $this->checkDatabaseWikiId( $db );
1689 return $revLens; // empty
1694 [ 'rev_id', 'rev_len' ],
1695 [ 'rev_id' => $revIds ],
1699 foreach ( $res as $row ) {
1700 $revLens[$row->rev_id
] = intval( $row->rev_len
);
1707 * Get previous revision for this title
1709 * MCR migration note: this replaces Revision::getPrevious
1711 * @param RevisionRecord $rev
1712 * @param Title $title if known (optional)
1714 * @return RevisionRecord|null
1716 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
1717 if ( $title === null ) {
1718 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1720 $prev = $title->getPreviousRevisionID( $rev->getId() );
1722 return $this->getRevisionByTitle( $title, $prev );
1728 * Get next revision for this title
1730 * MCR migration note: this replaces Revision::getNext
1732 * @param RevisionRecord $rev
1733 * @param Title $title if known (optional)
1735 * @return RevisionRecord|null
1737 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
1738 if ( $title === null ) {
1739 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1741 $next = $title->getNextRevisionID( $rev->getId() );
1743 return $this->getRevisionByTitle( $title, $next );
1749 * Get previous revision Id for this page_id
1750 * This is used to populate rev_parent_id on save
1752 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1754 * @param IDatabase $db
1755 * @param RevisionRecord $rev
1759 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
1760 $this->checkDatabaseWikiId( $db );
1762 if ( $rev->getPageId() === null ) {
1765 # Use page_latest if ID is not given
1766 if ( !$rev->getId() ) {
1767 $prevId = $db->selectField(
1768 'page', 'page_latest',
1769 [ 'page_id' => $rev->getPageId() ],
1773 $prevId = $db->selectField(
1774 'revision', 'rev_id',
1775 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1777 [ 'ORDER BY' => 'rev_id DESC' ]
1780 return intval( $prevId );
1784 * Get rev_timestamp from rev_id, without loading the rest of the row
1786 * MCR migration note: this replaces Revision::getTimestampFromId
1788 * @param Title $title
1791 * @return string|bool False if not found
1793 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1794 $db = $this->getDBConnection(
1795 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
1798 $conds = [ 'rev_id' => $id ];
1799 $conds['rev_page'] = $title->getArticleID();
1800 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1802 $this->releaseDBConnection( $db );
1803 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1807 * Get count of revisions per page...not very efficient
1809 * MCR migration note: this replaces Revision::countByPageId
1811 * @param IDatabase $db
1812 * @param int $id Page id
1815 public function countRevisionsByPageId( IDatabase
$db, $id ) {
1816 $this->checkDatabaseWikiId( $db );
1818 $row = $db->selectRow( 'revision',
1819 [ 'revCount' => 'COUNT(*)' ],
1820 [ 'rev_page' => $id ],
1824 return intval( $row->revCount
);
1830 * Get count of revisions per page...not very efficient
1832 * MCR migration note: this replaces Revision::countByTitle
1834 * @param IDatabase $db
1835 * @param Title $title
1838 public function countRevisionsByTitle( IDatabase
$db, $title ) {
1839 $id = $title->getArticleID();
1841 return $this->countRevisionsByPageId( $db, $id );
1847 * Check if no edits were made by other users since
1848 * the time a user started editing the page. Limit to
1849 * 50 revisions for the sake of performance.
1851 * MCR migration note: this replaces Revision::userWasLastToEdit
1853 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1854 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1855 * has been deprecated since 1.24.
1857 * @param IDatabase $db The Database to perform the check on.
1858 * @param int $pageId The ID of the page in question
1859 * @param int $userId The ID of the user in question
1860 * @param string $since Look at edits since this time
1862 * @return bool True if the given user was the only one to edit since the given timestamp
1864 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
1865 $this->checkDatabaseWikiId( $db );
1875 'rev_page' => $pageId,
1876 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1879 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ]
1881 foreach ( $res as $row ) {
1882 if ( $row->rev_user
!= $userId ) {
1890 * Load a revision based on a known page ID and current revision ID from the DB
1892 * This method allows for the use of caching, though accessing anything that normally
1893 * requires permission checks (aside from the text) will trigger a small DB lookup.
1895 * MCR migration note: this replaces Revision::newKnownCurrent
1897 * @param Title $title the associated page title
1898 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1900 * @return RevisionRecord|bool Returns false if missing
1902 public function getKnownCurrentRevision( Title
$title, $revId ) {
1903 $db = $this->getDBConnectionRef( DB_REPLICA
);
1905 $pageId = $title->getArticleID();
1912 $revId = $title->getLatestRevID();
1917 'No latest revision known for page ' . $title->getPrefixedDBkey()
1918 . ' even though it exists with page ID ' . $pageId
1923 $row = $this->cache
->getWithSetCallback(
1924 // Page/rev IDs passed in from DB to reflect history merges
1925 $this->cache
->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1926 WANObjectCache
::TTL_WEEK
,
1927 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1928 $setOpts +
= Database
::getCacheSetOptions( $db );
1931 'rev_page' => intval( $pageId ),
1932 'page_id' => intval( $pageId ),
1933 'rev_id' => intval( $revId ),
1936 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1937 return $row ?
: false; // don't cache negatives
1941 // Reflect revision deletion and user renames
1943 return $this->newRevisionFromRow( $row, 0, $title );
1949 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.