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
;
31 use CommentStoreComment
;
34 use DBAccessObjectUtils
;
37 use InvalidArgumentException
;
40 use MediaWiki\Linker\LinkTarget
;
41 use MediaWiki\User\UserIdentity
;
42 use MediaWiki\User\UserIdentityValue
;
45 use MWUnknownContentModelException
;
46 use Psr\Log\LoggerAwareInterface
;
47 use Psr\Log\LoggerInterface
;
48 use Psr\Log\NullLogger
;
54 use Wikimedia\Assert\Assert
;
55 use Wikimedia\Rdbms\Database
;
56 use Wikimedia\Rdbms\DBConnRef
;
57 use Wikimedia\Rdbms\IDatabase
;
58 use Wikimedia\Rdbms\LoadBalancer
;
61 * Service for looking up page revisions.
65 * @note This was written to act as a drop-in replacement for the corresponding
66 * static methods in Revision.
69 implements IDBAccessObject
, RevisionFactory
, RevisionLookup
, LoggerAwareInterface
{
84 private $contentHandlerUseDB = true;
89 private $loadBalancer;
99 private $commentStore;
102 * @var ActorMigration
104 private $actorMigration;
107 * @var LoggerInterface
112 * @todo $blobStore should be allowed to be any BlobStore!
114 * @param LoadBalancer $loadBalancer
115 * @param SqlBlobStore $blobStore
116 * @param WANObjectCache $cache
117 * @param CommentStore $commentStore
118 * @param ActorMigration $actorMigration
119 * @param bool|string $wikiId
121 public function __construct(
122 LoadBalancer
$loadBalancer,
123 SqlBlobStore
$blobStore,
124 WANObjectCache
$cache,
125 CommentStore
$commentStore,
126 ActorMigration
$actorMigration,
129 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
131 $this->loadBalancer
= $loadBalancer;
132 $this->blobStore
= $blobStore;
133 $this->cache
= $cache;
134 $this->commentStore
= $commentStore;
135 $this->actorMigration
= $actorMigration;
136 $this->wikiId
= $wikiId;
137 $this->logger
= new NullLogger();
140 public function setLogger( LoggerInterface
$logger ) {
141 $this->logger
= $logger;
145 * @return bool Whether the store is read-only
147 public function isReadOnly() {
148 return $this->blobStore
->isReadOnly();
154 public function getContentHandlerUseDB() {
155 return $this->contentHandlerUseDB
;
159 * @param bool $contentHandlerUseDB
161 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
162 $this->contentHandlerUseDB
= $contentHandlerUseDB;
166 * @return LoadBalancer
168 private function getDBLoadBalancer() {
169 return $this->loadBalancer
;
173 * @param int $mode DB_MASTER or DB_REPLICA
177 private function getDBConnection( $mode ) {
178 $lb = $this->getDBLoadBalancer();
179 return $lb->getConnection( $mode, [], $this->wikiId
);
183 * @param IDatabase $connection
185 private function releaseDBConnection( IDatabase
$connection ) {
186 $lb = $this->getDBLoadBalancer();
187 $lb->reuseConnection( $connection );
191 * @param int $mode DB_MASTER or DB_REPLICA
195 private function getDBConnectionRef( $mode ) {
196 $lb = $this->getDBLoadBalancer();
197 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
201 * Determines the page Title based on the available information.
203 * MCR migration note: this corresponds to Revision::getTitle
205 * @note this method should be private, external use should be avoided!
207 * @param int|null $pageId
208 * @param int|null $revId
209 * @param int $queryFlags
212 * @throws RevisionAccessException
214 public function getTitle( $pageId, $revId, $queryFlags = self
::READ_NORMAL
) {
215 if ( !$pageId && !$revId ) {
216 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
219 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
220 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
221 if ( DBAccessObjectUtils
::hasFlags( $queryFlags, self
::READ_LATEST_IMMUTABLE
) ) {
222 $queryFlags = self
::READ_NORMAL
;
225 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false );
226 list( $dbMode, $dbOptions ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
227 $titleFlags = ( $dbMode == DB_MASTER ? Title
::GAID_FOR_UPDATE
: 0 );
229 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
230 if ( $canUseTitleNewFromId ) {
231 // TODO: better foreign title handling (introduce TitleFactory)
232 $title = Title
::newFromID( $pageId, $titleFlags );
238 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
239 $canUseRevId = ( $revId !== null && $revId > 0 );
241 if ( $canUseRevId ) {
242 $dbr = $this->getDBConnectionRef( $dbMode );
243 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
244 $row = $dbr->selectRow(
245 [ 'revision', 'page' ],
254 [ 'rev_id' => $revId ],
257 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
260 // TODO: better foreign title handling (introduce TitleFactory)
261 return Title
::newFromRow( $row );
265 // If we still don't have a title, fallback to master if that wasn't already happening.
266 if ( $dbMode !== DB_MASTER
) {
267 $title = $this->getTitle( $pageId, $revId, self
::READ_LATEST
);
270 __METHOD__
. ' fell back to READ_LATEST and got a Title.',
271 [ 'trace' => wfBacktrace() ]
277 throw new RevisionAccessException(
278 "Could not determine title for page ID $pageId and revision ID $revId"
283 * @param mixed $value
284 * @param string $name
286 * @throw IncompleteRevisionException if $value is null
287 * @return mixed $value, if $value is not null
289 private function failOnNull( $value, $name ) {
290 if ( $value === null ) {
291 throw new IncompleteRevisionException(
292 "$name must not be " . var_export( $value, true ) . "!"
300 * @param mixed $value
301 * @param string $name
303 * @throw IncompleteRevisionException if $value is empty
304 * @return mixed $value, if $value is not null
306 private function failOnEmpty( $value, $name ) {
307 if ( $value === null ||
$value === 0 ||
$value === '' ) {
308 throw new IncompleteRevisionException(
309 "$name must not be " . var_export( $value, true ) . "!"
317 * Insert a new revision into the database, returning the new revision record
318 * on success and dies horribly on failure.
320 * MCR migration note: this replaces Revision::insertOn
322 * @param RevisionRecord $rev
323 * @param IDatabase $dbw (master connection)
325 * @throws InvalidArgumentException
326 * @return RevisionRecord the new revision record.
328 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
329 // TODO: pass in a DBTransactionContext instead of a database connection.
330 $this->checkDatabaseWikiId( $dbw );
332 if ( !$rev->getSlotRoles() ) {
333 throw new InvalidArgumentException( 'At least one slot needs to be defined!' );
336 if ( $rev->getSlotRoles() !== [ 'main' ] ) {
337 throw new InvalidArgumentException( 'Only the main slot is supported for now!' );
340 // TODO: we shouldn't need an actual Title here.
341 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
342 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
344 $parentId = $rev->getParentId() === null
345 ?
$this->getPreviousRevisionId( $dbw, $rev )
346 : $rev->getParentId();
348 // Record the text (or external storage URL) to the blob store
349 $slot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
351 $size = $this->failOnNull( $rev->getSize(), 'size field' );
352 $sha1 = $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
354 if ( !$slot->hasAddress() ) {
355 $content = $slot->getContent();
356 $format = $content->getDefaultFormat();
357 $model = $content->getModel();
359 $this->checkContentModel( $content, $title );
361 $data = $content->serialize( $format );
363 // Hints allow the blob store to optimize by "leaking" application level information to it.
364 // TODO: with the new MCR storage schema, we rev_id have this before storing the blobs.
365 // When we have it, add rev_id as a hint. Can be used with rev_parent_id for
366 // differential storage or compression of subsequent revisions.
368 BlobStore
::DESIGNATION_HINT
=> 'page-content', // BlobStore may be used for other things too.
369 BlobStore
::PAGE_HINT
=> $pageId,
370 BlobStore
::ROLE_HINT
=> $slot->getRole(),
371 BlobStore
::PARENT_HINT
=> $parentId,
372 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
373 BlobStore
::MODEL_HINT
=> $model,
374 BlobStore
::FORMAT_HINT
=> $format,
377 $blobAddress = $this->blobStore
->storeBlob( $data, $blobHints );
379 $blobAddress = $slot->getAddress();
380 $model = $slot->getModel();
381 $format = $slot->getFormat();
384 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
387 throw new LogicException(
388 'Blob address not supported in 1.29 database schema: ' . $blobAddress
392 // getTextIdFromAddress() is free to insert something into the text table, so $textId
393 // may be a new value, not anything already contained in $blobAddress.
394 $blobAddress = SqlBlobStore
::makeAddressFromTextId( $textId );
396 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
397 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
398 $timestamp = $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
401 $this->failOnNull( $user->getId(), 'user field' );
402 $this->failOnEmpty( $user->getName(), 'user_text field' );
404 # Record the edit in revisions
406 'rev_page' => $pageId,
407 'rev_parent_id' => $parentId,
408 'rev_text_id' => $textId,
409 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
410 'rev_timestamp' => $dbw->timestamp( $timestamp ),
411 'rev_deleted' => $rev->getVisibility(),
416 if ( $rev->getId() !== null ) {
417 // Needed to restore revisions with their original ID
418 $row['rev_id'] = $rev->getId();
421 list( $commentFields, $commentCallback ) =
422 $this->commentStore
->insertWithTempTable( $dbw, 'rev_comment', $comment );
423 $row +
= $commentFields;
425 list( $actorFields, $actorCallback ) =
426 $this->actorMigration
->getInsertValuesWithTempTable( $dbw, 'rev_user', $user );
427 $row +
= $actorFields;
429 if ( $this->contentHandlerUseDB
) {
430 // MCR migration note: rev_content_model and rev_content_format will go away
432 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
433 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
435 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
436 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
439 $dbw->insert( 'revision', $row, __METHOD__
);
441 if ( !isset( $row['rev_id'] ) ) {
442 // only if auto-increment was used
443 $row['rev_id'] = intval( $dbw->insertId() );
445 $commentCallback( $row['rev_id'] );
446 $actorCallback( $row['rev_id'], $row );
448 // Insert IP revision into ip_changes for use when querying for a range.
449 if ( $user->getId() === 0 && IP
::isValid( $user->getName() ) ) {
451 'ipc_rev_id' => $row['rev_id'],
452 'ipc_rev_timestamp' => $row['rev_timestamp'],
453 'ipc_hex' => IP
::toHex( $user->getName() ),
455 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
458 $newSlot = SlotRecord
::newSaved( $row['rev_id'], $textId, $blobAddress, $slot );
459 $slots = new RevisionSlots( [ 'main' => $newSlot ] );
461 $rev = new RevisionStoreRecord(
470 $newSlot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
473 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
474 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
475 Assert
::postcondition(
476 $rev->getComment( RevisionRecord
::RAW
) !== null,
477 'revision must have a comment'
479 Assert
::postcondition(
480 $rev->getUser( RevisionRecord
::RAW
) !== null,
481 'revision must have a user'
484 Assert
::postcondition( $newSlot !== null, 'revision must have a main slot' );
485 Assert
::postcondition(
486 $newSlot->getAddress() !== null,
487 'main slot must have an addess'
490 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
496 * MCR migration note: this corresponds to Revision::checkContentModel
498 * @param Content $content
499 * @param Title $title
501 * @throws MWException
502 * @throws MWUnknownContentModelException
504 private function checkContentModel( Content
$content, Title
$title ) {
505 // Note: may return null for revisions that have not yet been inserted
507 $model = $content->getModel();
508 $format = $content->getDefaultFormat();
509 $handler = $content->getContentHandler();
513 if ( !$handler->isSupportedFormat( $format ) ) {
514 throw new MWException( "Can't use format $format with content model $model on $name" );
517 if ( !$this->contentHandlerUseDB
) {
518 // if $wgContentHandlerUseDB is not set,
519 // all revisions must use the default content model and format.
521 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
522 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
523 $defaultFormat = $defaultHandler->getDefaultFormat();
525 if ( $model != $defaultModel ) {
526 throw new MWException( "Can't save non-default content model with "
527 . "\$wgContentHandlerUseDB disabled: model is $model, "
528 . "default for $name is $defaultModel"
532 if ( $format != $defaultFormat ) {
533 throw new MWException( "Can't use non-default content format with "
534 . "\$wgContentHandlerUseDB disabled: format is $format, "
535 . "default for $name is $defaultFormat"
540 if ( !$content->isValid() ) {
541 throw new MWException(
542 "New content for $name is not valid! Content model is $model"
548 * Create a new null-revision for insertion into a page's
549 * history. This will not re-save the text, but simply refer
550 * to the text from the previous version.
552 * Such revisions can for instance identify page rename
553 * operations and other such meta-modifications.
555 * MCR migration note: this replaces Revision::newNullRevision
557 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
560 * @param IDatabase $dbw
561 * @param Title $title Title of the page to read from
562 * @param CommentStoreComment $comment RevisionRecord's summary
563 * @param bool $minor Whether the revision should be considered as minor
564 * @param User $user The user to attribute the revision to
565 * @return RevisionRecord|null RevisionRecord or null on error
567 public function newNullRevision(
570 CommentStoreComment
$comment,
574 $this->checkDatabaseWikiId( $dbw );
576 $fields = [ 'page_latest', 'page_namespace', 'page_title',
577 'rev_id', 'rev_text_id', 'rev_len', 'rev_sha1' ];
579 if ( $this->contentHandlerUseDB
) {
580 $fields[] = 'rev_content_model';
581 $fields[] = 'rev_content_format';
584 $current = $dbw->selectRow(
585 [ 'page', 'revision' ],
588 'page_id' => $title->getArticleID(),
589 'page_latest=rev_id',
592 [ 'FOR UPDATE' ] // T51581
597 'page' => $title->getArticleID(),
598 'user_text' => $user->getName(),
599 'user' => $user->getId(),
600 'actor' => $user->getActorId(),
601 'comment' => $comment,
602 'minor_edit' => $minor,
603 'text_id' => $current->rev_text_id
,
604 'parent_id' => $current->page_latest
,
605 'slot_origin' => $current->page_latest
,
606 'len' => $current->rev_len
,
607 'sha1' => $current->rev_sha1
610 if ( $this->contentHandlerUseDB
) {
611 $fields['content_model'] = $current->rev_content_model
;
612 $fields['content_format'] = $current->rev_content_format
;
615 $fields['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
617 $mainSlot = $this->emulateMainSlot_1_29( $fields, self
::READ_LATEST
, $title );
618 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
619 $this->initializeMutableRevisionFromArray( $revision, $fields );
620 $revision->setSlot( $mainSlot );
629 * MCR migration note: this replaces Revision::isUnpatrolled
631 * @todo This is overly specific, so move or kill this method.
633 * @param RevisionRecord $rev
635 * @return int Rcid of the unpatrolled row, zero if there isn't one
637 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
638 $rc = $this->getRecentChange( $rev );
639 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == RecentChange
::PRC_UNPATROLLED
) {
640 return $rc->getAttribute( 'rc_id' );
647 * Get the RC object belonging to the current revision, if there's one
649 * MCR migration note: this replaces Revision::getRecentChange
651 * @todo move this somewhere else?
653 * @param RevisionRecord $rev
654 * @param int $flags (optional) $flags include:
655 * IDBAccessObject::READ_LATEST: Select the data from the master
657 * @return null|RecentChange
659 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
660 $dbr = $this->getDBConnection( DB_REPLICA
);
662 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
664 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
666 if ( !$userIdentity ) {
667 // If the revision has no user identity, chances are it never went
668 // into the database, and doesn't have an RC entry.
672 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
673 $actorWhere = $this->actorMigration
->getWhere( $dbr, 'rc_user', $rev->getUser(), false );
674 $rc = RecentChange
::newFromConds(
676 $actorWhere['conds'],
677 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
678 'rc_this_oldid' => $rev->getId()
684 $this->releaseDBConnection( $dbr );
686 // XXX: cache this locally? Glue it to the RevisionRecord?
691 * Maps fields of the archive row to corresponding revision rows.
693 * @param object $archiveRow
695 * @return object a revision row object, corresponding to $archiveRow.
697 private static function mapArchiveFields( $archiveRow ) {
699 // keep with ar prefix:
702 // not the same suffix:
703 'ar_page_id' => 'rev_page',
704 'ar_rev_id' => 'rev_id',
707 'ar_text_id' => 'rev_text_id',
708 'ar_timestamp' => 'rev_timestamp',
709 'ar_user_text' => 'rev_user_text',
710 'ar_user' => 'rev_user',
711 'ar_actor' => 'rev_actor',
712 'ar_minor_edit' => 'rev_minor_edit',
713 'ar_deleted' => 'rev_deleted',
714 'ar_len' => 'rev_len',
715 'ar_parent_id' => 'rev_parent_id',
716 'ar_sha1' => 'rev_sha1',
717 'ar_comment' => 'rev_comment',
718 'ar_comment_cid' => 'rev_comment_cid',
719 'ar_comment_id' => 'rev_comment_id',
720 'ar_comment_text' => 'rev_comment_text',
721 'ar_comment_data' => 'rev_comment_data',
722 'ar_comment_old' => 'rev_comment_old',
723 'ar_content_format' => 'rev_content_format',
724 'ar_content_model' => 'rev_content_model',
727 $revRow = new stdClass();
728 foreach ( $fieldMap as $arKey => $revKey ) {
729 if ( property_exists( $archiveRow, $arKey ) ) {
730 $revRow->$revKey = $archiveRow->$arKey;
738 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
740 * @param object|array $row Either a database row or an array
741 * @param int $queryFlags for callbacks
742 * @param Title $title
744 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
745 * @throws MWException
747 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
748 $mainSlotRow = new stdClass();
749 $mainSlotRow->role_name
= 'main';
750 $mainSlotRow->model_name
= null;
751 $mainSlotRow->slot_revision_id
= null;
752 $mainSlotRow->content_address
= null;
753 $mainSlotRow->slot_content_id
= null;
759 if ( is_object( $row ) ) {
761 if ( !isset( $row->rev_id
) && ( isset( $row->ar_user
) ||
isset( $row->ar_actor
) ) ) {
762 $row = $this->mapArchiveFields( $row );
765 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
766 $mainSlotRow->slot_content_id
= $row->rev_text_id
;
767 $mainSlotRow->content_address
= SqlBlobStore
::makeAddressFromTextId(
772 // This is used by null-revisions
773 $mainSlotRow->slot_origin
= isset( $row->slot_origin
)
774 ?
intval( $row->slot_origin
)
777 if ( isset( $row->old_text
) ) {
778 // this happens when the text-table gets joined directly, in the pre-1.30 schema
779 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
780 // Check against selects that might have not included old_flags
781 if ( !property_exists( $row, 'old_flags' ) ) {
782 throw new InvalidArgumentException( 'old_flags was not set in $row' );
784 $blobFlags = ( $row->old_flags
=== null ) ?
'' : $row->old_flags
;
787 $mainSlotRow->slot_revision_id
= intval( $row->rev_id
);
789 $mainSlotRow->content_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
790 $mainSlotRow->content_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
791 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
792 ?
strval( $row->rev_content_model
)
794 // XXX: in the future, we'll probably always use the default format, and drop content_format
795 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
796 ?
strval( $row->rev_content_format
)
798 } elseif ( is_array( $row ) ) {
799 $mainSlotRow->slot_revision_id
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
801 $mainSlotRow->slot_content_id
= isset( $row['text_id'] )
802 ?
intval( $row['text_id'] )
804 $mainSlotRow->slot_origin
= isset( $row['slot_origin'] )
805 ?
intval( $row['slot_origin'] )
807 $mainSlotRow->content_address
= isset( $row['text_id'] )
808 ? SqlBlobStore
::makeAddressFromTextId( intval( $row['text_id'] ) )
810 $mainSlotRow->content_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
811 $mainSlotRow->content_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
813 $mainSlotRow->model_name
= isset( $row['content_model'] )
814 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
815 // XXX: in the future, we'll probably always use the default format, and drop content_format
816 $mainSlotRow->format_name
= isset( $row['content_format'] )
817 ?
strval( $row['content_format'] ) : null;
818 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
819 // XXX: If the flags field is not set then $blobFlags should be null so that no
820 // decoding will happen. An empty string will result in default decodings.
821 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : null;
823 // if we have a Content object, override mText and mContentModel
824 if ( !empty( $row['content'] ) ) {
825 if ( !( $row['content'] instanceof Content
) ) {
826 throw new MWException( 'content field must contain a Content object.' );
829 /** @var Content $content */
830 $content = $row['content'];
831 $handler = $content->getContentHandler();
833 $mainSlotRow->model_name
= $content->getModel();
835 // XXX: in the future, we'll probably always use the default format.
836 if ( $mainSlotRow->format_name
=== null ) {
837 $mainSlotRow->format_name
= $handler->getDefaultFormat();
841 throw new MWException( 'Revision constructor passed invalid row format.' );
844 // With the old schema, the content changes with every revision,
845 // except for null-revisions.
846 if ( !isset( $mainSlotRow->slot_origin
) ) {
847 $mainSlotRow->slot_origin
= $mainSlotRow->slot_revision_id
;
850 if ( $mainSlotRow->model_name
=== null ) {
851 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
852 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
853 // TODO: MCR: deprecate $title->getModel().
854 return ContentHandler
::getDefaultModelFor( $title );
859 $content = function ( SlotRecord
$slot )
860 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
862 return $this->loadSlotContent(
866 $mainSlotRow->format_name
,
872 $mainSlotRow->slot_id
= $mainSlotRow->slot_revision_id
;
873 return new SlotRecord( $mainSlotRow, $content );
877 * Loads a Content object based on a slot row.
879 * This method does not call $slot->getContent(), and may be used as a callback
880 * called by $slot->getContent().
882 * MCR migration note: this roughly corresponds to Revision::getContentInternal
884 * @param SlotRecord $slot The SlotRecord to load content for
885 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
886 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
887 * Use null if no processing should happen. That is in constrast to the empty string,
888 * which causes the blob to be decoded according to the configured legacy encoding.
889 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
890 * @param int $queryFlags
892 * @throw RevisionAccessException
895 private function loadSlotContent(
902 if ( $blobData !== null ) {
903 Assert
::parameterType( 'string', $blobData, '$blobData' );
904 Assert
::parameterType( 'string|null', $blobFlags, '$blobFlags' );
906 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
908 if ( $blobFlags === null ) {
909 // No blob flags, so use the blob verbatim.
912 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
913 if ( $data === false ) {
914 throw new RevisionAccessException(
915 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
921 $address = $slot->getAddress();
923 $data = $this->blobStore
->getBlob( $address, $queryFlags );
924 } catch ( BlobAccessException
$e ) {
925 throw new RevisionAccessException(
926 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
931 // Unserialize content
932 $handler = ContentHandler
::getForModelID( $slot->getModel() );
934 $content = $handler->unserializeContent( $data, $blobFormat );
939 * Load a page revision from a given revision ID number.
940 * Returns null if no such revision can be found.
942 * MCR migration note: this replaces Revision::newFromId
945 * IDBAccessObject::READ_LATEST: Select the data from the master
946 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
949 * @param int $flags (optional)
950 * @return RevisionRecord|null
952 public function getRevisionById( $id, $flags = 0 ) {
953 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
957 * Load either the current, or a specified, revision
958 * that's attached to a given link target. If not attached
959 * to that link target, will return null.
961 * MCR migration note: this replaces Revision::newFromTitle
964 * IDBAccessObject::READ_LATEST: Select the data from the master
965 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
967 * @param LinkTarget $linkTarget
968 * @param int $revId (optional)
969 * @param int $flags Bitfield (optional)
970 * @return RevisionRecord|null
972 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
974 'page_namespace' => $linkTarget->getNamespace(),
975 'page_title' => $linkTarget->getDBkey()
978 // Use the specified revision ID.
979 // Note that we use newRevisionFromConds here because we want to retry
980 // and fall back to master if the page is not found on a replica.
981 // Since the caller supplied a revision ID, we are pretty sure the revision is
982 // supposed to exist, so we should try hard to find it.
983 $conds['rev_id'] = $revId;
984 return $this->newRevisionFromConds( $conds, $flags );
986 // Use a join to get the latest revision.
987 // Note that we don't use newRevisionFromConds here because we don't want to retry
988 // and fall back to master. The assumption is that we only want to force the fallback
989 // if we are quite sure the revision exists because the caller supplied a revision ID.
990 // If the page isn't found at all on a replica, it probably simply does not exist.
991 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
993 $conds[] = 'rev_id=page_latest';
994 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
996 $this->releaseDBConnection( $db );
1002 * Load either the current, or a specified, revision
1003 * that's attached to a given page ID.
1004 * Returns null if no such revision can be found.
1006 * MCR migration note: this replaces Revision::newFromPageId
1009 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
1010 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1012 * @param int $pageId
1013 * @param int $revId (optional)
1014 * @param int $flags Bitfield (optional)
1015 * @return RevisionRecord|null
1017 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1018 $conds = [ 'page_id' => $pageId ];
1020 // Use the specified revision ID.
1021 // Note that we use newRevisionFromConds here because we want to retry
1022 // and fall back to master if the page is not found on a replica.
1023 // Since the caller supplied a revision ID, we are pretty sure the revision is
1024 // supposed to exist, so we should try hard to find it.
1025 $conds['rev_id'] = $revId;
1026 return $this->newRevisionFromConds( $conds, $flags );
1028 // Use a join to get the latest revision.
1029 // Note that we don't use newRevisionFromConds here because we don't want to retry
1030 // and fall back to master. The assumption is that we only want to force the fallback
1031 // if we are quite sure the revision exists because the caller supplied a revision ID.
1032 // If the page isn't found at all on a replica, it probably simply does not exist.
1033 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1035 $conds[] = 'rev_id=page_latest';
1036 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1038 $this->releaseDBConnection( $db );
1044 * Load the revision for the given title with the given timestamp.
1045 * WARNING: Timestamps may in some circumstances not be unique,
1046 * so this isn't the best key to use.
1048 * MCR migration note: this replaces Revision::loadFromTimestamp
1050 * @param Title $title
1051 * @param string $timestamp
1052 * @return RevisionRecord|null
1054 public function getRevisionByTimestamp( $title, $timestamp ) {
1055 $db = $this->getDBConnection( DB_REPLICA
);
1056 return $this->newRevisionFromConds(
1058 'rev_timestamp' => $db->timestamp( $timestamp ),
1059 'page_namespace' => $title->getNamespace(),
1060 'page_title' => $title->getDBkey()
1068 * Make a fake revision object from an archive table row. This is queried
1069 * for permissions or even inserted (as in Special:Undelete)
1071 * MCR migration note: this replaces Revision::newFromArchiveRow
1073 * @param object $row
1074 * @param int $queryFlags
1075 * @param Title|null $title
1076 * @param array $overrides associative array with fields of $row to override. This may be
1077 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1078 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1079 * override ar_parent_id.
1081 * @return RevisionRecord
1082 * @throws MWException
1084 public function newRevisionFromArchiveRow(
1087 Title
$title = null,
1088 array $overrides = []
1090 Assert
::parameterType( 'object', $row, '$row' );
1092 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1093 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
1095 if ( !$title && isset( $overrides['title'] ) ) {
1096 if ( !( $overrides['title'] instanceof Title
) ) {
1097 throw new MWException( 'title field override must contain a Title object.' );
1100 $title = $overrides['title'];
1103 if ( !isset( $title ) ) {
1104 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1105 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1107 throw new InvalidArgumentException(
1108 'A Title or ar_namespace and ar_title must be given'
1113 foreach ( $overrides as $key => $value ) {
1115 $row->$field = $value;
1119 $user = User
::newFromAnyId(
1120 isset( $row->ar_user
) ?
$row->ar_user
: null,
1121 isset( $row->ar_user_text
) ?
$row->ar_user_text
: null,
1122 isset( $row->ar_actor
) ?
$row->ar_actor
: null
1124 } catch ( InvalidArgumentException
$ex ) {
1125 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1126 $user = new UserIdentityValue( 0, '', 0 );
1129 $comment = $this->commentStore
1130 // Legacy because $row may have come from self::selectFields()
1131 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'ar_comment', $row, true );
1133 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1134 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1136 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1140 * @see RevisionFactory::newRevisionFromRow_1_29
1142 * MCR migration note: this replaces Revision::newFromRow
1144 * @param object $row
1145 * @param int $queryFlags
1146 * @param Title|null $title
1148 * @return RevisionRecord
1149 * @throws MWException
1150 * @throws RevisionAccessException
1152 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title
$title = null ) {
1153 Assert
::parameterType( 'object', $row, '$row' );
1156 $pageId = isset( $row->rev_page
) ?
$row->rev_page
: 0; // XXX: also check page_id?
1157 $revId = isset( $row->rev_id
) ?
$row->rev_id
: 0;
1159 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1162 if ( !isset( $row->page_latest
) ) {
1163 $row->page_latest
= $title->getLatestRevID();
1164 if ( $row->page_latest
=== 0 && $title->exists() ) {
1165 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1170 $user = User
::newFromAnyId(
1171 isset( $row->rev_user
) ?
$row->rev_user
: null,
1172 isset( $row->rev_user_text
) ?
$row->rev_user_text
: null,
1173 isset( $row->rev_actor
) ?
$row->rev_actor
: null
1175 } catch ( InvalidArgumentException
$ex ) {
1176 wfWarn( __METHOD__
. ': ' . $ex->getMessage() );
1177 $user = new UserIdentityValue( 0, '', 0 );
1180 $comment = $this->commentStore
1181 // Legacy because $row may have come from self::selectFields()
1182 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), 'rev_comment', $row, true );
1184 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1185 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1187 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1191 * @see RevisionFactory::newRevisionFromRow
1193 * MCR migration note: this replaces Revision::newFromRow
1195 * @param object $row
1196 * @param int $queryFlags
1197 * @param Title|null $title
1199 * @return RevisionRecord
1201 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1202 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1206 * Constructs a new MutableRevisionRecord based on the given associative array following
1207 * the MW1.29 convention for the Revision constructor.
1209 * MCR migration note: this replaces Revision::newFromRow
1211 * @param array $fields
1212 * @param int $queryFlags
1213 * @param Title|null $title
1215 * @return MutableRevisionRecord
1216 * @throws MWException
1217 * @throws RevisionAccessException
1219 public function newMutableRevisionFromArray(
1224 if ( !$title && isset( $fields['title'] ) ) {
1225 if ( !( $fields['title'] instanceof Title
) ) {
1226 throw new MWException( 'title field must contain a Title object.' );
1229 $title = $fields['title'];
1233 $pageId = isset( $fields['page'] ) ?
$fields['page'] : 0;
1234 $revId = isset( $fields['id'] ) ?
$fields['id'] : 0;
1236 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1239 if ( !isset( $fields['page'] ) ) {
1240 $fields['page'] = $title->getArticleID( $queryFlags );
1243 // if we have a content object, use it to set the model and type
1244 if ( !empty( $fields['content'] ) ) {
1245 if ( !( $fields['content'] instanceof Content
) ) {
1246 throw new MWException( 'content field must contain a Content object.' );
1249 if ( !empty( $fields['text_id'] ) ) {
1250 throw new MWException(
1251 "Text already stored in external store (id {$fields['text_id']}), " .
1252 "can't serialize content object"
1258 isset( $fields['comment'] )
1259 && !( $fields['comment'] instanceof CommentStoreComment
)
1261 $commentData = isset( $fields['comment_data'] ) ?
$fields['comment_data'] : null;
1263 if ( $fields['comment'] instanceof Message
) {
1264 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1269 $commentText = trim( strval( $fields['comment'] ) );
1270 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1277 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1279 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1280 $this->initializeMutableRevisionFromArray( $revision, $fields );
1281 $revision->setSlot( $mainSlot );
1287 * @param MutableRevisionRecord $record
1288 * @param array $fields
1290 private function initializeMutableRevisionFromArray(
1291 MutableRevisionRecord
$record,
1294 /** @var UserIdentity $user */
1297 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1298 $user = $fields['user'];
1301 $user = User
::newFromAnyId(
1302 isset( $fields['user'] ) ?
$fields['user'] : null,
1303 isset( $fields['user_text'] ) ?
$fields['user_text'] : null,
1304 isset( $fields['actor'] ) ?
$fields['actor'] : null
1306 } catch ( InvalidArgumentException
$ex ) {
1312 $record->setUser( $user );
1315 $timestamp = isset( $fields['timestamp'] )
1316 ?
strval( $fields['timestamp'] )
1317 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1319 $record->setTimestamp( $timestamp );
1321 if ( isset( $fields['page'] ) ) {
1322 $record->setPageId( intval( $fields['page'] ) );
1325 if ( isset( $fields['id'] ) ) {
1326 $record->setId( intval( $fields['id'] ) );
1328 if ( isset( $fields['parent_id'] ) ) {
1329 $record->setParentId( intval( $fields['parent_id'] ) );
1332 if ( isset( $fields['sha1'] ) ) {
1333 $record->setSha1( $fields['sha1'] );
1335 if ( isset( $fields['size'] ) ) {
1336 $record->setSize( intval( $fields['size'] ) );
1339 if ( isset( $fields['minor_edit'] ) ) {
1340 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1342 if ( isset( $fields['deleted'] ) ) {
1343 $record->setVisibility( intval( $fields['deleted'] ) );
1346 if ( isset( $fields['comment'] ) ) {
1347 Assert
::parameterType(
1348 CommentStoreComment
::class,
1352 $record->setComment( $fields['comment'] );
1357 * Load a page revision from a given revision ID number.
1358 * Returns null if no such revision can be found.
1360 * MCR migration note: this corresponds to Revision::loadFromId
1362 * @note direct use is deprecated!
1363 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1365 * @param IDatabase $db
1368 * @return RevisionRecord|null
1370 public function loadRevisionFromId( IDatabase
$db, $id ) {
1371 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1375 * Load either the current, or a specified, revision
1376 * that's attached to a given page. If not attached
1377 * to that page, will return null.
1379 * MCR migration note: this replaces Revision::loadFromPageId
1381 * @note direct use is deprecated!
1382 * @todo remove when unused!
1384 * @param IDatabase $db
1385 * @param int $pageid
1387 * @return RevisionRecord|null
1389 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1390 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1392 $conds['rev_id'] = intval( $id );
1394 $conds[] = 'rev_id=page_latest';
1396 return $this->loadRevisionFromConds( $db, $conds );
1400 * Load either the current, or a specified, revision
1401 * that's attached to a given page. If not attached
1402 * to that page, will return null.
1404 * MCR migration note: this replaces Revision::loadFromTitle
1406 * @note direct use is deprecated!
1407 * @todo remove when unused!
1409 * @param IDatabase $db
1410 * @param Title $title
1413 * @return RevisionRecord|null
1415 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1417 $matchId = intval( $id );
1419 $matchId = 'page_latest';
1422 return $this->loadRevisionFromConds(
1426 'page_namespace' => $title->getNamespace(),
1427 'page_title' => $title->getDBkey()
1435 * Load the revision for the given title with the given timestamp.
1436 * WARNING: Timestamps may in some circumstances not be unique,
1437 * so this isn't the best key to use.
1439 * MCR migration note: this replaces Revision::loadFromTimestamp
1441 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1442 * @todo remove when unused!
1444 * @param IDatabase $db
1445 * @param Title $title
1446 * @param string $timestamp
1447 * @return RevisionRecord|null
1449 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1450 return $this->loadRevisionFromConds( $db,
1452 'rev_timestamp' => $db->timestamp( $timestamp ),
1453 'page_namespace' => $title->getNamespace(),
1454 'page_title' => $title->getDBkey()
1462 * Given a set of conditions, fetch a revision
1464 * This method should be used if we are pretty sure the revision exists.
1465 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1466 * on a replica before hitting the master database.
1468 * MCR migration note: this corresponds to Revision::newFromConds
1470 * @param array $conditions
1471 * @param int $flags (optional)
1472 * @param Title $title
1474 * @return RevisionRecord|null
1476 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1477 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1478 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1479 $this->releaseDBConnection( $db );
1481 $lb = $this->getDBLoadBalancer();
1483 // Make sure new pending/committed revision are visibile later on
1484 // within web requests to certain avoid bugs like T93866 and T94407.
1486 && !( $flags & self
::READ_LATEST
)
1487 && $lb->getServerCount() > 1
1488 && $lb->hasOrMadeRecentMasterChanges()
1490 $flags = self
::READ_LATEST
;
1491 $db = $this->getDBConnection( DB_MASTER
);
1492 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1493 $this->releaseDBConnection( $db );
1500 * Given a set of conditions, fetch a revision from
1501 * the given database connection.
1503 * MCR migration note: this corresponds to Revision::loadFromConds
1505 * @param IDatabase $db
1506 * @param array $conditions
1507 * @param int $flags (optional)
1508 * @param Title $title
1510 * @return RevisionRecord|null
1512 private function loadRevisionFromConds(
1518 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1520 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1529 * Throws an exception if the given database connection does not belong to the wiki this
1530 * RevisionStore is bound to.
1532 * @param IDatabase $db
1533 * @throws MWException
1535 private function checkDatabaseWikiId( IDatabase
$db ) {
1536 $storeWiki = $this->wikiId
;
1537 $dbWiki = $db->getDomainID();
1539 if ( $dbWiki === $storeWiki ) {
1543 // XXX: we really want the default database ID...
1544 $storeWiki = $storeWiki ?
: wfWikiID();
1545 $dbWiki = $dbWiki ?
: wfWikiID();
1547 if ( $dbWiki === $storeWiki ) {
1551 // HACK: counteract encoding imposed by DatabaseDomain
1552 $storeWiki = str_replace( '?h', '-', $storeWiki );
1553 $dbWiki = str_replace( '?h', '-', $dbWiki );
1555 if ( $dbWiki === $storeWiki ) {
1559 throw new MWException( "RevisionStore for $storeWiki "
1560 . "cannot be used with a DB connection for $dbWiki" );
1564 * Given a set of conditions, return a row with the
1565 * fields necessary to build RevisionRecord objects.
1567 * MCR migration note: this corresponds to Revision::fetchFromConds
1569 * @param IDatabase $db
1570 * @param array $conditions
1571 * @param int $flags (optional)
1573 * @return object|false data row as a raw object
1575 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1576 $this->checkDatabaseWikiId( $db );
1578 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
1580 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1581 $options[] = 'FOR UPDATE';
1583 return $db->selectRow(
1584 $revQuery['tables'],
1585 $revQuery['fields'],
1594 * Return the tables, fields, and join conditions to be selected to create
1595 * a new revision object.
1597 * MCR migration note: this replaces Revision::getQueryInfo
1601 * @param array $options Any combination of the following strings
1602 * - 'page': Join with the page table, and select fields to identify the page
1603 * - 'user': Join with the user table, and select the user name
1604 * - 'text': Join with the text table, and select fields to load page text
1606 * @return array With three keys:
1607 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1608 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1609 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1611 public function getQueryInfo( $options = [] ) {
1618 $ret['tables'][] = 'revision';
1619 $ret['fields'] = array_merge( $ret['fields'], [
1631 $commentQuery = $this->commentStore
->getJoin( 'rev_comment' );
1632 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1633 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1634 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1636 $actorQuery = $this->actorMigration
->getJoin( 'rev_user' );
1637 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
1638 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
1639 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
1641 if ( $this->contentHandlerUseDB
) {
1642 $ret['fields'][] = 'rev_content_format';
1643 $ret['fields'][] = 'rev_content_model';
1646 if ( in_array( 'page', $options, true ) ) {
1647 $ret['tables'][] = 'page';
1648 $ret['fields'] = array_merge( $ret['fields'], [
1656 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1659 if ( in_array( 'user', $options, true ) ) {
1660 $ret['tables'][] = 'user';
1661 $ret['fields'] = array_merge( $ret['fields'], [
1664 $u = $actorQuery['fields']['rev_user'];
1665 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
1668 if ( in_array( 'text', $options, true ) ) {
1669 $ret['tables'][] = 'text';
1670 $ret['fields'] = array_merge( $ret['fields'], [
1674 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1681 * Return the tables, fields, and join conditions to be selected to create
1682 * a new archived revision object.
1684 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1688 * @return array With three keys:
1689 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1690 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1691 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1693 public function getArchiveQueryInfo() {
1694 $commentQuery = $this->commentStore
->getJoin( 'ar_comment' );
1695 $actorQuery = $this->actorMigration
->getJoin( 'ar_user' );
1697 'tables' => [ 'archive' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
1711 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
1712 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
1715 if ( $this->contentHandlerUseDB
) {
1716 $ret['fields'][] = 'ar_content_format';
1717 $ret['fields'][] = 'ar_content_model';
1724 * Do a batched query for the sizes of a set of revisions.
1726 * MCR migration note: this replaces Revision::getParentLengths
1728 * @param int[] $revIds
1729 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1730 * of the corresponding revision.
1732 public function getRevisionSizes( array $revIds ) {
1733 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
1737 * Do a batched query for the sizes of a set of revisions.
1739 * MCR migration note: this replaces Revision::getParentLengths
1741 * @deprecated use RevisionStore::getRevisionSizes instead.
1743 * @param IDatabase $db
1744 * @param int[] $revIds
1745 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1746 * of the corresponding revision.
1748 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
1749 $this->checkDatabaseWikiId( $db );
1753 return $revLens; // empty
1758 [ 'rev_id', 'rev_len' ],
1759 [ 'rev_id' => $revIds ],
1763 foreach ( $res as $row ) {
1764 $revLens[$row->rev_id
] = intval( $row->rev_len
);
1771 * Get previous revision for this title
1773 * MCR migration note: this replaces Revision::getPrevious
1775 * @param RevisionRecord $rev
1776 * @param Title $title if known (optional)
1778 * @return RevisionRecord|null
1780 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
1781 if ( $title === null ) {
1782 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1784 $prev = $title->getPreviousRevisionID( $rev->getId() );
1786 return $this->getRevisionByTitle( $title, $prev );
1792 * Get next revision for this title
1794 * MCR migration note: this replaces Revision::getNext
1796 * @param RevisionRecord $rev
1797 * @param Title $title if known (optional)
1799 * @return RevisionRecord|null
1801 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
1802 if ( $title === null ) {
1803 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1805 $next = $title->getNextRevisionID( $rev->getId() );
1807 return $this->getRevisionByTitle( $title, $next );
1813 * Get previous revision Id for this page_id
1814 * This is used to populate rev_parent_id on save
1816 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1818 * @param IDatabase $db
1819 * @param RevisionRecord $rev
1823 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
1824 $this->checkDatabaseWikiId( $db );
1826 if ( $rev->getPageId() === null ) {
1829 # Use page_latest if ID is not given
1830 if ( !$rev->getId() ) {
1831 $prevId = $db->selectField(
1832 'page', 'page_latest',
1833 [ 'page_id' => $rev->getPageId() ],
1837 $prevId = $db->selectField(
1838 'revision', 'rev_id',
1839 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1841 [ 'ORDER BY' => 'rev_id DESC' ]
1844 return intval( $prevId );
1848 * Get rev_timestamp from rev_id, without loading the rest of the row
1850 * MCR migration note: this replaces Revision::getTimestampFromId
1852 * @param Title $title
1855 * @return string|bool False if not found
1857 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1858 $db = $this->getDBConnection(
1859 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
1862 $conds = [ 'rev_id' => $id ];
1863 $conds['rev_page'] = $title->getArticleID();
1864 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1866 $this->releaseDBConnection( $db );
1867 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1871 * Get count of revisions per page...not very efficient
1873 * MCR migration note: this replaces Revision::countByPageId
1875 * @param IDatabase $db
1876 * @param int $id Page id
1879 public function countRevisionsByPageId( IDatabase
$db, $id ) {
1880 $this->checkDatabaseWikiId( $db );
1882 $row = $db->selectRow( 'revision',
1883 [ 'revCount' => 'COUNT(*)' ],
1884 [ 'rev_page' => $id ],
1888 return intval( $row->revCount
);
1894 * Get count of revisions per page...not very efficient
1896 * MCR migration note: this replaces Revision::countByTitle
1898 * @param IDatabase $db
1899 * @param Title $title
1902 public function countRevisionsByTitle( IDatabase
$db, $title ) {
1903 $id = $title->getArticleID();
1905 return $this->countRevisionsByPageId( $db, $id );
1911 * Check if no edits were made by other users since
1912 * the time a user started editing the page. Limit to
1913 * 50 revisions for the sake of performance.
1915 * MCR migration note: this replaces Revision::userWasLastToEdit
1917 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1918 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1919 * has been deprecated since 1.24.
1921 * @param IDatabase $db The Database to perform the check on.
1922 * @param int $pageId The ID of the page in question
1923 * @param int $userId The ID of the user in question
1924 * @param string $since Look at edits since this time
1926 * @return bool True if the given user was the only one to edit since the given timestamp
1928 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
1929 $this->checkDatabaseWikiId( $db );
1935 $revQuery = self
::getQueryInfo();
1937 $revQuery['tables'],
1939 'rev_user' => $revQuery['fields']['rev_user'],
1942 'rev_page' => $pageId,
1943 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1946 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
1949 foreach ( $res as $row ) {
1950 if ( $row->rev_user
!= $userId ) {
1958 * Load a revision based on a known page ID and current revision ID from the DB
1960 * This method allows for the use of caching, though accessing anything that normally
1961 * requires permission checks (aside from the text) will trigger a small DB lookup.
1963 * MCR migration note: this replaces Revision::newKnownCurrent
1965 * @param Title $title the associated page title
1966 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1968 * @return RevisionRecord|bool Returns false if missing
1970 public function getKnownCurrentRevision( Title
$title, $revId ) {
1971 $db = $this->getDBConnectionRef( DB_REPLICA
);
1973 $pageId = $title->getArticleID();
1980 $revId = $title->getLatestRevID();
1985 'No latest revision known for page ' . $title->getPrefixedDBkey()
1986 . ' even though it exists with page ID ' . $pageId
1991 $row = $this->cache
->getWithSetCallback(
1992 // Page/rev IDs passed in from DB to reflect history merges
1993 $this->cache
->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1994 WANObjectCache
::TTL_WEEK
,
1995 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1996 $setOpts +
= Database
::getCacheSetOptions( $db );
1999 'rev_page' => intval( $pageId ),
2000 'page_id' => intval( $pageId ),
2001 'rev_id' => intval( $revId ),
2004 $row = $this->fetchRevisionRowFromConds( $db, $conds );
2005 return $row ?
: false; // don't cache negatives
2009 // Reflect revision deletion and user renames
2011 return $this->newRevisionFromRow( $row, 0, $title );
2017 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.