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
;
45 use Psr\Log\LoggerAwareInterface
;
46 use Psr\Log\LoggerInterface
;
47 use Psr\Log\NullLogger
;
53 use Wikimedia\Assert\Assert
;
54 use Wikimedia\Rdbms\Database
;
55 use Wikimedia\Rdbms\DBConnRef
;
56 use Wikimedia\Rdbms\IDatabase
;
57 use Wikimedia\Rdbms\LoadBalancer
;
60 * Service for looking up page revisions.
64 * @note This was written to act as a drop-in replacement for the corresponding
65 * static methods in Revision.
68 implements IDBAccessObject
, RevisionFactory
, RevisionLookup
, LoggerAwareInterface
{
83 private $contentHandlerUseDB = true;
88 private $loadBalancer;
98 private $commentStore;
101 * @var LoggerInterface
106 * @todo $blobStore should be allowed to be any BlobStore!
108 * @param LoadBalancer $loadBalancer
109 * @param SqlBlobStore $blobStore
110 * @param WANObjectCache $cache
111 * @param CommentStore $commentStore
112 * @param bool|string $wikiId
114 public function __construct(
115 LoadBalancer
$loadBalancer,
116 SqlBlobStore
$blobStore,
117 WANObjectCache
$cache,
118 CommentStore
$commentStore,
121 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
123 $this->loadBalancer
= $loadBalancer;
124 $this->blobStore
= $blobStore;
125 $this->cache
= $cache;
126 $this->commentStore
= $commentStore;
127 $this->wikiId
= $wikiId;
128 $this->logger
= new NullLogger();
131 public function setLogger( LoggerInterface
$logger ) {
132 $this->logger
= $logger;
138 public function getContentHandlerUseDB() {
139 return $this->contentHandlerUseDB
;
143 * @param bool $contentHandlerUseDB
145 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
146 $this->contentHandlerUseDB
= $contentHandlerUseDB;
150 * @return LoadBalancer
152 private function getDBLoadBalancer() {
153 return $this->loadBalancer
;
157 * @param int $mode DB_MASTER or DB_REPLICA
161 private function getDBConnection( $mode ) {
162 $lb = $this->getDBLoadBalancer();
163 return $lb->getConnection( $mode, [], $this->wikiId
);
167 * @param IDatabase $connection
169 private function releaseDBConnection( IDatabase
$connection ) {
170 $lb = $this->getDBLoadBalancer();
171 $lb->reuseConnection( $connection );
175 * @param int $mode DB_MASTER or DB_REPLICA
179 private function getDBConnectionRef( $mode ) {
180 $lb = $this->getDBLoadBalancer();
181 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
185 * Determines the page Title based on the available information.
187 * MCR migration note: this corresponds to Revision::getTitle
189 * @note this method should be private, external use should be avoided!
191 * @param int|null $pageId
192 * @param int|null $revId
193 * @param int $queryFlags
196 * @throws RevisionAccessException
198 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
199 if ( !$pageId && !$revId ) {
200 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
203 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
204 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
205 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
206 $queryFlags = self
::READ_NORMAL
;
209 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false );
210 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
211 $titleFlags = ( $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0 );
213 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
214 if ( $canUseTitleNewFromId ) {
215 // TODO: better foreign title handling (introduce TitleFactory)
216 $title = Title
::newFromID( $pageId, $titleFlags );
222 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
223 $canUseRevId = ( $revId !== null && $revId > 0 );
225 if ( $canUseRevId ) {
226 $dbr = $this->getDBConnectionRef( $dbMode );
227 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
228 $row = $dbr->selectRow(
229 [ 'revision', 'page' ],
238 [ 'rev_id' => $revId ],
241 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
244 // TODO: better foreign title handling (introduce TitleFactory)
245 return Title
::newFromRow( $row );
249 // If we still don't have a title, fallback to master if that wasn't already happening.
250 if ( $dbMode !== DB_MASTER
) {
251 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
254 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
255 [ 'trace' => wfBacktrace() ]
261 throw new RevisionAccessException(
262 "Could not determine title for page ID $pageId and revision ID $revId"
267 * @param mixed $value
268 * @param string $name
270 * @throw IncompleteRevisionException if $value is null
271 * @return mixed $value, if $value is not null
273 private function failOnNull( $value, $name ) {
274 if ( $value === null ) {
275 throw new IncompleteRevisionException(
276 "$name must not be " . var_export( $value, true ) . "!"
284 * @param mixed $value
285 * @param string $name
287 * @throw IncompleteRevisionException if $value is empty
288 * @return mixed $value, if $value is not null
290 private function failOnEmpty( $value, $name ) {
291 if ( $value === null ||
$value === 0 ||
$value === '' ) {
292 throw new IncompleteRevisionException(
293 "$name must not be " . var_export( $value, true ) . "!"
301 * Insert a new revision into the database, returning the new revision record
302 * on success and dies horribly on failure.
304 * MCR migration note: this replaces Revision::insertOn
306 * @param RevisionRecord $rev
307 * @param IDatabase $dbw (master connection)
309 * @throws InvalidArgumentException
310 * @return RevisionRecord the new revision record.
312 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
313 // TODO: pass in a DBTransactionContext instead of a database connection.
314 $this->checkDatabaseWikiId( $dbw );
316 if ( !$rev->getSlotRoles() ) {
317 throw new InvalidArgumentException( 'At least one slot needs to be defined!' );
320 if ( $rev->getSlotRoles() !== [ 'main' ] ) {
321 throw new InvalidArgumentException( 'Only the main slot is supported for now!' );
324 // TODO: we shouldn't need an actual Title here.
325 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
326 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
328 $parentId = $rev->getParentId() === null
329 ?
$this->getPreviousRevisionId( $dbw, $rev )
330 : $rev->getParentId();
332 // Record the text (or external storage URL) to the blob store
333 $slot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
335 $size = $this->failOnNull( $rev->getSize(), 'size field' );
336 $sha1 = $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
338 if ( !$slot->hasAddress() ) {
339 $content = $slot->getContent();
340 $format = $content->getDefaultFormat();
341 $model = $content->getModel();
343 $this->checkContentModel( $content, $title );
345 $data = $content->serialize( $format );
347 // Hints allow the blob store to optimize by "leaking" application level information to it.
348 // TODO: with the new MCR storage schema, we rev_id have this before storing the blobs.
349 // When we have it, add rev_id as a hint. Can be used with rev_parent_id for
350 // differential storage or compression of subsequent revisions.
352 BlobStore
::DESIGNATION_HINT
=> 'page-content', // BlobStore may be used for other things too.
353 BlobStore
::PAGE_HINT
=> $pageId,
354 BlobStore
::ROLE_HINT
=> $slot->getRole(),
355 BlobStore
::PARENT_HINT
=> $parentId,
356 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
357 BlobStore
::MODEL_HINT
=> $model,
358 BlobStore
::FORMAT_HINT
=> $format,
361 $blobAddress = $this->blobStore
->storeBlob( $data, $blobHints );
363 $blobAddress = $slot->getAddress();
364 $model = $slot->getModel();
365 $format = $slot->getFormat();
368 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
371 throw new LogicException(
372 'Blob address not supported in 1.29 database schema: ' . $blobAddress
376 // getTextIdFromAddress() is free to insert something into the text table, so $textId
377 // may be a new value, not anything already contained in $blobAddress.
378 $blobAddress = 'tt:' . $textId;
380 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
381 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
382 $timestamp = $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
384 # Record the edit in revisions
386 'rev_page' => $pageId,
387 'rev_parent_id' => $parentId,
388 'rev_text_id' => $textId,
389 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
390 'rev_user' => $this->failOnNull( $user->getId(), 'user field' ),
391 'rev_user_text' => $this->failOnEmpty( $user->getName(), 'user_text field' ),
392 'rev_timestamp' => $dbw->timestamp( $timestamp ),
393 'rev_deleted' => $rev->getVisibility(),
398 if ( $rev->getId() !== null ) {
399 // Needed to restore revisions with their original ID
400 $row['rev_id'] = $rev->getId();
403 list( $commentFields, $commentCallback ) =
404 $this->commentStore
->insertWithTempTable( $dbw, 'rev_comment', $comment );
405 $row +
= $commentFields;
407 if ( $this->contentHandlerUseDB
) {
408 // MCR migration note: rev_content_model and rev_content_format will go away
410 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
411 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
413 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
414 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
417 $dbw->insert( 'revision', $row, __METHOD__
);
419 if ( !isset( $row['rev_id'] ) ) {
420 // only if auto-increment was used
421 $row['rev_id'] = intval( $dbw->insertId() );
423 $commentCallback( $row['rev_id'] );
425 // Insert IP revision into ip_changes for use when querying for a range.
426 if ( $row['rev_user'] === 0 && IP
::isValid( $row['rev_user_text'] ) ) {
428 'ipc_rev_id' => $row['rev_id'],
429 'ipc_rev_timestamp' => $row['rev_timestamp'],
430 'ipc_hex' => IP
::toHex( $row['rev_user_text'] ),
432 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
435 $newSlot = SlotRecord
::newSaved( $row['rev_id'], $blobAddress, $slot );
436 $slots = new RevisionSlots( [ 'main' => $newSlot ] );
438 $user = new UserIdentityValue( intval( $row['rev_user'] ), $row['rev_user_text'] );
440 $rev = new RevisionStoreRecord(
449 $newSlot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
452 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
453 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
454 Assert
::postcondition(
455 $rev->getComment( RevisionRecord
::RAW
) !== null,
456 'revision must have a comment'
458 Assert
::postcondition(
459 $rev->getUser( RevisionRecord
::RAW
) !== null,
460 'revision must have a user'
463 Assert
::postcondition( $newSlot !== null, 'revision must have a main slot' );
464 Assert
::postcondition(
465 $newSlot->getAddress() !== null,
466 'main slot must have an addess'
469 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
475 * MCR migration note: this corresponds to Revision::checkContentModel
477 * @param Content $content
478 * @param Title $title
480 * @throws MWException
481 * @throws MWUnknownContentModelException
483 private function checkContentModel( Content
$content, Title
$title ) {
484 // Note: may return null for revisions that have not yet been inserted
486 $model = $content->getModel();
487 $format = $content->getDefaultFormat();
488 $handler = $content->getContentHandler();
492 if ( !$handler->isSupportedFormat( $format ) ) {
493 throw new MWException( "Can't use format $format with content model $model on $name" );
496 if ( !$this->contentHandlerUseDB
) {
497 // if $wgContentHandlerUseDB is not set,
498 // all revisions must use the default content model and format.
500 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
501 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
502 $defaultFormat = $defaultHandler->getDefaultFormat();
504 if ( $model != $defaultModel ) {
505 throw new MWException( "Can't save non-default content model with "
506 . "\$wgContentHandlerUseDB disabled: model is $model, "
507 . "default for $name is $defaultModel"
511 if ( $format != $defaultFormat ) {
512 throw new MWException( "Can't use non-default content format with "
513 . "\$wgContentHandlerUseDB disabled: format is $format, "
514 . "default for $name is $defaultFormat"
519 if ( !$content->isValid() ) {
520 throw new MWException(
521 "New content for $name is not valid! Content model is $model"
527 * Create a new null-revision for insertion into a page's
528 * history. This will not re-save the text, but simply refer
529 * to the text from the previous version.
531 * Such revisions can for instance identify page rename
532 * operations and other such meta-modifications.
534 * MCR migration note: this replaces Revision::newNullRevision
536 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
539 * @param IDatabase $dbw
540 * @param Title $title Title of the page to read from
541 * @param CommentStoreComment $comment RevisionRecord's summary
542 * @param bool $minor Whether the revision should be considered as minor
543 * @param User $user The user to attribute the revision to
544 * @return RevisionRecord|null RevisionRecord or null on error
546 public function newNullRevision(
549 CommentStoreComment
$comment,
553 $this->checkDatabaseWikiId( $dbw );
555 $fields = [ 'page_latest', 'page_namespace', 'page_title',
556 'rev_id', 'rev_text_id', 'rev_len', 'rev_sha1' ];
558 if ( $this->contentHandlerUseDB
) {
559 $fields[] = 'rev_content_model';
560 $fields[] = 'rev_content_format';
563 $current = $dbw->selectRow(
564 [ 'page', 'revision' ],
567 'page_id' => $title->getArticleID(),
568 'page_latest=rev_id',
571 [ 'FOR UPDATE' ] // T51581
576 'page' => $title->getArticleID(),
577 'user_text' => $user->getName(),
578 'user' => $user->getId(),
579 'comment' => $comment,
580 'minor_edit' => $minor,
581 'text_id' => $current->rev_text_id
,
582 'parent_id' => $current->page_latest
,
583 'len' => $current->rev_len
,
584 'sha1' => $current->rev_sha1
587 if ( $this->contentHandlerUseDB
) {
588 $fields['content_model'] = $current->rev_content_model
;
589 $fields['content_format'] = $current->rev_content_format
;
592 $fields['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
594 $mainSlot = $this->emulateMainSlot_1_29( $fields, 0, $title );
595 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
596 $this->initializeMutableRevisionFromArray( $revision, $fields );
597 $revision->setSlot( $mainSlot );
606 * MCR migration note: this replaces Revision::isUnpatrolled
608 * @todo This is overly specific, so move or kill this method.
610 * @param RevisionRecord $rev
612 * @return int Rcid of the unpatrolled row, zero if there isn't one
614 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
615 $rc = $this->getRecentChange( $rev );
616 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
617 return $rc->getAttribute( 'rc_id' );
624 * Get the RC object belonging to the current revision, if there's one
626 * MCR migration note: this replaces Revision::getRecentChange
628 * @todo move this somewhere else?
630 * @param RevisionRecord $rev
631 * @param int $flags (optional) $flags include:
632 * IDBAccessObject::READ_LATEST: Select the data from the master
634 * @return null|RecentChange
636 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
637 $dbr = $this->getDBConnection( DB_REPLICA
);
639 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
641 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
643 if ( !$userIdentity ) {
644 // If the revision has no user identity, chances are it never went
645 // into the database, and doesn't have an RC entry.
649 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
650 $rc = RecentChange
::newFromConds(
652 'rc_user_text' => $userIdentity->getName(),
653 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
654 'rc_this_oldid' => $rev->getId()
660 $this->releaseDBConnection( $dbr );
662 // XXX: cache this locally? Glue it to the RevisionRecord?
667 * Maps fields of the archive row to corresponding revision rows.
669 * @param object $archiveRow
671 * @return object a revision row object, corresponding to $archiveRow.
673 private static function mapArchiveFields( $archiveRow ) {
675 // keep with ar prefix:
678 // not the same suffix:
679 'ar_page_id' => 'rev_page',
680 'ar_rev_id' => 'rev_id',
683 'ar_text_id' => 'rev_text_id',
684 'ar_timestamp' => 'rev_timestamp',
685 'ar_user_text' => 'rev_user_text',
686 'ar_user' => 'rev_user',
687 'ar_minor_edit' => 'rev_minor_edit',
688 'ar_deleted' => 'rev_deleted',
689 'ar_len' => 'rev_len',
690 'ar_parent_id' => 'rev_parent_id',
691 'ar_sha1' => 'rev_sha1',
692 'ar_comment' => 'rev_comment',
693 'ar_comment_cid' => 'rev_comment_cid',
694 'ar_comment_id' => 'rev_comment_id',
695 'ar_comment_text' => 'rev_comment_text',
696 'ar_comment_data' => 'rev_comment_data',
697 'ar_comment_old' => 'rev_comment_old',
698 'ar_content_format' => 'rev_content_format',
699 'ar_content_model' => 'rev_content_model',
702 if ( empty( $archiveRow->ar_text_id
) ) {
703 $fieldMap['ar_text'] = 'old_text';
704 $fieldMap['ar_flags'] = 'old_flags';
707 $revRow = new stdClass();
708 foreach ( $fieldMap as $arKey => $revKey ) {
709 if ( property_exists( $archiveRow, $arKey ) ) {
710 $revRow->$revKey = $archiveRow->$arKey;
718 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
720 * @param object|array $row Either a database row or an array
721 * @param int $queryFlags for callbacks
722 * @param Title $title
724 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
725 * @throws MWException
727 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
728 $mainSlotRow = new stdClass();
729 $mainSlotRow->role_name
= 'main';
735 if ( is_object( $row ) ) {
737 if ( !isset( $row->rev_id
) && isset( $row->ar_user
) ) {
738 $row = $this->mapArchiveFields( $row );
741 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
742 $mainSlotRow->cont_address
= 'tt:' . $row->rev_text_id
;
745 if ( isset( $row->old_text
) ) {
746 // this happens when the text-table gets joined directly, in the pre-1.30 schema
747 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
748 // Check against selects that might have not included old_flags
749 if ( !property_exists( $row, 'old_flags' ) ) {
750 throw new InvalidArgumentException( 'old_flags was not set in $row' );
752 $blobFlags = ( $row->old_flags
=== null ) ?
'' : $row->old_flags
;
755 $mainSlotRow->slot_revision
= intval( $row->rev_id
);
757 $mainSlotRow->cont_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
758 $mainSlotRow->cont_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
759 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
760 ?
strval( $row->rev_content_model
)
762 // XXX: in the future, we'll probably always use the default format, and drop content_format
763 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
764 ?
strval( $row->rev_content_format
)
766 } elseif ( is_array( $row ) ) {
767 $mainSlotRow->slot_revision
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
769 $mainSlotRow->cont_address
= isset( $row['text_id'] )
770 ?
'tt:' . intval( $row['text_id'] )
772 $mainSlotRow->cont_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
773 $mainSlotRow->cont_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
775 $mainSlotRow->model_name
= isset( $row['content_model'] )
776 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
777 // XXX: in the future, we'll probably always use the default format, and drop content_format
778 $mainSlotRow->format_name
= isset( $row['content_format'] )
779 ?
strval( $row['content_format'] ) : null;
780 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
781 // XXX: If the flags field is not set then $blobFlags should be null so that no
782 // decoding will happen. An empty string will result in default decodings.
783 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
785 // if we have a Content object, override mText and mContentModel
786 if ( !empty( $row['content'] ) ) {
787 if ( !( $row['content'] instanceof Content
) ) {
788 throw new MWException( 'content field must contain a Content object.' );
791 /** @var Content $content */
792 $content = $row['content'];
793 $handler = $content->getContentHandler();
795 $mainSlotRow->model_name
= $content->getModel();
797 // XXX: in the future, we'll probably always use the default format.
798 if ( $mainSlotRow->format_name
=== null ) {
799 $mainSlotRow->format_name
= $handler->getDefaultFormat();
803 throw new MWException( 'Revision constructor passed invalid row format.' );
806 // With the old schema, the content changes with every revision.
807 // ...except for null-revisions. Would be nice if we could detect them.
808 $mainSlotRow->slot_inherited
= 0;
810 if ( $mainSlotRow->model_name
=== null ) {
811 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
812 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
813 // TODO: MCR: deprecate $title->getModel().
814 return ContentHandler
::getDefaultModelFor( $title );
819 $content = function ( SlotRecord
$slot )
820 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
822 return $this->loadSlotContent(
826 $mainSlotRow->format_name
,
832 return new SlotRecord( $mainSlotRow, $content );
836 * Loads a Content object based on a slot row.
838 * This method does not call $slot->getContent(), and may be used as a callback
839 * called by $slot->getContent().
841 * MCR migration note: this roughly corresponds to Revision::getContentInternal
843 * @param SlotRecord $slot The SlotRecord to load content for
844 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
845 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
846 * Use null if no processing should happen. That is in constrast to the empty string,
847 * which causes the blob to be decoded according to the configured legacy encoding.
848 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
849 * @param int $queryFlags
851 * @throw RevisionAccessException
854 private function loadSlotContent(
861 if ( $blobData !== null ) {
862 Assert
::parameterType( 'string', $blobData, '$blobData' );
863 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
865 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
867 if ( $blobFlags === null ) {
868 // No blob flags, so use the blob verbatim.
871 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
872 if ( $data === false ) {
873 throw new RevisionAccessException(
874 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
880 $address = $slot->getAddress();
882 $data = $this->blobStore
->getBlob( $address, $queryFlags );
883 } catch ( BlobAccessException
$e ) {
884 throw new RevisionAccessException(
885 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
890 // Unserialize content
891 $handler = ContentHandler
::getForModelID( $slot->getModel() );
893 $content = $handler->unserializeContent( $data, $blobFormat );
898 * Load a page revision from a given revision ID number.
899 * Returns null if no such revision can be found.
901 * MCR migration note: this replaces Revision::newFromId
904 * IDBAccessObject::READ_LATEST: Select the data from the master
905 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
908 * @param int $flags (optional)
909 * @return RevisionRecord|null
911 public function getRevisionById( $id, $flags = 0 ) {
912 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
916 * Load either the current, or a specified, revision
917 * that's attached to a given link target. If not attached
918 * to that link target, will return null.
920 * MCR migration note: this replaces Revision::newFromTitle
923 * IDBAccessObject::READ_LATEST: Select the data from the master
924 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
926 * @param LinkTarget $linkTarget
927 * @param int $revId (optional)
928 * @param int $flags Bitfield (optional)
929 * @return RevisionRecord|null
931 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
933 'page_namespace' => $linkTarget->getNamespace(),
934 'page_title' => $linkTarget->getDBkey()
937 // Use the specified revision ID.
938 // Note that we use newRevisionFromConds here because we want to retry
939 // and fall back to master if the page is not found on a replica.
940 // Since the caller supplied a revision ID, we are pretty sure the revision is
941 // supposed to exist, so we should try hard to find it.
942 $conds['rev_id'] = $revId;
943 return $this->newRevisionFromConds( $conds, $flags );
945 // Use a join to get the latest revision.
946 // Note that we don't use newRevisionFromConds here because we don't want to retry
947 // and fall back to master. The assumption is that we only want to force the fallback
948 // if we are quite sure the revision exists because the caller supplied a revision ID.
949 // If the page isn't found at all on a replica, it probably simply does not exist.
950 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
952 $conds[] = 'rev_id=page_latest';
953 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
955 $this->releaseDBConnection( $db );
961 * Load either the current, or a specified, revision
962 * that's attached to a given page ID.
963 * Returns null if no such revision can be found.
965 * MCR migration note: this replaces Revision::newFromPageId
968 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
969 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
972 * @param int $revId (optional)
973 * @param int $flags Bitfield (optional)
974 * @return RevisionRecord|null
976 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
977 $conds = [ 'page_id' => $pageId ];
979 // Use the specified revision ID.
980 // Note that we use newRevisionFromConds here because we want to retry
981 // and fall back to master if the page is not found on a replica.
982 // Since the caller supplied a revision ID, we are pretty sure the revision is
983 // supposed to exist, so we should try hard to find it.
984 $conds['rev_id'] = $revId;
985 return $this->newRevisionFromConds( $conds, $flags );
987 // Use a join to get the latest revision.
988 // Note that we don't use newRevisionFromConds here because we don't want to retry
989 // and fall back to master. The assumption is that we only want to force the fallback
990 // if we are quite sure the revision exists because the caller supplied a revision ID.
991 // If the page isn't found at all on a replica, it probably simply does not exist.
992 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
994 $conds[] = 'rev_id=page_latest';
995 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
997 $this->releaseDBConnection( $db );
1003 * Load the revision for the given title with the given timestamp.
1004 * WARNING: Timestamps may in some circumstances not be unique,
1005 * so this isn't the best key to use.
1007 * MCR migration note: this replaces Revision::loadFromTimestamp
1009 * @param Title $title
1010 * @param string $timestamp
1011 * @return RevisionRecord|null
1013 public function getRevisionByTimestamp( $title, $timestamp ) {
1014 return $this->newRevisionFromConds(
1016 'rev_timestamp' => $timestamp,
1017 'page_namespace' => $title->getNamespace(),
1018 'page_title' => $title->getDBkey()
1026 * Make a fake revision object from an archive table row. This is queried
1027 * for permissions or even inserted (as in Special:Undelete)
1029 * MCR migration note: this replaces Revision::newFromArchiveRow
1031 * @param object $row
1032 * @param int $queryFlags
1033 * @param Title|null $title
1034 * @param array $overrides associative array with fields of $row to override. This may be
1035 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1036 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1037 * override ar_parent_id.
1039 * @return RevisionRecord
1040 * @throws MWException
1042 public function newRevisionFromArchiveRow(
1045 Title
$title = null,
1046 array $overrides = []
1048 Assert
::parameterType( 'object', $row, '$row' );
1050 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1051 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1053 if ( !$title && isset( $overrides['title'] ) ) {
1054 if ( !( $overrides['title'] instanceof Title
) ) {
1055 throw new MWException( 'title field override must contain a Title object.' );
1058 $title = $overrides['title'];
1061 if ( !isset( $title ) ) {
1062 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1063 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1065 throw new InvalidArgumentException(
1066 'A Title or ar_namespace and ar_title must be given'
1071 foreach ( $overrides as $key => $value ) {
1073 $row->$field = $value;
1076 $user = $this->getUserIdentityFromRowObject( $row, 'ar_' );
1078 $comment = $this->commentStore
1079 // Legacy because $row may have come from self::selectFields()
1080 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'ar_comment', $row, true );
1082 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1083 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1085 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1089 * @param object $row
1090 * @param string $prefix Field prefix, such as 'rev_' or 'ar_'.
1092 * @return UserIdentityValue
1094 private function getUserIdentityFromRowObject( $row, $prefix = 'rev_' ) {
1095 $idField = "{$prefix}user";
1096 $nameField = "{$prefix}user_text";
1098 $userId = intval( $row->$idField );
1100 if ( isset( $row->user_name
) ) {
1101 $userName = $row->user_name
;
1102 } elseif ( isset( $row->$nameField ) ) {
1103 $userName = $row->$nameField;
1105 $userName = User
::whoIs( $userId );
1108 if ( $userName === false ) {
1109 wfWarn( __METHOD__
. ': Cannot determine user name for user ID ' . $userId );
1113 return new UserIdentityValue( $userId, $userName );
1117 * @see RevisionFactory::newRevisionFromRow_1_29
1119 * MCR migration note: this replaces Revision::newFromRow
1121 * @param object $row
1122 * @param int $queryFlags
1123 * @param Title|null $title
1125 * @return RevisionRecord
1126 * @throws MWException
1127 * @throws RevisionAccessException
1129 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title
$title = null ) {
1130 Assert
::parameterType( 'object', $row, '$row' );
1133 $pageId = isset( $row->rev_page
) ?
$row->rev_page
: 0; // XXX: also check page_id?
1134 $revId = isset( $row->rev_id
) ?
$row->rev_id
: 0;
1136 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1139 if ( !isset( $row->page_latest
) ) {
1140 $row->page_latest
= $title->getLatestRevID();
1141 if ( $row->page_latest
=== 0 && $title->exists() ) {
1142 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1146 $user = $this->getUserIdentityFromRowObject( $row );
1148 $comment = $this->commentStore
1149 // Legacy because $row may have come from self::selectFields()
1150 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'rev_comment', $row, true );
1152 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1153 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1155 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1159 * @see RevisionFactory::newRevisionFromRow
1161 * MCR migration note: this replaces Revision::newFromRow
1163 * @param object $row
1164 * @param int $queryFlags
1165 * @param Title|null $title
1167 * @return RevisionRecord
1169 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1170 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1174 * Constructs a new MutableRevisionRecord based on the given associative array following
1175 * the MW1.29 convention for the Revision constructor.
1177 * MCR migration note: this replaces Revision::newFromRow
1179 * @param array $fields
1180 * @param int $queryFlags
1181 * @param Title|null $title
1183 * @return MutableRevisionRecord
1184 * @throws MWException
1185 * @throws RevisionAccessException
1187 public function newMutableRevisionFromArray(
1192 if ( !$title && isset( $fields['title'] ) ) {
1193 if ( !( $fields['title'] instanceof Title
) ) {
1194 throw new MWException( 'title field must contain a Title object.' );
1197 $title = $fields['title'];
1201 $pageId = isset( $fields['page'] ) ?
$fields['page'] : 0;
1202 $revId = isset( $fields['id'] ) ?
$fields['id'] : 0;
1204 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1207 if ( !isset( $fields['page'] ) ) {
1208 $fields['page'] = $title->getArticleID( $queryFlags );
1211 // if we have a content object, use it to set the model and type
1212 if ( !empty( $fields['content'] ) ) {
1213 if ( !( $fields['content'] instanceof Content
) ) {
1214 throw new MWException( 'content field must contain a Content object.' );
1217 if ( !empty( $fields['text_id'] ) ) {
1218 throw new MWException(
1219 "Text already stored in external store (id {$fields['text_id']}), " .
1220 "can't serialize content object"
1225 // Replaces old lazy loading logic in Revision::getUserText.
1226 if ( !isset( $fields['user_text'] ) && isset( $fields['user'] ) ) {
1227 if ( $fields['user'] instanceof UserIdentity
) {
1228 /** @var User $user */
1229 $user = $fields['user'];
1230 $fields['user_text'] = $user->getName();
1231 $fields['user'] = $user->getId();
1233 // TODO: wrap this in a callback to make it lazy again.
1234 $name = $fields['user'] === 0 ?
false : User
::whoIs( $fields['user'] );
1236 if ( $name === false ) {
1237 throw new MWException(
1238 'user_text not given, and unknown user ID ' . $fields['user']
1242 $fields['user_text'] = $name;
1247 isset( $fields['comment'] )
1248 && !( $fields['comment'] instanceof CommentStoreComment
)
1250 $commentData = isset( $fields['comment_data'] ) ?
$fields['comment_data'] : null;
1252 if ( $fields['comment'] instanceof Message
) {
1253 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1258 $commentText = trim( strval( $fields['comment'] ) );
1259 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1266 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1268 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1269 $this->initializeMutableRevisionFromArray( $revision, $fields );
1270 $revision->setSlot( $mainSlot );
1276 * @param MutableRevisionRecord $record
1277 * @param array $fields
1279 private function initializeMutableRevisionFromArray(
1280 MutableRevisionRecord
$record,
1283 /** @var UserIdentity $user */
1286 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1287 $user = $fields['user'];
1288 } elseif ( isset( $fields['user'] ) && isset( $fields['user_text'] ) ) {
1289 $user = new UserIdentityValue( intval( $fields['user'] ), $fields['user_text'] );
1290 } elseif ( isset( $fields['user'] ) ) {
1291 $user = User
::newFromId( intval( $fields['user'] ) );
1292 } elseif ( isset( $fields['user_text'] ) ) {
1293 $user = User
::newFromName( $fields['user_text'] );
1295 // User::newFromName will return false for IP addresses (and invalid names)
1296 if ( $user == false ) {
1297 $user = new UserIdentityValue( 0, $fields['user_text'] );
1302 $record->setUser( $user );
1305 $timestamp = isset( $fields['timestamp'] )
1306 ?
strval( $fields['timestamp'] )
1307 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1309 $record->setTimestamp( $timestamp );
1311 if ( isset( $fields['page'] ) ) {
1312 $record->setPageId( intval( $fields['page'] ) );
1315 if ( isset( $fields['id'] ) ) {
1316 $record->setId( intval( $fields['id'] ) );
1318 if ( isset( $fields['parent_id'] ) ) {
1319 $record->setParentId( intval( $fields['parent_id'] ) );
1322 if ( isset( $fields['sha1'] ) ) {
1323 $record->setSha1( $fields['sha1'] );
1325 if ( isset( $fields['size'] ) ) {
1326 $record->setSize( intval( $fields['size'] ) );
1329 if ( isset( $fields['minor_edit'] ) ) {
1330 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1332 if ( isset( $fields['deleted'] ) ) {
1333 $record->setVisibility( intval( $fields['deleted'] ) );
1336 if ( isset( $fields['comment'] ) ) {
1337 Assert
::parameterType(
1338 CommentStoreComment
::class,
1342 $record->setComment( $fields['comment'] );
1347 * Load a page revision from a given revision ID number.
1348 * Returns null if no such revision can be found.
1350 * MCR migration note: this corresponds to Revision::loadFromId
1352 * @note direct use is deprecated!
1353 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1355 * @param IDatabase $db
1358 * @return RevisionRecord|null
1360 public function loadRevisionFromId( IDatabase
$db, $id ) {
1361 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1365 * Load either the current, or a specified, revision
1366 * that's attached to a given page. If not attached
1367 * to that page, will return null.
1369 * MCR migration note: this replaces Revision::loadFromPageId
1371 * @note direct use is deprecated!
1372 * @todo remove when unused!
1374 * @param IDatabase $db
1375 * @param int $pageid
1377 * @return RevisionRecord|null
1379 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1380 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1382 $conds['rev_id'] = intval( $id );
1384 $conds[] = 'rev_id=page_latest';
1386 return $this->loadRevisionFromConds( $db, $conds );
1390 * Load either the current, or a specified, revision
1391 * that's attached to a given page. If not attached
1392 * to that page, will return null.
1394 * MCR migration note: this replaces Revision::loadFromTitle
1396 * @note direct use is deprecated!
1397 * @todo remove when unused!
1399 * @param IDatabase $db
1400 * @param Title $title
1403 * @return RevisionRecord|null
1405 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1407 $matchId = intval( $id );
1409 $matchId = 'page_latest';
1412 return $this->loadRevisionFromConds(
1416 'page_namespace' => $title->getNamespace(),
1417 'page_title' => $title->getDBkey()
1425 * Load the revision for the given title with the given timestamp.
1426 * WARNING: Timestamps may in some circumstances not be unique,
1427 * so this isn't the best key to use.
1429 * MCR migration note: this replaces Revision::loadFromTimestamp
1431 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1432 * @todo remove when unused!
1434 * @param IDatabase $db
1435 * @param Title $title
1436 * @param string $timestamp
1437 * @return RevisionRecord|null
1439 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1440 return $this->loadRevisionFromConds( $db,
1442 'rev_timestamp' => $db->timestamp( $timestamp ),
1443 'page_namespace' => $title->getNamespace(),
1444 'page_title' => $title->getDBkey()
1452 * Given a set of conditions, fetch a revision
1454 * This method should be used if we are pretty sure the revision exists.
1455 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1456 * on a replica before hitting the master database.
1458 * MCR migration note: this corresponds to Revision::newFromConds
1460 * @param array $conditions
1461 * @param int $flags (optional)
1462 * @param Title $title
1464 * @return RevisionRecord|null
1466 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1467 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1468 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1469 $this->releaseDBConnection( $db );
1471 $lb = $this->getDBLoadBalancer();
1473 // Make sure new pending/committed revision are visibile later on
1474 // within web requests to certain avoid bugs like T93866 and T94407.
1476 && !( $flags & self
::READ_LATEST
)
1477 && $lb->getServerCount() > 1
1478 && $lb->hasOrMadeRecentMasterChanges()
1480 $flags = self
::READ_LATEST
;
1481 $db = $this->getDBConnection( DB_MASTER
);
1482 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1483 $this->releaseDBConnection( $db );
1490 * Given a set of conditions, fetch a revision from
1491 * the given database connection.
1493 * MCR migration note: this corresponds to Revision::loadFromConds
1495 * @param IDatabase $db
1496 * @param array $conditions
1497 * @param int $flags (optional)
1498 * @param Title $title
1500 * @return RevisionRecord|null
1502 private function loadRevisionFromConds(
1508 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1510 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1519 * Throws an exception if the given database connection does not belong to the wiki this
1520 * RevisionStore is bound to.
1522 * @param IDatabase $db
1523 * @throws MWException
1525 private function checkDatabaseWikiId( IDatabase
$db ) {
1526 $storeWiki = $this->wikiId
;
1527 $dbWiki = $db->getDomainID();
1529 if ( $dbWiki === $storeWiki ) {
1533 // XXX: we really want the default database ID...
1534 $storeWiki = $storeWiki ?
: wfWikiID();
1535 $dbWiki = $dbWiki ?
: wfWikiID();
1537 if ( $dbWiki === $storeWiki ) {
1541 // HACK: counteract encoding imposed by DatabaseDomain
1542 $storeWiki = str_replace( '?h', '-', $storeWiki );
1543 $dbWiki = str_replace( '?h', '-', $dbWiki );
1545 if ( $dbWiki === $storeWiki ) {
1549 throw new MWException( "RevisionStore for $storeWiki "
1550 . "cannot be used with a DB connection for $dbWiki" );
1554 * Given a set of conditions, return a row with the
1555 * fields necessary to build RevisionRecord objects.
1557 * MCR migration note: this corresponds to Revision::fetchFromConds
1559 * @param IDatabase $db
1560 * @param array $conditions
1561 * @param int $flags (optional)
1563 * @return object|false data row as a raw object
1565 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1566 $this->checkDatabaseWikiId( $db );
1568 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
1570 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1571 $options[] = 'FOR UPDATE';
1573 return $db->selectRow(
1574 $revQuery['tables'],
1575 $revQuery['fields'],
1584 * Return the tables, fields, and join conditions to be selected to create
1585 * a new revision object.
1587 * MCR migration note: this replaces Revision::getQueryInfo
1591 * @param array $options Any combination of the following strings
1592 * - 'page': Join with the page table, and select fields to identify the page
1593 * - 'user': Join with the user table, and select the user name
1594 * - 'text': Join with the text table, and select fields to load page text
1596 * @return array With three keys:
1597 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1598 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1599 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1601 public function getQueryInfo( $options = [] ) {
1608 $ret['tables'][] = 'revision';
1609 $ret['fields'] = array_merge( $ret['fields'], [
1623 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
1624 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1625 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1626 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1628 if ( $this->contentHandlerUseDB
) {
1629 $ret['fields'][] = 'rev_content_format';
1630 $ret['fields'][] = 'rev_content_model';
1633 if ( in_array( 'page', $options, true ) ) {
1634 $ret['tables'][] = 'page';
1635 $ret['fields'] = array_merge( $ret['fields'], [
1643 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1646 if ( in_array( 'user', $options, true ) ) {
1647 $ret['tables'][] = 'user';
1648 $ret['fields'] = array_merge( $ret['fields'], [
1651 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
1654 if ( in_array( 'text', $options, true ) ) {
1655 $ret['tables'][] = 'text';
1656 $ret['fields'] = array_merge( $ret['fields'], [
1660 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1667 * Return the tables, fields, and join conditions to be selected to create
1668 * a new archived revision object.
1670 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1674 * @return array With three keys:
1675 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1676 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1677 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1679 public function getArchiveQueryInfo() {
1680 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
1682 'tables' => [ 'archive' ] +
$commentQuery['tables'],
1699 ] +
$commentQuery['fields'],
1700 'joins' => $commentQuery['joins'],
1703 if ( $this->contentHandlerUseDB
) {
1704 $ret['fields'][] = 'ar_content_format';
1705 $ret['fields'][] = 'ar_content_model';
1712 * Do a batched query for the sizes of a set of revisions.
1714 * MCR migration note: this replaces Revision::getParentLengths
1716 * @param int[] $revIds
1717 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1718 * of the corresponding revision.
1720 public function getRevisionSizes( array $revIds ) {
1721 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
1725 * Do a batched query for the sizes of a set of revisions.
1727 * MCR migration note: this replaces Revision::getParentLengths
1729 * @deprecated use RevisionStore::getRevisionSizes instead.
1731 * @param IDatabase $db
1732 * @param int[] $revIds
1733 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1734 * of the corresponding revision.
1736 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
1737 $this->checkDatabaseWikiId( $db );
1741 return $revLens; // empty
1746 [ 'rev_id', 'rev_len' ],
1747 [ 'rev_id' => $revIds ],
1751 foreach ( $res as $row ) {
1752 $revLens[$row->rev_id
] = intval( $row->rev_len
);
1759 * Get previous revision for this title
1761 * MCR migration note: this replaces Revision::getPrevious
1763 * @param RevisionRecord $rev
1764 * @param Title $title if known (optional)
1766 * @return RevisionRecord|null
1768 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
1769 if ( $title === null ) {
1770 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1772 $prev = $title->getPreviousRevisionID( $rev->getId() );
1774 return $this->getRevisionByTitle( $title, $prev );
1780 * Get next revision for this title
1782 * MCR migration note: this replaces Revision::getNext
1784 * @param RevisionRecord $rev
1785 * @param Title $title if known (optional)
1787 * @return RevisionRecord|null
1789 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
1790 if ( $title === null ) {
1791 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1793 $next = $title->getNextRevisionID( $rev->getId() );
1795 return $this->getRevisionByTitle( $title, $next );
1801 * Get previous revision Id for this page_id
1802 * This is used to populate rev_parent_id on save
1804 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1806 * @param IDatabase $db
1807 * @param RevisionRecord $rev
1811 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
1812 $this->checkDatabaseWikiId( $db );
1814 if ( $rev->getPageId() === null ) {
1817 # Use page_latest if ID is not given
1818 if ( !$rev->getId() ) {
1819 $prevId = $db->selectField(
1820 'page', 'page_latest',
1821 [ 'page_id' => $rev->getPageId() ],
1825 $prevId = $db->selectField(
1826 'revision', 'rev_id',
1827 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1829 [ 'ORDER BY' => 'rev_id DESC' ]
1832 return intval( $prevId );
1836 * Get rev_timestamp from rev_id, without loading the rest of the row
1838 * MCR migration note: this replaces Revision::getTimestampFromId
1840 * @param Title $title
1843 * @return string|bool False if not found
1845 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1846 $db = $this->getDBConnection(
1847 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
1850 $conds = [ 'rev_id' => $id ];
1851 $conds['rev_page'] = $title->getArticleID();
1852 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1854 $this->releaseDBConnection( $db );
1855 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1859 * Get count of revisions per page...not very efficient
1861 * MCR migration note: this replaces Revision::countByPageId
1863 * @param IDatabase $db
1864 * @param int $id Page id
1867 public function countRevisionsByPageId( IDatabase
$db, $id ) {
1868 $this->checkDatabaseWikiId( $db );
1870 $row = $db->selectRow( 'revision',
1871 [ 'revCount' => 'COUNT(*)' ],
1872 [ 'rev_page' => $id ],
1876 return intval( $row->revCount
);
1882 * Get count of revisions per page...not very efficient
1884 * MCR migration note: this replaces Revision::countByTitle
1886 * @param IDatabase $db
1887 * @param Title $title
1890 public function countRevisionsByTitle( IDatabase
$db, $title ) {
1891 $id = $title->getArticleID();
1893 return $this->countRevisionsByPageId( $db, $id );
1899 * Check if no edits were made by other users since
1900 * the time a user started editing the page. Limit to
1901 * 50 revisions for the sake of performance.
1903 * MCR migration note: this replaces Revision::userWasLastToEdit
1905 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1906 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1907 * has been deprecated since 1.24.
1909 * @param IDatabase $db The Database to perform the check on.
1910 * @param int $pageId The ID of the page in question
1911 * @param int $userId The ID of the user in question
1912 * @param string $since Look at edits since this time
1914 * @return bool True if the given user was the only one to edit since the given timestamp
1916 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
1917 $this->checkDatabaseWikiId( $db );
1927 'rev_page' => $pageId,
1928 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1931 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ]
1933 foreach ( $res as $row ) {
1934 if ( $row->rev_user
!= $userId ) {
1942 * Load a revision based on a known page ID and current revision ID from the DB
1944 * This method allows for the use of caching, though accessing anything that normally
1945 * requires permission checks (aside from the text) will trigger a small DB lookup.
1947 * MCR migration note: this replaces Revision::newKnownCurrent
1949 * @param Title $title the associated page title
1950 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1952 * @return RevisionRecord|bool Returns false if missing
1954 public function getKnownCurrentRevision( Title
$title, $revId ) {
1955 $db = $this->getDBConnectionRef( DB_REPLICA
);
1957 $pageId = $title->getArticleID();
1964 $revId = $title->getLatestRevID();
1969 'No latest revision known for page ' . $title->getPrefixedDBkey()
1970 . ' even though it exists with page ID ' . $pageId
1975 $row = $this->cache
->getWithSetCallback(
1976 // Page/rev IDs passed in from DB to reflect history merges
1977 $this->cache
->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1978 WANObjectCache
::TTL_WEEK
,
1979 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1980 $setOpts +
= Database
::getCacheSetOptions( $db );
1983 'rev_page' => intval( $pageId ),
1984 'page_id' => intval( $pageId ),
1985 'rev_id' => intval( $revId ),
1988 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1989 return $row ?
: false; // don't cache negatives
1993 // Reflect revision deletion and user renames
1995 return $this->newRevisionFromRow( $row, 0, $title );
2001 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.