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