selenium: invoke jobs to enforce eventual consistency
[lhc/web/wiklou.git] / includes / Storage / RevisionStore.php
1 <?php
2 /**
3 * Service for looking up page revisions.
4 *
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.
9 *
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.
14 *
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
19 *
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.
23 *
24 * @file
25 */
26
27 namespace MediaWiki\Storage;
28
29 use ActorMigration;
30 use CommentStore;
31 use CommentStoreComment;
32 use Content;
33 use ContentHandler;
34 use DBAccessObjectUtils;
35 use Hooks;
36 use IDBAccessObject;
37 use InvalidArgumentException;
38 use IP;
39 use LogicException;
40 use MediaWiki\Linker\LinkTarget;
41 use MediaWiki\User\UserIdentity;
42 use MediaWiki\User\UserIdentityValue;
43 use Message;
44 use MWException;
45 use MWUnknownContentModelException;
46 use Psr\Log\LoggerAwareInterface;
47 use Psr\Log\LoggerInterface;
48 use Psr\Log\NullLogger;
49 use RecentChange;
50 use Revision;
51 use stdClass;
52 use Title;
53 use User;
54 use WANObjectCache;
55 use Wikimedia\Assert\Assert;
56 use Wikimedia\Rdbms\Database;
57 use Wikimedia\Rdbms\DBConnRef;
58 use Wikimedia\Rdbms\IDatabase;
59 use Wikimedia\Rdbms\ILoadBalancer;
60
61 /**
62 * Service for looking up page revisions.
63 *
64 * @since 1.31
65 *
66 * @note This was written to act as a drop-in replacement for the corresponding
67 * static methods in Revision.
68 */
69 class RevisionStore
70 implements IDBAccessObject, RevisionFactory, RevisionLookup, LoggerAwareInterface {
71
72 const ROW_CACHE_KEY = 'revision-row-1.29';
73
74 /**
75 * @var SqlBlobStore
76 */
77 private $blobStore;
78
79 /**
80 * @var bool|string
81 */
82 private $wikiId;
83
84 /**
85 * @var boolean
86 * @see $wgContentHandlerUseDB
87 */
88 private $contentHandlerUseDB = true;
89
90 /**
91 * @var ILoadBalancer
92 */
93 private $loadBalancer;
94
95 /**
96 * @var WANObjectCache
97 */
98 private $cache;
99
100 /**
101 * @var CommentStore
102 */
103 private $commentStore;
104
105 /**
106 * @var ActorMigration
107 */
108 private $actorMigration;
109
110 /**
111 * @var LoggerInterface
112 */
113 private $logger;
114
115 /**
116 * @var NameTableStore
117 */
118 private $contentModelStore;
119
120 /**
121 * @var NameTableStore
122 */
123 private $slotRoleStore;
124
125 /** @var int An appropriate combination of SCHEMA_COMPAT_XXX flags. */
126 private $mcrMigrationStage;
127
128 /**
129 * @todo $blobStore should be allowed to be any BlobStore!
130 *
131 * @param ILoadBalancer $loadBalancer
132 * @param SqlBlobStore $blobStore
133 * @param WANObjectCache $cache A cache for caching revision rows. This can be the local
134 * wiki's default instance even if $wikiId refers to a different wiki, since
135 * makeGlobalKey() is used to constructed a key that allows cached revision rows from
136 * the same database to be re-used between wikis. For example, enwiki and frwiki will
137 * use the same cache keys for revision rows from the wikidatawiki database, regardless
138 * of the cache's default key space.
139 * @param CommentStore $commentStore
140 * @param NameTableStore $contentModelStore
141 * @param NameTableStore $slotRoleStore
142 * @param int $mcrMigrationStage An appropriate combination of SCHEMA_COMPAT_XXX flags
143 * @param ActorMigration $actorMigration
144 * @param bool|string $wikiId
145 *
146 * @throws MWException if $mcrMigrationStage or $wikiId is invalid.
147 */
148 public function __construct(
149 ILoadBalancer $loadBalancer,
150 SqlBlobStore $blobStore,
151 WANObjectCache $cache,
152 CommentStore $commentStore,
153 NameTableStore $contentModelStore,
154 NameTableStore $slotRoleStore,
155 $mcrMigrationStage,
156 ActorMigration $actorMigration,
157 $wikiId = false
158 ) {
159 Assert::parameterType( 'string|boolean', $wikiId, '$wikiId' );
160 Assert::parameterType( 'integer', $mcrMigrationStage, '$mcrMigrationStage' );
161 Assert::parameter(
162 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH ) !== SCHEMA_COMPAT_READ_BOTH,
163 '$mcrMigrationStage',
164 'Reading from the old and the new schema at the same time is not supported.'
165 );
166 Assert::parameter(
167 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_BOTH ) !== 0,
168 '$mcrMigrationStage',
169 'Reading needs to be enabled for the old or the new schema.'
170 );
171 Assert::parameter(
172 ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_BOTH ) !== 0,
173 '$mcrMigrationStage',
174 'Writing needs to be enabled for the old or the new schema.'
175 );
176 Assert::parameter(
177 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_OLD ) === 0
178 || ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) !== 0,
179 '$mcrMigrationStage',
180 'Cannot read the old schema when not also writing it.'
181 );
182 Assert::parameter(
183 ( $mcrMigrationStage & SCHEMA_COMPAT_READ_NEW ) === 0
184 || ( $mcrMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) !== 0,
185 '$mcrMigrationStage',
186 'Cannot read the new schema when not also writing it.'
187 );
188
189 $this->loadBalancer = $loadBalancer;
190 $this->blobStore = $blobStore;
191 $this->cache = $cache;
192 $this->commentStore = $commentStore;
193 $this->contentModelStore = $contentModelStore;
194 $this->slotRoleStore = $slotRoleStore;
195 $this->mcrMigrationStage = $mcrMigrationStage;
196 $this->actorMigration = $actorMigration;
197 $this->wikiId = $wikiId;
198 $this->logger = new NullLogger();
199 }
200
201 /**
202 * @param int $flags A combination of SCHEMA_COMPAT_XXX flags.
203 * @return bool True if all the given flags were set in the $mcrMigrationStage
204 * parameter passed to the constructor.
205 */
206 private function hasMcrSchemaFlags( $flags ) {
207 return ( $this->mcrMigrationStage & $flags ) === $flags;
208 }
209
210 /**
211 * Throws a RevisionAccessException if this RevisionStore is configured for cross-wiki loading
212 * and still reading from the old DB schema.
213 *
214 * @throws RevisionAccessException
215 */
216 private function assertCrossWikiContentLoadingIsSafe() {
217 if ( $this->wikiId !== false && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD ) ) {
218 throw new RevisionAccessException(
219 "Cross-wiki content loading is not supported by the pre-MCR schema"
220 );
221 }
222 }
223
224 public function setLogger( LoggerInterface $logger ) {
225 $this->logger = $logger;
226 }
227
228 /**
229 * @return bool Whether the store is read-only
230 */
231 public function isReadOnly() {
232 return $this->blobStore->isReadOnly();
233 }
234
235 /**
236 * @return bool
237 */
238 public function getContentHandlerUseDB() {
239 return $this->contentHandlerUseDB;
240 }
241
242 /**
243 * @see $wgContentHandlerUseDB
244 * @param bool $contentHandlerUseDB
245 * @throws MWException
246 */
247 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
248 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW )
249 || $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW )
250 ) {
251 if ( !$contentHandlerUseDB ) {
252 throw new MWException(
253 'Content model must be stored in the database for multi content revision migration.'
254 );
255 }
256 }
257 $this->contentHandlerUseDB = $contentHandlerUseDB;
258 }
259
260 /**
261 * @return ILoadBalancer
262 */
263 private function getDBLoadBalancer() {
264 return $this->loadBalancer;
265 }
266
267 /**
268 * @param int $mode DB_MASTER or DB_REPLICA
269 *
270 * @return IDatabase
271 */
272 private function getDBConnection( $mode ) {
273 $lb = $this->getDBLoadBalancer();
274 return $lb->getConnection( $mode, [], $this->wikiId );
275 }
276
277 /**
278 * @param int $queryFlags a bit field composed of READ_XXX flags
279 *
280 * @return DBConnRef
281 */
282 private function getDBConnectionRefForQueryFlags( $queryFlags ) {
283 list( $mode, ) = DBAccessObjectUtils::getDBOptions( $queryFlags );
284 return $this->getDBConnectionRef( $mode );
285 }
286
287 /**
288 * @param IDatabase $connection
289 */
290 private function releaseDBConnection( IDatabase $connection ) {
291 $lb = $this->getDBLoadBalancer();
292 $lb->reuseConnection( $connection );
293 }
294
295 /**
296 * @param int $mode DB_MASTER or DB_REPLICA
297 *
298 * @return DBConnRef
299 */
300 private function getDBConnectionRef( $mode ) {
301 $lb = $this->getDBLoadBalancer();
302 return $lb->getConnectionRef( $mode, [], $this->wikiId );
303 }
304
305 /**
306 * Determines the page Title based on the available information.
307 *
308 * MCR migration note: this corresponds to Revision::getTitle
309 *
310 * @note this method should be private, external use should be avoided!
311 *
312 * @param int|null $pageId
313 * @param int|null $revId
314 * @param int $queryFlags
315 *
316 * @return Title
317 * @throws RevisionAccessException
318 */
319 public function getTitle( $pageId, $revId, $queryFlags = self::READ_NORMAL ) {
320 if ( !$pageId && !$revId ) {
321 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
322 }
323
324 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
325 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
326 if ( DBAccessObjectUtils::hasFlags( $queryFlags, self::READ_LATEST_IMMUTABLE ) ) {
327 $queryFlags = self::READ_NORMAL;
328 }
329
330 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId === false );
331 list( $dbMode, $dbOptions ) = DBAccessObjectUtils::getDBOptions( $queryFlags );
332 $titleFlags = ( $dbMode == DB_MASTER ? Title::GAID_FOR_UPDATE : 0 );
333
334 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
335 if ( $canUseTitleNewFromId ) {
336 // TODO: better foreign title handling (introduce TitleFactory)
337 $title = Title::newFromID( $pageId, $titleFlags );
338 if ( $title ) {
339 return $title;
340 }
341 }
342
343 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
344 $canUseRevId = ( $revId !== null && $revId > 0 );
345
346 if ( $canUseRevId ) {
347 $dbr = $this->getDBConnectionRef( $dbMode );
348 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
349 $row = $dbr->selectRow(
350 [ 'revision', 'page' ],
351 [
352 'page_namespace',
353 'page_title',
354 'page_id',
355 'page_latest',
356 'page_is_redirect',
357 'page_len',
358 ],
359 [ 'rev_id' => $revId ],
360 __METHOD__,
361 $dbOptions,
362 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
363 );
364 if ( $row ) {
365 // TODO: better foreign title handling (introduce TitleFactory)
366 return Title::newFromRow( $row );
367 }
368 }
369
370 // If we still don't have a title, fallback to master if that wasn't already happening.
371 if ( $dbMode !== DB_MASTER ) {
372 $title = $this->getTitle( $pageId, $revId, self::READ_LATEST );
373 if ( $title ) {
374 $this->logger->info(
375 __METHOD__ . ' fell back to READ_LATEST and got a Title.',
376 [ 'trace' => wfBacktrace() ]
377 );
378 return $title;
379 }
380 }
381
382 throw new RevisionAccessException(
383 "Could not determine title for page ID $pageId and revision ID $revId"
384 );
385 }
386
387 /**
388 * @param mixed $value
389 * @param string $name
390 *
391 * @throws IncompleteRevisionException if $value is null
392 * @return mixed $value, if $value is not null
393 */
394 private function failOnNull( $value, $name ) {
395 if ( $value === null ) {
396 throw new IncompleteRevisionException(
397 "$name must not be " . var_export( $value, true ) . "!"
398 );
399 }
400
401 return $value;
402 }
403
404 /**
405 * @param mixed $value
406 * @param string $name
407 *
408 * @throws IncompleteRevisionException if $value is empty
409 * @return mixed $value, if $value is not null
410 */
411 private function failOnEmpty( $value, $name ) {
412 if ( $value === null || $value === 0 || $value === '' ) {
413 throw new IncompleteRevisionException(
414 "$name must not be " . var_export( $value, true ) . "!"
415 );
416 }
417
418 return $value;
419 }
420
421 /**
422 * Insert a new revision into the database, returning the new revision record
423 * on success and dies horribly on failure.
424 *
425 * MCR migration note: this replaces Revision::insertOn
426 *
427 * @param RevisionRecord $rev
428 * @param IDatabase $dbw (master connection)
429 *
430 * @throws InvalidArgumentException
431 * @return RevisionRecord the new revision record.
432 */
433 public function insertRevisionOn( RevisionRecord $rev, IDatabase $dbw ) {
434 // TODO: pass in a DBTransactionContext instead of a database connection.
435 $this->checkDatabaseWikiId( $dbw );
436
437 $slotRoles = $rev->getSlotRoles();
438
439 // Make sure the main slot is always provided throughout migration
440 if ( !in_array( 'main', $slotRoles ) ) {
441 throw new InvalidArgumentException(
442 'main slot must be provided'
443 );
444 }
445
446 // If we are not writing into the new schema, we can't support extra slots.
447 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW ) && $slotRoles !== [ 'main' ] ) {
448 throw new InvalidArgumentException(
449 'Only the main slot is supported when not writing to the MCR enabled schema!'
450 );
451 }
452
453 // As long as we are not reading from the new schema, we don't want to write extra slots.
454 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW ) && $slotRoles !== [ 'main' ] ) {
455 throw new InvalidArgumentException(
456 'Only the main slot is supported when not reading from the MCR enabled schema!'
457 );
458 }
459
460 // Checks
461 $this->failOnNull( $rev->getSize(), 'size field' );
462 $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
463 $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
464 $comment = $this->failOnNull( $rev->getComment( RevisionRecord::RAW ), 'comment' );
465 $user = $this->failOnNull( $rev->getUser( RevisionRecord::RAW ), 'user' );
466 $this->failOnNull( $user->getId(), 'user field' );
467 $this->failOnEmpty( $user->getName(), 'user_text field' );
468
469 // TODO: we shouldn't need an actual Title here.
470 $title = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
471 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
472
473 $parentId = $rev->getParentId() === null
474 ? $this->getPreviousRevisionId( $dbw, $rev )
475 : $rev->getParentId();
476
477 /** @var RevisionRecord $rev */
478 $rev = $dbw->doAtomicSection(
479 __METHOD__,
480 function ( IDatabase $dbw, $fname ) use (
481 $rev,
482 $user,
483 $comment,
484 $title,
485 $pageId,
486 $parentId
487 ) {
488 return $this->insertRevisionInternal(
489 $rev,
490 $dbw,
491 $user,
492 $comment,
493 $title,
494 $pageId,
495 $parentId
496 );
497 }
498 );
499
500 // sanity checks
501 Assert::postcondition( $rev->getId() > 0, 'revision must have an ID' );
502 Assert::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
503 Assert::postcondition(
504 $rev->getComment( RevisionRecord::RAW ) !== null,
505 'revision must have a comment'
506 );
507 Assert::postcondition(
508 $rev->getUser( RevisionRecord::RAW ) !== null,
509 'revision must have a user'
510 );
511
512 // Trigger exception if the main slot is missing.
513 // Technically, this could go away after MCR migration: while
514 // calling code may require a main slot to exist, RevisionStore
515 // really should not know or care about that requirement.
516 $rev->getSlot( 'main', RevisionRecord::RAW );
517
518 foreach ( $slotRoles as $role ) {
519 $slot = $rev->getSlot( $role, RevisionRecord::RAW );
520 Assert::postcondition(
521 $slot->getContent() !== null,
522 $role . ' slot must have content'
523 );
524 Assert::postcondition(
525 $slot->hasRevision(),
526 $role . ' slot must have a revision associated'
527 );
528 }
529
530 Hooks::run( 'RevisionRecordInserted', [ $rev ] );
531
532 // TODO: deprecate in 1.32!
533 $legacyRevision = new Revision( $rev );
534 Hooks::run( 'RevisionInsertComplete', [ &$legacyRevision, null, null ] );
535
536 return $rev;
537 }
538
539 private function insertRevisionInternal(
540 RevisionRecord $rev,
541 IDatabase $dbw,
542 User $user,
543 CommentStoreComment $comment,
544 Title $title,
545 $pageId,
546 $parentId
547 ) {
548 $slotRoles = $rev->getSlotRoles();
549
550 $revisionRow = $this->insertRevisionRowOn(
551 $dbw,
552 $rev,
553 $title,
554 $parentId
555 );
556
557 $revisionId = $revisionRow['rev_id'];
558
559 $blobHints = [
560 BlobStore::PAGE_HINT => $pageId,
561 BlobStore::REVISION_HINT => $revisionId,
562 BlobStore::PARENT_HINT => $parentId,
563 ];
564
565 $newSlots = [];
566 foreach ( $slotRoles as $role ) {
567 $slot = $rev->getSlot( $role, RevisionRecord::RAW );
568
569 // If the SlotRecord already has a revision ID set, this means it already exists
570 // in the database, and should already belong to the current revision.
571 // However, a slot may already have a revision, but no content ID, if the slot
572 // is emulated based on the archive table, because we are in SCHEMA_COMPAT_READ_OLD
573 // mode, and the respective archive row was not yet migrated to the new schema.
574 // In that case, a new slot row (and content row) must be inserted even during
575 // undeletion.
576 if ( $slot->hasRevision() && $slot->hasContentId() ) {
577 // TODO: properly abort transaction if the assertion fails!
578 Assert::parameter(
579 $slot->getRevision() === $revisionId,
580 'slot role ' . $slot->getRole(),
581 'Existing slot should belong to revision '
582 . $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
583 );
584
585 // Slot exists, nothing to do, move along.
586 // This happens when restoring archived revisions.
587
588 $newSlots[$role] = $slot;
589
590 // Write the main slot's text ID to the revision table for backwards compatibility
591 if ( $slot->getRole() === 'main'
592 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD )
593 ) {
594 $blobAddress = $slot->getAddress();
595 $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
596 }
597 } else {
598 $newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $title, $blobHints );
599 }
600 }
601
602 $this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
603
604 $rev = new RevisionStoreRecord(
605 $title,
606 $user,
607 $comment,
608 (object)$revisionRow,
609 new RevisionSlots( $newSlots ),
610 $this->wikiId
611 );
612
613 return $rev;
614 }
615
616 /**
617 * @param IDatabase $dbw
618 * @param int $revisionId
619 * @param string &$blobAddress (may change!)
620 *
621 * @return int the text row id
622 */
623 private function updateRevisionTextId( IDatabase $dbw, $revisionId, &$blobAddress ) {
624 $textId = $this->blobStore->getTextIdFromAddress( $blobAddress );
625 if ( !$textId ) {
626 throw new LogicException(
627 'Blob address not supported in 1.29 database schema: ' . $blobAddress
628 );
629 }
630
631 // getTextIdFromAddress() is free to insert something into the text table, so $textId
632 // may be a new value, not anything already contained in $blobAddress.
633 $blobAddress = SqlBlobStore::makeAddressFromTextId( $textId );
634
635 $dbw->update(
636 'revision',
637 [ 'rev_text_id' => $textId ],
638 [ 'rev_id' => $revisionId ],
639 __METHOD__
640 );
641
642 return $textId;
643 }
644
645 /**
646 * @param IDatabase $dbw
647 * @param int $revisionId
648 * @param SlotRecord $protoSlot
649 * @param Title $title
650 * @param array $blobHints See the BlobStore::XXX_HINT constants
651 * @return SlotRecord
652 */
653 private function insertSlotOn(
654 IDatabase $dbw,
655 $revisionId,
656 SlotRecord $protoSlot,
657 Title $title,
658 array $blobHints = []
659 ) {
660 if ( $protoSlot->hasAddress() ) {
661 $blobAddress = $protoSlot->getAddress();
662 } else {
663 $blobAddress = $this->storeContentBlob( $protoSlot, $title, $blobHints );
664 }
665
666 $contentId = null;
667
668 // Write the main slot's text ID to the revision table for backwards compatibility
669 if ( $protoSlot->getRole() === 'main'
670 && $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD )
671 ) {
672 // If SCHEMA_COMPAT_WRITE_NEW is also set, the fake content ID is overwritten
673 // with the real content ID below.
674 $textId = $this->updateRevisionTextId( $dbw, $revisionId, $blobAddress );
675 $contentId = $this->emulateContentId( $textId );
676 }
677
678 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW ) ) {
679 if ( $protoSlot->hasContentId() ) {
680 $contentId = $protoSlot->getContentId();
681 } else {
682 $contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
683 }
684
685 $this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
686 }
687
688 $savedSlot = SlotRecord::newSaved(
689 $revisionId,
690 $contentId,
691 $blobAddress,
692 $protoSlot
693 );
694
695 return $savedSlot;
696 }
697
698 /**
699 * Insert IP revision into ip_changes for use when querying for a range.
700 * @param IDatabase $dbw
701 * @param User $user
702 * @param RevisionRecord $rev
703 * @param int $revisionId
704 */
705 private function insertIpChangesRow(
706 IDatabase $dbw,
707 User $user,
708 RevisionRecord $rev,
709 $revisionId
710 ) {
711 if ( $user->getId() === 0 && IP::isValid( $user->getName() ) ) {
712 $ipcRow = [
713 'ipc_rev_id' => $revisionId,
714 'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
715 'ipc_hex' => IP::toHex( $user->getName() ),
716 ];
717 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__ );
718 }
719 }
720
721 /**
722 * @param IDatabase $dbw
723 * @param RevisionRecord $rev
724 * @param Title $title
725 * @param int $parentId
726 *
727 * @return array a revision table row
728 *
729 * @throws MWException
730 * @throws MWUnknownContentModelException
731 */
732 private function insertRevisionRowOn(
733 IDatabase $dbw,
734 RevisionRecord $rev,
735 Title $title,
736 $parentId
737 ) {
738 $revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $title, $parentId );
739
740 list( $commentFields, $commentCallback ) =
741 $this->commentStore->insertWithTempTable(
742 $dbw,
743 'rev_comment',
744 $rev->getComment( RevisionRecord::RAW )
745 );
746 $revisionRow += $commentFields;
747
748 list( $actorFields, $actorCallback ) =
749 $this->actorMigration->getInsertValuesWithTempTable(
750 $dbw,
751 'rev_user',
752 $rev->getUser( RevisionRecord::RAW )
753 );
754 $revisionRow += $actorFields;
755
756 $dbw->insert( 'revision', $revisionRow, __METHOD__ );
757
758 if ( !isset( $revisionRow['rev_id'] ) ) {
759 // only if auto-increment was used
760 $revisionRow['rev_id'] = intval( $dbw->insertId() );
761
762 if ( $dbw->getType() === 'mysql' ) {
763 // (T202032) MySQL until 8.0 and MariaDB until some version after 10.1.34 don't save the
764 // auto-increment value to disk, so on server restart it might reuse IDs from deleted
765 // revisions. We can fix that with an insert with an explicit rev_id value, if necessary.
766
767 $maxRevId = intval( $dbw->selectField( 'archive', 'MAX(ar_rev_id)', '', __METHOD__ ) );
768 $table = 'archive';
769 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW ) ) {
770 $maxRevId2 = intval( $dbw->selectField( 'slots', 'MAX(slot_revision_id)', '', __METHOD__ ) );
771 if ( $maxRevId2 >= $maxRevId ) {
772 $maxRevId = $maxRevId2;
773 $table = 'slots';
774 }
775 }
776
777 if ( $maxRevId >= $revisionRow['rev_id'] ) {
778 $this->logger->debug(
779 '__METHOD__: Inserted revision {revid} but {table} has revisions up to {maxrevid}.'
780 . ' Trying to fix it.',
781 [
782 'revid' => $revisionRow['rev_id'],
783 'table' => $table,
784 'maxrevid' => $maxRevId,
785 ]
786 );
787
788 if ( !$dbw->lock( 'fix-for-T202032', __METHOD__ ) ) {
789 throw new MWException( 'Failed to get database lock for T202032' );
790 }
791 $fname = __METHOD__;
792 $dbw->onTransactionResolution( function ( $trigger, $dbw ) use ( $fname ) {
793 $dbw->unlock( 'fix-for-T202032', $fname );
794 } );
795
796 $dbw->delete( 'revision', [ 'rev_id' => $revisionRow['rev_id'] ], __METHOD__ );
797
798 // The locking here is mostly to make MySQL bypass the REPEATABLE-READ transaction
799 // isolation (weird MySQL "feature"). It does seem to block concurrent auto-incrementing
800 // inserts too, though, at least on MariaDB 10.1.29.
801 //
802 // Don't try to lock `revision` in this way, it'll deadlock if there are concurrent
803 // transactions in this code path thanks to the row lock from the original ->insert() above.
804 //
805 // And we have to use raw SQL to bypass the "aggregation used with a locking SELECT" warning
806 // that's for non-MySQL DBs.
807 $row1 = $dbw->query(
808 $dbw->selectSqlText( 'archive', [ 'v' => "MAX(ar_rev_id)" ], '', __METHOD__ ) . ' FOR UPDATE'
809 )->fetchObject();
810 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW ) ) {
811 $row2 = $dbw->query(
812 $dbw->selectSqlText( 'slots', [ 'v' => "MAX(slot_revision_id)" ], '', __METHOD__ )
813 . ' FOR UPDATE'
814 )->fetchObject();
815 } else {
816 $row2 = null;
817 }
818 $maxRevId = max(
819 $maxRevId,
820 $row1 ? intval( $row1->v ) : 0,
821 $row2 ? intval( $row2->v ) : 0
822 );
823
824 // If we don't have SCHEMA_COMPAT_WRITE_NEW, all except the first of any concurrent
825 // transactions will throw a duplicate key error here. It doesn't seem worth trying
826 // to avoid that.
827 $revisionRow['rev_id'] = $maxRevId + 1;
828 $dbw->insert( 'revision', $revisionRow, __METHOD__ );
829 }
830 }
831 }
832
833 $commentCallback( $revisionRow['rev_id'] );
834 $actorCallback( $revisionRow['rev_id'], $revisionRow );
835
836 return $revisionRow;
837 }
838
839 /**
840 * @param IDatabase $dbw
841 * @param RevisionRecord $rev
842 * @param Title $title
843 * @param int $parentId
844 *
845 * @return array [ 0 => array $revisionRow, 1 => callable ]
846 * @throws MWException
847 * @throws MWUnknownContentModelException
848 */
849 private function getBaseRevisionRow(
850 IDatabase $dbw,
851 RevisionRecord $rev,
852 Title $title,
853 $parentId
854 ) {
855 // Record the edit in revisions
856 $revisionRow = [
857 'rev_page' => $rev->getPageId(),
858 'rev_parent_id' => $parentId,
859 'rev_minor_edit' => $rev->isMinor() ? 1 : 0,
860 'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
861 'rev_deleted' => $rev->getVisibility(),
862 'rev_len' => $rev->getSize(),
863 'rev_sha1' => $rev->getSha1(),
864 ];
865
866 if ( $rev->getId() !== null ) {
867 // Needed to restore revisions with their original ID
868 $revisionRow['rev_id'] = $rev->getId();
869 }
870
871 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD ) ) {
872 // In non MCR mode this IF section will relate to the main slot
873 $mainSlot = $rev->getSlot( 'main' );
874 $model = $mainSlot->getModel();
875 $format = $mainSlot->getFormat();
876
877 // MCR migration note: rev_content_model and rev_content_format will go away
878 if ( $this->contentHandlerUseDB ) {
879 $this->assertCrossWikiContentLoadingIsSafe();
880
881 $defaultModel = ContentHandler::getDefaultModelFor( $title );
882 $defaultFormat = ContentHandler::getForModelID( $defaultModel )->getDefaultFormat();
883
884 $revisionRow['rev_content_model'] = ( $model === $defaultModel ) ? null : $model;
885 $revisionRow['rev_content_format'] = ( $format === $defaultFormat ) ? null : $format;
886 }
887 }
888
889 return $revisionRow;
890 }
891
892 /**
893 * @param SlotRecord $slot
894 * @param Title $title
895 * @param array $blobHints See the BlobStore::XXX_HINT constants
896 *
897 * @throws MWException
898 * @return string the blob address
899 */
900 private function storeContentBlob(
901 SlotRecord $slot,
902 Title $title,
903 array $blobHints = []
904 ) {
905 $content = $slot->getContent();
906 $format = $content->getDefaultFormat();
907 $model = $content->getModel();
908
909 $this->checkContent( $content, $title );
910
911 return $this->blobStore->storeBlob(
912 $content->serialize( $format ),
913 // These hints "leak" some information from the higher abstraction layer to
914 // low level storage to allow for optimization.
915 array_merge(
916 $blobHints,
917 [
918 BlobStore::DESIGNATION_HINT => 'page-content',
919 BlobStore::ROLE_HINT => $slot->getRole(),
920 BlobStore::SHA1_HINT => $slot->getSha1(),
921 BlobStore::MODEL_HINT => $model,
922 BlobStore::FORMAT_HINT => $format,
923 ]
924 )
925 );
926 }
927
928 /**
929 * @param SlotRecord $slot
930 * @param IDatabase $dbw
931 * @param int $revisionId
932 * @param int $contentId
933 */
934 private function insertSlotRowOn( SlotRecord $slot, IDatabase $dbw, $revisionId, $contentId ) {
935 $slotRow = [
936 'slot_revision_id' => $revisionId,
937 'slot_role_id' => $this->slotRoleStore->acquireId( $slot->getRole() ),
938 'slot_content_id' => $contentId,
939 // If the slot has a specific origin use that ID, otherwise use the ID of the revision
940 // that we just inserted.
941 'slot_origin' => $slot->hasOrigin() ? $slot->getOrigin() : $revisionId,
942 ];
943 $dbw->insert( 'slots', $slotRow, __METHOD__ );
944 }
945
946 /**
947 * @param SlotRecord $slot
948 * @param IDatabase $dbw
949 * @param string $blobAddress
950 * @return int content row ID
951 */
952 private function insertContentRowOn( SlotRecord $slot, IDatabase $dbw, $blobAddress ) {
953 $contentRow = [
954 'content_size' => $slot->getSize(),
955 'content_sha1' => $slot->getSha1(),
956 'content_model' => $this->contentModelStore->acquireId( $slot->getModel() ),
957 'content_address' => $blobAddress,
958 ];
959 $dbw->insert( 'content', $contentRow, __METHOD__ );
960 return intval( $dbw->insertId() );
961 }
962
963 /**
964 * MCR migration note: this corresponds to Revision::checkContentModel
965 *
966 * @param Content $content
967 * @param Title $title
968 *
969 * @throws MWException
970 * @throws MWUnknownContentModelException
971 */
972 private function checkContent( Content $content, Title $title ) {
973 // Note: may return null for revisions that have not yet been inserted
974
975 $model = $content->getModel();
976 $format = $content->getDefaultFormat();
977 $handler = $content->getContentHandler();
978
979 $name = "$title";
980
981 if ( !$handler->isSupportedFormat( $format ) ) {
982 throw new MWException( "Can't use format $format with content model $model on $name" );
983 }
984
985 if ( !$this->contentHandlerUseDB ) {
986 // if $wgContentHandlerUseDB is not set,
987 // all revisions must use the default content model and format.
988
989 $this->assertCrossWikiContentLoadingIsSafe();
990
991 $defaultModel = ContentHandler::getDefaultModelFor( $title );
992 $defaultHandler = ContentHandler::getForModelID( $defaultModel );
993 $defaultFormat = $defaultHandler->getDefaultFormat();
994
995 if ( $model != $defaultModel ) {
996 throw new MWException( "Can't save non-default content model with "
997 . "\$wgContentHandlerUseDB disabled: model is $model, "
998 . "default for $name is $defaultModel"
999 );
1000 }
1001
1002 if ( $format != $defaultFormat ) {
1003 throw new MWException( "Can't use non-default content format with "
1004 . "\$wgContentHandlerUseDB disabled: format is $format, "
1005 . "default for $name is $defaultFormat"
1006 );
1007 }
1008 }
1009
1010 if ( !$content->isValid() ) {
1011 throw new MWException(
1012 "New content for $name is not valid! Content model is $model"
1013 );
1014 }
1015 }
1016
1017 /**
1018 * Create a new null-revision for insertion into a page's
1019 * history. This will not re-save the text, but simply refer
1020 * to the text from the previous version.
1021 *
1022 * Such revisions can for instance identify page rename
1023 * operations and other such meta-modifications.
1024 *
1025 * @note This method grabs a FOR UPDATE lock on the relevant row of the page table,
1026 * to prevent a new revision from being inserted before the null revision has been written
1027 * to the database.
1028 *
1029 * MCR migration note: this replaces Revision::newNullRevision
1030 *
1031 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
1032 * (or go away).
1033 *
1034 * @param IDatabase $dbw used for obtaining the lock on the page table row
1035 * @param Title $title Title of the page to read from
1036 * @param CommentStoreComment $comment RevisionRecord's summary
1037 * @param bool $minor Whether the revision should be considered as minor
1038 * @param User $user The user to attribute the revision to
1039 *
1040 * @return RevisionRecord|null RevisionRecord or null on error
1041 */
1042 public function newNullRevision(
1043 IDatabase $dbw,
1044 Title $title,
1045 CommentStoreComment $comment,
1046 $minor,
1047 User $user
1048 ) {
1049 $this->checkDatabaseWikiId( $dbw );
1050
1051 // T51581: Lock the page table row to ensure no other process
1052 // is adding a revision to the page at the same time.
1053 // Avoid locking extra tables, compare T191892.
1054 $pageLatest = $dbw->selectField(
1055 'page',
1056 'page_latest',
1057 [ 'page_id' => $title->getArticleID() ],
1058 __METHOD__,
1059 [ 'FOR UPDATE' ]
1060 );
1061
1062 if ( !$pageLatest ) {
1063 return null;
1064 }
1065
1066 // Fetch the actual revision row from master, without locking all extra tables.
1067 $oldRevision = $this->loadRevisionFromConds(
1068 $dbw,
1069 [ 'rev_id' => intval( $pageLatest ) ],
1070 self::READ_LATEST,
1071 $title
1072 );
1073
1074 // Construct the new revision
1075 $timestamp = wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1076 $newRevision = MutableRevisionRecord::newFromParentRevision( $oldRevision );
1077
1078 $newRevision->setComment( $comment );
1079 $newRevision->setUser( $user );
1080 $newRevision->setTimestamp( $timestamp );
1081 $newRevision->setMinorEdit( $minor );
1082
1083 return $newRevision;
1084 }
1085
1086 /**
1087 * MCR migration note: this replaces Revision::isUnpatrolled
1088 *
1089 * @todo This is overly specific, so move or kill this method.
1090 *
1091 * @param RevisionRecord $rev
1092 *
1093 * @return int Rcid of the unpatrolled row, zero if there isn't one
1094 */
1095 public function getRcIdIfUnpatrolled( RevisionRecord $rev ) {
1096 $rc = $this->getRecentChange( $rev );
1097 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == RecentChange::PRC_UNPATROLLED ) {
1098 return $rc->getAttribute( 'rc_id' );
1099 } else {
1100 return 0;
1101 }
1102 }
1103
1104 /**
1105 * Get the RC object belonging to the current revision, if there's one
1106 *
1107 * MCR migration note: this replaces Revision::getRecentChange
1108 *
1109 * @todo move this somewhere else?
1110 *
1111 * @param RevisionRecord $rev
1112 * @param int $flags (optional) $flags include:
1113 * IDBAccessObject::READ_LATEST: Select the data from the master
1114 *
1115 * @return null|RecentChange
1116 */
1117 public function getRecentChange( RevisionRecord $rev, $flags = 0 ) {
1118 list( $dbType, ) = DBAccessObjectUtils::getDBOptions( $flags );
1119 $db = $this->getDBConnection( $dbType );
1120
1121 $userIdentity = $rev->getUser( RevisionRecord::RAW );
1122
1123 if ( !$userIdentity ) {
1124 // If the revision has no user identity, chances are it never went
1125 // into the database, and doesn't have an RC entry.
1126 return null;
1127 }
1128
1129 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
1130 $actorWhere = $this->actorMigration->getWhere( $db, 'rc_user', $rev->getUser(), false );
1131 $rc = RecentChange::newFromConds(
1132 [
1133 $actorWhere['conds'],
1134 'rc_timestamp' => $db->timestamp( $rev->getTimestamp() ),
1135 'rc_this_oldid' => $rev->getId()
1136 ],
1137 __METHOD__,
1138 $dbType
1139 );
1140
1141 $this->releaseDBConnection( $db );
1142
1143 // XXX: cache this locally? Glue it to the RevisionRecord?
1144 return $rc;
1145 }
1146
1147 /**
1148 * Maps fields of the archive row to corresponding revision rows.
1149 *
1150 * @param object $archiveRow
1151 *
1152 * @return object a revision row object, corresponding to $archiveRow.
1153 */
1154 private static function mapArchiveFields( $archiveRow ) {
1155 $fieldMap = [
1156 // keep with ar prefix:
1157 'ar_id' => 'ar_id',
1158
1159 // not the same suffix:
1160 'ar_page_id' => 'rev_page',
1161 'ar_rev_id' => 'rev_id',
1162
1163 // same suffix:
1164 'ar_text_id' => 'rev_text_id',
1165 'ar_timestamp' => 'rev_timestamp',
1166 'ar_user_text' => 'rev_user_text',
1167 'ar_user' => 'rev_user',
1168 'ar_actor' => 'rev_actor',
1169 'ar_minor_edit' => 'rev_minor_edit',
1170 'ar_deleted' => 'rev_deleted',
1171 'ar_len' => 'rev_len',
1172 'ar_parent_id' => 'rev_parent_id',
1173 'ar_sha1' => 'rev_sha1',
1174 'ar_comment' => 'rev_comment',
1175 'ar_comment_cid' => 'rev_comment_cid',
1176 'ar_comment_id' => 'rev_comment_id',
1177 'ar_comment_text' => 'rev_comment_text',
1178 'ar_comment_data' => 'rev_comment_data',
1179 'ar_comment_old' => 'rev_comment_old',
1180 'ar_content_format' => 'rev_content_format',
1181 'ar_content_model' => 'rev_content_model',
1182 ];
1183
1184 $revRow = new stdClass();
1185 foreach ( $fieldMap as $arKey => $revKey ) {
1186 if ( property_exists( $archiveRow, $arKey ) ) {
1187 $revRow->$revKey = $archiveRow->$arKey;
1188 }
1189 }
1190
1191 return $revRow;
1192 }
1193
1194 /**
1195 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
1196 *
1197 * @param object|array $row Either a database row or an array
1198 * @param int $queryFlags for callbacks
1199 * @param Title $title
1200 *
1201 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
1202 * @throws MWException
1203 */
1204 private function emulateMainSlot_1_29( $row, $queryFlags, Title $title ) {
1205 $mainSlotRow = new stdClass();
1206 $mainSlotRow->role_name = 'main';
1207 $mainSlotRow->model_name = null;
1208 $mainSlotRow->slot_revision_id = null;
1209 $mainSlotRow->slot_content_id = null;
1210 $mainSlotRow->content_address = null;
1211
1212 $content = null;
1213 $blobData = null;
1214 $blobFlags = null;
1215
1216 if ( is_object( $row ) ) {
1217 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW ) ) {
1218 // Don't emulate from a row when using the new schema.
1219 // Emulating from an array is still OK.
1220 throw new LogicException( 'Can\'t emulate the main slot when using MCR schema.' );
1221 }
1222
1223 // archive row
1224 if ( !isset( $row->rev_id ) && ( isset( $row->ar_user ) || isset( $row->ar_actor ) ) ) {
1225 $row = $this->mapArchiveFields( $row );
1226 }
1227
1228 if ( isset( $row->rev_text_id ) && $row->rev_text_id > 0 ) {
1229 $mainSlotRow->content_address = SqlBlobStore::makeAddressFromTextId(
1230 $row->rev_text_id
1231 );
1232 }
1233
1234 // This is used by null-revisions
1235 $mainSlotRow->slot_origin = isset( $row->slot_origin )
1236 ? intval( $row->slot_origin )
1237 : null;
1238
1239 if ( isset( $row->old_text ) ) {
1240 // this happens when the text-table gets joined directly, in the pre-1.30 schema
1241 $blobData = isset( $row->old_text ) ? strval( $row->old_text ) : null;
1242 // Check against selects that might have not included old_flags
1243 if ( !property_exists( $row, 'old_flags' ) ) {
1244 throw new InvalidArgumentException( 'old_flags was not set in $row' );
1245 }
1246 $blobFlags = $row->old_flags ?? '';
1247 }
1248
1249 $mainSlotRow->slot_revision_id = intval( $row->rev_id );
1250
1251 $mainSlotRow->content_size = isset( $row->rev_len ) ? intval( $row->rev_len ) : null;
1252 $mainSlotRow->content_sha1 = isset( $row->rev_sha1 ) ? strval( $row->rev_sha1 ) : null;
1253 $mainSlotRow->model_name = isset( $row->rev_content_model )
1254 ? strval( $row->rev_content_model )
1255 : null;
1256 // XXX: in the future, we'll probably always use the default format, and drop content_format
1257 $mainSlotRow->format_name = isset( $row->rev_content_format )
1258 ? strval( $row->rev_content_format )
1259 : null;
1260
1261 if ( isset( $row->rev_text_id ) && intval( $row->rev_text_id ) > 0 ) {
1262 // Overwritten below for SCHEMA_COMPAT_WRITE_NEW
1263 $mainSlotRow->slot_content_id
1264 = $this->emulateContentId( intval( $row->rev_text_id ) );
1265 }
1266 } elseif ( is_array( $row ) ) {
1267 $mainSlotRow->slot_revision_id = isset( $row['id'] ) ? intval( $row['id'] ) : null;
1268
1269 $mainSlotRow->slot_origin = isset( $row['slot_origin'] )
1270 ? intval( $row['slot_origin'] )
1271 : null;
1272 $mainSlotRow->content_address = isset( $row['text_id'] )
1273 ? SqlBlobStore::makeAddressFromTextId( intval( $row['text_id'] ) )
1274 : null;
1275 $mainSlotRow->content_size = isset( $row['len'] ) ? intval( $row['len'] ) : null;
1276 $mainSlotRow->content_sha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
1277
1278 $mainSlotRow->model_name = isset( $row['content_model'] )
1279 ? strval( $row['content_model'] ) : null; // XXX: must be a string!
1280 // XXX: in the future, we'll probably always use the default format, and drop content_format
1281 $mainSlotRow->format_name = isset( $row['content_format'] )
1282 ? strval( $row['content_format'] ) : null;
1283 $blobData = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
1284 // XXX: If the flags field is not set then $blobFlags should be null so that no
1285 // decoding will happen. An empty string will result in default decodings.
1286 $blobFlags = isset( $row['flags'] ) ? trim( strval( $row['flags'] ) ) : null;
1287
1288 // if we have a Content object, override mText and mContentModel
1289 if ( !empty( $row['content'] ) ) {
1290 if ( !( $row['content'] instanceof Content ) ) {
1291 throw new MWException( 'content field must contain a Content object.' );
1292 }
1293
1294 /** @var Content $content */
1295 $content = $row['content'];
1296 $handler = $content->getContentHandler();
1297
1298 $mainSlotRow->model_name = $content->getModel();
1299
1300 // XXX: in the future, we'll probably always use the default format.
1301 if ( $mainSlotRow->format_name === null ) {
1302 $mainSlotRow->format_name = $handler->getDefaultFormat();
1303 }
1304 }
1305
1306 if ( isset( $row['text_id'] ) && intval( $row['text_id'] ) > 0 ) {
1307 // Overwritten below for SCHEMA_COMPAT_WRITE_NEW
1308 $mainSlotRow->slot_content_id
1309 = $this->emulateContentId( intval( $row['text_id'] ) );
1310 }
1311 } else {
1312 throw new MWException( 'Revision constructor passed invalid row format.' );
1313 }
1314
1315 // With the old schema, the content changes with every revision,
1316 // except for null-revisions.
1317 if ( !isset( $mainSlotRow->slot_origin ) ) {
1318 $mainSlotRow->slot_origin = $mainSlotRow->slot_revision_id;
1319 }
1320
1321 if ( $mainSlotRow->model_name === null ) {
1322 $mainSlotRow->model_name = function ( SlotRecord $slot ) use ( $title ) {
1323 $this->assertCrossWikiContentLoadingIsSafe();
1324
1325 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
1326 // TODO: MCR: deprecate $title->getModel().
1327 return ContentHandler::getDefaultModelFor( $title );
1328 };
1329 }
1330
1331 if ( !$content ) {
1332 // XXX: We should perhaps fail if $blobData is null and $mainSlotRow->content_address
1333 // is missing, but "empty revisions" with no content are used in some edge cases.
1334
1335 $content = function ( SlotRecord $slot )
1336 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
1337 {
1338 return $this->loadSlotContent(
1339 $slot,
1340 $blobData,
1341 $blobFlags,
1342 $mainSlotRow->format_name,
1343 $queryFlags
1344 );
1345 };
1346 }
1347
1348 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW ) ) {
1349 // NOTE: this callback will be looped through RevisionSlot::newInherited(), allowing
1350 // the inherited slot to have the same content_id as the original slot. In that case,
1351 // $slot will be the inherited slot, while $mainSlotRow still refers to the original slot.
1352 $mainSlotRow->slot_content_id =
1353 function ( SlotRecord $slot ) use ( $queryFlags, $mainSlotRow ) {
1354 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1355 return $this->findSlotContentId( $db, $mainSlotRow->slot_revision_id, 'main' );
1356 };
1357 }
1358
1359 return new SlotRecord( $mainSlotRow, $content );
1360 }
1361
1362 /**
1363 * Provides a content ID to use with emulated SlotRecords in SCHEMA_COMPAT_OLD mode,
1364 * based on the revision's text ID (rev_text_id or ar_text_id, respectively).
1365 * Note that in SCHEMA_COMPAT_WRITE_BOTH, a callback to findSlotContentId() should be used
1366 * instead, since in that mode, some revision rows may already have a real content ID,
1367 * while other's don't - and for the ones that don't, we should indicate that it
1368 * is missing and cause SlotRecords::hasContentId() to return false.
1369 *
1370 * @param int $textId
1371 * @return int The emulated content ID
1372 */
1373 private function emulateContentId( $textId ) {
1374 // Return a negative number to ensure the ID is distinct from any real content IDs
1375 // that will be assigned in SCHEMA_COMPAT_WRITE_NEW mode and read in SCHEMA_COMPAT_READ_NEW
1376 // mode.
1377 return -$textId;
1378 }
1379
1380 /**
1381 * Loads a Content object based on a slot row.
1382 *
1383 * This method does not call $slot->getContent(), and may be used as a callback
1384 * called by $slot->getContent().
1385 *
1386 * MCR migration note: this roughly corresponds to Revision::getContentInternal
1387 *
1388 * @param SlotRecord $slot The SlotRecord to load content for
1389 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
1390 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
1391 * Use null if no processing should happen. That is in constrast to the empty string,
1392 * which causes the blob to be decoded according to the configured legacy encoding.
1393 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
1394 * @param int $queryFlags
1395 *
1396 * @throws RevisionAccessException
1397 * @return Content
1398 */
1399 private function loadSlotContent(
1400 SlotRecord $slot,
1401 $blobData = null,
1402 $blobFlags = null,
1403 $blobFormat = null,
1404 $queryFlags = 0
1405 ) {
1406 if ( $blobData !== null ) {
1407 Assert::parameterType( 'string', $blobData, '$blobData' );
1408 Assert::parameterType( 'string|null', $blobFlags, '$blobFlags' );
1409
1410 $cacheKey = $slot->hasAddress() ? $slot->getAddress() : null;
1411
1412 if ( $blobFlags === null ) {
1413 // No blob flags, so use the blob verbatim.
1414 $data = $blobData;
1415 } else {
1416 $data = $this->blobStore->expandBlob( $blobData, $blobFlags, $cacheKey );
1417 if ( $data === false ) {
1418 throw new RevisionAccessException(
1419 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
1420 );
1421 }
1422 }
1423
1424 } else {
1425 $address = $slot->getAddress();
1426 try {
1427 $data = $this->blobStore->getBlob( $address, $queryFlags );
1428 } catch ( BlobAccessException $e ) {
1429 throw new RevisionAccessException(
1430 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
1431 );
1432 }
1433 }
1434
1435 // Unserialize content
1436 $handler = ContentHandler::getForModelID( $slot->getModel() );
1437
1438 $content = $handler->unserializeContent( $data, $blobFormat );
1439 return $content;
1440 }
1441
1442 /**
1443 * Load a page revision from a given revision ID number.
1444 * Returns null if no such revision can be found.
1445 *
1446 * MCR migration note: this replaces Revision::newFromId
1447 *
1448 * $flags include:
1449 * IDBAccessObject::READ_LATEST: Select the data from the master
1450 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1451 *
1452 * @param int $id
1453 * @param int $flags (optional)
1454 * @return RevisionRecord|null
1455 */
1456 public function getRevisionById( $id, $flags = 0 ) {
1457 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
1458 }
1459
1460 /**
1461 * Load either the current, or a specified, revision
1462 * that's attached to a given link target. If not attached
1463 * to that link target, will return null.
1464 *
1465 * MCR migration note: this replaces Revision::newFromTitle
1466 *
1467 * $flags include:
1468 * IDBAccessObject::READ_LATEST: Select the data from the master
1469 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1470 *
1471 * @param LinkTarget $linkTarget
1472 * @param int $revId (optional)
1473 * @param int $flags Bitfield (optional)
1474 * @return RevisionRecord|null
1475 */
1476 public function getRevisionByTitle( LinkTarget $linkTarget, $revId = 0, $flags = 0 ) {
1477 $conds = [
1478 'page_namespace' => $linkTarget->getNamespace(),
1479 'page_title' => $linkTarget->getDBkey()
1480 ];
1481 if ( $revId ) {
1482 // Use the specified revision ID.
1483 // Note that we use newRevisionFromConds here because we want to retry
1484 // and fall back to master if the page is not found on a replica.
1485 // Since the caller supplied a revision ID, we are pretty sure the revision is
1486 // supposed to exist, so we should try hard to find it.
1487 $conds['rev_id'] = $revId;
1488 return $this->newRevisionFromConds( $conds, $flags );
1489 } else {
1490 // Use a join to get the latest revision.
1491 // Note that we don't use newRevisionFromConds here because we don't want to retry
1492 // and fall back to master. The assumption is that we only want to force the fallback
1493 // if we are quite sure the revision exists because the caller supplied a revision ID.
1494 // If the page isn't found at all on a replica, it probably simply does not exist.
1495 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1496
1497 $conds[] = 'rev_id=page_latest';
1498 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1499
1500 return $rev;
1501 }
1502 }
1503
1504 /**
1505 * Load either the current, or a specified, revision
1506 * that's attached to a given page ID.
1507 * Returns null if no such revision can be found.
1508 *
1509 * MCR migration note: this replaces Revision::newFromPageId
1510 *
1511 * $flags include:
1512 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
1513 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
1514 *
1515 * @param int $pageId
1516 * @param int $revId (optional)
1517 * @param int $flags Bitfield (optional)
1518 * @return RevisionRecord|null
1519 */
1520 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1521 $conds = [ 'page_id' => $pageId ];
1522 if ( $revId ) {
1523 // Use the specified revision ID.
1524 // Note that we use newRevisionFromConds here because we want to retry
1525 // and fall back to master if the page is not found on a replica.
1526 // Since the caller supplied a revision ID, we are pretty sure the revision is
1527 // supposed to exist, so we should try hard to find it.
1528 $conds['rev_id'] = $revId;
1529 return $this->newRevisionFromConds( $conds, $flags );
1530 } else {
1531 // Use a join to get the latest revision.
1532 // Note that we don't use newRevisionFromConds here because we don't want to retry
1533 // and fall back to master. The assumption is that we only want to force the fallback
1534 // if we are quite sure the revision exists because the caller supplied a revision ID.
1535 // If the page isn't found at all on a replica, it probably simply does not exist.
1536 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1537
1538 $conds[] = 'rev_id=page_latest';
1539 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1540
1541 return $rev;
1542 }
1543 }
1544
1545 /**
1546 * Load the revision for the given title with the given timestamp.
1547 * WARNING: Timestamps may in some circumstances not be unique,
1548 * so this isn't the best key to use.
1549 *
1550 * MCR migration note: this replaces Revision::loadFromTimestamp
1551 *
1552 * @param Title $title
1553 * @param string $timestamp
1554 * @return RevisionRecord|null
1555 */
1556 public function getRevisionByTimestamp( $title, $timestamp ) {
1557 $db = $this->getDBConnection( DB_REPLICA );
1558 return $this->newRevisionFromConds(
1559 [
1560 'rev_timestamp' => $db->timestamp( $timestamp ),
1561 'page_namespace' => $title->getNamespace(),
1562 'page_title' => $title->getDBkey()
1563 ],
1564 0,
1565 $title
1566 );
1567 }
1568
1569 /**
1570 * @param int $revId The revision to load slots for.
1571 * @param int $queryFlags
1572 *
1573 * @return SlotRecord[]
1574 */
1575 private function loadSlotRecords( $revId, $queryFlags ) {
1576 $revQuery = self::getSlotsQueryInfo( [ 'content' ] );
1577
1578 list( $dbMode, $dbOptions ) = DBAccessObjectUtils::getDBOptions( $queryFlags );
1579 $db = $this->getDBConnectionRef( $dbMode );
1580
1581 $res = $db->select(
1582 $revQuery['tables'],
1583 $revQuery['fields'],
1584 [
1585 'slot_revision_id' => $revId,
1586 ],
1587 __METHOD__,
1588 $dbOptions,
1589 $revQuery['joins']
1590 );
1591
1592 $slots = [];
1593
1594 foreach ( $res as $row ) {
1595 // resolve role names and model names from in-memory cache, instead of joining.
1596 $row->role_name = $this->slotRoleStore->getName( (int)$row->slot_role_id );
1597 $row->model_name = $this->contentModelStore->getName( (int)$row->content_model );
1598
1599 $contentCallback = function ( SlotRecord $slot ) use ( $queryFlags, $row ) {
1600 return $this->loadSlotContent( $slot, null, null, null, $queryFlags );
1601 };
1602
1603 $slots[$row->role_name] = new SlotRecord( $row, $contentCallback );
1604 }
1605
1606 if ( !isset( $slots['main'] ) ) {
1607 throw new RevisionAccessException(
1608 'Main slot of revision ' . $revId . ' not found in database!'
1609 );
1610 };
1611
1612 return $slots;
1613 }
1614
1615 /**
1616 * Factory method for RevisionSlots.
1617 *
1618 * @note If other code has a need to construct RevisionSlots objects, this should be made
1619 * public, since RevisionSlots instances should not be constructed directly.
1620 *
1621 * @param int $revId
1622 * @param object $revisionRow
1623 * @param int $queryFlags
1624 * @param Title $title
1625 *
1626 * @return RevisionSlots
1627 * @throws MWException
1628 */
1629 private function newRevisionSlots(
1630 $revId,
1631 $revisionRow,
1632 $queryFlags,
1633 Title $title
1634 ) {
1635 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_NEW ) ) {
1636 $mainSlot = $this->emulateMainSlot_1_29( $revisionRow, $queryFlags, $title );
1637 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1638 } else {
1639 // XXX: do we need the same kind of caching here
1640 // that getKnownCurrentRevision uses (if $revId == page_latest?)
1641
1642 $slots = new RevisionSlots( function () use( $revId, $queryFlags ) {
1643 return $this->loadSlotRecords( $revId, $queryFlags );
1644 } );
1645 }
1646
1647 return $slots;
1648 }
1649
1650 /**
1651 * Make a fake revision object from an archive table row. This is queried
1652 * for permissions or even inserted (as in Special:Undelete)
1653 *
1654 * MCR migration note: this replaces Revision::newFromArchiveRow
1655 *
1656 * @param object $row
1657 * @param int $queryFlags
1658 * @param Title|null $title
1659 * @param array $overrides associative array with fields of $row to override. This may be
1660 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1661 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1662 * override ar_parent_id.
1663 *
1664 * @return RevisionRecord
1665 * @throws MWException
1666 */
1667 public function newRevisionFromArchiveRow(
1668 $row,
1669 $queryFlags = 0,
1670 Title $title = null,
1671 array $overrides = []
1672 ) {
1673 Assert::parameterType( 'object', $row, '$row' );
1674
1675 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1676 Assert::parameterType( 'integer', $queryFlags, '$queryFlags' );
1677
1678 if ( !$title && isset( $overrides['title'] ) ) {
1679 if ( !( $overrides['title'] instanceof Title ) ) {
1680 throw new MWException( 'title field override must contain a Title object.' );
1681 }
1682
1683 $title = $overrides['title'];
1684 }
1685
1686 if ( !isset( $title ) ) {
1687 if ( isset( $row->ar_namespace ) && isset( $row->ar_title ) ) {
1688 $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
1689 } else {
1690 throw new InvalidArgumentException(
1691 'A Title or ar_namespace and ar_title must be given'
1692 );
1693 }
1694 }
1695
1696 foreach ( $overrides as $key => $value ) {
1697 $field = "ar_$key";
1698 $row->$field = $value;
1699 }
1700
1701 try {
1702 $user = User::newFromAnyId(
1703 $row->ar_user ?? null,
1704 $row->ar_user_text ?? null,
1705 $row->ar_actor ?? null
1706 );
1707 } catch ( InvalidArgumentException $ex ) {
1708 wfWarn( __METHOD__ . ': ' . $ex->getMessage() );
1709 $user = new UserIdentityValue( 0, '', 0 );
1710 }
1711
1712 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1713 // Legacy because $row may have come from self::selectFields()
1714 $comment = $this->commentStore->getCommentLegacy( $db, 'ar_comment', $row, true );
1715
1716 $slots = $this->newRevisionSlots( $row->ar_rev_id, $row, $queryFlags, $title );
1717
1718 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId );
1719 }
1720
1721 /**
1722 * @see RevisionFactory::newRevisionFromRow
1723 *
1724 * MCR migration note: this replaces Revision::newFromRow
1725 *
1726 * @param object $row
1727 * @param int $queryFlags
1728 * @param Title|null $title
1729 *
1730 * @return RevisionRecord
1731 */
1732 public function newRevisionFromRow( $row, $queryFlags = 0, Title $title = null ) {
1733 Assert::parameterType( 'object', $row, '$row' );
1734
1735 if ( !$title ) {
1736 $pageId = $row->rev_page ?? 0; // XXX: also check page_id?
1737 $revId = $row->rev_id ?? 0;
1738
1739 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1740 }
1741
1742 if ( !isset( $row->page_latest ) ) {
1743 $row->page_latest = $title->getLatestRevID();
1744 if ( $row->page_latest === 0 && $title->exists() ) {
1745 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1746 }
1747 }
1748
1749 try {
1750 $user = User::newFromAnyId(
1751 $row->rev_user ?? null,
1752 $row->rev_user_text ?? null,
1753 $row->rev_actor ?? null
1754 );
1755 } catch ( InvalidArgumentException $ex ) {
1756 wfWarn( __METHOD__ . ': ' . $ex->getMessage() );
1757 $user = new UserIdentityValue( 0, '', 0 );
1758 }
1759
1760 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1761 // Legacy because $row may have come from self::selectFields()
1762 $comment = $this->commentStore->getCommentLegacy( $db, 'rev_comment', $row, true );
1763
1764 $slots = $this->newRevisionSlots( $row->rev_id, $row, $queryFlags, $title );
1765
1766 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId );
1767 }
1768
1769 /**
1770 * Constructs a new MutableRevisionRecord based on the given associative array following
1771 * the MW1.29 convention for the Revision constructor.
1772 *
1773 * MCR migration note: this replaces Revision::newFromRow
1774 *
1775 * @param array $fields
1776 * @param int $queryFlags
1777 * @param Title|null $title
1778 *
1779 * @return MutableRevisionRecord
1780 * @throws MWException
1781 * @throws RevisionAccessException
1782 */
1783 public function newMutableRevisionFromArray(
1784 array $fields,
1785 $queryFlags = 0,
1786 Title $title = null
1787 ) {
1788 if ( !$title && isset( $fields['title'] ) ) {
1789 if ( !( $fields['title'] instanceof Title ) ) {
1790 throw new MWException( 'title field must contain a Title object.' );
1791 }
1792
1793 $title = $fields['title'];
1794 }
1795
1796 if ( !$title ) {
1797 $pageId = $fields['page'] ?? 0;
1798 $revId = $fields['id'] ?? 0;
1799
1800 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1801 }
1802
1803 if ( !isset( $fields['page'] ) ) {
1804 $fields['page'] = $title->getArticleID( $queryFlags );
1805 }
1806
1807 // if we have a content object, use it to set the model and type
1808 if ( !empty( $fields['content'] ) ) {
1809 if ( !( $fields['content'] instanceof Content ) && !is_array( $fields['content'] ) ) {
1810 throw new MWException(
1811 'content field must contain a Content object or an array of Content objects.'
1812 );
1813 }
1814 }
1815
1816 if ( !empty( $fields['text_id'] ) ) {
1817 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD ) ) {
1818 throw new MWException( "The text_id field is only available in the pre-MCR schema" );
1819 }
1820
1821 if ( !empty( $fields['content'] ) ) {
1822 throw new MWException(
1823 "Text already stored in external store (id {$fields['text_id']}), " .
1824 "can't specify content object"
1825 );
1826 }
1827 }
1828
1829 if (
1830 isset( $fields['comment'] )
1831 && !( $fields['comment'] instanceof CommentStoreComment )
1832 ) {
1833 $commentData = $fields['comment_data'] ?? null;
1834
1835 if ( $fields['comment'] instanceof Message ) {
1836 $fields['comment'] = CommentStoreComment::newUnsavedComment(
1837 $fields['comment'],
1838 $commentData
1839 );
1840 } else {
1841 $commentText = trim( strval( $fields['comment'] ) );
1842 $fields['comment'] = CommentStoreComment::newUnsavedComment(
1843 $commentText,
1844 $commentData
1845 );
1846 }
1847 }
1848
1849 $revision = new MutableRevisionRecord( $title, $this->wikiId );
1850 $this->initializeMutableRevisionFromArray( $revision, $fields );
1851
1852 if ( isset( $fields['content'] ) && is_array( $fields['content'] ) ) {
1853 foreach ( $fields['content'] as $role => $content ) {
1854 $revision->setContent( $role, $content );
1855 }
1856 } else {
1857 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1858 $revision->setSlot( $mainSlot );
1859 }
1860
1861 return $revision;
1862 }
1863
1864 /**
1865 * @param MutableRevisionRecord $record
1866 * @param array $fields
1867 */
1868 private function initializeMutableRevisionFromArray(
1869 MutableRevisionRecord $record,
1870 array $fields
1871 ) {
1872 /** @var UserIdentity $user */
1873 $user = null;
1874
1875 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity ) ) {
1876 $user = $fields['user'];
1877 } else {
1878 try {
1879 $user = User::newFromAnyId(
1880 $fields['user'] ?? null,
1881 $fields['user_text'] ?? null,
1882 $fields['actor'] ?? null
1883 );
1884 } catch ( InvalidArgumentException $ex ) {
1885 $user = null;
1886 }
1887 }
1888
1889 if ( $user ) {
1890 $record->setUser( $user );
1891 }
1892
1893 $timestamp = isset( $fields['timestamp'] )
1894 ? strval( $fields['timestamp'] )
1895 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1896
1897 $record->setTimestamp( $timestamp );
1898
1899 if ( isset( $fields['page'] ) ) {
1900 $record->setPageId( intval( $fields['page'] ) );
1901 }
1902
1903 if ( isset( $fields['id'] ) ) {
1904 $record->setId( intval( $fields['id'] ) );
1905 }
1906 if ( isset( $fields['parent_id'] ) ) {
1907 $record->setParentId( intval( $fields['parent_id'] ) );
1908 }
1909
1910 if ( isset( $fields['sha1'] ) ) {
1911 $record->setSha1( $fields['sha1'] );
1912 }
1913 if ( isset( $fields['size'] ) ) {
1914 $record->setSize( intval( $fields['size'] ) );
1915 }
1916
1917 if ( isset( $fields['minor_edit'] ) ) {
1918 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1919 }
1920 if ( isset( $fields['deleted'] ) ) {
1921 $record->setVisibility( intval( $fields['deleted'] ) );
1922 }
1923
1924 if ( isset( $fields['comment'] ) ) {
1925 Assert::parameterType(
1926 CommentStoreComment::class,
1927 $fields['comment'],
1928 '$row[\'comment\']'
1929 );
1930 $record->setComment( $fields['comment'] );
1931 }
1932 }
1933
1934 /**
1935 * Load a page revision from a given revision ID number.
1936 * Returns null if no such revision can be found.
1937 *
1938 * MCR migration note: this corresponds to Revision::loadFromId
1939 *
1940 * @note direct use is deprecated!
1941 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1942 *
1943 * @param IDatabase $db
1944 * @param int $id
1945 *
1946 * @return RevisionRecord|null
1947 */
1948 public function loadRevisionFromId( IDatabase $db, $id ) {
1949 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1950 }
1951
1952 /**
1953 * Load either the current, or a specified, revision
1954 * that's attached to a given page. If not attached
1955 * to that page, will return null.
1956 *
1957 * MCR migration note: this replaces Revision::loadFromPageId
1958 *
1959 * @note direct use is deprecated!
1960 * @todo remove when unused!
1961 *
1962 * @param IDatabase $db
1963 * @param int $pageid
1964 * @param int $id
1965 * @return RevisionRecord|null
1966 */
1967 public function loadRevisionFromPageId( IDatabase $db, $pageid, $id = 0 ) {
1968 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1969 if ( $id ) {
1970 $conds['rev_id'] = intval( $id );
1971 } else {
1972 $conds[] = 'rev_id=page_latest';
1973 }
1974 return $this->loadRevisionFromConds( $db, $conds );
1975 }
1976
1977 /**
1978 * Load either the current, or a specified, revision
1979 * that's attached to a given page. If not attached
1980 * to that page, will return null.
1981 *
1982 * MCR migration note: this replaces Revision::loadFromTitle
1983 *
1984 * @note direct use is deprecated!
1985 * @todo remove when unused!
1986 *
1987 * @param IDatabase $db
1988 * @param Title $title
1989 * @param int $id
1990 *
1991 * @return RevisionRecord|null
1992 */
1993 public function loadRevisionFromTitle( IDatabase $db, $title, $id = 0 ) {
1994 if ( $id ) {
1995 $matchId = intval( $id );
1996 } else {
1997 $matchId = 'page_latest';
1998 }
1999
2000 return $this->loadRevisionFromConds(
2001 $db,
2002 [
2003 "rev_id=$matchId",
2004 'page_namespace' => $title->getNamespace(),
2005 'page_title' => $title->getDBkey()
2006 ],
2007 0,
2008 $title
2009 );
2010 }
2011
2012 /**
2013 * Load the revision for the given title with the given timestamp.
2014 * WARNING: Timestamps may in some circumstances not be unique,
2015 * so this isn't the best key to use.
2016 *
2017 * MCR migration note: this replaces Revision::loadFromTimestamp
2018 *
2019 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
2020 * @todo remove when unused!
2021 *
2022 * @param IDatabase $db
2023 * @param Title $title
2024 * @param string $timestamp
2025 * @return RevisionRecord|null
2026 */
2027 public function loadRevisionFromTimestamp( IDatabase $db, $title, $timestamp ) {
2028 return $this->loadRevisionFromConds( $db,
2029 [
2030 'rev_timestamp' => $db->timestamp( $timestamp ),
2031 'page_namespace' => $title->getNamespace(),
2032 'page_title' => $title->getDBkey()
2033 ],
2034 0,
2035 $title
2036 );
2037 }
2038
2039 /**
2040 * Given a set of conditions, fetch a revision
2041 *
2042 * This method should be used if we are pretty sure the revision exists.
2043 * Unless $flags has READ_LATEST set, this method will first try to find the revision
2044 * on a replica before hitting the master database.
2045 *
2046 * MCR migration note: this corresponds to Revision::newFromConds
2047 *
2048 * @param array $conditions
2049 * @param int $flags (optional)
2050 * @param Title|null $title
2051 *
2052 * @return RevisionRecord|null
2053 */
2054 private function newRevisionFromConds( $conditions, $flags = 0, Title $title = null ) {
2055 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2056 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
2057
2058 $lb = $this->getDBLoadBalancer();
2059
2060 // Make sure new pending/committed revision are visibile later on
2061 // within web requests to certain avoid bugs like T93866 and T94407.
2062 if ( !$rev
2063 && !( $flags & self::READ_LATEST )
2064 && $lb->getServerCount() > 1
2065 && $lb->hasOrMadeRecentMasterChanges()
2066 ) {
2067 $flags = self::READ_LATEST;
2068 $dbw = $this->getDBConnection( DB_MASTER );
2069 $rev = $this->loadRevisionFromConds( $dbw, $conditions, $flags, $title );
2070 $this->releaseDBConnection( $dbw );
2071 }
2072
2073 return $rev;
2074 }
2075
2076 /**
2077 * Given a set of conditions, fetch a revision from
2078 * the given database connection.
2079 *
2080 * MCR migration note: this corresponds to Revision::loadFromConds
2081 *
2082 * @param IDatabase $db
2083 * @param array $conditions
2084 * @param int $flags (optional)
2085 * @param Title|null $title
2086 *
2087 * @return RevisionRecord|null
2088 */
2089 private function loadRevisionFromConds(
2090 IDatabase $db,
2091 $conditions,
2092 $flags = 0,
2093 Title $title = null
2094 ) {
2095 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
2096 if ( $row ) {
2097 $rev = $this->newRevisionFromRow( $row, $flags, $title );
2098
2099 return $rev;
2100 }
2101
2102 return null;
2103 }
2104
2105 /**
2106 * Throws an exception if the given database connection does not belong to the wiki this
2107 * RevisionStore is bound to.
2108 *
2109 * @param IDatabase $db
2110 * @throws MWException
2111 */
2112 private function checkDatabaseWikiId( IDatabase $db ) {
2113 $storeWiki = $this->wikiId;
2114 $dbWiki = $db->getDomainID();
2115
2116 if ( $dbWiki === $storeWiki ) {
2117 return;
2118 }
2119
2120 // XXX: we really want the default database ID...
2121 $storeWiki = $storeWiki ?: wfWikiID();
2122 $dbWiki = $dbWiki ?: wfWikiID();
2123
2124 if ( $dbWiki === $storeWiki ) {
2125 return;
2126 }
2127
2128 // HACK: counteract encoding imposed by DatabaseDomain
2129 $storeWiki = str_replace( '?h', '-', $storeWiki );
2130 $dbWiki = str_replace( '?h', '-', $dbWiki );
2131
2132 if ( $dbWiki === $storeWiki ) {
2133 return;
2134 }
2135
2136 throw new MWException( "RevisionStore for $storeWiki "
2137 . "cannot be used with a DB connection for $dbWiki" );
2138 }
2139
2140 /**
2141 * Given a set of conditions, return a row with the
2142 * fields necessary to build RevisionRecord objects.
2143 *
2144 * MCR migration note: this corresponds to Revision::fetchFromConds
2145 *
2146 * @param IDatabase $db
2147 * @param array $conditions
2148 * @param int $flags (optional)
2149 *
2150 * @return object|false data row as a raw object
2151 */
2152 private function fetchRevisionRowFromConds( IDatabase $db, $conditions, $flags = 0 ) {
2153 $this->checkDatabaseWikiId( $db );
2154
2155 $revQuery = $this->getQueryInfo( [ 'page', 'user' ] );
2156 $options = [];
2157 if ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING ) {
2158 $options[] = 'FOR UPDATE';
2159 }
2160 return $db->selectRow(
2161 $revQuery['tables'],
2162 $revQuery['fields'],
2163 $conditions,
2164 __METHOD__,
2165 $options,
2166 $revQuery['joins']
2167 );
2168 }
2169
2170 /**
2171 * Finds the ID of a content row for a given revision and slot role.
2172 * This can be used to re-use content rows even while the content ID
2173 * is still missing from SlotRecords, when writing to both the old and
2174 * the new schema during MCR schema migration.
2175 *
2176 * @todo remove after MCR schema migration is complete.
2177 *
2178 * @param IDatabase $db
2179 * @param int $revId
2180 * @param string $role
2181 *
2182 * @return int|null
2183 */
2184 private function findSlotContentId( IDatabase $db, $revId, $role ) {
2185 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_NEW ) ) {
2186 return null;
2187 }
2188
2189 try {
2190 $roleId = $this->slotRoleStore->getId( $role );
2191 $conditions = [
2192 'slot_revision_id' => $revId,
2193 'slot_role_id' => $roleId,
2194 ];
2195
2196 $contentId = $db->selectField( 'slots', 'slot_content_id', $conditions, __METHOD__ );
2197
2198 return $contentId ?: null;
2199 } catch ( NameTableAccessException $ex ) {
2200 // If the role is missing from the slot_roles table,
2201 // the corresponding row in slots cannot exist.
2202 return null;
2203 }
2204 }
2205
2206 /**
2207 * Return the tables, fields, and join conditions to be selected to create
2208 * a new RevisionStoreRecord object.
2209 *
2210 * MCR migration note: this replaces Revision::getQueryInfo
2211 *
2212 * If the format of fields returned changes in any way then the cache key provided by
2213 * self::getRevisionRowCacheKey should be updated.
2214 *
2215 * @since 1.31
2216 *
2217 * @param array $options Any combination of the following strings
2218 * - 'page': Join with the page table, and select fields to identify the page
2219 * - 'user': Join with the user table, and select the user name
2220 * - 'text': Join with the text table, and select fields to load page text. This
2221 * option is deprecated in MW 1.32 when the MCR migration flag SCHEMA_COMPAT_WRITE_NEW
2222 * is set, and disallowed when SCHEMA_COMPAT_READ_OLD is not set.
2223 *
2224 * @return array With three keys:
2225 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2226 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2227 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2228 */
2229 public function getQueryInfo( $options = [] ) {
2230 $ret = [
2231 'tables' => [],
2232 'fields' => [],
2233 'joins' => [],
2234 ];
2235
2236 $ret['tables'][] = 'revision';
2237 $ret['fields'] = array_merge( $ret['fields'], [
2238 'rev_id',
2239 'rev_page',
2240 'rev_timestamp',
2241 'rev_minor_edit',
2242 'rev_deleted',
2243 'rev_len',
2244 'rev_parent_id',
2245 'rev_sha1',
2246 ] );
2247
2248 $commentQuery = $this->commentStore->getJoin( 'rev_comment' );
2249 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
2250 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
2251 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
2252
2253 $actorQuery = $this->actorMigration->getJoin( 'rev_user' );
2254 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
2255 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
2256 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
2257
2258 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD ) ) {
2259 $ret['fields'][] = 'rev_text_id';
2260
2261 if ( $this->contentHandlerUseDB ) {
2262 $ret['fields'][] = 'rev_content_format';
2263 $ret['fields'][] = 'rev_content_model';
2264 }
2265 }
2266
2267 if ( in_array( 'page', $options, true ) ) {
2268 $ret['tables'][] = 'page';
2269 $ret['fields'] = array_merge( $ret['fields'], [
2270 'page_namespace',
2271 'page_title',
2272 'page_id',
2273 'page_latest',
2274 'page_is_redirect',
2275 'page_len',
2276 ] );
2277 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
2278 }
2279
2280 if ( in_array( 'user', $options, true ) ) {
2281 $ret['tables'][] = 'user';
2282 $ret['fields'] = array_merge( $ret['fields'], [
2283 'user_name',
2284 ] );
2285 $u = $actorQuery['fields']['rev_user'];
2286 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
2287 }
2288
2289 if ( in_array( 'text', $options, true ) ) {
2290 if ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_WRITE_OLD ) ) {
2291 throw new InvalidArgumentException( 'text table can no longer be joined directly' );
2292 } elseif ( !$this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD ) ) {
2293 // NOTE: even when this class is set to not read from the old schema, callers
2294 // should still be able to join against the text table, as long as we are still
2295 // writing the old schema for compatibility.
2296 // TODO: This should trigger a deprecation warning eventually (T200918), but not
2297 // before all known usages are removed (see T198341 and T201164).
2298 // wfDeprecated( __METHOD__ . ' with `text` option', '1.32' );
2299 }
2300
2301 $ret['tables'][] = 'text';
2302 $ret['fields'] = array_merge( $ret['fields'], [
2303 'old_text',
2304 'old_flags'
2305 ] );
2306 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
2307 }
2308
2309 return $ret;
2310 }
2311
2312 /**
2313 * Return the tables, fields, and join conditions to be selected to create
2314 * a new SlotRecord.
2315 *
2316 * @since 1.32
2317 *
2318 * @param array $options Any combination of the following strings
2319 * - 'content': Join with the content table, and select content meta-data fields
2320 * - 'model': Join with the content_models table, and select the model_name field.
2321 * Only applicable if 'content' is also set.
2322 * - 'role': Join with the slot_roles table, and select the role_name field
2323 *
2324 * @return array With three keys:
2325 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2326 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2327 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2328 */
2329 public function getSlotsQueryInfo( $options = [] ) {
2330 $ret = [
2331 'tables' => [],
2332 'fields' => [],
2333 'joins' => [],
2334 ];
2335
2336 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD ) ) {
2337 $db = $this->getDBConnectionRef( DB_REPLICA );
2338 $ret['tables']['slots'] = 'revision';
2339
2340 $ret['fields']['slot_revision_id'] = 'slots.rev_id';
2341 $ret['fields']['slot_content_id'] = 'NULL';
2342 $ret['fields']['slot_origin'] = 'slots.rev_id';
2343 $ret['fields']['role_name'] = $db->addQuotes( 'main' );
2344
2345 if ( in_array( 'content', $options, true ) ) {
2346 $ret['fields']['content_size'] = 'slots.rev_len';
2347 $ret['fields']['content_sha1'] = 'slots.rev_sha1';
2348 $ret['fields']['content_address']
2349 = $db->buildConcat( [ $db->addQuotes( 'tt:' ), 'slots.rev_text_id' ] );
2350
2351 if ( $this->contentHandlerUseDB ) {
2352 $ret['fields']['model_name'] = 'slots.rev_content_model';
2353 } else {
2354 $ret['fields']['model_name'] = 'NULL';
2355 }
2356 }
2357 } else {
2358 $ret['tables'][] = 'slots';
2359 $ret['fields'] = array_merge( $ret['fields'], [
2360 'slot_revision_id',
2361 'slot_content_id',
2362 'slot_origin',
2363 'slot_role_id',
2364 ] );
2365
2366 if ( in_array( 'role', $options, true ) ) {
2367 // Use left join to attach role name, so we still find the revision row even
2368 // if the role name is missing. This triggers a more obvious failure mode.
2369 $ret['tables'][] = 'slot_roles';
2370 $ret['joins']['slot_roles'] = [ 'LEFT JOIN', [ 'slot_role_id = role_id' ] ];
2371 $ret['fields'][] = 'role_name';
2372 }
2373
2374 if ( in_array( 'content', $options, true ) ) {
2375 $ret['tables'][] = 'content';
2376 $ret['fields'] = array_merge( $ret['fields'], [
2377 'content_size',
2378 'content_sha1',
2379 'content_address',
2380 'content_model',
2381 ] );
2382 $ret['joins']['content'] = [ 'INNER JOIN', [ 'slot_content_id = content_id' ] ];
2383
2384 if ( in_array( 'model', $options, true ) ) {
2385 // Use left join to attach model name, so we still find the revision row even
2386 // if the model name is missing. This triggers a more obvious failure mode.
2387 $ret['tables'][] = 'content_models';
2388 $ret['joins']['content_models'] = [ 'LEFT JOIN', [ 'content_model = model_id' ] ];
2389 $ret['fields'][] = 'model_name';
2390 }
2391
2392 }
2393 }
2394
2395 return $ret;
2396 }
2397
2398 /**
2399 * Return the tables, fields, and join conditions to be selected to create
2400 * a new RevisionArchiveRecord object.
2401 *
2402 * MCR migration note: this replaces Revision::getArchiveQueryInfo
2403 *
2404 * @since 1.31
2405 *
2406 * @return array With three keys:
2407 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
2408 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
2409 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
2410 */
2411 public function getArchiveQueryInfo() {
2412 $commentQuery = $this->commentStore->getJoin( 'ar_comment' );
2413 $actorQuery = $this->actorMigration->getJoin( 'ar_user' );
2414 $ret = [
2415 'tables' => [ 'archive' ] + $commentQuery['tables'] + $actorQuery['tables'],
2416 'fields' => [
2417 'ar_id',
2418 'ar_page_id',
2419 'ar_namespace',
2420 'ar_title',
2421 'ar_rev_id',
2422 'ar_timestamp',
2423 'ar_minor_edit',
2424 'ar_deleted',
2425 'ar_len',
2426 'ar_parent_id',
2427 'ar_sha1',
2428 ] + $commentQuery['fields'] + $actorQuery['fields'],
2429 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
2430 ];
2431
2432 if ( $this->hasMcrSchemaFlags( SCHEMA_COMPAT_READ_OLD ) ) {
2433 $ret['fields'][] = 'ar_text_id';
2434
2435 if ( $this->contentHandlerUseDB ) {
2436 $ret['fields'][] = 'ar_content_format';
2437 $ret['fields'][] = 'ar_content_model';
2438 }
2439 }
2440
2441 return $ret;
2442 }
2443
2444 /**
2445 * Do a batched query for the sizes of a set of revisions.
2446 *
2447 * MCR migration note: this replaces Revision::getParentLengths
2448 *
2449 * @param int[] $revIds
2450 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2451 * of the corresponding revision.
2452 */
2453 public function getRevisionSizes( array $revIds ) {
2454 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA ), $revIds );
2455 }
2456
2457 /**
2458 * Do a batched query for the sizes of a set of revisions.
2459 *
2460 * MCR migration note: this replaces Revision::getParentLengths
2461 *
2462 * @deprecated use RevisionStore::getRevisionSizes instead.
2463 *
2464 * @param IDatabase $db
2465 * @param int[] $revIds
2466 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2467 * of the corresponding revision.
2468 */
2469 public function listRevisionSizes( IDatabase $db, array $revIds ) {
2470 $this->checkDatabaseWikiId( $db );
2471
2472 $revLens = [];
2473 if ( !$revIds ) {
2474 return $revLens; // empty
2475 }
2476
2477 $res = $db->select(
2478 'revision',
2479 [ 'rev_id', 'rev_len' ],
2480 [ 'rev_id' => $revIds ],
2481 __METHOD__
2482 );
2483
2484 foreach ( $res as $row ) {
2485 $revLens[$row->rev_id] = intval( $row->rev_len );
2486 }
2487
2488 return $revLens;
2489 }
2490
2491 /**
2492 * Get previous revision for this title
2493 *
2494 * MCR migration note: this replaces Revision::getPrevious
2495 *
2496 * @param RevisionRecord $rev
2497 * @param Title|null $title if known (optional)
2498 *
2499 * @return RevisionRecord|null
2500 */
2501 public function getPreviousRevision( RevisionRecord $rev, Title $title = null ) {
2502 if ( $title === null ) {
2503 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2504 }
2505 $prev = $title->getPreviousRevisionID( $rev->getId() );
2506 if ( $prev ) {
2507 return $this->getRevisionByTitle( $title, $prev );
2508 }
2509 return null;
2510 }
2511
2512 /**
2513 * Get next revision for this title
2514 *
2515 * MCR migration note: this replaces Revision::getNext
2516 *
2517 * @param RevisionRecord $rev
2518 * @param Title|null $title if known (optional)
2519 *
2520 * @return RevisionRecord|null
2521 */
2522 public function getNextRevision( RevisionRecord $rev, Title $title = null ) {
2523 if ( $title === null ) {
2524 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
2525 }
2526 $next = $title->getNextRevisionID( $rev->getId() );
2527 if ( $next ) {
2528 return $this->getRevisionByTitle( $title, $next );
2529 }
2530 return null;
2531 }
2532
2533 /**
2534 * Get previous revision Id for this page_id
2535 * This is used to populate rev_parent_id on save
2536 *
2537 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
2538 *
2539 * @param IDatabase $db
2540 * @param RevisionRecord $rev
2541 *
2542 * @return int
2543 */
2544 private function getPreviousRevisionId( IDatabase $db, RevisionRecord $rev ) {
2545 $this->checkDatabaseWikiId( $db );
2546
2547 if ( $rev->getPageId() === null ) {
2548 return 0;
2549 }
2550 # Use page_latest if ID is not given
2551 if ( !$rev->getId() ) {
2552 $prevId = $db->selectField(
2553 'page', 'page_latest',
2554 [ 'page_id' => $rev->getPageId() ],
2555 __METHOD__
2556 );
2557 } else {
2558 $prevId = $db->selectField(
2559 'revision', 'rev_id',
2560 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
2561 __METHOD__,
2562 [ 'ORDER BY' => 'rev_id DESC' ]
2563 );
2564 }
2565 return intval( $prevId );
2566 }
2567
2568 /**
2569 * Get rev_timestamp from rev_id, without loading the rest of the row
2570 *
2571 * MCR migration note: this replaces Revision::getTimestampFromId
2572 *
2573 * @param Title $title
2574 * @param int $id
2575 * @param int $flags
2576 * @return string|bool False if not found
2577 */
2578 public function getTimestampFromId( $title, $id, $flags = 0 ) {
2579 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2580
2581 $conds = [ 'rev_id' => $id ];
2582 $conds['rev_page'] = $title->getArticleID();
2583 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
2584
2585 return ( $timestamp !== false ) ? wfTimestamp( TS_MW, $timestamp ) : false;
2586 }
2587
2588 /**
2589 * Get count of revisions per page...not very efficient
2590 *
2591 * MCR migration note: this replaces Revision::countByPageId
2592 *
2593 * @param IDatabase $db
2594 * @param int $id Page id
2595 * @return int
2596 */
2597 public function countRevisionsByPageId( IDatabase $db, $id ) {
2598 $this->checkDatabaseWikiId( $db );
2599
2600 $row = $db->selectRow( 'revision',
2601 [ 'revCount' => 'COUNT(*)' ],
2602 [ 'rev_page' => $id ],
2603 __METHOD__
2604 );
2605 if ( $row ) {
2606 return intval( $row->revCount );
2607 }
2608 return 0;
2609 }
2610
2611 /**
2612 * Get count of revisions per page...not very efficient
2613 *
2614 * MCR migration note: this replaces Revision::countByTitle
2615 *
2616 * @param IDatabase $db
2617 * @param Title $title
2618 * @return int
2619 */
2620 public function countRevisionsByTitle( IDatabase $db, $title ) {
2621 $id = $title->getArticleID();
2622 if ( $id ) {
2623 return $this->countRevisionsByPageId( $db, $id );
2624 }
2625 return 0;
2626 }
2627
2628 /**
2629 * Check if no edits were made by other users since
2630 * the time a user started editing the page. Limit to
2631 * 50 revisions for the sake of performance.
2632 *
2633 * MCR migration note: this replaces Revision::userWasLastToEdit
2634 *
2635 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
2636 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
2637 * has been deprecated since 1.24.
2638 *
2639 * @param IDatabase $db The Database to perform the check on.
2640 * @param int $pageId The ID of the page in question
2641 * @param int $userId The ID of the user in question
2642 * @param string $since Look at edits since this time
2643 *
2644 * @return bool True if the given user was the only one to edit since the given timestamp
2645 */
2646 public function userWasLastToEdit( IDatabase $db, $pageId, $userId, $since ) {
2647 $this->checkDatabaseWikiId( $db );
2648
2649 if ( !$userId ) {
2650 return false;
2651 }
2652
2653 $revQuery = $this->getQueryInfo();
2654 $res = $db->select(
2655 $revQuery['tables'],
2656 [
2657 'rev_user' => $revQuery['fields']['rev_user'],
2658 ],
2659 [
2660 'rev_page' => $pageId,
2661 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
2662 ],
2663 __METHOD__,
2664 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
2665 $revQuery['joins']
2666 );
2667 foreach ( $res as $row ) {
2668 if ( $row->rev_user != $userId ) {
2669 return false;
2670 }
2671 }
2672 return true;
2673 }
2674
2675 /**
2676 * Load a revision based on a known page ID and current revision ID from the DB
2677 *
2678 * This method allows for the use of caching, though accessing anything that normally
2679 * requires permission checks (aside from the text) will trigger a small DB lookup.
2680 *
2681 * MCR migration note: this replaces Revision::newKnownCurrent
2682 *
2683 * @param Title $title the associated page title
2684 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
2685 *
2686 * @return RevisionRecord|bool Returns false if missing
2687 */
2688 public function getKnownCurrentRevision( Title $title, $revId ) {
2689 $db = $this->getDBConnectionRef( DB_REPLICA );
2690
2691 $pageId = $title->getArticleID();
2692
2693 if ( !$pageId ) {
2694 return false;
2695 }
2696
2697 if ( !$revId ) {
2698 $revId = $title->getLatestRevID();
2699 }
2700
2701 if ( !$revId ) {
2702 wfWarn(
2703 'No latest revision known for page ' . $title->getPrefixedDBkey()
2704 . ' even though it exists with page ID ' . $pageId
2705 );
2706 return false;
2707 }
2708
2709 $row = $this->cache->getWithSetCallback(
2710 // Page/rev IDs passed in from DB to reflect history merges
2711 $this->getRevisionRowCacheKey( $db, $pageId, $revId ),
2712 WANObjectCache::TTL_WEEK,
2713 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
2714 $setOpts += Database::getCacheSetOptions( $db );
2715
2716 $conds = [
2717 'rev_page' => intval( $pageId ),
2718 'page_id' => intval( $pageId ),
2719 'rev_id' => intval( $revId ),
2720 ];
2721
2722 $row = $this->fetchRevisionRowFromConds( $db, $conds );
2723 return $row ?: false; // don't cache negatives
2724 }
2725 );
2726
2727 // Reflect revision deletion and user renames
2728 if ( $row ) {
2729 return $this->newRevisionFromRow( $row, 0, $title );
2730 } else {
2731 return false;
2732 }
2733 }
2734
2735 /**
2736 * Get a cache key for use with a row as selected with getQueryInfo( [ 'page', 'user' ] )
2737 * Caching rows without 'page' or 'user' could lead to issues.
2738 * If the format of the rows returned by the query provided by getQueryInfo changes the
2739 * cache key should be updated to avoid conflicts.
2740 *
2741 * @param IDatabase $db
2742 * @param int $pageId
2743 * @param int $revId
2744 * @return string
2745 */
2746 private function getRevisionRowCacheKey( IDatabase $db, $pageId, $revId ) {
2747 return $this->cache->makeGlobalKey(
2748 self::ROW_CACHE_KEY,
2749 $db->getDomainID(),
2750 $pageId,
2751 $revId
2752 );
2753 }
2754
2755 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.
2756
2757 }