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;
136 * @return bool Whether the store is read-only
138 public function isReadOnly() {
139 return $this->blobStore
->isReadOnly();
145 public function getContentHandlerUseDB() {
146 return $this->contentHandlerUseDB
;
150 * @param bool $contentHandlerUseDB
152 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
153 $this->contentHandlerUseDB
= $contentHandlerUseDB;
157 * @return LoadBalancer
159 private function getDBLoadBalancer() {
160 return $this->loadBalancer
;
164 * @param int $mode DB_MASTER or DB_REPLICA
168 private function getDBConnection( $mode ) {
169 $lb = $this->getDBLoadBalancer();
170 return $lb->getConnection( $mode, [], $this->wikiId
);
174 * @param IDatabase $connection
176 private function releaseDBConnection( IDatabase
$connection ) {
177 $lb = $this->getDBLoadBalancer();
178 $lb->reuseConnection( $connection );
182 * @param int $mode DB_MASTER or DB_REPLICA
186 private function getDBConnectionRef( $mode ) {
187 $lb = $this->getDBLoadBalancer();
188 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
192 * Determines the page Title based on the available information.
194 * MCR migration note: this corresponds to Revision::getTitle
196 * @note this method should be private, external use should be avoided!
198 * @param int|null $pageId
199 * @param int|null $revId
200 * @param int $queryFlags
203 * @throws RevisionAccessException
205 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
206 if ( !$pageId && !$revId ) {
207 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
210 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
211 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
212 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
213 $queryFlags = self
::READ_NORMAL
;
216 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false );
217 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
218 $titleFlags = ( $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0 );
220 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
221 if ( $canUseTitleNewFromId ) {
222 // TODO: better foreign title handling (introduce TitleFactory)
223 $title = Title
::newFromID( $pageId, $titleFlags );
229 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
230 $canUseRevId = ( $revId !== null && $revId > 0 );
232 if ( $canUseRevId ) {
233 $dbr = $this->getDBConnectionRef( $dbMode );
234 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
235 $row = $dbr->selectRow(
236 [ 'revision', 'page' ],
245 [ 'rev_id' => $revId ],
248 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
251 // TODO: better foreign title handling (introduce TitleFactory)
252 return Title
::newFromRow( $row );
256 // If we still don't have a title, fallback to master if that wasn't already happening.
257 if ( $dbMode !== DB_MASTER
) {
258 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
261 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
262 [ 'trace' => wfBacktrace() ]
268 throw new RevisionAccessException(
269 "Could not determine title for page ID $pageId and revision ID $revId"
274 * @param mixed $value
275 * @param string $name
277 * @throw IncompleteRevisionException if $value is null
278 * @return mixed $value, if $value is not null
280 private function failOnNull( $value, $name ) {
281 if ( $value === null ) {
282 throw new IncompleteRevisionException(
283 "$name must not be " . var_export( $value, true ) . "!"
291 * @param mixed $value
292 * @param string $name
294 * @throw IncompleteRevisionException if $value is empty
295 * @return mixed $value, if $value is not null
297 private function failOnEmpty( $value, $name ) {
298 if ( $value === null ||
$value === 0 ||
$value === '' ) {
299 throw new IncompleteRevisionException(
300 "$name must not be " . var_export( $value, true ) . "!"
308 * Insert a new revision into the database, returning the new revision record
309 * on success and dies horribly on failure.
311 * MCR migration note: this replaces Revision::insertOn
313 * @param RevisionRecord $rev
314 * @param IDatabase $dbw (master connection)
316 * @throws InvalidArgumentException
317 * @return RevisionRecord the new revision record.
319 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
320 // TODO: pass in a DBTransactionContext instead of a database connection.
321 $this->checkDatabaseWikiId( $dbw );
323 if ( !$rev->getSlotRoles() ) {
324 throw new InvalidArgumentException( 'At least one slot needs to be defined!' );
327 if ( $rev->getSlotRoles() !== [ 'main' ] ) {
328 throw new InvalidArgumentException( 'Only the main slot is supported for now!' );
331 // TODO: we shouldn't need an actual Title here.
332 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
333 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
335 $parentId = $rev->getParentId() === null
336 ?
$this->getPreviousRevisionId( $dbw, $rev )
337 : $rev->getParentId();
339 // Record the text (or external storage URL) to the blob store
340 $slot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
342 $size = $this->failOnNull( $rev->getSize(), 'size field' );
343 $sha1 = $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
345 if ( !$slot->hasAddress() ) {
346 $content = $slot->getContent();
347 $format = $content->getDefaultFormat();
348 $model = $content->getModel();
350 $this->checkContentModel( $content, $title );
352 $data = $content->serialize( $format );
354 // Hints allow the blob store to optimize by "leaking" application level information to it.
355 // TODO: with the new MCR storage schema, we rev_id have this before storing the blobs.
356 // When we have it, add rev_id as a hint. Can be used with rev_parent_id for
357 // differential storage or compression of subsequent revisions.
359 BlobStore
::DESIGNATION_HINT
=> 'page-content', // BlobStore may be used for other things too.
360 BlobStore
::PAGE_HINT
=> $pageId,
361 BlobStore
::ROLE_HINT
=> $slot->getRole(),
362 BlobStore
::PARENT_HINT
=> $parentId,
363 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
364 BlobStore
::MODEL_HINT
=> $model,
365 BlobStore
::FORMAT_HINT
=> $format,
368 $blobAddress = $this->blobStore
->storeBlob( $data, $blobHints );
370 $blobAddress = $slot->getAddress();
371 $model = $slot->getModel();
372 $format = $slot->getFormat();
375 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
378 throw new LogicException(
379 'Blob address not supported in 1.29 database schema: ' . $blobAddress
383 // getTextIdFromAddress() is free to insert something into the text table, so $textId
384 // may be a new value, not anything already contained in $blobAddress.
385 $blobAddress = 'tt:' . $textId;
387 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
388 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
389 $timestamp = $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
391 # Record the edit in revisions
393 'rev_page' => $pageId,
394 'rev_parent_id' => $parentId,
395 'rev_text_id' => $textId,
396 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
397 'rev_user' => $this->failOnNull( $user->getId(), 'user field' ),
398 'rev_user_text' => $this->failOnEmpty( $user->getName(), 'user_text field' ),
399 'rev_timestamp' => $dbw->timestamp( $timestamp ),
400 'rev_deleted' => $rev->getVisibility(),
405 if ( $rev->getId() !== null ) {
406 // Needed to restore revisions with their original ID
407 $row['rev_id'] = $rev->getId();
410 list( $commentFields, $commentCallback ) =
411 $this->commentStore
->insertWithTempTable( $dbw, 'rev_comment', $comment );
412 $row +
= $commentFields;
414 if ( $this->contentHandlerUseDB
) {
415 // MCR migration note: rev_content_model and rev_content_format will go away
417 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
418 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
420 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
421 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
424 $dbw->insert( 'revision', $row, __METHOD__
);
426 if ( !isset( $row['rev_id'] ) ) {
427 // only if auto-increment was used
428 $row['rev_id'] = intval( $dbw->insertId() );
430 $commentCallback( $row['rev_id'] );
432 // Insert IP revision into ip_changes for use when querying for a range.
433 if ( $row['rev_user'] === 0 && IP
::isValid( $row['rev_user_text'] ) ) {
435 'ipc_rev_id' => $row['rev_id'],
436 'ipc_rev_timestamp' => $row['rev_timestamp'],
437 'ipc_hex' => IP
::toHex( $row['rev_user_text'] ),
439 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
442 $newSlot = SlotRecord
::newSaved( $row['rev_id'], $blobAddress, $slot );
443 $slots = new RevisionSlots( [ 'main' => $newSlot ] );
445 $user = new UserIdentityValue( intval( $row['rev_user'] ), $row['rev_user_text'] );
447 $rev = new RevisionStoreRecord(
456 $newSlot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
459 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
460 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
461 Assert
::postcondition(
462 $rev->getComment( RevisionRecord
::RAW
) !== null,
463 'revision must have a comment'
465 Assert
::postcondition(
466 $rev->getUser( RevisionRecord
::RAW
) !== null,
467 'revision must have a user'
470 Assert
::postcondition( $newSlot !== null, 'revision must have a main slot' );
471 Assert
::postcondition(
472 $newSlot->getAddress() !== null,
473 'main slot must have an addess'
476 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
482 * MCR migration note: this corresponds to Revision::checkContentModel
484 * @param Content $content
485 * @param Title $title
487 * @throws MWException
488 * @throws MWUnknownContentModelException
490 private function checkContentModel( Content
$content, Title
$title ) {
491 // Note: may return null for revisions that have not yet been inserted
493 $model = $content->getModel();
494 $format = $content->getDefaultFormat();
495 $handler = $content->getContentHandler();
499 if ( !$handler->isSupportedFormat( $format ) ) {
500 throw new MWException( "Can't use format $format with content model $model on $name" );
503 if ( !$this->contentHandlerUseDB
) {
504 // if $wgContentHandlerUseDB is not set,
505 // all revisions must use the default content model and format.
507 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
508 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
509 $defaultFormat = $defaultHandler->getDefaultFormat();
511 if ( $model != $defaultModel ) {
512 throw new MWException( "Can't save non-default content model with "
513 . "\$wgContentHandlerUseDB disabled: model is $model, "
514 . "default for $name is $defaultModel"
518 if ( $format != $defaultFormat ) {
519 throw new MWException( "Can't use non-default content format with "
520 . "\$wgContentHandlerUseDB disabled: format is $format, "
521 . "default for $name is $defaultFormat"
526 if ( !$content->isValid() ) {
527 throw new MWException(
528 "New content for $name is not valid! Content model is $model"
534 * Create a new null-revision for insertion into a page's
535 * history. This will not re-save the text, but simply refer
536 * to the text from the previous version.
538 * Such revisions can for instance identify page rename
539 * operations and other such meta-modifications.
541 * MCR migration note: this replaces Revision::newNullRevision
543 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
546 * @param IDatabase $dbw
547 * @param Title $title Title of the page to read from
548 * @param CommentStoreComment $comment RevisionRecord's summary
549 * @param bool $minor Whether the revision should be considered as minor
550 * @param User $user The user to attribute the revision to
551 * @return RevisionRecord|null RevisionRecord or null on error
553 public function newNullRevision(
556 CommentStoreComment
$comment,
560 $this->checkDatabaseWikiId( $dbw );
562 $fields = [ 'page_latest', 'page_namespace', 'page_title',
563 'rev_id', 'rev_text_id', 'rev_len', 'rev_sha1' ];
565 if ( $this->contentHandlerUseDB
) {
566 $fields[] = 'rev_content_model';
567 $fields[] = 'rev_content_format';
570 $current = $dbw->selectRow(
571 [ 'page', 'revision' ],
574 'page_id' => $title->getArticleID(),
575 'page_latest=rev_id',
578 [ 'FOR UPDATE' ] // T51581
583 'page' => $title->getArticleID(),
584 'user_text' => $user->getName(),
585 'user' => $user->getId(),
586 'comment' => $comment,
587 'minor_edit' => $minor,
588 'text_id' => $current->rev_text_id
,
589 'parent_id' => $current->page_latest
,
590 'len' => $current->rev_len
,
591 'sha1' => $current->rev_sha1
594 if ( $this->contentHandlerUseDB
) {
595 $fields['content_model'] = $current->rev_content_model
;
596 $fields['content_format'] = $current->rev_content_format
;
599 $fields['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
601 $mainSlot = $this->emulateMainSlot_1_29( $fields, 0, $title );
602 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
603 $this->initializeMutableRevisionFromArray( $revision, $fields );
604 $revision->setSlot( $mainSlot );
613 * MCR migration note: this replaces Revision::isUnpatrolled
615 * @todo This is overly specific, so move or kill this method.
617 * @param RevisionRecord $rev
619 * @return int Rcid of the unpatrolled row, zero if there isn't one
621 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
622 $rc = $this->getRecentChange( $rev );
623 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
624 return $rc->getAttribute( 'rc_id' );
631 * Get the RC object belonging to the current revision, if there's one
633 * MCR migration note: this replaces Revision::getRecentChange
635 * @todo move this somewhere else?
637 * @param RevisionRecord $rev
638 * @param int $flags (optional) $flags include:
639 * IDBAccessObject::READ_LATEST: Select the data from the master
641 * @return null|RecentChange
643 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
644 $dbr = $this->getDBConnection( DB_REPLICA
);
646 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
648 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
650 if ( !$userIdentity ) {
651 // If the revision has no user identity, chances are it never went
652 // into the database, and doesn't have an RC entry.
656 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
657 $rc = RecentChange
::newFromConds(
659 'rc_user_text' => $userIdentity->getName(),
660 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
661 'rc_this_oldid' => $rev->getId()
667 $this->releaseDBConnection( $dbr );
669 // XXX: cache this locally? Glue it to the RevisionRecord?
674 * Maps fields of the archive row to corresponding revision rows.
676 * @param object $archiveRow
678 * @return object a revision row object, corresponding to $archiveRow.
680 private static function mapArchiveFields( $archiveRow ) {
682 // keep with ar prefix:
685 // not the same suffix:
686 'ar_page_id' => 'rev_page',
687 'ar_rev_id' => 'rev_id',
690 'ar_text_id' => 'rev_text_id',
691 'ar_timestamp' => 'rev_timestamp',
692 'ar_user_text' => 'rev_user_text',
693 'ar_user' => 'rev_user',
694 'ar_minor_edit' => 'rev_minor_edit',
695 'ar_deleted' => 'rev_deleted',
696 'ar_len' => 'rev_len',
697 'ar_parent_id' => 'rev_parent_id',
698 'ar_sha1' => 'rev_sha1',
699 'ar_comment' => 'rev_comment',
700 'ar_comment_cid' => 'rev_comment_cid',
701 'ar_comment_id' => 'rev_comment_id',
702 'ar_comment_text' => 'rev_comment_text',
703 'ar_comment_data' => 'rev_comment_data',
704 'ar_comment_old' => 'rev_comment_old',
705 'ar_content_format' => 'rev_content_format',
706 'ar_content_model' => 'rev_content_model',
709 if ( empty( $archiveRow->ar_text_id
) ) {
710 $fieldMap['ar_text'] = 'old_text';
711 $fieldMap['ar_flags'] = 'old_flags';
714 $revRow = new stdClass();
715 foreach ( $fieldMap as $arKey => $revKey ) {
716 if ( property_exists( $archiveRow, $arKey ) ) {
717 $revRow->$revKey = $archiveRow->$arKey;
725 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
727 * @param object|array $row Either a database row or an array
728 * @param int $queryFlags for callbacks
729 * @param Title $title
731 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
732 * @throws MWException
734 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
735 $mainSlotRow = new stdClass();
736 $mainSlotRow->role_name
= 'main';
742 if ( is_object( $row ) ) {
744 if ( !isset( $row->rev_id
) && isset( $row->ar_user
) ) {
745 $row = $this->mapArchiveFields( $row );
748 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
749 $mainSlotRow->cont_address
= 'tt:' . $row->rev_text_id
;
752 if ( isset( $row->old_text
) ) {
753 // this happens when the text-table gets joined directly, in the pre-1.30 schema
754 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
755 // Check against selects that might have not included old_flags
756 if ( !property_exists( $row, 'old_flags' ) ) {
757 throw new InvalidArgumentException( 'old_flags was not set in $row' );
759 $blobFlags = ( $row->old_flags
=== null ) ?
'' : $row->old_flags
;
762 $mainSlotRow->slot_revision
= intval( $row->rev_id
);
764 $mainSlotRow->cont_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
765 $mainSlotRow->cont_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
766 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
767 ?
strval( $row->rev_content_model
)
769 // XXX: in the future, we'll probably always use the default format, and drop content_format
770 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
771 ?
strval( $row->rev_content_format
)
773 } elseif ( is_array( $row ) ) {
774 $mainSlotRow->slot_revision
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
776 $mainSlotRow->cont_address
= isset( $row['text_id'] )
777 ?
'tt:' . intval( $row['text_id'] )
779 $mainSlotRow->cont_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
780 $mainSlotRow->cont_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
782 $mainSlotRow->model_name
= isset( $row['content_model'] )
783 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
784 // XXX: in the future, we'll probably always use the default format, and drop content_format
785 $mainSlotRow->format_name
= isset( $row['content_format'] )
786 ?
strval( $row['content_format'] ) : null;
787 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
788 // XXX: If the flags field is not set then $blobFlags should be null so that no
789 // decoding will happen. An empty string will result in default decodings.
790 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
792 // if we have a Content object, override mText and mContentModel
793 if ( !empty( $row['content'] ) ) {
794 if ( !( $row['content'] instanceof Content
) ) {
795 throw new MWException( 'content field must contain a Content object.' );
798 /** @var Content $content */
799 $content = $row['content'];
800 $handler = $content->getContentHandler();
802 $mainSlotRow->model_name
= $content->getModel();
804 // XXX: in the future, we'll probably always use the default format.
805 if ( $mainSlotRow->format_name
=== null ) {
806 $mainSlotRow->format_name
= $handler->getDefaultFormat();
810 throw new MWException( 'Revision constructor passed invalid row format.' );
813 // With the old schema, the content changes with every revision.
814 // ...except for null-revisions. Would be nice if we could detect them.
815 $mainSlotRow->slot_inherited
= 0;
817 if ( $mainSlotRow->model_name
=== null ) {
818 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
819 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
820 // TODO: MCR: deprecate $title->getModel().
821 return ContentHandler
::getDefaultModelFor( $title );
826 $content = function ( SlotRecord
$slot )
827 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
829 return $this->loadSlotContent(
833 $mainSlotRow->format_name
,
839 return new SlotRecord( $mainSlotRow, $content );
843 * Loads a Content object based on a slot row.
845 * This method does not call $slot->getContent(), and may be used as a callback
846 * called by $slot->getContent().
848 * MCR migration note: this roughly corresponds to Revision::getContentInternal
850 * @param SlotRecord $slot The SlotRecord to load content for
851 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
852 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
853 * Use null if no processing should happen. That is in constrast to the empty string,
854 * which causes the blob to be decoded according to the configured legacy encoding.
855 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
856 * @param int $queryFlags
858 * @throw RevisionAccessException
861 private function loadSlotContent(
868 if ( $blobData !== null ) {
869 Assert
::parameterType( 'string', $blobData, '$blobData' );
870 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
872 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
874 if ( $blobFlags === null ) {
875 // No blob flags, so use the blob verbatim.
878 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
879 if ( $data === false ) {
880 throw new RevisionAccessException(
881 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
887 $address = $slot->getAddress();
889 $data = $this->blobStore
->getBlob( $address, $queryFlags );
890 } catch ( BlobAccessException
$e ) {
891 throw new RevisionAccessException(
892 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
897 // Unserialize content
898 $handler = ContentHandler
::getForModelID( $slot->getModel() );
900 $content = $handler->unserializeContent( $data, $blobFormat );
905 * Load a page revision from a given revision ID number.
906 * Returns null if no such revision can be found.
908 * MCR migration note: this replaces Revision::newFromId
911 * IDBAccessObject::READ_LATEST: Select the data from the master
912 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
915 * @param int $flags (optional)
916 * @return RevisionRecord|null
918 public function getRevisionById( $id, $flags = 0 ) {
919 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
923 * Load either the current, or a specified, revision
924 * that's attached to a given link target. If not attached
925 * to that link target, will return null.
927 * MCR migration note: this replaces Revision::newFromTitle
930 * IDBAccessObject::READ_LATEST: Select the data from the master
931 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
933 * @param LinkTarget $linkTarget
934 * @param int $revId (optional)
935 * @param int $flags Bitfield (optional)
936 * @return RevisionRecord|null
938 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
940 'page_namespace' => $linkTarget->getNamespace(),
941 'page_title' => $linkTarget->getDBkey()
944 // Use the specified revision ID.
945 // Note that we use newRevisionFromConds here because we want to retry
946 // and fall back to master if the page is not found on a replica.
947 // Since the caller supplied a revision ID, we are pretty sure the revision is
948 // supposed to exist, so we should try hard to find it.
949 $conds['rev_id'] = $revId;
950 return $this->newRevisionFromConds( $conds, $flags );
952 // Use a join to get the latest revision.
953 // Note that we don't use newRevisionFromConds here because we don't want to retry
954 // and fall back to master. The assumption is that we only want to force the fallback
955 // if we are quite sure the revision exists because the caller supplied a revision ID.
956 // If the page isn't found at all on a replica, it probably simply does not exist.
957 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
959 $conds[] = 'rev_id=page_latest';
960 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
962 $this->releaseDBConnection( $db );
968 * Load either the current, or a specified, revision
969 * that's attached to a given page ID.
970 * Returns null if no such revision can be found.
972 * MCR migration note: this replaces Revision::newFromPageId
975 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
976 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
979 * @param int $revId (optional)
980 * @param int $flags Bitfield (optional)
981 * @return RevisionRecord|null
983 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
984 $conds = [ 'page_id' => $pageId ];
986 // Use the specified revision ID.
987 // Note that we use newRevisionFromConds here because we want to retry
988 // and fall back to master if the page is not found on a replica.
989 // Since the caller supplied a revision ID, we are pretty sure the revision is
990 // supposed to exist, so we should try hard to find it.
991 $conds['rev_id'] = $revId;
992 return $this->newRevisionFromConds( $conds, $flags );
994 // Use a join to get the latest revision.
995 // Note that we don't use newRevisionFromConds here because we don't want to retry
996 // and fall back to master. The assumption is that we only want to force the fallback
997 // if we are quite sure the revision exists because the caller supplied a revision ID.
998 // If the page isn't found at all on a replica, it probably simply does not exist.
999 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1001 $conds[] = 'rev_id=page_latest';
1002 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1004 $this->releaseDBConnection( $db );
1010 * Load the revision for the given title with the given timestamp.
1011 * WARNING: Timestamps may in some circumstances not be unique,
1012 * so this isn't the best key to use.
1014 * MCR migration note: this replaces Revision::loadFromTimestamp
1016 * @param Title $title
1017 * @param string $timestamp
1018 * @return RevisionRecord|null
1020 public function getRevisionByTimestamp( $title, $timestamp ) {
1021 return $this->newRevisionFromConds(
1023 'rev_timestamp' => $timestamp,
1024 'page_namespace' => $title->getNamespace(),
1025 'page_title' => $title->getDBkey()
1033 * Make a fake revision object from an archive table row. This is queried
1034 * for permissions or even inserted (as in Special:Undelete)
1036 * MCR migration note: this replaces Revision::newFromArchiveRow
1038 * @param object $row
1039 * @param int $queryFlags
1040 * @param Title|null $title
1041 * @param array $overrides associative array with fields of $row to override. This may be
1042 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1043 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1044 * override ar_parent_id.
1046 * @return RevisionRecord
1047 * @throws MWException
1049 public function newRevisionFromArchiveRow(
1052 Title
$title = null,
1053 array $overrides = []
1055 Assert
::parameterType( 'object', $row, '$row' );
1057 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1058 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1060 if ( !$title && isset( $overrides['title'] ) ) {
1061 if ( !( $overrides['title'] instanceof Title
) ) {
1062 throw new MWException( 'title field override must contain a Title object.' );
1065 $title = $overrides['title'];
1068 if ( !isset( $title ) ) {
1069 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1070 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1072 throw new InvalidArgumentException(
1073 'A Title or ar_namespace and ar_title must be given'
1078 foreach ( $overrides as $key => $value ) {
1080 $row->$field = $value;
1083 $user = $this->getUserIdentityFromRowObject( $row, 'ar_' );
1085 $comment = $this->commentStore
1086 // Legacy because $row may have come from self::selectFields()
1087 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'ar_comment', $row, true );
1089 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1090 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1092 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1096 * @param object $row
1097 * @param string $prefix Field prefix, such as 'rev_' or 'ar_'.
1099 * @return UserIdentityValue
1101 private function getUserIdentityFromRowObject( $row, $prefix = 'rev_' ) {
1102 $idField = "{$prefix}user";
1103 $nameField = "{$prefix}user_text";
1105 $userId = intval( $row->$idField );
1107 if ( isset( $row->user_name
) ) {
1108 $userName = $row->user_name
;
1109 } elseif ( isset( $row->$nameField ) ) {
1110 $userName = $row->$nameField;
1112 $userName = User
::whoIs( $userId );
1115 if ( $userName === false ) {
1116 wfWarn( __METHOD__
. ': Cannot determine user name for user ID ' . $userId );
1120 return new UserIdentityValue( $userId, $userName );
1124 * @see RevisionFactory::newRevisionFromRow_1_29
1126 * MCR migration note: this replaces Revision::newFromRow
1128 * @param object $row
1129 * @param int $queryFlags
1130 * @param Title|null $title
1132 * @return RevisionRecord
1133 * @throws MWException
1134 * @throws RevisionAccessException
1136 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title
$title = null ) {
1137 Assert
::parameterType( 'object', $row, '$row' );
1140 $pageId = isset( $row->rev_page
) ?
$row->rev_page
: 0; // XXX: also check page_id?
1141 $revId = isset( $row->rev_id
) ?
$row->rev_id
: 0;
1143 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1146 if ( !isset( $row->page_latest
) ) {
1147 $row->page_latest
= $title->getLatestRevID();
1148 if ( $row->page_latest
=== 0 && $title->exists() ) {
1149 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1153 $user = $this->getUserIdentityFromRowObject( $row );
1155 $comment = $this->commentStore
1156 // Legacy because $row may have come from self::selectFields()
1157 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'rev_comment', $row, true );
1159 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1160 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1162 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1166 * @see RevisionFactory::newRevisionFromRow
1168 * MCR migration note: this replaces Revision::newFromRow
1170 * @param object $row
1171 * @param int $queryFlags
1172 * @param Title|null $title
1174 * @return RevisionRecord
1176 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1177 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1181 * Constructs a new MutableRevisionRecord based on the given associative array following
1182 * the MW1.29 convention for the Revision constructor.
1184 * MCR migration note: this replaces Revision::newFromRow
1186 * @param array $fields
1187 * @param int $queryFlags
1188 * @param Title|null $title
1190 * @return MutableRevisionRecord
1191 * @throws MWException
1192 * @throws RevisionAccessException
1194 public function newMutableRevisionFromArray(
1199 if ( !$title && isset( $fields['title'] ) ) {
1200 if ( !( $fields['title'] instanceof Title
) ) {
1201 throw new MWException( 'title field must contain a Title object.' );
1204 $title = $fields['title'];
1208 $pageId = isset( $fields['page'] ) ?
$fields['page'] : 0;
1209 $revId = isset( $fields['id'] ) ?
$fields['id'] : 0;
1211 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1214 if ( !isset( $fields['page'] ) ) {
1215 $fields['page'] = $title->getArticleID( $queryFlags );
1218 // if we have a content object, use it to set the model and type
1219 if ( !empty( $fields['content'] ) ) {
1220 if ( !( $fields['content'] instanceof Content
) ) {
1221 throw new MWException( 'content field must contain a Content object.' );
1224 if ( !empty( $fields['text_id'] ) ) {
1225 throw new MWException(
1226 "Text already stored in external store (id {$fields['text_id']}), " .
1227 "can't serialize content object"
1232 // Replaces old lazy loading logic in Revision::getUserText.
1233 if ( !isset( $fields['user_text'] ) && isset( $fields['user'] ) ) {
1234 if ( $fields['user'] instanceof UserIdentity
) {
1235 /** @var User $user */
1236 $user = $fields['user'];
1237 $fields['user_text'] = $user->getName();
1238 $fields['user'] = $user->getId();
1240 // TODO: wrap this in a callback to make it lazy again.
1241 $name = $fields['user'] === 0 ?
false : User
::whoIs( $fields['user'] );
1243 if ( $name === false ) {
1244 throw new MWException(
1245 'user_text not given, and unknown user ID ' . $fields['user']
1249 $fields['user_text'] = $name;
1254 isset( $fields['comment'] )
1255 && !( $fields['comment'] instanceof CommentStoreComment
)
1257 $commentData = isset( $fields['comment_data'] ) ?
$fields['comment_data'] : null;
1259 if ( $fields['comment'] instanceof Message
) {
1260 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1265 $commentText = trim( strval( $fields['comment'] ) );
1266 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1273 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1275 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1276 $this->initializeMutableRevisionFromArray( $revision, $fields );
1277 $revision->setSlot( $mainSlot );
1283 * @param MutableRevisionRecord $record
1284 * @param array $fields
1286 private function initializeMutableRevisionFromArray(
1287 MutableRevisionRecord
$record,
1290 /** @var UserIdentity $user */
1293 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1294 $user = $fields['user'];
1295 } elseif ( isset( $fields['user'] ) && isset( $fields['user_text'] ) ) {
1296 $user = new UserIdentityValue( intval( $fields['user'] ), $fields['user_text'] );
1297 } elseif ( isset( $fields['user'] ) ) {
1298 $user = User
::newFromId( intval( $fields['user'] ) );
1299 } elseif ( isset( $fields['user_text'] ) ) {
1300 $user = User
::newFromName( $fields['user_text'] );
1302 // User::newFromName will return false for IP addresses (and invalid names)
1303 if ( $user == false ) {
1304 $user = new UserIdentityValue( 0, $fields['user_text'] );
1309 $record->setUser( $user );
1312 $timestamp = isset( $fields['timestamp'] )
1313 ?
strval( $fields['timestamp'] )
1314 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1316 $record->setTimestamp( $timestamp );
1318 if ( isset( $fields['page'] ) ) {
1319 $record->setPageId( intval( $fields['page'] ) );
1322 if ( isset( $fields['id'] ) ) {
1323 $record->setId( intval( $fields['id'] ) );
1325 if ( isset( $fields['parent_id'] ) ) {
1326 $record->setParentId( intval( $fields['parent_id'] ) );
1329 if ( isset( $fields['sha1'] ) ) {
1330 $record->setSha1( $fields['sha1'] );
1332 if ( isset( $fields['size'] ) ) {
1333 $record->setSize( intval( $fields['size'] ) );
1336 if ( isset( $fields['minor_edit'] ) ) {
1337 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1339 if ( isset( $fields['deleted'] ) ) {
1340 $record->setVisibility( intval( $fields['deleted'] ) );
1343 if ( isset( $fields['comment'] ) ) {
1344 Assert
::parameterType(
1345 CommentStoreComment
::class,
1349 $record->setComment( $fields['comment'] );
1354 * Load a page revision from a given revision ID number.
1355 * Returns null if no such revision can be found.
1357 * MCR migration note: this corresponds to Revision::loadFromId
1359 * @note direct use is deprecated!
1360 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1362 * @param IDatabase $db
1365 * @return RevisionRecord|null
1367 public function loadRevisionFromId( IDatabase
$db, $id ) {
1368 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1372 * Load either the current, or a specified, revision
1373 * that's attached to a given page. If not attached
1374 * to that page, will return null.
1376 * MCR migration note: this replaces Revision::loadFromPageId
1378 * @note direct use is deprecated!
1379 * @todo remove when unused!
1381 * @param IDatabase $db
1382 * @param int $pageid
1384 * @return RevisionRecord|null
1386 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1387 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1389 $conds['rev_id'] = intval( $id );
1391 $conds[] = 'rev_id=page_latest';
1393 return $this->loadRevisionFromConds( $db, $conds );
1397 * Load either the current, or a specified, revision
1398 * that's attached to a given page. If not attached
1399 * to that page, will return null.
1401 * MCR migration note: this replaces Revision::loadFromTitle
1403 * @note direct use is deprecated!
1404 * @todo remove when unused!
1406 * @param IDatabase $db
1407 * @param Title $title
1410 * @return RevisionRecord|null
1412 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1414 $matchId = intval( $id );
1416 $matchId = 'page_latest';
1419 return $this->loadRevisionFromConds(
1423 'page_namespace' => $title->getNamespace(),
1424 'page_title' => $title->getDBkey()
1432 * Load the revision for the given title with the given timestamp.
1433 * WARNING: Timestamps may in some circumstances not be unique,
1434 * so this isn't the best key to use.
1436 * MCR migration note: this replaces Revision::loadFromTimestamp
1438 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1439 * @todo remove when unused!
1441 * @param IDatabase $db
1442 * @param Title $title
1443 * @param string $timestamp
1444 * @return RevisionRecord|null
1446 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1447 return $this->loadRevisionFromConds( $db,
1449 'rev_timestamp' => $db->timestamp( $timestamp ),
1450 'page_namespace' => $title->getNamespace(),
1451 'page_title' => $title->getDBkey()
1459 * Given a set of conditions, fetch a revision
1461 * This method should be used if we are pretty sure the revision exists.
1462 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1463 * on a replica before hitting the master database.
1465 * MCR migration note: this corresponds to Revision::newFromConds
1467 * @param array $conditions
1468 * @param int $flags (optional)
1469 * @param Title $title
1471 * @return RevisionRecord|null
1473 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1474 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1475 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1476 $this->releaseDBConnection( $db );
1478 $lb = $this->getDBLoadBalancer();
1480 // Make sure new pending/committed revision are visibile later on
1481 // within web requests to certain avoid bugs like T93866 and T94407.
1483 && !( $flags & self
::READ_LATEST
)
1484 && $lb->getServerCount() > 1
1485 && $lb->hasOrMadeRecentMasterChanges()
1487 $flags = self
::READ_LATEST
;
1488 $db = $this->getDBConnection( DB_MASTER
);
1489 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1490 $this->releaseDBConnection( $db );
1497 * Given a set of conditions, fetch a revision from
1498 * the given database connection.
1500 * MCR migration note: this corresponds to Revision::loadFromConds
1502 * @param IDatabase $db
1503 * @param array $conditions
1504 * @param int $flags (optional)
1505 * @param Title $title
1507 * @return RevisionRecord|null
1509 private function loadRevisionFromConds(
1515 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1517 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1526 * Throws an exception if the given database connection does not belong to the wiki this
1527 * RevisionStore is bound to.
1529 * @param IDatabase $db
1530 * @throws MWException
1532 private function checkDatabaseWikiId( IDatabase
$db ) {
1533 $storeWiki = $this->wikiId
;
1534 $dbWiki = $db->getDomainID();
1536 if ( $dbWiki === $storeWiki ) {
1540 // XXX: we really want the default database ID...
1541 $storeWiki = $storeWiki ?
: wfWikiID();
1542 $dbWiki = $dbWiki ?
: wfWikiID();
1544 if ( $dbWiki === $storeWiki ) {
1548 // HACK: counteract encoding imposed by DatabaseDomain
1549 $storeWiki = str_replace( '?h', '-', $storeWiki );
1550 $dbWiki = str_replace( '?h', '-', $dbWiki );
1552 if ( $dbWiki === $storeWiki ) {
1556 throw new MWException( "RevisionStore for $storeWiki "
1557 . "cannot be used with a DB connection for $dbWiki" );
1561 * Given a set of conditions, return a row with the
1562 * fields necessary to build RevisionRecord objects.
1564 * MCR migration note: this corresponds to Revision::fetchFromConds
1566 * @param IDatabase $db
1567 * @param array $conditions
1568 * @param int $flags (optional)
1570 * @return object|false data row as a raw object
1572 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1573 $this->checkDatabaseWikiId( $db );
1575 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
1577 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1578 $options[] = 'FOR UPDATE';
1580 return $db->selectRow(
1581 $revQuery['tables'],
1582 $revQuery['fields'],
1591 * Return the tables, fields, and join conditions to be selected to create
1592 * a new revision object.
1594 * MCR migration note: this replaces Revision::getQueryInfo
1598 * @param array $options Any combination of the following strings
1599 * - 'page': Join with the page table, and select fields to identify the page
1600 * - 'user': Join with the user table, and select the user name
1601 * - 'text': Join with the text table, and select fields to load page text
1603 * @return array With three keys:
1604 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1605 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1606 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1608 public function getQueryInfo( $options = [] ) {
1615 $ret['tables'][] = 'revision';
1616 $ret['fields'] = array_merge( $ret['fields'], [
1630 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
1631 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1632 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1633 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1635 if ( $this->contentHandlerUseDB
) {
1636 $ret['fields'][] = 'rev_content_format';
1637 $ret['fields'][] = 'rev_content_model';
1640 if ( in_array( 'page', $options, true ) ) {
1641 $ret['tables'][] = 'page';
1642 $ret['fields'] = array_merge( $ret['fields'], [
1650 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1653 if ( in_array( 'user', $options, true ) ) {
1654 $ret['tables'][] = 'user';
1655 $ret['fields'] = array_merge( $ret['fields'], [
1658 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
1661 if ( in_array( 'text', $options, true ) ) {
1662 $ret['tables'][] = 'text';
1663 $ret['fields'] = array_merge( $ret['fields'], [
1667 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1674 * Return the tables, fields, and join conditions to be selected to create
1675 * a new archived revision object.
1677 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1681 * @return array With three keys:
1682 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1683 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1684 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1686 public function getArchiveQueryInfo() {
1687 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
1689 'tables' => [ 'archive' ] +
$commentQuery['tables'],
1706 ] +
$commentQuery['fields'],
1707 'joins' => $commentQuery['joins'],
1710 if ( $this->contentHandlerUseDB
) {
1711 $ret['fields'][] = 'ar_content_format';
1712 $ret['fields'][] = 'ar_content_model';
1719 * Do a batched query for the sizes of a set of revisions.
1721 * MCR migration note: this replaces Revision::getParentLengths
1723 * @param int[] $revIds
1724 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1725 * of the corresponding revision.
1727 public function getRevisionSizes( array $revIds ) {
1728 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
1732 * Do a batched query for the sizes of a set of revisions.
1734 * MCR migration note: this replaces Revision::getParentLengths
1736 * @deprecated use RevisionStore::getRevisionSizes instead.
1738 * @param IDatabase $db
1739 * @param int[] $revIds
1740 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1741 * of the corresponding revision.
1743 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
1744 $this->checkDatabaseWikiId( $db );
1748 return $revLens; // empty
1753 [ 'rev_id', 'rev_len' ],
1754 [ 'rev_id' => $revIds ],
1758 foreach ( $res as $row ) {
1759 $revLens[$row->rev_id
] = intval( $row->rev_len
);
1766 * Get previous revision for this title
1768 * MCR migration note: this replaces Revision::getPrevious
1770 * @param RevisionRecord $rev
1771 * @param Title $title if known (optional)
1773 * @return RevisionRecord|null
1775 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
1776 if ( $title === null ) {
1777 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1779 $prev = $title->getPreviousRevisionID( $rev->getId() );
1781 return $this->getRevisionByTitle( $title, $prev );
1787 * Get next revision for this title
1789 * MCR migration note: this replaces Revision::getNext
1791 * @param RevisionRecord $rev
1792 * @param Title $title if known (optional)
1794 * @return RevisionRecord|null
1796 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
1797 if ( $title === null ) {
1798 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1800 $next = $title->getNextRevisionID( $rev->getId() );
1802 return $this->getRevisionByTitle( $title, $next );
1808 * Get previous revision Id for this page_id
1809 * This is used to populate rev_parent_id on save
1811 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1813 * @param IDatabase $db
1814 * @param RevisionRecord $rev
1818 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
1819 $this->checkDatabaseWikiId( $db );
1821 if ( $rev->getPageId() === null ) {
1824 # Use page_latest if ID is not given
1825 if ( !$rev->getId() ) {
1826 $prevId = $db->selectField(
1827 'page', 'page_latest',
1828 [ 'page_id' => $rev->getPageId() ],
1832 $prevId = $db->selectField(
1833 'revision', 'rev_id',
1834 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1836 [ 'ORDER BY' => 'rev_id DESC' ]
1839 return intval( $prevId );
1843 * Get rev_timestamp from rev_id, without loading the rest of the row
1845 * MCR migration note: this replaces Revision::getTimestampFromId
1847 * @param Title $title
1850 * @return string|bool False if not found
1852 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1853 $db = $this->getDBConnection(
1854 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
1857 $conds = [ 'rev_id' => $id ];
1858 $conds['rev_page'] = $title->getArticleID();
1859 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1861 $this->releaseDBConnection( $db );
1862 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1866 * Get count of revisions per page...not very efficient
1868 * MCR migration note: this replaces Revision::countByPageId
1870 * @param IDatabase $db
1871 * @param int $id Page id
1874 public function countRevisionsByPageId( IDatabase
$db, $id ) {
1875 $this->checkDatabaseWikiId( $db );
1877 $row = $db->selectRow( 'revision',
1878 [ 'revCount' => 'COUNT(*)' ],
1879 [ 'rev_page' => $id ],
1883 return intval( $row->revCount
);
1889 * Get count of revisions per page...not very efficient
1891 * MCR migration note: this replaces Revision::countByTitle
1893 * @param IDatabase $db
1894 * @param Title $title
1897 public function countRevisionsByTitle( IDatabase
$db, $title ) {
1898 $id = $title->getArticleID();
1900 return $this->countRevisionsByPageId( $db, $id );
1906 * Check if no edits were made by other users since
1907 * the time a user started editing the page. Limit to
1908 * 50 revisions for the sake of performance.
1910 * MCR migration note: this replaces Revision::userWasLastToEdit
1912 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1913 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1914 * has been deprecated since 1.24.
1916 * @param IDatabase $db The Database to perform the check on.
1917 * @param int $pageId The ID of the page in question
1918 * @param int $userId The ID of the user in question
1919 * @param string $since Look at edits since this time
1921 * @return bool True if the given user was the only one to edit since the given timestamp
1923 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
1924 $this->checkDatabaseWikiId( $db );
1934 'rev_page' => $pageId,
1935 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1938 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ]
1940 foreach ( $res as $row ) {
1941 if ( $row->rev_user
!= $userId ) {
1949 * Load a revision based on a known page ID and current revision ID from the DB
1951 * This method allows for the use of caching, though accessing anything that normally
1952 * requires permission checks (aside from the text) will trigger a small DB lookup.
1954 * MCR migration note: this replaces Revision::newKnownCurrent
1956 * @param Title $title the associated page title
1957 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1959 * @return RevisionRecord|bool Returns false if missing
1961 public function getKnownCurrentRevision( Title
$title, $revId ) {
1962 $db = $this->getDBConnectionRef( DB_REPLICA
);
1964 $pageId = $title->getArticleID();
1971 $revId = $title->getLatestRevID();
1976 'No latest revision known for page ' . $title->getPrefixedDBkey()
1977 . ' even though it exists with page ID ' . $pageId
1982 $row = $this->cache
->getWithSetCallback(
1983 // Page/rev IDs passed in from DB to reflect history merges
1984 $this->cache
->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1985 WANObjectCache
::TTL_WEEK
,
1986 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1987 $setOpts +
= Database
::getCacheSetOptions( $db );
1990 'rev_page' => intval( $pageId ),
1991 'page_id' => intval( $pageId ),
1992 'rev_id' => intval( $revId ),
1995 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1996 return $row ?
: false; // don't cache negatives
2000 // Reflect revision deletion and user renames
2002 return $this->newRevisionFromRow( $row, 0, $title );
2008 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.