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