Debian Codegraph @

includes/Revision/RevisionStore.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * Attribution notice: when this file was created, much of its content was taken
19 * from the Revision.php file as present in release 1.30. Refer to the history
20 * of that file for original authorship (that file was removed entirely in 1.37,
21 * but its history can still be found in prior versions of MediaWiki).
22 *
23 * @file
24 */
25
26 namespace MediaWiki\Revision;
27
28 use InvalidArgumentException;
29 use LogicException;
30 use MediaWiki\CommentStore\CommentStore;
31 use MediaWiki\CommentStore\CommentStoreComment;
32 use MediaWiki\Content\Content;
33 use MediaWiki\Content\FallbackContent;
34 use MediaWiki\Content\IContentHandlerFactory;
35 use MediaWiki\DAO\WikiAwareEntity;
36 use MediaWiki\HookContainer\HookContainer;
37 use MediaWiki\HookContainer\HookRunner;
38 use MediaWiki\Linker\LinkTarget;
39 use MediaWiki\MainConfigNames;
40 use MediaWiki\MediaWikiServices;
41 use MediaWiki\Page\LegacyArticleIdAccess;
42 use MediaWiki\Page\PageIdentity;
43 use MediaWiki\Page\PageIdentityValue;
44 use MediaWiki\Page\PageStore;
45 use MediaWiki\Permissions\Authority;
46 use MediaWiki\Storage\BadBlobException;
47 use MediaWiki\Storage\BlobAccessException;
48 use MediaWiki\Storage\BlobStore;
49 use MediaWiki\Storage\NameTableAccessException;
50 use MediaWiki\Storage\NameTableStore;
51 use MediaWiki\Storage\RevisionSlotsUpdate;
52 use MediaWiki\Storage\SqlBlobStore;
53 use MediaWiki\Title\Title;
54 use MediaWiki\Title\TitleFactory;
55 use MediaWiki\User\ActorStore;
56 use MediaWiki\User\UserIdentity;
57 use MediaWiki\Utils\MWTimestamp;
58 use MWException;
59 use MWUnknownContentModelException;
60 use Psr\Log\LoggerAwareInterface;
61 use Psr\Log\LoggerInterface;
62 use Psr\Log\NullLogger;
63 use RecentChange;
64 use RuntimeException;
65 use StatusValue;
66 use stdClass;
67 use Traversable;
68 use Wikimedia\Assert\Assert;
69 use Wikimedia\IPUtils;
70 use Wikimedia\ObjectCache\BagOStuff;
71 use Wikimedia\ObjectCache\WANObjectCache;
72 use Wikimedia\Rdbms\Database;
73 use Wikimedia\Rdbms\DBAccessObjectUtils;
74 use Wikimedia\Rdbms\IDatabase;
75 use Wikimedia\Rdbms\IDBAccessObject;
76 use Wikimedia\Rdbms\ILoadBalancer;
77 use Wikimedia\Rdbms\IReadableDatabase;
78 use Wikimedia\Rdbms\IResultWrapper;
79 use Wikimedia\Rdbms\Platform\ISQLPlatform;
80 use Wikimedia\Rdbms\SelectQueryBuilder;
81
82 /**
83 * Service for looking up page revisions.
84 *
85 * @since 1.31
86 * @since 1.32 Renamed from MediaWiki\Storage\RevisionStore
87 *
88 * @note This was written to act as a drop-in replacement for the corresponding
89 * static methods in the old Revision class (which was later removed in 1.37).
90 */
91 class RevisionStore implements RevisionFactory, RevisionLookup, LoggerAwareInterface {
92
93 use LegacyArticleIdAccess;
94
95 public const ROW_CACHE_KEY = 'revision-row-1.29';
96
97 public const ORDER_OLDEST_TO_NEWEST = 'ASC';
98 public const ORDER_NEWEST_TO_OLDEST = 'DESC';
99
100 // Constants for get(...)Between methods
101 public const INCLUDE_OLD = 'include_old';
102 public const INCLUDE_NEW = 'include_new';
103 public const INCLUDE_BOTH = 'include_both';
104
105 /**
106 * @var SqlBlobStore
107 */
108 private $blobStore;
109
110 /**
111 * @var false|string
112 */
113 private $wikiId;
114
115 /**
116 * @var ILoadBalancer
117 */
118 private $loadBalancer;
119
120 /**
121 * @var WANObjectCache
122 */
123 private $cache;
124
125 /**
126 * @var BagOStuff
127 */
128 private $localCache;
129
130 /**
131 * @var CommentStore
132 */
133 private $commentStore;
134
135 /** @var ActorStore */
136 private $actorStore;
137
138 /**
139 * @var LoggerInterface
140 */
141 private $logger;
142
143 /**
144 * @var NameTableStore
145 */
146 private $contentModelStore;
147
148 /**
149 * @var NameTableStore
150 */
151 private $slotRoleStore;
152
153 /** @var SlotRoleRegistry */
154 private $slotRoleRegistry;
155
156 /** @var IContentHandlerFactory */
157 private $contentHandlerFactory;
158
159 /** @var HookRunner */
160 private $hookRunner;
161
162 /** @var PageStore */
163 private $pageStore;
164
165 /** @var TitleFactory */
166 private $titleFactory;
167
168 /**
169 * @param ILoadBalancer $loadBalancer
170 * @param SqlBlobStore $blobStore
171 * @param WANObjectCache $cache A cache for caching revision rows. This can be the local
172 * wiki's default instance even if $wikiId refers to a different wiki, since
173 * makeGlobalKey() is used to constructed a key that allows cached revision rows from
174 * the same database to be re-used between wikis. For example, enwiki and frwiki will
175 * use the same cache keys for revision rows from the wikidatawiki database, regardless
176 * of the cache's default key space.
177 * @param BagOStuff $localCache Another layer of cache, best to use APCu here.
178 * @param CommentStore $commentStore
179 * @param NameTableStore $contentModelStore
180 * @param NameTableStore $slotRoleStore
181 * @param SlotRoleRegistry $slotRoleRegistry
182 * @param ActorStore $actorStore
183 * @param IContentHandlerFactory $contentHandlerFactory
184 * @param PageStore $pageStore
185 * @param TitleFactory $titleFactory
186 * @param HookContainer $hookContainer
187 * @param false|string $wikiId Relevant wiki id or WikiAwareEntity::LOCAL for the current one
188 *
189 * @todo $blobStore should be allowed to be any BlobStore!
190 *
191 */
192 public function __construct(
193 ILoadBalancer $loadBalancer,
194 SqlBlobStore $blobStore,
195 WANObjectCache $cache,
196 BagOStuff $localCache,
197 CommentStore $commentStore,
198 NameTableStore $contentModelStore,
199 NameTableStore $slotRoleStore,
200 SlotRoleRegistry $slotRoleRegistry,
201 ActorStore $actorStore,
202 IContentHandlerFactory $contentHandlerFactory,
203 PageStore $pageStore,
204 TitleFactory $titleFactory,
205 HookContainer $hookContainer,
206 $wikiId = WikiAwareEntity::LOCAL
207 ) {
208 Assert::parameterType( [ 'string', 'false' ], $wikiId, '$wikiId' );
209
210 $this->loadBalancer = $loadBalancer;
211 $this->blobStore = $blobStore;
212 $this->cache = $cache;
213 $this->localCache = $localCache;
214 $this->commentStore = $commentStore;
215 $this->contentModelStore = $contentModelStore;
216 $this->slotRoleStore = $slotRoleStore;
217 $this->slotRoleRegistry = $slotRoleRegistry;
218 $this->actorStore = $actorStore;
219 $this->wikiId = $wikiId;
220 $this->logger = new NullLogger();
221 $this->contentHandlerFactory = $contentHandlerFactory;
222 $this->pageStore = $pageStore;
223 $this->titleFactory = $titleFactory;
224 $this->hookRunner = new HookRunner( $hookContainer );
225 }
226
227 public function setLogger( LoggerInterface $logger ) {
228 $this->logger = $logger;
229 }
230
231 /**
232 * @return bool Whether the store is read-only
233 */
234 public function isReadOnly() {
235 return $this->blobStore->isReadOnly();
236 }
237
238 /**
239 * Get the ID of the wiki this revision belongs to.
240 *
241 * @return string|false The wiki's logical name, of false to indicate the local wiki.
242 */
243 public function getWikiId() {
244 return $this->wikiId;
245 }
246
247 /**
248 * @param int $queryFlags a bit field composed of READ_XXX flags
249 *
250 * @return IReadableDatabase
251 */
252 private function getDBConnectionRefForQueryFlags( $queryFlags ) {
253 if ( ( $queryFlags & IDBAccessObject::READ_LATEST ) == IDBAccessObject::READ_LATEST ) {
254 return $this->getPrimaryConnection();
255 } else {
256 return $this->getReplicaConnection();
257 }
258 }
259
260 /**
261 * @param string|array $groups
262 * @return IReadableDatabase
263 */
264 private function getReplicaConnection( $groups = [] ) {
265 // TODO: Replace with ICP
266 return $this->loadBalancer->getConnection( DB_REPLICA, $groups, $this->wikiId );
267 }
268
269 private function getPrimaryConnection(): IDatabase {
270 // TODO: Replace with ICP
271 return $this->loadBalancer->getConnection( DB_PRIMARY, [], $this->wikiId );
272 }
273
274 /**
275 * Determines the page Title based on the available information.
276 *
277 * MCR migration note: this corresponded to Revision::getTitle
278 *
279 * @deprecated since 1.36, Use RevisionRecord::getPage() instead.
280 * @note The resulting Title object will be misleading if the RevisionStore is not
281 * for the local wiki.
282 *
283 * @param int|null $pageId
284 * @param int|null $revId
285 * @param int $queryFlags
286 *
287 * @return Title
288 * @throws RevisionAccessException
289 */
290 public function getTitle( $pageId, $revId, $queryFlags = IDBAccessObject::READ_NORMAL ) {
291 // TODO: Hard-deprecate this once getPage() returns a PageRecord. T195069
292 if ( $this->wikiId !== WikiAwareEntity::LOCAL ) {
293 wfDeprecatedMsg( 'Using a Title object to refer to a page on another site.', '1.36' );
294 }
295
296 $page = $this->getPage( $pageId, $revId, $queryFlags );
297 return $this->titleFactory->newFromPageIdentity( $page );
298 }
299
300 /**
301 * Determines the page based on the available information.
302 *
303 * @param int|null $pageId
304 * @param int|null $revId
305 * @param int $queryFlags
306 *
307 * @return PageIdentity
308 * @throws RevisionAccessException
309 */
310 private function getPage( ?int $pageId, ?int $revId, int $queryFlags = IDBAccessObject::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, IDBAccessObject::READ_LATEST_IMMUTABLE ) ) {
318 $queryFlags = IDBAccessObject::READ_NORMAL;
319 }
320
321 // Loading by ID is best
322 if ( $pageId !== null && $pageId > 0 ) {
323 $page = $this->pageStore->getPageById( $pageId, $queryFlags );
324 if ( $page ) {
325 return $this->wrapPage( $page );
326 }
327 }
328
329 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
330 if ( $revId !== null && $revId > 0 ) {
331 $pageQuery = $this->pageStore->newSelectQueryBuilder( $queryFlags )
332 ->join( 'revision', null, 'page_id=rev_page' )
333 ->conds( [ 'rev_id' => $revId ] )
334 ->caller( __METHOD__ );
335
336 $page = $pageQuery->fetchPageRecord();
337 if ( $page ) {
338 return $this->wrapPage( $page );
339 }
340 }
341
342 // If we still don't have a title, fallback to primary DB if that wasn't already happening.
343 if ( $queryFlags === IDBAccessObject::READ_NORMAL ) {
344 $title = $this->getPage( $pageId, $revId, IDBAccessObject::READ_LATEST );
345 if ( $title ) {
346 $this->logger->info(
347 __METHOD__ . ' fell back to READ_LATEST and got a Title.',
348 [ 'exception' => new RuntimeException() ]
349 );
350 return $title;
351 }
352 }
353
354 throw new RevisionAccessException(
355 'Could not determine title for page ID {page_id} and revision ID {rev_id}',
356 [
357 'page_id' => $pageId,
358 'rev_id' => $revId,
359 ]
360 );
361 }
362
363 /**
364 * @param PageIdentity $page
365 *
366 * @return PageIdentity
367 */
368 private function wrapPage( PageIdentity $page ): PageIdentity {
369 if ( $this->wikiId === WikiAwareEntity::LOCAL ) {
370 // NOTE: since there is still a lot of code that needs a full Title,
371 // and uses Title::castFromPageIdentity() to get one, it's beneficial
372 // to create a Title right away if we can, so we don't have to convert
373 // over and over later on.
374 // When there is less need to convert to Title, this special case can
375 // be removed.
376 return $this->titleFactory->newFromPageIdentity( $page );
377 } else {
378 return $page;
379 }
380 }
381
382 /**
383 * @param mixed $value
384 * @param string $name
385 *
386 * @throws IncompleteRevisionException if $value is null
387 * @return mixed $value, if $value is not null
388 */
389 private function failOnNull( $value, $name ) {
390 if ( $value === null ) {
391 throw new IncompleteRevisionException(
392 "$name must not be " . var_export( $value, true ) . "!"
393 );
394 }
395
396 return $value;
397 }
398
399 /**
400 * @param mixed $value
401 * @param string $name
402 *
403 * @throws IncompleteRevisionException if $value is empty
404 * @return mixed $value, if $value is not null
405 */
406 private function failOnEmpty( $value, $name ) {
407 if ( $value === null || $value === 0 || $value === '' ) {
408 throw new IncompleteRevisionException(
409 "$name must not be " . var_export( $value, true ) . "!"
410 );
411 }
412
413 return $value;
414 }
415
416 /**
417 * Insert a new revision into the database, returning the new revision record
418 * on success and dies horribly on failure.
419 *
420 * This should be followed up by a WikiPage::updateRevisionOn on call to update
421 * page_latest on the page the revision is added to.
422 *
423 * MCR migration note: this replaced Revision::insertOn
424 *
425 * @param RevisionRecord $rev
426 * @param IDatabase $dbw (primary connection)
427 *
428 * @return RevisionRecord the new revision record.
429 */
430 public function insertRevisionOn( RevisionRecord $rev, IDatabase $dbw ) {
431 // TODO: pass in a DBTransactionContext instead of a database connection.
432 $this->checkDatabaseDomain( $dbw );
433
434 $slotRoles = $rev->getSlotRoles();
435
436 // Make sure the main slot is always provided throughout migration
437 if ( !in_array( SlotRecord::MAIN, $slotRoles ) ) {
438 throw new IncompleteRevisionException(
439 'main slot must be provided'
440 );
441 }
442
443 // Checks
444 $this->failOnNull( $rev->getSize(), 'size field' );
445 $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
446 $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
447 $comment = $this->failOnNull( $rev->getComment( RevisionRecord::RAW ), 'comment' );
448 $user = $this->failOnNull( $rev->getUser( RevisionRecord::RAW ), 'user' );
449 $this->failOnNull( $user->getId(), 'user field' );
450 $this->failOnEmpty( $user->getName(), 'user_text field' );
451
452 if ( !$rev->isReadyForInsertion() ) {
453 // This is here for future-proofing. At the time this check being added, it
454 // was redundant to the individual checks above.
455 throw new IncompleteRevisionException( 'Revision is incomplete' );
456 }
457
458 if ( $slotRoles == [ SlotRecord::MAIN ] ) {
459 // T239717: If the main slot is the only slot, make sure the revision's nominal size
460 // and hash match the main slot's nominal size and hash.
461 $mainSlot = $rev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW );
462 Assert::precondition(
463 $mainSlot->getSize() === $rev->getSize(),
464 'The revisions\'s size must match the main slot\'s size (see T239717)'
465 );
466 Assert::precondition(
467 $mainSlot->getSha1() === $rev->getSha1(),
468 'The revisions\'s SHA1 hash must match the main slot\'s SHA1 hash (see T239717)'
469 );
470 }
471
472 $pageId = $this->failOnEmpty( $rev->getPageId( $this->wikiId ), 'rev_page field' ); // check this early
473
474 $parentId = $rev->getParentId() ?? $this->getPreviousRevisionId( $dbw, $rev );
475
476 /** @var RevisionRecord $rev */
477 $rev = $dbw->doAtomicSection(
478 __METHOD__,
479 function ( IDatabase $dbw, $fname ) use (
480 $rev,
481 $user,
482 $comment,
483 $pageId,
484 $parentId
485 ) {
486 return $this->insertRevisionInternal(
487 $rev,
488 $dbw,
489 $user,
490 $comment,
491 $rev->getPage(),
492 $pageId,
493 $parentId
494 );
495 }
496 );
497
498 Assert::postcondition( $rev->getId( $this->wikiId ) > 0, 'revision must have an ID' );
499 Assert::postcondition( $rev->getPageId( $this->wikiId ) > 0, 'revision must have a page ID' );
500 Assert::postcondition(
501 $rev->getComment( RevisionRecord::RAW ) !== null,
502 'revision must have a comment'
503 );
504 Assert::postcondition(
505 $rev->getUser( RevisionRecord::RAW ) !== null,
506 'revision must have a user'
507 );
508
509 // Trigger exception if the main slot is missing.
510 // Technically, this could go away after MCR migration: while
511 // calling code may require a main slot to exist, RevisionStore
512 // really should not know or care about that requirement.
513 $rev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW );
514
515 foreach ( $slotRoles as $role ) {
516 $slot = $rev->getSlot( $role, RevisionRecord::RAW );
517 Assert::postcondition(
518 $slot->getContent() !== null,
519 $role . ' slot must have content'
520 );
521 Assert::postcondition(
522 $slot->hasRevision(),
523 $role . ' slot must have a revision associated'
524 );
525 }
526
527 $this->hookRunner->onRevisionRecordInserted( $rev );
528
529 return $rev;
530 }
531
532 /**
533 * Update derived slots in an existing revision into the database, returning the modified
534 * slots on success.
535 *
536 * @param RevisionRecord $revision After this method returns, the $revision object will be
537 * obsolete in that it does not have the new slots.
538 * @param RevisionSlotsUpdate $revisionSlotsUpdate
539 * @param IDatabase $dbw (primary connection)
540 *
541 * @return SlotRecord[] the new slot records.
542 * @internal
543 */
544 public function updateSlotsOn(
545 RevisionRecord $revision,
546 RevisionSlotsUpdate $revisionSlotsUpdate,
547 IDatabase $dbw
548 ): array {
549 $this->checkDatabaseDomain( $dbw );
550
551 // Make sure all modified and removed slots are derived slots
552 foreach ( $revisionSlotsUpdate->getModifiedRoles() as $role ) {
553 Assert::precondition(
554 $this->slotRoleRegistry->getRoleHandler( $role )->isDerived(),
555 'Trying to modify a slot that is not derived'
556 );
557 }
558 foreach ( $revisionSlotsUpdate->getRemovedRoles() as $role ) {
559 $isDerived = $this->slotRoleRegistry->getRoleHandler( $role )->isDerived();
560 Assert::precondition(
561 $isDerived,
562 'Trying to remove a slot that is not derived'
563 );
564 throw new LogicException( 'Removing derived slots is not yet implemented. See T277394.' );
565 }
566
567 /** @var SlotRecord[] $slotRecords */
568 $slotRecords = $dbw->doAtomicSection(
569 __METHOD__,
570 function ( IDatabase $dbw, $fname ) use (
571 $revision,
572 $revisionSlotsUpdate
573 ) {
574 return $this->updateSlotsInternal(
575 $revision,
576 $revisionSlotsUpdate,
577 $dbw
578 );
579 }
580 );
581
582 foreach ( $slotRecords as $role => $slot ) {
583 Assert::postcondition(
584 $slot->getContent() !== null,
585 $role . ' slot must have content'
586 );
587 Assert::postcondition(
588 $slot->hasRevision(),
589 $role . ' slot must have a revision associated'
590 );
591 }
592
593 return $slotRecords;
594 }
595
596 /**
597 * @param RevisionRecord $revision
598 * @param RevisionSlotsUpdate $revisionSlotsUpdate
599 * @param IDatabase $dbw
600 * @return SlotRecord[]
601 */
602 private function updateSlotsInternal(
603 RevisionRecord $revision,
604 RevisionSlotsUpdate $revisionSlotsUpdate,
605 IDatabase $dbw
606 ): array {
607 $page = $revision->getPage();
608 $revId = $revision->getId( $this->wikiId );
609 $blobHints = [
610 BlobStore::PAGE_HINT => $page->getId( $this->wikiId ),
611 BlobStore::REVISION_HINT => $revId,
612 BlobStore::PARENT_HINT => $revision->getParentId( $this->wikiId ),
613 ];
614
615 $newSlots = [];
616 foreach ( $revisionSlotsUpdate->getModifiedRoles() as $role ) {
617 $slot = $revisionSlotsUpdate->getModifiedSlot( $role );
618 $newSlots[$role] = $this->insertSlotOn( $dbw, $revId, $slot, $page, $blobHints );
619 }
620
621 return $newSlots;
622 }
623
624 private function insertRevisionInternal(
625 RevisionRecord $rev,
626 IDatabase $dbw,
627 UserIdentity $user,
628 CommentStoreComment $comment,
629 PageIdentity $page,
630 $pageId,
631 $parentId
632 ) {
633 $slotRoles = $rev->getSlotRoles();
634
635 $revisionRow = $this->insertRevisionRowOn(
636 $dbw,
637 $rev,
638 $parentId
639 );
640
641 $revisionId = $revisionRow['rev_id'];
642
643 $blobHints = [
644 BlobStore::PAGE_HINT => $pageId,
645 BlobStore::REVISION_HINT => $revisionId,
646 BlobStore::PARENT_HINT => $parentId,
647 ];
648
649 $newSlots = [];
650 foreach ( $slotRoles as $role ) {
651 $slot = $rev->getSlot( $role, RevisionRecord::RAW );
652
653 // If the SlotRecord already has a revision ID set, this means it already exists
654 // in the database, and should already belong to the current revision.
655 // However, a slot may already have a revision, but no content ID, if the slot
656 // is emulated based on the archive table, because we are in SCHEMA_COMPAT_READ_OLD
657 // mode, and the respective archive row was not yet migrated to the new schema.
658 // In that case, a new slot row (and content row) must be inserted even during
659 // undeletion.
660 if ( $slot->hasRevision() && $slot->hasContentId() ) {
661 // TODO: properly abort transaction if the assertion fails!
662 Assert::parameter(
663 $slot->getRevision() === $revisionId,
664 'slot role ' . $slot->getRole(),
665 'Existing slot should belong to revision '
666 . $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
667 );
668
669 // Slot exists, nothing to do, move along.
670 // This happens when restoring archived revisions.
671
672 $newSlots[$role] = $slot;
673 } else {
674 $newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $page, $blobHints );
675 }
676 }
677
678 $this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
679
680 $rev = new RevisionStoreRecord(
681 $page,
682 $user,
683 $comment,
684 (object)$revisionRow,
685 new RevisionSlots( $newSlots ),
686 $this->wikiId
687 );
688
689 return $rev;
690 }
691
692 /**
693 * @param IDatabase $dbw
694 * @param int $revisionId
695 * @param SlotRecord $protoSlot
696 * @param PageIdentity $page
697 * @param array $blobHints See the BlobStore::XXX_HINT constants
698 * @return SlotRecord
699 */
700 private function insertSlotOn(
701 IDatabase $dbw,
702 $revisionId,
703 SlotRecord $protoSlot,
704 PageIdentity $page,
705 array $blobHints = []
706 ) {
707 if ( $protoSlot->hasAddress() ) {
708 $blobAddress = $protoSlot->getAddress();
709 } else {
710 $blobAddress = $this->storeContentBlob( $protoSlot, $page, $blobHints );
711 }
712
713 if ( $protoSlot->hasContentId() ) {
714 $contentId = $protoSlot->getContentId();
715 } else {
716 $contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
717 }
718
719 $this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
720
721 return SlotRecord::newSaved(
722 $revisionId,
723 $contentId,
724 $blobAddress,
725 $protoSlot
726 );
727 }
728
729 /**
730 * Insert IP revision into ip_changes for use when querying for a range.
731 * @param IDatabase $dbw
732 * @param UserIdentity $user
733 * @param RevisionRecord $rev
734 * @param int $revisionId
735 */
736 private function insertIpChangesRow(
737 IDatabase $dbw,
738 UserIdentity $user,
739 RevisionRecord $rev,
740 $revisionId
741 ) {
742 if ( !$user->isRegistered() && IPUtils::isValid( $user->getName() ) ) {
743 $dbw->newInsertQueryBuilder()
744 ->insertInto( 'ip_changes' )
745 ->row( [
746 'ipc_rev_id' => $revisionId,
747 'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
748 'ipc_hex' => IPUtils::toHex( $user->getName() ),
749 ] )
750 ->caller( __METHOD__ )->execute();
751
752 }
753 }
754
755 /**
756 * @param IDatabase $dbw
757 * @param RevisionRecord $rev
758 * @param int $parentId
759 *
760 * @return array a revision table row
761 *
762 * @throws MWException
763 * @throws MWUnknownContentModelException
764 */
765 private function insertRevisionRowOn(
766 IDatabase $dbw,
767 RevisionRecord $rev,
768 $parentId
769 ) {
770 $revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $parentId );
771
772 $revisionRow += $this->commentStore->insert(
773 $dbw,
774 'rev_comment',
775 $rev->getComment( RevisionRecord::RAW )
776 );
777
778 $dbw->newInsertQueryBuilder()
779 ->insertInto( 'revision' )
780 ->row( $revisionRow )
781 ->caller( __METHOD__ )->execute();
782
783 if ( !isset( $revisionRow['rev_id'] ) ) {
784 // only if auto-increment was used
785 $revisionRow['rev_id'] = intval( $dbw->insertId() );
786
787 if ( $dbw->getType() === 'mysql' ) {
788 // (T202032) MySQL until 8.0 and MariaDB until some version after 10.1.34 don't save the
789 // auto-increment value to disk, so on server restart it might reuse IDs from deleted
790 // revisions. We can fix that with an insert with an explicit rev_id value, if necessary.
791
792 $maxRevId = intval( $dbw->newSelectQueryBuilder()
793 ->select( 'MAX(ar_rev_id)' )
794 ->from( 'archive' )
795 ->caller( __METHOD__ )
796 ->fetchField() );
797 $table = 'archive';
798 $maxRevId2 = intval( $dbw->newSelectQueryBuilder()
799 ->select( 'MAX(slot_revision_id)' )
800 ->from( 'slots' )
801 ->caller( __METHOD__ )
802 ->fetchField() );
803 if ( $maxRevId2 >= $maxRevId ) {
804 $maxRevId = $maxRevId2;
805 $table = 'slots';
806 }
807
808 if ( $maxRevId >= $revisionRow['rev_id'] ) {
809 $this->logger->debug(
810 '__METHOD__: Inserted revision {revid} but {table} has revisions up to {maxrevid}.'
811 . ' Trying to fix it.',
812 [
813 'revid' => $revisionRow['rev_id'],
814 'table' => $table,
815 'maxrevid' => $maxRevId,
816 ]
817 );
818
819 if ( !$dbw->lock( 'fix-for-T202032', __METHOD__ ) ) {
820 throw new MWException( 'Failed to get database lock for T202032' );
821 }
822 $fname = __METHOD__;
823 $dbw->onTransactionResolution(
824 static function ( $trigger, IDatabase $dbw ) use ( $fname ) {
825 $dbw->unlock( 'fix-for-T202032', $fname );
826 },
827 __METHOD__
828 );
829
830 $dbw->newDeleteQueryBuilder()
831 ->deleteFrom( 'revision' )
832 ->where( [ 'rev_id' => $revisionRow['rev_id'] ] )
833 ->caller( __METHOD__ )->execute();
834
835 // The locking here is mostly to make MySQL bypass the REPEATABLE-READ transaction
836 // isolation (weird MySQL "feature"). It does seem to block concurrent auto-incrementing
837 // inserts too, though, at least on MariaDB 10.1.29.
838 //
839 // Don't try to lock `revision` in this way, it'll deadlock if there are concurrent
840 // transactions in this code path thanks to the row lock from the original ->insert() above.
841 //
842 // And we have to use raw SQL to bypass the "aggregation used with a locking SELECT" warning
843 // that's for non-MySQL DBs.
844 $row1 = $dbw->query(
845 $dbw->selectSQLText( 'archive', [ 'v' => "MAX(ar_rev_id)" ], '', __METHOD__ ) . ' FOR UPDATE',
846 __METHOD__
847 )->fetchObject();
848
849 $row2 = $dbw->query(
850 $dbw->selectSQLText( 'slots', [ 'v' => "MAX(slot_revision_id)" ], '', __METHOD__ )
851 . ' FOR UPDATE',
852 __METHOD__
853 )->fetchObject();
854
855 $maxRevId = max(
856 $maxRevId,
857 $row1 ? intval( $row1->v ) : 0,
858 $row2 ? intval( $row2->v ) : 0
859 );
860
861 // If we don't have SCHEMA_COMPAT_WRITE_NEW, all except the first of any concurrent
862 // transactions will throw a duplicate key error here. It doesn't seem worth trying
863 // to avoid that.
864 $revisionRow['rev_id'] = $maxRevId + 1;
865 $dbw->newInsertQueryBuilder()
866 ->insertInto( 'revision' )
867 ->row( $revisionRow )
868 ->caller( __METHOD__ )->execute();
869 }
870 }
871 }
872
873 return $revisionRow;
874 }
875
876 /**
877 * @param IDatabase $dbw
878 * @param RevisionRecord $rev
879 * @param int $parentId
880 *
881 * @return array a revision table row
882 */
883 private function getBaseRevisionRow(
884 IDatabase $dbw,
885 RevisionRecord $rev,
886 $parentId
887 ) {
888 // Record the edit in revisions
889 $revisionRow = [
890 'rev_page' => $rev->getPageId( $this->wikiId ),
891 'rev_parent_id' => $parentId,
892 'rev_actor' => $this->actorStore->acquireActorId(
893 $rev->getUser( RevisionRecord::RAW ),
894 $dbw
895 ),
896 'rev_minor_edit' => $rev->isMinor() ? 1 : 0,
897 'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
898 'rev_deleted' => $rev->getVisibility(),
899 'rev_len' => $rev->getSize(),
900 'rev_sha1' => $rev->getSha1(),
901 ];
902
903 if ( $rev->getId( $this->wikiId ) !== null ) {
904 // Needed to restore revisions with their original ID
905 $revisionRow['rev_id'] = $rev->getId( $this->wikiId );
906 }
907
908 return $revisionRow;
909 }
910
911 /**
912 * @param SlotRecord $slot
913 * @param PageIdentity $page
914 * @param array $blobHints See the BlobStore::XXX_HINT constants
915 *
916 * @throws MWException
917 * @return string the blob address
918 */
919 private function storeContentBlob(
920 SlotRecord $slot,
921 PageIdentity $page,
922 array $blobHints = []
923 ) {
924 $content = $slot->getContent();
925 $format = $content->getDefaultFormat();
926 $model = $content->getModel();
927
928 $this->checkContent( $content, $page, $slot->getRole() );
929
930 return $this->blobStore->storeBlob(
931 $content->serialize( $format ),
932 // These hints "leak" some information from the higher abstraction layer to
933 // low level storage to allow for optimization.
934 array_merge(
935 $blobHints,
936 [
937 BlobStore::DESIGNATION_HINT => 'page-content',
938 BlobStore::ROLE_HINT => $slot->getRole(),
939 BlobStore::SHA1_HINT => $slot->getSha1(),
940 BlobStore::MODEL_HINT => $model,
941 BlobStore::FORMAT_HINT => $format,
942 ]
943 )
944 );
945 }
946
947 /**
948 * @param SlotRecord $slot
949 * @param IDatabase $dbw
950 * @param int $revisionId
951 * @param int $contentId
952 */
953 private function insertSlotRowOn( SlotRecord $slot, IDatabase $dbw, $revisionId, $contentId ) {
954 $dbw->newInsertQueryBuilder()
955 ->insertInto( 'slots' )
956 ->row( [
957 'slot_revision_id' => $revisionId,
958 'slot_role_id' => $this->slotRoleStore->acquireId( $slot->getRole() ),
959 'slot_content_id' => $contentId,
960 // If the slot has a specific origin use that ID, otherwise use the ID of the revision
961 // that we just inserted.
962 'slot_origin' => $slot->hasOrigin() ? $slot->getOrigin() : $revisionId,
963 ] )
964 ->caller( __METHOD__ )->execute();
965 }
966
967 /**
968 * @param SlotRecord $slot
969 * @param IDatabase $dbw
970 * @param string $blobAddress
971 * @return int content row ID
972 */
973 private function insertContentRowOn( SlotRecord $slot, IDatabase $dbw, $blobAddress ) {
974 $dbw->newInsertQueryBuilder()
975 ->insertInto( 'content' )
976 ->row( [
977 'content_size' => $slot->getSize(),
978 'content_sha1' => $slot->getSha1(),
979 'content_model' => $this->contentModelStore->acquireId( $slot->getModel() ),
980 'content_address' => $blobAddress,
981 ] )
982 ->caller( __METHOD__ )->execute();
983 return intval( $dbw->insertId() );
984 }
985
986 /**
987 * MCR migration note: this corresponded to Revision::checkContentModel
988 *
989 * @param Content $content
990 * @param PageIdentity $page
991 * @param string $role
992 *
993 * @throws MWException
994 * @throws MWUnknownContentModelException
995 */
996 private function checkContent( Content $content, PageIdentity $page, string $role ) {
997 // Note: may return null for revisions that have not yet been inserted
998
999 $model = $content->getModel();
1000 $format = $content->getDefaultFormat();
1001 $handler = $content->getContentHandler();
1002
1003 if ( !$handler->isSupportedFormat( $format ) ) {
1004 throw new MWException(
1005 "Can't use format $format with content model $model on $page role $role"
1006 );
1007 }
1008
1009 if ( !$content->isValid() ) {
1010 throw new MWException(
1011 "New content for $page role $role is not valid! Content model is $model"
1012 );
1013 }
1014 }
1015
1016 /**
1017 * Create a new null-revision for insertion into a page's
1018 * history. This will not re-save the text, but simply refer
1019 * to the text from the previous version.
1020 *
1021 * Such revisions can for instance identify page rename
1022 * operations and other such meta-modifications.
1023 *
1024 * @note This method grabs a FOR UPDATE lock on the relevant row of the page table,
1025 * to prevent a new revision from being inserted before the null revision has been written
1026 * to the database.
1027 *
1028 * MCR migration note: this replaced Revision::newNullRevision
1029 *
1030 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
1031 * (or go away).
1032 *
1033 * @param IDatabase $dbw used for obtaining the lock on the page table row
1034 * @param PageIdentity $page the page to read from
1035 * @param CommentStoreComment $comment RevisionRecord's summary
1036 * @param bool $minor Whether the revision should be considered as minor
1037 * @param UserIdentity $user The user to attribute the revision to
1038 *
1039 * @return RevisionRecord|null RevisionRecord or null on error
1040 */
1041 public function newNullRevision(
1042 IDatabase $dbw,
1043 PageIdentity $page,
1044 CommentStoreComment $comment,
1045 $minor,
1046 UserIdentity $user
1047 ) {
1048 $this->checkDatabaseDomain( $dbw );
1049
1050 $pageId = $this->getArticleId( $page );
1051
1052 // T51581: Lock the page table row to ensure no other process
1053 // is adding a revision to the page at the same time.
1054 // Avoid locking extra tables, compare T191892.
1055 $pageLatest = $dbw->newSelectQueryBuilder()
1056 ->select( 'page_latest' )
1057 ->forUpdate()
1058 ->from( 'page' )
1059 ->where( [ 'page_id' => $pageId ] )
1060 ->caller( __METHOD__ )->fetchField();
1061
1062 if ( !$pageLatest ) {
1063 $msg = 'T235589: Failed to select table row during null revision creation' .
1064 " Page id '$pageId' does not exist.";
1065 $this->logger->error(
1066 $msg,
1067 [ 'exception' => new RuntimeException( $msg ) ]
1068 );
1069
1070 return null;
1071 }
1072
1073 // Fetch the actual revision row from primary DB, without locking all extra tables.
1074 $oldRevision = $this->loadRevisionFromConds(
1075 $dbw,
1076 [ 'rev_id' => intval( $pageLatest ) ],
1077 IDBAccessObject::READ_LATEST,
1078 $page
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 = MWTimestamp::now( TS_MW );
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 replaced 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 replaced 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 primary DB
1130 *
1131 * @return null|RecentChange
1132 */
1133 public function getRecentChange( RevisionRecord $rev, $flags = 0 ) {
1134 if ( ( $flags & IDBAccessObject::READ_LATEST ) == IDBAccessObject::READ_LATEST ) {
1135 $dbType = DB_PRIMARY;
1136 } else {
1137 $dbType = DB_REPLICA;
1138 }
1139
1140 $rc = RecentChange::newFromConds(
1141 [
1142 'rc_this_oldid' => $rev->getId( $this->wikiId ),
1143 // rc_this_oldid does not have to be unique,
1144 // in particular, it is shared with categorization
1145 // changes. Prefer the original change because callers
1146 // often expect a change for patrolling.
1147 'rc_type' => [ RC_EDIT, RC_NEW, RC_LOG ],
1148 ],
1149 __METHOD__,
1150 $dbType
1151 );
1152
1153 // XXX: cache this locally? Glue it to the RevisionRecord?
1154 return $rc;
1155 }
1156
1157 /**
1158 * Loads a Content object based on a slot row.
1159 *
1160 * This method does not call $slot->getContent(), and may be used as a callback
1161 * called by $slot->getContent().
1162 *
1163 * MCR migration note: this roughly corresponded to Revision::getContentInternal
1164 *
1165 * @param SlotRecord $slot The SlotRecord to load content for
1166 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
1167 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
1168 * Use null if no processing should happen. That is in contrast to the empty string,
1169 * which causes the blob to be decoded according to the configured legacy encoding.
1170 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
1171 * @param int $queryFlags
1172 *
1173 * @throws RevisionAccessException
1174 * @return Content
1175 */
1176 private function loadSlotContent(
1177 SlotRecord $slot,
1178 ?string $blobData = null,
1179 ?string $blobFlags = null,
1180 ?string $blobFormat = null,
1181 int $queryFlags = 0
1182 ) {
1183 if ( $blobData !== null ) {
1184 $blobAddress = $slot->hasAddress() ? $slot->getAddress() : null;
1185
1186 if ( $blobFlags === null ) {
1187 // No blob flags, so use the blob verbatim.
1188 $data = $blobData;
1189 } else {
1190 try {
1191 $data = $this->blobStore->expandBlob( $blobData, $blobFlags, $blobAddress );
1192 } catch ( BadBlobException $e ) {
1193 throw new BadRevisionException( $e->getMessage(), [], 0, $e );
1194 }
1195
1196 if ( $data === false ) {
1197 throw new RevisionAccessException(
1198 'Failed to expand blob data using flags {flags} (key: {cache_key})',
1199 [
1200 'flags' => $blobFlags,
1201 'cache_key' => $blobAddress,
1202 ]
1203 );
1204 }
1205 }
1206
1207 } else {
1208 $address = $slot->getAddress();
1209 try {
1210 $data = $this->blobStore->getBlob( $address, $queryFlags );
1211 } catch ( BadBlobException $e ) {
1212 throw new BadRevisionException( $e->getMessage(), [], 0, $e );
1213 } catch ( BlobAccessException $e ) {
1214 throw new RevisionAccessException(
1215 'Failed to load data blob from {address} for revision {revision}. '
1216 . 'If this problem persist, use the findBadBlobs maintenance script '
1217 . 'to investigate the issue and mark bad blobs.',
1218 [ 'address' => $e->getMessage(), 'revision' => $slot->getRevision() ],
1219 0,
1220 $e
1221 );
1222 }
1223 }
1224
1225 $model = $slot->getModel();
1226
1227 // If the content model is not known, don't fail here (T220594, T220793, T228921)
1228 if ( !$this->contentHandlerFactory->isDefinedModel( $model ) ) {
1229 $this->logger->warning(
1230 "Undefined content model '$model', falling back to FallbackContent",
1231 [
1232 'content_address' => $slot->getAddress(),
1233 'rev_id' => $slot->getRevision(),
1234 'role_name' => $slot->getRole(),
1235 'model_name' => $model,
1236 'exception' => new RuntimeException()
1237 ]
1238 );
1239
1240 return new FallbackContent( $data, $model );
1241 }
1242
1243 return $this->contentHandlerFactory
1244 ->getContentHandler( $model )
1245 ->unserializeContent( $data, $blobFormat );
1246 }
1247
1248 /**
1249 * Load a page revision from a given revision ID number.
1250 * Returns null if no such revision can be found.
1251 *
1252 * MCR migration note: this replaced Revision::newFromId
1253 *
1254 * $flags include:
1255 * IDBAccessObject::READ_LATEST: Select the data from the primary DB
1256 * IDBAccessObject::READ_LOCKING : Select & lock the data from the primary DB
1257 *
1258 * @param int $id
1259 * @param int $flags (optional)
1260 * @param PageIdentity|null $page The page the revision belongs to.
1261 * Providing the page may improve performance.
1262 *
1263 * @return RevisionRecord|null
1264 */
1265 public function getRevisionById( $id, $flags = 0, ?PageIdentity $page = null ) {
1266 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags, $page );
1267 }
1268
1269 /**
1270 * Load either the current, or a specified, revision
1271 * that's attached to a given link target. If not attached
1272 * to that link target, will return null.
1273 *
1274 * MCR migration note: this replaced Revision::newFromTitle
1275 *
1276 * $flags include:
1277 * IDBAccessObject::READ_LATEST: Select the data from the primary DB
1278 * IDBAccessObject::READ_LOCKING : Select & lock the data from the primary DB
1279 *
1280 * @param LinkTarget|PageIdentity $page Calling with LinkTarget is deprecated since 1.36
1281 * @param int $revId (optional)
1282 * @param int $flags Bitfield (optional)
1283 * @return RevisionRecord|null
1284 */
1285 public function getRevisionByTitle( $page, $revId = 0, $flags = 0 ) {
1286 $conds = [
1287 'page_namespace' => $page->getNamespace(),
1288 'page_title' => $page->getDBkey()
1289 ];
1290
1291 if ( $page instanceof LinkTarget ) {
1292 // Only resolve LinkTarget to a Title when operating in the context of the local wiki (T248756)
1293 $page = $this->wikiId === WikiAwareEntity::LOCAL ? Title::castFromLinkTarget( $page ) : null;
1294 }
1295
1296 if ( $revId ) {
1297 // Use the specified revision ID.
1298 // Note that we use newRevisionFromConds here because we want to retry
1299 // and fall back to primary DB if the page is not found on a replica.
1300 // Since the caller supplied a revision ID, we are pretty sure the revision is
1301 // supposed to exist, so we should try hard to find it.
1302 $conds['rev_id'] = $revId;
1303 return $this->newRevisionFromConds( $conds, $flags, $page );
1304 } else {
1305 // Use a join to get the latest revision.
1306 // Note that we don't use newRevisionFromConds here because we don't want to retry
1307 // and fall back to primary DB. The assumption is that we only want to force the fallback
1308 // if we are quite sure the revision exists because the caller supplied a revision ID.
1309 // If the page isn't found at all on a replica, it probably simply does not exist.
1310 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1311 $conds[] = 'rev_id=page_latest';
1312 return $this->loadRevisionFromConds( $db, $conds, $flags, $page );
1313 }
1314 }
1315
1316 /**
1317 * Load either the current, or a specified, revision
1318 * that's attached to a given page ID.
1319 * Returns null if no such revision can be found.
1320 *
1321 * MCR migration note: this replaced Revision::newFromPageId
1322 *
1323 * $flags include:
1324 * IDBAccessObject::READ_LATEST: Select the data from the primary DB (since 1.20)
1325 * IDBAccessObject::READ_LOCKING : Select & lock the data from the primary DB
1326 *
1327 * @param int $pageId
1328 * @param int $revId (optional)
1329 * @param int $flags Bitfield (optional)
1330 * @return RevisionRecord|null
1331 */
1332 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1333 $conds = [ 'page_id' => $pageId ];
1334 if ( $revId ) {
1335 // Use the specified revision ID.
1336 // Note that we use newRevisionFromConds here because we want to retry
1337 // and fall back to primary DB if the page is not found on a replica.
1338 // Since the caller supplied a revision ID, we are pretty sure the revision is
1339 // supposed to exist, so we should try hard to find it.
1340 $conds['rev_id'] = $revId;
1341 return $this->newRevisionFromConds( $conds, $flags );
1342 } else {
1343 // Use a join to get the latest revision.
1344 // Note that we don't use newRevisionFromConds here because we don't want to retry
1345 // and fall back to primary DB. The assumption is that we only want to force the fallback
1346 // if we are quite sure the revision exists because the caller supplied a revision ID.
1347 // If the page isn't found at all on a replica, it probably simply does not exist.
1348 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1349
1350 $conds[] = 'rev_id=page_latest';
1351
1352 return $this->loadRevisionFromConds( $db, $conds, $flags );
1353 }
1354 }
1355
1356 /**
1357 * Load the revision for the given title with the given timestamp.
1358 * WARNING: Timestamps may in some circumstances not be unique,
1359 * so this isn't the best key to use.
1360 *
1361 * MCR migration note: this replaced Revision::loadFromTimestamp
1362 *
1363 * @param LinkTarget|PageIdentity $page Calling with LinkTarget is deprecated since 1.36
1364 * @param string $timestamp
1365 * @param int $flags Bitfield (optional) include:
1366 * IDBAccessObject::READ_LATEST: Select the data from the primary DB
1367 * IDBAccessObject::READ_LOCKING: Select & lock the data from the primary DB
1368 * Default: IDBAccessObject::READ_NORMAL
1369 * @return RevisionRecord|null
1370 */
1371 public function getRevisionByTimestamp(
1372 $page,
1373 string $timestamp,
1374 int $flags = IDBAccessObject::READ_NORMAL
1375 ): ?RevisionRecord {
1376 if ( $page instanceof LinkTarget ) {
1377 // Only resolve LinkTarget to a Title when operating in the context of the local wiki (T248756)
1378 $page = $this->wikiId === WikiAwareEntity::LOCAL ? Title::castFromLinkTarget( $page ) : null;
1379 }
1380 $db = $this->getDBConnectionRefForQueryFlags( $flags );
1381 return $this->newRevisionFromConds(
1382 [
1383 'rev_timestamp' => $db->timestamp( $timestamp ),
1384 'page_namespace' => $page->getNamespace(),
1385 'page_title' => $page->getDBkey()
1386 ],
1387 $flags,
1388 $page
1389 );
1390 }
1391
1392 /**
1393 * @param int $revId The revision to load slots for.
1394 * @param int $queryFlags
1395 * @param PageIdentity $page
1396 *
1397 * @return SlotRecord[]
1398 */
1399 private function loadSlotRecords( $revId, $queryFlags, PageIdentity $page ) {
1400 // TODO: Find a way to add NS_MODULE from Scribunto here
1401 if ( $page->getNamespace() !== NS_TEMPLATE ) {
1402 $res = $this->loadSlotRecordsFromDb( $revId, $queryFlags, $page );
1403 return $this->constructSlotRecords( $revId, $res, $queryFlags, $page );
1404 }
1405
1406 $ttl = MediaWikiServices::getInstance()
1407 ->getMainConfig()
1408 ->get( MainConfigNames::RevisionSlotsCacheExpiry );
1409
1410 // TODO: These caches should not be needed. See T297147#7563670
1411 $res = $this->localCache->getWithSetCallback(
1412 $this->localCache->makeKey(
1413 'revision-slots',
1414 $page->getWikiId(),
1415 $page->getId( $page->getWikiId() ),
1416 $revId
1417 ),
1418 $ttl['local'] ?? $this->localCache::TTL_UNCACHEABLE,
1419 function () use ( $revId, $queryFlags, $page, $ttl ) {
1420 return $this->cache->getWithSetCallback(
1421 $this->cache->makeKey(
1422 'revision-slots',
1423 $page->getWikiId(),
1424 $page->getId( $page->getWikiId() ),
1425 $revId
1426 ),
1427 $ttl['WAN'] ?? WANObjectCache::TTL_UNCACHEABLE,
1428 function () use ( $revId, $queryFlags, $page ) {
1429 $res = $this->loadSlotRecordsFromDb( $revId, $queryFlags, $page );
1430 if ( !$res ) {
1431 // Avoid caching
1432 return false;
1433 }
1434 return $res;
1435 }
1436 );
1437 }
1438 );
1439 if ( !$res ) {
1440 $res = [];
1441 }
1442
1443 return $this->constructSlotRecords( $revId, $res, $queryFlags, $page );
1444 }
1445
1446 private function loadSlotRecordsFromDb( $revId, $queryFlags, PageIdentity $page ): array {
1447 $revQuery = $this->getSlotsQueryInfo( [ 'content' ] );
1448
1449 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1450 $res = $db->newSelectQueryBuilder()
1451 ->queryInfo( $revQuery )
1452 ->where( [ 'slot_revision_id' => $revId ] )
1453 ->recency( $queryFlags )
1454 ->caller( __METHOD__ )->fetchResultSet();
1455
1456 if ( !$res->numRows() && !( $queryFlags & IDBAccessObject::READ_LATEST ) ) {
1457 // If we found no slots, try looking on the primary database (T212428, T252156)
1458 $this->logger->info(
1459 __METHOD__ . ' falling back to READ_LATEST.',
1460 [
1461 'revid' => $revId,
1462 'exception' => new RuntimeException(),
1463 ]
1464 );
1465 return $this->loadSlotRecordsFromDb(
1466 $revId,
1467 $queryFlags | IDBAccessObject::READ_LATEST,
1468 $page
1469 );
1470 }
1471 return iterator_to_array( $res );
1472 }
1473
1474 /**
1475 * Factory method for SlotRecords based on known slot rows.
1476 *
1477 * @param int $revId The revision to load slots for.
1478 * @param \stdClass[]|IResultWrapper $slotRows
1479 * @param int $queryFlags
1480 * @param PageIdentity $page
1481 * @param array|null $slotContents a map from blobAddress to slot
1482 * content blob or Content object.
1483 *
1484 * @return SlotRecord[]
1485 */
1486 private function constructSlotRecords(
1487 $revId,
1488 $slotRows,
1489 $queryFlags,
1490 PageIdentity $page,
1491 $slotContents = null
1492 ) {
1493 $slots = [];
1494
1495 foreach ( $slotRows as $row ) {
1496 // Resolve role names and model names from in-memory cache, if they were not joined in.
1497 if ( !isset( $row->role_name ) ) {
1498 $row->role_name = $this->slotRoleStore->getName( (int)$row->slot_role_id );
1499 }
1500
1501 if ( !isset( $row->model_name ) ) {
1502 if ( isset( $row->content_model ) ) {
1503 $row->model_name = $this->contentModelStore->getName( (int)$row->content_model );
1504 } else {
1505 // We may get here if $row->model_name is set but null, perhaps because it
1506 // came from rev_content_model, which is NULL for the default model.
1507 $slotRoleHandler = $this->slotRoleRegistry->getRoleHandler( $row->role_name );
1508 $row->model_name = $slotRoleHandler->getDefaultModel( $page );
1509 }
1510 }
1511
1512 // We may have a fake blob_data field from getSlotRowsForBatch(), use it!
1513 if ( isset( $row->blob_data ) ) {
1514 $slotContents[$row->content_address] = $row->blob_data;
1515 }
1516
1517 $contentCallback = function ( SlotRecord $slot ) use ( $slotContents, $queryFlags ) {
1518 $blob = null;
1519 if ( isset( $slotContents[$slot->getAddress()] ) ) {
1520 $blob = $slotContents[$slot->getAddress()];
1521 if ( $blob instanceof Content ) {
1522 return $blob;
1523 }
1524 }
1525 return $this->loadSlotContent( $slot, $blob, null, null, $queryFlags );
1526 };
1527
1528 $slots[$row->role_name] = new SlotRecord( $row, $contentCallback );
1529 }
1530
1531 if ( !isset( $slots[SlotRecord::MAIN] ) ) {
1532 $this->logger->error(
1533 __METHOD__ . ': Main slot of revision not found in database. See T212428.',
1534 [
1535 'revid' => $revId,
1536 'queryFlags' => $queryFlags,
1537 'exception' => new RuntimeException(),
1538 ]
1539 );
1540
1541 throw new RevisionAccessException(
1542 'Main slot of revision not found in database. See T212428.'
1543 );
1544 }
1545
1546 return $slots;
1547 }
1548
1549 /**
1550 * Factory method for RevisionSlots based on a revision ID.
1551 *
1552 * @note If other code has a need to construct RevisionSlots objects, this should be made
1553 * public, since RevisionSlots instances should not be constructed directly.
1554 *
1555 * @param int $revId
1556 * @param \stdClass[]|null $slotRows
1557 * @param int $queryFlags
1558 * @param PageIdentity $page
1559 *
1560 * @return RevisionSlots
1561 */
1562 private function newRevisionSlots(
1563 $revId,
1564 $slotRows,
1565 $queryFlags,
1566 PageIdentity $page
1567 ) {
1568 if ( $slotRows ) {
1569 $slots = new RevisionSlots(
1570 $this->constructSlotRecords( $revId, $slotRows, $queryFlags, $page )
1571 );
1572 } else {
1573 $slots = new RevisionSlots( function () use( $revId, $queryFlags, $page ) {
1574 return $this->loadSlotRecords( $revId, $queryFlags, $page );
1575 } );
1576 }
1577
1578 return $slots;
1579 }
1580
1581 /**
1582 * Make a fake RevisionRecord object from an archive table row. This is queried
1583 * for permissions or even inserted (as in Special:Undelete)
1584 *
1585 * The user ID and user name may optionally be supplied using the aliases
1586 * ar_user and ar_user_text (the names of fields which existed before
1587 * MW 1.34).
1588 *
1589 * MCR migration note: this replaced Revision::newFromArchiveRow
1590 *
1591 * @param \stdClass $row
1592 * @param int $queryFlags
1593 * @param PageIdentity|null $page
1594 * @param array $overrides associative array with fields of $row to override. This may be
1595 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1596 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1597 * override ar_parent_id.
1598 *
1599 * @return RevisionRecord
1600 */
1601 public function newRevisionFromArchiveRow(
1602 $row,
1603 $queryFlags = 0,
1604 ?PageIdentity $page = null,
1605 array $overrides = []
1606 ) {
1607 return $this->newRevisionFromArchiveRowAndSlots( $row, null, $queryFlags, $page, $overrides );
1608 }
1609
1610 /**
1611 * @see RevisionFactory::newRevisionFromRow
1612 *
1613 * MCR migration note: this replaced Revision::newFromRow
1614 *
1615 * @param \stdClass $row A database row generated from a query based on RevisionSelectQueryBuilder
1616 * @param int $queryFlags
1617 * @param PageIdentity|null $page Preloaded page object
1618 * @param bool $fromCache if true, the returned RevisionRecord will ensure that no stale
1619 * data is returned from getters, by querying the database as needed
1620 * @return RevisionRecord
1621 */
1622 public function newRevisionFromRow(
1623 $row,
1624 $queryFlags = 0,
1625 ?PageIdentity $page = null,
1626 $fromCache = false
1627 ) {
1628 return $this->newRevisionFromRowAndSlots( $row, null, $queryFlags, $page, $fromCache );
1629 }
1630
1631 /**
1632 * @see newRevisionFromArchiveRow()
1633 * @since 1.35
1634 *
1635 * @param stdClass $row
1636 * @param null|stdClass[]|RevisionSlots $slots
1637 * - Database rows generated from a query based on getSlotsQueryInfo
1638 * with the 'content' flag set. Or
1639 * - RevisionSlots instance
1640 * @param int $queryFlags
1641 * @param PageIdentity|null $page
1642 * @param array $overrides associative array with fields of $row to override. This may be
1643 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1644 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1645 * override ar_parent_id.
1646 *
1647 * @return RevisionRecord
1648 */
1649 public function newRevisionFromArchiveRowAndSlots(
1650 stdClass $row,
1651 $slots,
1652 int $queryFlags = 0,
1653 ?PageIdentity $page = null,
1654 array $overrides = []
1655 ) {
1656 if ( !$page && isset( $overrides['title'] ) ) {
1657 if ( !( $overrides['title'] instanceof PageIdentity ) ) {
1658 throw new InvalidArgumentException( 'title field override must contain a PageIdentity object.' );
1659 }
1660
1661 $page = $overrides['title'];
1662 }
1663
1664 if ( !isset( $page ) ) {
1665 if ( isset( $row->ar_namespace ) && isset( $row->ar_title ) ) {
1666 $page = Title::makeTitle( $row->ar_namespace, $row->ar_title );
1667 } else {
1668 throw new InvalidArgumentException(
1669 'A Title or ar_namespace and ar_title must be given'
1670 );
1671 }
1672 }
1673
1674 foreach ( $overrides as $key => $value ) {
1675 $field = "ar_$key";
1676 $row->$field = $value;
1677 }
1678
1679 try {
1680 $user = $this->actorStore->newActorFromRowFields(
1681 $row->ar_user ?? null,
1682 $row->ar_user_text ?? null,
1683 $row->ar_actor ?? null
1684 );
1685 } catch ( InvalidArgumentException $ex ) {
1686 $this->logger->warning( 'Could not load user for archive revision {rev_id}', [
1687 'ar_rev_id' => $row->ar_rev_id,
1688 'ar_actor' => $row->ar_actor ?? 'null',
1689 'ar_user_text' => $row->ar_user_text ?? 'null',
1690 'ar_user' => $row->ar_user ?? 'null',
1691 'exception' => $ex
1692 ] );
1693 $user = $this->actorStore->getUnknownActor();
1694 }
1695
1696 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1697 // Legacy because $row may have come from self::selectFields()
1698 $comment = $this->commentStore->getCommentLegacy( $db, 'ar_comment', $row, true );
1699
1700 if ( !( $slots instanceof RevisionSlots ) ) {
1701 $slots = $this->newRevisionSlots( (int)$row->ar_rev_id, $slots, $queryFlags, $page );
1702 }
1703 return new RevisionArchiveRecord( $page, $user, $comment, $row, $slots, $this->wikiId );
1704 }
1705
1706 /**
1707 * @see newFromRevisionRow()
1708 *
1709 * @param stdClass $row A database row generated from a query based on RevisionSelectQueryBuilder
1710 * @param null|stdClass[]|RevisionSlots $slots
1711 * - Database rows generated from a query based on getSlotsQueryInfo
1712 * with the 'content' flag set. Or
1713 * - RevisionSlots instance
1714 * @param int $queryFlags
1715 * @param PageIdentity|null $page
1716 * @param bool $fromCache if true, the returned RevisionRecord will ensure that no stale
1717 * data is returned from getters, by querying the database as needed
1718 *
1719 * @return RevisionRecord
1720 * @throws RevisionAccessException
1721 * @see RevisionFactory::newRevisionFromRow
1722 */
1723 public function newRevisionFromRowAndSlots(
1724 stdClass $row,
1725 $slots,
1726 int $queryFlags = 0,
1727 ?PageIdentity $page = null,
1728 bool $fromCache = false
1729 ) {
1730 if ( !$page ) {
1731 if ( isset( $row->page_id )
1732 && isset( $row->page_namespace )
1733 && isset( $row->page_title )
1734 ) {
1735 $page = new PageIdentityValue(
1736 (int)$row->page_id,
1737 (int)$row->page_namespace,
1738 $row->page_title,
1739 $this->wikiId
1740 );
1741
1742 $page = $this->wrapPage( $page );
1743 } else {
1744 $pageId = (int)( $row->rev_page ?? 0 );
1745 $revId = (int)( $row->rev_id ?? 0 );
1746
1747 $page = $this->getPage( $pageId, $revId, $queryFlags );
1748 }
1749 } else {
1750 $page = $this->ensureRevisionRowMatchesPage( $row, $page );
1751 }
1752
1753 if ( !$page ) {
1754 // This should already have been caught about, but apparently
1755 // it not always is, see T286877.
1756 throw new RevisionAccessException(
1757 "Failed to determine page associated with revision {$row->rev_id}"
1758 );
1759 }
1760
1761 try {
1762 $user = $this->actorStore->newActorFromRowFields(
1763 $row->rev_user ?? null,
1764 $row->rev_user_text ?? null,
1765 $row->rev_actor ?? null
1766 );
1767 } catch ( InvalidArgumentException $ex ) {
1768 $this->logger->warning( 'Could not load user for revision {rev_id}', [
1769 'rev_id' => $row->rev_id,
1770 'rev_actor' => $row->rev_actor ?? 'null',
1771 'rev_user_text' => $row->rev_user_text ?? 'null',
1772 'rev_user' => $row->rev_user ?? 'null',
1773 'exception' => $ex
1774 ] );
1775 $user = $this->actorStore->getUnknownActor();
1776 }
1777
1778 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1779 // Legacy because $row may have come from self::selectFields()
1780 $comment = $this->commentStore->getCommentLegacy( $db, 'rev_comment', $row, true );
1781
1782 if ( !( $slots instanceof RevisionSlots ) ) {
1783 $slots = $this->newRevisionSlots( (int)$row->rev_id, $slots, $queryFlags, $page );
1784 }
1785
1786 // If this is a cached row, instantiate a cache-aware RevisionRecord to avoid stale data.
1787 if ( $fromCache ) {
1788 $rev = new RevisionStoreCacheRecord(
1789 function ( $revId ) use ( $queryFlags ) {
1790 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
1791 $row = $this->fetchRevisionRowFromConds(
1792 $db,
1793 [ 'rev_id' => intval( $revId ) ]
1794 );
1795 if ( !$row && !( $queryFlags & IDBAccessObject::READ_LATEST ) ) {
1796 // If we found no slots, try looking on the primary database (T259738)
1797 $this->logger->info(
1798 'RevisionStoreCacheRecord refresh callback falling back to READ_LATEST.',
1799 [
1800 'revid' => $revId,
1801 'exception' => new RuntimeException(),
1802 ]
1803 );
1804 $dbw = $this->getDBConnectionRefForQueryFlags( IDBAccessObject::READ_LATEST );
1805 $row = $this->fetchRevisionRowFromConds(
1806 $dbw,
1807 [ 'rev_id' => intval( $revId ) ]
1808 );
1809 }
1810 if ( !$row ) {
1811 return [ null, null ];
1812 }
1813 return [
1814 $row->rev_deleted,
1815 $this->actorStore->newActorFromRowFields(
1816 $row->rev_user ?? null,
1817 $row->rev_user_text ?? null,
1818 $row->rev_actor ?? null
1819 )
1820 ];
1821 },
1822 $page, $user, $comment, $row, $slots, $this->wikiId
1823 );
1824 } else {
1825 $rev = new RevisionStoreRecord(
1826 $page, $user, $comment, $row, $slots, $this->wikiId );
1827 }
1828 return $rev;
1829 }
1830
1831 /**
1832 * Check that the given row matches the given Title object.
1833 * When a mismatch is detected, this tries to re-load the title from primary DB,
1834 * to avoid spurious errors during page moves.
1835 *
1836 * @param \stdClass $row
1837 * @param PageIdentity $page
1838 * @param array $context
1839 *
1840 * @return Pageidentity
1841 */
1842 private function ensureRevisionRowMatchesPage( $row, PageIdentity $page, $context = [] ) {
1843 $revId = (int)( $row->rev_id ?? 0 );
1844 $revPageId = (int)( $row->rev_page ?? 0 ); // XXX: also check $row->page_id?
1845 $expectedPageId = $page->getId( $this->wikiId );
1846 // Avoid fatal error when the Title's ID changed, T246720
1847 if ( $revPageId && $expectedPageId && $revPageId !== $expectedPageId ) {
1848 // NOTE: PageStore::getPageByReference may use the page ID, which we don't want here.
1849 $pageRec = $this->pageStore->getPageByName(
1850 $page->getNamespace(),
1851 $page->getDBkey(),
1852 IDBAccessObject::READ_LATEST
1853 );
1854 $masterPageId = $pageRec->getId( $this->wikiId );
1855 $masterLatest = $pageRec->getLatest( $this->wikiId );
1856 if ( $revPageId === $masterPageId ) {
1857 if ( $page instanceof Title ) {
1858 // If we were using a Title object, keep using it, but update the page ID.
1859 // This way, we don't unexpectedly mix Titles with immutable value objects.
1860 $page->resetArticleID( $masterPageId );
1861
1862 } else {
1863 $page = $pageRec;
1864 }
1865
1866 $this->logger->info(
1867 "Encountered stale Title object",
1868 [
1869 'page_id_stale' => $expectedPageId,
1870 'page_id_reloaded' => $masterPageId,
1871 'page_latest' => $masterLatest,
1872 'rev_id' => $revId,
1873 'exception' => new RuntimeException(),
1874 ] + $context
1875 );
1876 } else {
1877 $expectedTitle = (string)$page;
1878 if ( $page instanceof Title ) {
1879 // If we started with a Title, keep using a Title.
1880 $page = $this->titleFactory->newFromID( $revPageId );
1881 } else {
1882 $page = $pageRec;
1883 }
1884
1885 // This could happen if a caller to e.g. getRevisionById supplied a Title that is
1886 // plain wrong. In this case, we should ideally throw an IllegalArgumentException.
1887 // However, it is more likely that we encountered a race condition during a page
1888 // move (T268910, T279832) or database corruption (T263340). That situation
1889 // should not be ignored, but we can allow the request to continue in a reasonable
1890 // manner without breaking things for the user.
1891 $this->logger->error(
1892 "Encountered mismatching Title object (see T259022, T268910, T279832, T263340)",
1893 [
1894 'expected_page_id' => $masterPageId,
1895 'expected_page_title' => $expectedTitle,
1896 'rev_page' => $revPageId,
1897 'rev_page_title' => (string)$page,
1898 'page_latest' => $masterLatest,
1899 'rev_id' => $revId,
1900 'exception' => new RuntimeException(),
1901 ] + $context
1902 );
1903 }
1904 }
1905
1906 // @phan-suppress-next-line PhanTypeMismatchReturnNullable getPageByName/newFromID should not return null
1907 return $page;
1908 }
1909
1910 /**
1911 * Construct a RevisionRecord instance for each row in $rows,
1912 * and return them as an associative array indexed by revision ID.
1913 * Use RevisionSelectQueryBuilder or getArchiveQueryInfo() to construct the
1914 * query that produces the rows.
1915 *
1916 * @param IResultWrapper|\stdClass[] $rows the rows to construct revision records from
1917 * @param array $options Supports the following options:
1918 * 'slots' - whether metadata about revision slots should be
1919 * loaded immediately. Supports falsy or truthy value as well
1920 * as an explicit list of slot role names. The main slot will
1921 * always be loaded.
1922 * 'content' - whether the actual content of the slots should be
1923 * preloaded.
1924 * 'archive' - whether the rows where generated using getArchiveQueryInfo(),
1925 * rather than getQueryInfo.
1926 * @param int $queryFlags
1927 * @param PageIdentity|null $page The page to which all the revision rows belong, if there
1928 * is such a page and the caller has it handy, so we don't have to look it up again.
1929 * If this parameter is given and any of the rows has a rev_page_id that is different
1930 * from Article Id associated with the page, an InvalidArgumentException is thrown.
1931 *
1932 * @return StatusValue a status with a RevisionRecord[] of successfully fetched revisions
1933 * and an array of errors for the revisions failed to fetch.
1934 */
1935 public function newRevisionsFromBatch(
1936 $rows,
1937 array $options = [],
1938 $queryFlags = 0,
1939 ?PageIdentity $page = null
1940 ) {
1941 $result = new StatusValue();
1942 $archiveMode = $options['archive'] ?? false;
1943
1944 if ( $archiveMode ) {
1945 $revIdField = 'ar_rev_id';
1946 } else {
1947 $revIdField = 'rev_id';
1948 }
1949
1950 $rowsByRevId = [];
1951 $pageIdsToFetchTitles = [];
1952 $titlesByPageKey = [];
1953 foreach ( $rows as $row ) {
1954 if ( isset( $rowsByRevId[$row->$revIdField] ) ) {
1955 $result->warning(
1956 'internalerror_info',
1957 "Duplicate rows in newRevisionsFromBatch, $revIdField {$row->$revIdField}"
1958 );
1959 }
1960
1961 // Attach a page key to the row, so we can find and reuse Title objects easily.
1962 $row->_page_key =
1963 $archiveMode ? $row->ar_namespace . ':' . $row->ar_title : $row->rev_page;
1964
1965 if ( $page ) {
1966 if ( !$archiveMode && $row->rev_page != $this->getArticleId( $page ) ) {
1967 throw new InvalidArgumentException(
1968 "Revision {$row->$revIdField} doesn't belong to page "
1969 . $this->getArticleId( $page )
1970 );
1971 }
1972
1973 if ( $archiveMode
1974 && ( $row->ar_namespace != $page->getNamespace()
1975 || $row->ar_title !== $page->getDBkey() )
1976 ) {
1977 throw new InvalidArgumentException(
1978 "Revision {$row->$revIdField} doesn't belong to page "
1979 . $page
1980 );
1981 }
1982 } elseif ( !isset( $titlesByPageKey[ $row->_page_key ] ) ) {
1983 if ( isset( $row->page_namespace ) && isset( $row->page_title )
1984 // This should always be true, but just in case we don't have a page_id
1985 // set or it doesn't match rev_page, let's fetch the title again.
1986 && isset( $row->page_id ) && isset( $row->rev_page )
1987 && $row->rev_page === $row->page_id
1988 ) {
1989 $titlesByPageKey[ $row->_page_key ] = Title::newFromRow( $row );
1990 } elseif ( $archiveMode ) {
1991 // Can't look up deleted pages by ID, but we have namespace and title
1992 $titlesByPageKey[ $row->_page_key ] =
1993 Title::makeTitle( $row->ar_namespace, $row->ar_title );
1994 } else {
1995 $pageIdsToFetchTitles[] = $row->rev_page;
1996 }
1997 }
1998 $rowsByRevId[$row->$revIdField] = $row;
1999 }
2000
2001 if ( !$rowsByRevId ) {
2002 $result->setResult( true, [] );
2003 return $result;
2004 }
2005
2006 // If the page is not supplied, batch-fetch Title objects.
2007 if ( $page ) {
2008 // same logic as for $row->_page_key above
2009 $pageKey = $archiveMode
2010 ? $page->getNamespace() . ':' . $page->getDBkey()
2011 : $this->getArticleId( $page );
2012
2013 $titlesByPageKey[$pageKey] = $page;
2014 } elseif ( $pageIdsToFetchTitles ) {
2015 // Note: when we fetch titles by ID, the page key is also the ID.
2016 // We should never get here if $archiveMode is true.
2017 Assert::invariant( !$archiveMode, 'Titles are not loaded by ID in archive mode.' );
2018
2019 $pageIdsToFetchTitles = array_unique( $pageIdsToFetchTitles );
2020 $pageRecords = $this->pageStore
2021 ->newSelectQueryBuilder()
2022 ->wherePageIds( $pageIdsToFetchTitles )
2023 ->caller( __METHOD__ )
2024 ->fetchPageRecordArray();
2025 // Cannot array_merge because it re-indexes entries
2026 $titlesByPageKey = $pageRecords + $titlesByPageKey;
2027 }
2028
2029 // which method to use for creating RevisionRecords
2030 $newRevisionRecord = $archiveMode
2031 ? [ $this, 'newRevisionFromArchiveRowAndSlots' ]
2032 : [ $this, 'newRevisionFromRowAndSlots' ];
2033
2034 if ( !isset( $options['slots'] ) ) {
2035 $result->setResult(
2036 true,
2037 array_map(
2038 static function ( $row )
2039 use ( $queryFlags, $titlesByPageKey, $result, $newRevisionRecord, $revIdField ) {
2040 try {
2041 if ( !isset( $titlesByPageKey[$row->_page_key] ) ) {
2042 $result->warning(
2043 'internalerror_info',
2044 "Couldn't find title for rev {$row->$revIdField} "
2045 . "(page key {$row->_page_key})"
2046 );
2047 return null;
2048 }
2049 return $newRevisionRecord( $row, null, $queryFlags,
2050 $titlesByPageKey[ $row->_page_key ] );
2051 } catch ( MWException $e ) {
2052 $result->warning( 'internalerror_info', $e->getMessage() );
2053 return null;
2054 }
2055 },
2056 $rowsByRevId
2057 )
2058 );
2059 return $result;
2060 }
2061
2062 $slotRowOptions = [
2063 'slots' => $options['slots'] ?? true,
2064 'blobs' => $options['content'] ?? false,
2065 ];
2066
2067 if ( is_array( $slotRowOptions['slots'] )
2068 && !in_array( SlotRecord::MAIN, $slotRowOptions['slots'] )
2069 ) {
2070 // Make sure the main slot is always loaded, RevisionRecord requires this.
2071 $slotRowOptions['slots'][] = SlotRecord::MAIN;
2072 }
2073
2074 $slotRowsStatus = $this->getSlotRowsForBatch( $rowsByRevId, $slotRowOptions, $queryFlags );
2075
2076 $result->merge( $slotRowsStatus );
2077 $slotRowsByRevId = $slotRowsStatus->getValue();
2078
2079 $result->setResult(
2080 true,
2081 array_map(
2082 function ( $row )
2083 use ( $slotRowsByRevId, $queryFlags, $titlesByPageKey, $result,
2084 $revIdField, $newRevisionRecord
2085 ) {
2086 if ( !isset( $slotRowsByRevId[$row->$revIdField] ) ) {
2087 $result->warning(
2088 'internalerror_info',
2089 "Couldn't find slots for rev {$row->$revIdField}"
2090 );
2091 return null;
2092 }
2093 if ( !isset( $titlesByPageKey[$row->_page_key] ) ) {
2094 $result->warning(
2095 'internalerror_info',
2096 "Couldn't find title for rev {$row->$revIdField} "
2097 . "(page key {$row->_page_key})"
2098 );
2099 return null;
2100 }
2101 try {
2102 return $newRevisionRecord(
2103 $row,
2104 new RevisionSlots(
2105 $this->constructSlotRecords(
2106 $row->$revIdField,
2107 $slotRowsByRevId[$row->$revIdField],
2108 $queryFlags,
2109 $titlesByPageKey[$row->_page_key]
2110 )
2111 ),
2112 $queryFlags,
2113 $titlesByPageKey[$row->_page_key]
2114 );
2115 } catch ( MWException $e ) {
2116 $result->warning( 'internalerror_info', $e->getMessage() );
2117 return null;
2118 }
2119 },
2120 $rowsByRevId
2121 )
2122 );
2123 return $result;
2124 }
2125
2126 /**
2127 * Gets the slot rows associated with a batch of revisions.
2128 * The serialized content of each slot can be included by setting the 'blobs' option.
2129 * Callers are responsible for unserializing and interpreting the content blobs
2130 * based on the model_name and role_name fields.
2131 *
2132 * @param Traversable|array $rowsOrIds list of revision ids, or revision or archive rows
2133 * from a db query.
2134 * @param array $options Supports the following options:
2135 * 'slots' - a list of slot role names to fetch. If omitted or true or null,
2136 * all slots are fetched
2137 * 'blobs' - whether the serialized content of each slot should be loaded.
2138 * If true, the serialized content will be present in the slot row
2139 * in the blob_data field.
2140 * @param int $queryFlags
2141 *
2142 * @return StatusValue a status containing, if isOK() returns true, a two-level nested
2143 * associative array, mapping from revision ID to an associative array that maps from
2144 * role name to a database row object. The database row object will contain the fields
2145 * defined by getSlotQueryInfo() with the 'content' flag set, plus the blob_data field
2146 * if the 'blobs' is set in $options. The model_name and role_name fields will also be
2147 * set.
2148 */
2149 private function getSlotRowsForBatch(
2150 $rowsOrIds,
2151 array $options = [],
2152 $queryFlags = 0
2153 ) {
2154 $result = new StatusValue();
2155
2156 $revIds = [];
2157 foreach ( $rowsOrIds as $row ) {
2158 if ( is_object( $row ) ) {
2159 $revIds[] = isset( $row->ar_rev_id ) ? (int)$row->ar_rev_id : (int)$row->rev_id;
2160 } else {
2161 $revIds[] = (int)$row;
2162 }
2163 }
2164
2165 // Nothing to do.
2166 // Note that $rowsOrIds may not be "empty" even if $revIds is, e.g. if it's a ResultWrapper.
2167 if ( !$revIds ) {
2168 $result->setResult( true, [] );
2169 return $result;
2170 }
2171
2172 // We need to set the `content` flag to join in content meta-data
2173 $slotQueryInfo = $this->getSlotsQueryInfo( [ 'content' ] );
2174 $revIdField = $slotQueryInfo['keys']['rev_id'];
2175 $slotQueryConds = [ $revIdField => $revIds ];
2176
2177 if ( isset( $options['slots'] ) && is_array( $options['slots'] ) ) {
2178 $slotIds = [];
2179 foreach ( $options['slots'] as $slot ) {
2180 try {
2181 $slotIds[] = $this->slotRoleStore->getId( $slot );
2182 } catch ( NameTableAccessException $exception ) {
2183 // Do not fail when slot has no id (unused slot)
2184 // This also means for this slot are never data in the database
2185 }
2186 }
2187 if ( $slotIds === [] ) {
2188 // Degenerate case: return no slots for each revision.
2189 $result->setResult( true, array_fill_keys( $revIds, [] ) );
2190 return $result;
2191 }
2192
2193 $roleIdField = $slotQueryInfo['keys']['role_id'];
2194 $slotQueryConds[$roleIdField] = $slotIds;
2195 }
2196
2197 $db = $this->getDBConnectionRefForQueryFlags( $queryFlags );
2198 $slotRows = $db->newSelectQueryBuilder()
2199 ->queryInfo( $slotQueryInfo )
2200 ->where( $slotQueryConds )
2201 ->caller( __METHOD__ )
2202 ->fetchResultSet();
2203
2204 $slotContents = null;
2205 if ( $options['blobs'] ?? false ) {
2206 $blobAddresses = [];
2207 foreach ( $slotRows as $slotRow ) {
2208 $blobAddresses[] = $slotRow->content_address;
2209 }
2210 $slotContentFetchStatus = $this->blobStore
2211 ->getBlobBatch( $blobAddresses, $queryFlags );
2212 foreach ( $slotContentFetchStatus->getMessages() as $msg ) {
2213 $result->warning( $msg );
2214 }
2215 $slotContents = $slotContentFetchStatus->getValue();
2216 }
2217
2218 $slotRowsByRevId = [];
2219 foreach ( $slotRows as $slotRow ) {
2220 if ( $slotContents === null ) {
2221 // nothing to do
2222 } elseif ( isset( $slotContents[$slotRow->content_address] ) ) {
2223 $slotRow->blob_data = $slotContents[$slotRow->content_address];
2224 } else {
2225 $result->warning(
2226 'internalerror_info',
2227 "Couldn't find blob data for rev {$slotRow->slot_revision_id}"
2228 );
2229 $slotRow->blob_data = null;
2230 }
2231
2232 // conditional needed for SCHEMA_COMPAT_READ_OLD
2233 if ( !isset( $slotRow->role_name ) && isset( $slotRow->slot_role_id ) ) {
2234 $slotRow->role_name = $this->slotRoleStore->getName( (int)$slotRow->slot_role_id );
2235 }
2236
2237 // conditional needed for SCHEMA_COMPAT_READ_OLD
2238 if ( !isset( $slotRow->model_name ) && isset( $slotRow->content_model ) ) {
2239 $slotRow->model_name = $this->contentModelStore->getName( (int)$slotRow->content_model );
2240 }
2241
2242 $slotRowsByRevId[$slotRow->slot_revision_id][$slotRow->role_name] = $slotRow;
2243 }
2244
2245 $result->setResult( true, $slotRowsByRevId );
2246 return $result;
2247 }
2248
2249 /**
2250 * Gets raw (serialized) content blobs for the given set of revisions.
2251 * Callers are responsible for unserializing and interpreting the content blobs
2252 * based on the model_name field and the slot role.
2253 *
2254 * This method is intended for bulk operations in maintenance scripts.
2255 * It may be chosen over newRevisionsFromBatch by code that are only interested
2256 * in raw content, as opposed to meta data. Code that needs to access meta data of revisions,
2257 * slots, or content objects should use newRevisionsFromBatch() instead.
2258 *
2259 * @param Traversable|array $rowsOrIds list of revision ids, or revision rows from a db query.
2260 * @param array|null $slots the role names for which to get slots.
2261 * @param int $queryFlags
2262 *
2263 * @return StatusValue a status containing, if isOK() returns true, a two-level nested
2264 * associative array, mapping from revision ID to an associative array that maps from
2265 * role name to an anonymous object containing two fields:
2266 * - model_name: the name of the content's model
2267 * - blob_data: serialized content data
2268 */
2269 public function getContentBlobsForBatch(
2270 $rowsOrIds,
2271 $slots = null,
2272 $queryFlags = 0
2273 ) {
2274 $result = $this->getSlotRowsForBatch(
2275 $rowsOrIds,
2276 [ 'slots' => $slots, 'blobs' => true ],
2277 $queryFlags
2278 );
2279
2280 if ( $result->isOK() ) {
2281 // strip out all internal meta data that we don't want to expose
2282 foreach ( $result->value as $revId => $rowsByRole ) {
2283 foreach ( $rowsByRole as $role => $slotRow ) {
2284 if ( is_array( $slots ) && !in_array( $role, $slots ) ) {
2285 // In SCHEMA_COMPAT_READ_OLD mode we may get the main slot even
2286 // if we didn't ask for it.
2287 unset( $result->value[$revId][$role] );
2288 continue;
2289 }
2290
2291 $result->value[$revId][$role] = (object)[
2292 'blob_data' => $slotRow->blob_data,
2293 'model_name' => $slotRow->model_name,
2294 ];
2295 }
2296 }
2297 }
2298
2299 return $result;
2300 }
2301
2302 /**
2303 * Given a set of conditions, fetch a revision
2304 *
2305 * This method should be used if we are pretty sure the revision exists.
2306 * Unless $flags has READ_LATEST set, this method will first try to find the revision
2307 * on a replica before hitting the primary database.
2308 *
2309 * MCR migration note: this corresponded to Revision::newFromConds
2310 *
2311 * @param array $conditions
2312 * @param int $flags (optional)
2313 * @param PageIdentity|null $page (optional)
2314 * @param array $options (optional) additional query options
2315 *
2316 * @return RevisionRecord|null
2317 */
2318 private function newRevisionFromConds(
2319 array $conditions,
2320 int $flags = IDBAccessObject::READ_NORMAL,
2321 ?PageIdentity $page = null,
2322 array $options = []
2323 ) {
2324 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2325 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $page, $options );
2326
2327 // Make sure new pending/committed revision are visible later on
2328 // within web requests to certain avoid bugs like T93866 and T94407.
2329 if ( !$rev
2330 && !( $flags & IDBAccessObject::READ_LATEST )
2331 && $this->loadBalancer->hasStreamingReplicaServers()
2332 && $this->loadBalancer->hasOrMadeRecentPrimaryChanges()
2333 ) {
2334 $flags = IDBAccessObject::READ_LATEST;
2335 $dbw = $this->getPrimaryConnection();
2336 $rev = $this->loadRevisionFromConds( $dbw, $conditions, $flags, $page, $options );
2337 }
2338
2339 return $rev;
2340 }
2341
2342 /**
2343 * Given a set of conditions, fetch a revision from
2344 * the given database connection.
2345 *
2346 * MCR migration note: this corresponded to Revision::loadFromConds
2347 *
2348 * @param IReadableDatabase $db
2349 * @param array $conditions
2350 * @param int $flags (optional)
2351 * @param PageIdentity|null $page (optional) additional query options
2352 * @param array $options (optional) additional query options
2353 *
2354 * @return RevisionRecord|null
2355 */
2356 private function loadRevisionFromConds(
2357 IReadableDatabase $db,
2358 array $conditions,
2359 int $flags = IDBAccessObject::READ_NORMAL,
2360 ?PageIdentity $page = null,
2361 array $options = []
2362 ) {
2363 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags, $options );
2364 if ( $row ) {
2365 return $this->newRevisionFromRow( $row, $flags, $page );
2366 }
2367
2368 return null;
2369 }
2370
2371 /**
2372 * Throws an exception if the given database connection does not belong to the wiki this
2373 * RevisionStore is bound to.
2374 *
2375 * @param IReadableDatabase $db
2376 */
2377 private function checkDatabaseDomain( IReadableDatabase $db ) {
2378 $dbDomain = $db->getDomainID();
2379 $storeDomain = $this->loadBalancer->resolveDomainID( $this->wikiId );
2380 if ( $dbDomain === $storeDomain ) {
2381 return;
2382 }
2383
2384 throw new RuntimeException( "DB connection domain '$dbDomain' does not match '$storeDomain'" );
2385 }
2386
2387 /**
2388 * Given a set of conditions, return a row with the
2389 * fields necessary to build RevisionRecord objects.
2390 *
2391 * MCR migration note: this corresponded to Revision::fetchFromConds
2392 *
2393 * @param IReadableDatabase $db
2394 * @param array $conditions
2395 * @param int $flags (optional)
2396 * @param array $options (optional) additional query options
2397 *
2398 * @return \stdClass|false data row as a raw object
2399 */
2400 private function fetchRevisionRowFromConds(
2401 IReadableDatabase $db,
2402 array $conditions,
2403 int $flags = IDBAccessObject::READ_NORMAL,
2404 array $options = []
2405 ) {
2406 $this->checkDatabaseDomain( $db );
2407
2408 $queryBuilder = $this->newSelectQueryBuilder( $db )
2409 ->joinComment()
2410 ->joinPage()
2411 ->joinUser()
2412 ->where( $conditions )
2413 ->options( $options );
2414 if ( ( $flags & IDBAccessObject::READ_LOCKING ) == IDBAccessObject::READ_LOCKING ) {
2415 $queryBuilder->forUpdate();
2416 }
2417 return $queryBuilder->caller( __METHOD__ )->fetchRow();
2418 }
2419
2420 /**
2421 * Return the tables, fields, and join conditions to be selected to create
2422 * a new RevisionStoreRecord object.
2423 *
2424 * MCR migration note: this replaced Revision::getQueryInfo
2425 *
2426 * If the format of fields returned changes in any way then the cache key provided by
2427 * self::getRevisionRowCacheKey should be updated.
2428 *
2429 * @since 1.31
2430 * @deprecated since 1.41 use RevisionStore::newSelectQueryBuilder() instead.
2431 *
2432 * @param array $options Any combination of the following strings
2433 * - 'page': Join with the page table, and select fields to identify the page
2434 * - 'user': Join with the user table, and select the user name
2435 *
2436 * @return array[] With three keys:
2437 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
2438 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
2439 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
2440 * @phan-return array{tables:string[],fields:string[],joins:array}
2441 */
2442 public function getQueryInfo( $options = [] ) {
2443 $ret = [
2444 'tables' => [],
2445 'fields' => [],
2446 'joins' => [],
2447 ];
2448
2449 $ret['tables'] = array_merge( $ret['tables'], [
2450 'revision',
2451 'actor_rev_user' => 'actor',
2452 ] );
2453 $ret['fields'] = array_merge( $ret['fields'], [
2454 'rev_id',
2455 'rev_page',
2456 'rev_actor' => 'rev_actor',
2457 'rev_user' => 'actor_rev_user.actor_user',
2458 'rev_user_text' => 'actor_rev_user.actor_name',
2459 'rev_timestamp',
2460 'rev_minor_edit',
2461 'rev_deleted',
2462 'rev_len',
2463 'rev_parent_id',
2464 'rev_sha1',
2465 ] );
2466 $ret['joins']['actor_rev_user'] = [ 'JOIN', "actor_rev_user.actor_id = rev_actor" ];
2467
2468 $commentQuery = $this->commentStore->getJoin( 'rev_comment' );
2469 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
2470 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
2471 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
2472
2473 if ( in_array( 'page', $options, true ) ) {
2474 $ret['tables'][] = 'page';
2475 $ret['fields'] = array_merge( $ret['fields'], [
2476 'page_namespace',
2477 'page_title',
2478 'page_id',
2479 'page_latest',
2480 'page_is_redirect',
2481 'page_len',
2482 ] );
2483 $ret['joins']['page'] = [ 'JOIN', [ 'page_id = rev_page' ] ];
2484 }
2485
2486 if ( in_array( 'user', $options, true ) ) {
2487 $ret['tables'][] = 'user';
2488 $ret['fields'] = array_merge( $ret['fields'], [
2489 'user_name',
2490 ] );
2491 $ret['joins']['user'] = [
2492 'LEFT JOIN',
2493 [ 'actor_rev_user.actor_user != 0', 'user_id = actor_rev_user.actor_user' ]
2494 ];
2495 }
2496
2497 if ( in_array( 'text', $options, true ) ) {
2498 throw new InvalidArgumentException(
2499 'The `text` option is no longer supported in MediaWiki 1.35 and later.'
2500 );
2501 }
2502
2503 return $ret;
2504 }
2505
2506 /**
2507 * @inheritDoc
2508 */
2509 public function newSelectQueryBuilder( IReadableDatabase $dbr ): RevisionSelectQueryBuilder {
2510 return new RevisionSelectQueryBuilder( $dbr );
2511 }
2512
2513 /**
2514 * @inheritDoc
2515 */
2516 public function newArchiveSelectQueryBuilder( IReadableDatabase $dbr ): ArchiveSelectQueryBuilder {
2517 return new ArchiveSelectQueryBuilder( $dbr );
2518 }
2519
2520 /**
2521 * Return the tables, fields, and join conditions to be selected to create
2522 * a new SlotRecord.
2523 *
2524 * @since 1.32
2525 *
2526 * @param array $options Any combination of the following strings
2527 * - 'content': Join with the content table, and select content meta-data fields
2528 * - 'model': Join with the content_models table, and select the model_name field.
2529 * Only applicable if 'content' is also set.
2530 * - 'role': Join with the slot_roles table, and select the role_name field
2531 *
2532 * @return array[] With three keys:
2533 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
2534 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
2535 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
2536 * - keys: (associative array) to look up fields to match against.
2537 * In particular, the field that can be used to find slots by rev_id
2538 * can be found in ['keys']['rev_id'].
2539 * @phan-return array{tables:string[],fields:string[],joins:array,keys:array}
2540 */
2541 public function getSlotsQueryInfo( $options = [] ) {
2542 $ret = [
2543 'tables' => [],
2544 'fields' => [],
2545 'joins' => [],
2546 'keys' => [],
2547 ];
2548
2549 $ret['keys']['rev_id'] = 'slot_revision_id';
2550 $ret['keys']['role_id'] = 'slot_role_id';
2551
2552 $ret['tables'][] = 'slots';
2553 $ret['fields'] = array_merge( $ret['fields'], [
2554 'slot_revision_id',
2555 'slot_content_id',
2556 'slot_origin',
2557 'slot_role_id',
2558 ] );
2559
2560 if ( in_array( 'role', $options, true ) ) {
2561 // Use left join to attach role name, so we still find the revision row even
2562 // if the role name is missing. This triggers a more obvious failure mode.
2563 $ret['tables'][] = 'slot_roles';
2564 $ret['joins']['slot_roles'] = [ 'LEFT JOIN', [ 'slot_role_id = role_id' ] ];
2565 $ret['fields'][] = 'role_name';
2566 }
2567
2568 if ( in_array( 'content', $options, true ) ) {
2569 $ret['keys']['model_id'] = 'content_model';
2570
2571 $ret['tables'][] = 'content';
2572 $ret['fields'] = array_merge( $ret['fields'], [
2573 'content_size',
2574 'content_sha1',
2575 'content_address',
2576 'content_model',
2577 ] );
2578 $ret['joins']['content'] = [ 'JOIN', [ 'slot_content_id = content_id' ] ];
2579
2580 if ( in_array( 'model', $options, true ) ) {
2581 // Use left join to attach model name, so we still find the revision row even
2582 // if the model name is missing. This triggers a more obvious failure mode.
2583 $ret['tables'][] = 'content_models';
2584 $ret['joins']['content_models'] = [ 'LEFT JOIN', [ 'content_model = model_id' ] ];
2585 $ret['fields'][] = 'model_name';
2586 }
2587
2588 }
2589
2590 return $ret;
2591 }
2592
2593 /**
2594 * Determine whether the parameter is a row containing all the fields
2595 * that RevisionStore needs to create a RevisionRecord from the row.
2596 *
2597 * @param mixed $row
2598 * @param string $table 'archive' or empty
2599 * @return bool
2600 */
2601 public function isRevisionRow( $row, string $table = '' ) {
2602 if ( !( $row instanceof stdClass ) ) {
2603 return false;
2604 }
2605 $queryInfo = $table === 'archive' ? $this->getArchiveQueryInfo() : $this->getQueryInfo();
2606 foreach ( $queryInfo['fields'] as $alias => $field ) {
2607 $name = is_numeric( $alias ) ? $field : $alias;
2608 if ( !property_exists( $row, $name ) ) {
2609 return false;
2610 }
2611 }
2612 return true;
2613 }
2614
2615 /**
2616 * Return the tables, fields, and join conditions to be selected to create
2617 * a new RevisionArchiveRecord object.
2618 *
2619 * Since 1.34, ar_user and ar_user_text have not been present in the
2620 * database, but they continue to be available in query results as
2621 * aliases.
2622 *
2623 * MCR migration note: this replaced Revision::getArchiveQueryInfo
2624 *
2625 * @since 1.31
2626 * @deprecated since 1.41 use RevisionStore::newArchiveSelectQueryBuilder() instead.
2627 *
2628 * @return array[] With three keys:
2629 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
2630 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
2631 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
2632 * @phan-return array{tables:string[],fields:string[],joins:array}
2633 */
2634 public function getArchiveQueryInfo() {
2635 $commentQuery = $this->commentStore->getJoin( 'ar_comment' );
2636 $ret = [
2637 'tables' => [
2638 'archive',
2639 'archive_actor' => 'actor'
2640 ] + $commentQuery['tables'],
2641 'fields' => [
2642 'ar_id',
2643 'ar_page_id',
2644 'ar_namespace',
2645 'ar_title',
2646 'ar_rev_id',
2647 'ar_timestamp',
2648 'ar_minor_edit',
2649 'ar_deleted',
2650 'ar_len',
2651 'ar_parent_id',
2652 'ar_sha1',
2653 'ar_actor',
2654 'ar_user' => 'archive_actor.actor_user',
2655 'ar_user_text' => 'archive_actor.actor_name',
2656 ] + $commentQuery['fields'],
2657 'joins' => [
2658 'archive_actor' => [ 'JOIN', 'actor_id=ar_actor' ]
2659 ] + $commentQuery['joins'],
2660 ];
2661
2662 return $ret;
2663 }
2664
2665 /**
2666 * Do a batched query for the sizes of a set of revisions.
2667 *
2668 * MCR migration note: this replaced Revision::getParentLengths
2669 *
2670 * @param int[] $revIds
2671 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
2672 * of the corresponding revision.
2673 */
2674 public function getRevisionSizes( array $revIds ) {
2675 $dbr = $this->getReplicaConnection();
2676 $revLens = [];
2677 if ( !$revIds ) {
2678 return $revLens; // empty
2679 }
2680
2681 $res = $dbr->newSelectQueryBuilder()
2682 ->select( [ 'rev_id', 'rev_len' ] )
2683 ->from( 'revision' )
2684 ->where( [ 'rev_id' => $revIds ] )
2685 ->caller( __METHOD__ )->fetchResultSet();
2686
2687 foreach ( $res as $row ) {
2688 $revLens[$row->rev_id] = intval( $row->rev_len );
2689 }
2690
2691 return $revLens;
2692 }
2693
2694 /**
2695 * Implementation of getPreviousRevision and getNextRevision.
2696 *
2697 * @param RevisionRecord $rev
2698 * @param int $flags
2699 * @param string $dir 'next' or 'prev'
2700 * @return RevisionRecord|null
2701 */
2702 private function getRelativeRevision( RevisionRecord $rev, $flags, $dir ) {
2703 $op = $dir === 'next' ? '>' : '<';
2704 $sort = $dir === 'next' ? 'ASC' : 'DESC';
2705
2706 $revisionIdValue = $rev->getId( $this->wikiId );
2707
2708 if ( !$revisionIdValue || !$rev->getPageId( $this->wikiId ) ) {
2709 // revision is unsaved or otherwise incomplete
2710 return null;
2711 }
2712
2713 if ( $rev instanceof RevisionArchiveRecord ) {
2714 // revision is deleted, so it's not part of the page history
2715 return null;
2716 }
2717
2718 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2719
2720 $ts = $rev->getTimestamp() ?? $this->getTimestampFromId( $revisionIdValue, $flags );
2721 if ( $ts === false ) {
2722 // XXX Should this be moved into getTimestampFromId?
2723 $ts = $db->newSelectQueryBuilder()
2724 ->select( 'ar_timestamp' )
2725 ->from( 'archive' )
2726 ->where( [ 'ar_rev_id' => $revisionIdValue ] )
2727 ->caller( __METHOD__ )->fetchField();
2728 if ( $ts === false ) {
2729 // XXX Is this reachable? How can we have a page id but no timestamp?
2730 return null;
2731 }
2732 }
2733
2734 $revId = $db->newSelectQueryBuilder()
2735 ->select( 'rev_id' )
2736 ->from( 'revision' )
2737 ->where( [
2738 'rev_page' => $rev->getPageId( $this->wikiId ),
2739 $db->buildComparison( $op, [
2740 'rev_timestamp' => $db->timestamp( $ts ),
2741 'rev_id' => $revisionIdValue,
2742 ] ),
2743 ] )
2744 ->orderBy( [ 'rev_timestamp', 'rev_id' ], $sort )
2745 ->ignoreIndex( 'rev_timestamp' ) // Probably needed for T159319
2746 ->caller( __METHOD__ )
2747 ->fetchField();
2748
2749 if ( $revId === false ) {
2750 return null;
2751 }
2752
2753 return $this->getRevisionById( intval( $revId ), $flags );
2754 }
2755
2756 /**
2757 * Get the revision before $rev in the page's history, if any.
2758 * Will return null for the first revision but also for deleted or unsaved revisions.
2759 *
2760 * MCR migration note: this replaced Revision::getPrevious
2761 *
2762 * @see PageArchive::getPreviousRevisionRecord
2763 *
2764 * @param RevisionRecord $rev
2765 * @param int $flags (optional) $flags include:
2766 * IDBAccessObject::READ_LATEST: Select the data from the primary DB
2767 *
2768 * @return RevisionRecord|null
2769 */
2770 public function getPreviousRevision( RevisionRecord $rev, $flags = IDBAccessObject::READ_NORMAL ) {
2771 return $this->getRelativeRevision( $rev, $flags, 'prev' );
2772 }
2773
2774 /**
2775 * Get the revision after $rev in the page's history, if any.
2776 * Will return null for the latest revision but also for deleted or unsaved revisions.
2777 *
2778 * MCR migration note: this replaced Revision::getNext
2779 *
2780 * @param RevisionRecord $rev
2781 * @param int $flags (optional) $flags include:
2782 * IDBAccessObject::READ_LATEST: Select the data from the primary DB
2783 * @return RevisionRecord|null
2784 */
2785 public function getNextRevision( RevisionRecord $rev, $flags = IDBAccessObject::READ_NORMAL ) {
2786 return $this->getRelativeRevision( $rev, $flags, 'next' );
2787 }
2788
2789 /**
2790 * Get previous revision Id for this page_id
2791 * This is used to populate rev_parent_id on save
2792 *
2793 * MCR migration note: this corresponded to Revision::getPreviousRevisionId
2794 *
2795 * @param IReadableDatabase $db
2796 * @param RevisionRecord $rev
2797 *
2798 * @return int
2799 */
2800 private function getPreviousRevisionId( IReadableDatabase $db, RevisionRecord $rev ) {
2801 $this->checkDatabaseDomain( $db );
2802
2803 if ( $rev->getPageId( $this->wikiId ) === null ) {
2804 return 0;
2805 }
2806 # Use page_latest if ID is not given
2807 if ( !$rev->getId( $this->wikiId ) ) {
2808 $prevId = $db->newSelectQueryBuilder()
2809 ->select( 'page_latest' )
2810 ->from( 'page' )
2811 ->where( [ 'page_id' => $rev->getPageId( $this->wikiId ) ] )
2812 ->caller( __METHOD__ )->fetchField();
2813 } else {
2814 $prevId = $db->newSelectQueryBuilder()
2815 ->select( 'rev_id' )
2816 ->from( 'revision' )
2817 ->where( [ 'rev_page' => $rev->getPageId( $this->wikiId ) ] )
2818 ->andWhere( $db->expr( 'rev_id', '<', $rev->getId( $this->wikiId ) ) )
2819 ->orderBy( 'rev_id DESC' )
2820 ->caller( __METHOD__ )->fetchField();
2821 }
2822 return intval( $prevId );
2823 }
2824
2825 /**
2826 * Get rev_timestamp from rev_id, without loading the rest of the row.
2827 *
2828 * Historically, there was an extra Title parameter that was passed before $id. This is no
2829 * longer needed and is deprecated in 1.34.
2830 *
2831 * MCR migration note: this replaced Revision::getTimestampFromId
2832 *
2833 * @param int $id
2834 * @param int $flags
2835 * @return string|false False if not found
2836 */
2837 public function getTimestampFromId( $id, $flags = 0 ) {
2838 if ( $id instanceof Title ) {
2839 // Old deprecated calling convention supported for backwards compatibility
2840 $id = $flags;
2841 $flags = func_num_args() > 2 ? func_get_arg( 2 ) : 0;
2842 }
2843
2844 // T270149: Bail out if we know the query will definitely return false. Some callers are
2845 // passing RevisionRecord::getId() call directly as $id which can possibly return null.
2846 // Null $id or $id <= 0 will lead to useless query with WHERE clause of 'rev_id IS NULL'
2847 // or 'rev_id = 0', but 'rev_id' is always greater than zero and cannot be null.
2848 // @todo typehint $id and remove the null check
2849 if ( $id === null || $id <= 0 ) {
2850 return false;
2851 }
2852
2853 $db = $this->getDBConnectionRefForQueryFlags( $flags );
2854
2855 $timestamp =
2856 $db->newSelectQueryBuilder()
2857 ->select( 'rev_timestamp' )
2858 ->from( 'revision' )
2859 ->where( [ 'rev_id' => $id ] )
2860 ->caller( __METHOD__ )->fetchField();
2861
2862 return ( $timestamp !== false ) ? MWTimestamp::convert( TS_MW, $timestamp ) : false;
2863 }
2864
2865 /**
2866 * Get count of revisions per page...not very efficient
2867 *
2868 * MCR migration note: this replaced Revision::countByPageId
2869 *
2870 * @param IReadableDatabase $db
2871 * @param int $id Page id
2872 * @return int
2873 */
2874 public function countRevisionsByPageId( IReadableDatabase $db, $id ) {
2875 $this->checkDatabaseDomain( $db );
2876
2877 $row = $db->newSelectQueryBuilder()
2878 ->select( [ 'revCount' => 'COUNT(*)' ] )
2879 ->from( 'revision' )
2880 ->where( [ 'rev_page' => $id ] )
2881 ->caller( __METHOD__ )->fetchRow();
2882 if ( $row ) {
2883 return intval( $row->revCount );
2884 }
2885 return 0;
2886 }
2887
2888 /**
2889 * Get count of revisions per page...not very efficient
2890 *
2891 * MCR migration note: this replaced Revision::countByTitle
2892 *
2893 * @param IReadableDatabase $db
2894 * @param PageIdentity $page
2895 * @return int
2896 */
2897 public function countRevisionsByTitle( IReadableDatabase $db, PageIdentity $page ) {
2898 $id = $this->getArticleId( $page );
2899 if ( $id ) {
2900 return $this->countRevisionsByPageId( $db, $id );
2901 }
2902 return 0;
2903 }
2904
2905 /**
2906 * Check if no edits were made by other users since
2907 * the time a user started editing the page. Limit to
2908 * 50 revisions for the sake of performance.
2909 *
2910 * MCR migration note: this replaced Revision::userWasLastToEdit
2911 *
2912 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
2913 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
2914 * had been deprecated since 1.24 (the Revision class was removed entirely in 1.37).
2915 *
2916 * @param IReadableDatabase $db The Database to perform the check on.
2917 * @param int $pageId The ID of the page in question
2918 * @param int $userId The ID of the user in question
2919 * @param string $since Look at edits since this time
2920 *
2921 * @return bool True if the given user was the only one to edit since the given timestamp
2922 */
2923 public function userWasLastToEdit( IReadableDatabase $db, $pageId, $userId, $since ) {
2924 $this->checkDatabaseDomain( $db );
2925
2926 if ( !$userId ) {
2927 return false;
2928 }
2929
2930 $queryBuilder = $this->newSelectQueryBuilder( $db )
2931 ->where( [
2932 'rev_page' => $pageId,
2933 $db->expr( 'rev_timestamp', '>', $db->timestamp( $since ) )
2934 ] )
2935 ->orderBy( 'rev_timestamp', SelectQueryBuilder::SORT_ASC )
2936 ->limit( 50 );
2937 $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
2938 foreach ( $res as $row ) {
2939 if ( $row->rev_user != $userId ) {
2940 return false;
2941 }
2942 }
2943 return true;
2944 }
2945
2946 /**
2947 * Load a revision based on a known page ID and current revision ID from the DB
2948 *
2949 * This method allows for the use of caching, though accessing anything that normally
2950 * requires permission checks (aside from the text) will trigger a small DB lookup.
2951 *
2952 * MCR migration note: this replaced Revision::newKnownCurrent
2953 *
2954 * @param PageIdentity $page the associated page
2955 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
2956 *
2957 * @return RevisionRecord|false Returns false if missing
2958 */
2959 public function getKnownCurrentRevision( PageIdentity $page, $revId = 0 ) {
2960 $db = $this->getReplicaConnection();
2961 $revIdPassed = $revId;
2962 $pageId = $this->getArticleId( $page );
2963 if ( !$pageId ) {
2964 return false;
2965 }
2966
2967 if ( !$revId ) {
2968 if ( $page instanceof Title ) {
2969 $revId = $page->getLatestRevID();
2970 } else {
2971 $pageRecord = $this->pageStore->getPageByReference( $page );
2972 if ( $pageRecord ) {
2973 $revId = $pageRecord->getLatest( $this->getWikiId() );
2974 }
2975 }
2976 }
2977
2978 if ( !$revId ) {
2979 $this->logger->warning(
2980 'No latest revision known for page {page} even though it exists with page ID {page_id}', [
2981 'page' => $page->__toString(),
2982 'page_id' => $pageId,
2983 'wiki_id' => $this->getWikiId() ?: 'local',
2984 ] );
2985 return false;
2986 }
2987
2988 // Load the row from cache if possible. If not possible, populate the cache.
2989 // As a minor optimization, remember if this was a cache hit or miss.
2990 // We can sometimes avoid a database query later if this is a cache miss.
2991 $fromCache = true;
2992 $row = $this->cache->getWithSetCallback(
2993 // Page/rev IDs passed in from DB to reflect history merges
2994 $this->getRevisionRowCacheKey( $db, $pageId, $revId ),
2995 WANObjectCache::TTL_WEEK,
2996 function ( $curValue, &$ttl, array &$setOpts ) use (
2997 $db, $revId, &$fromCache
2998 ) {
2999 $setOpts += Database::getCacheSetOptions( $db );
3000 $row = $this->fetchRevisionRowFromConds( $db, [ 'rev_id' => intval( $revId ) ] );
3001 if ( $row ) {
3002 $fromCache = false;
3003 }
3004 return $row; // don't cache negatives
3005 }
3006 );
3007
3008 // Reflect revision deletion and user renames.
3009 if ( $row ) {
3010 $title = $this->ensureRevisionRowMatchesPage( $row, $page, [
3011 'from_cache_flag' => $fromCache,
3012 'page_id_initial' => $pageId,
3013 'rev_id_used' => $revId,
3014 'rev_id_requested' => $revIdPassed,
3015 ] );
3016
3017 return $this->newRevisionFromRow( $row, 0, $title, $fromCache );
3018 } else {
3019 return false;
3020 }
3021 }
3022
3023 /**
3024 * Get the first revision of a given page.
3025 *
3026 * @since 1.35
3027 * @param LinkTarget|PageIdentity $page Calling with LinkTarget is deprecated since 1.36
3028 * @param int $flags
3029 * @return RevisionRecord|null
3030 */
3031 public function getFirstRevision(
3032 $page,
3033 int $flags = IDBAccessObject::READ_NORMAL
3034 ): ?RevisionRecord {
3035 if ( $page instanceof LinkTarget ) {
3036 // Only resolve LinkTarget to a Title when operating in the context of the local wiki (T248756)
3037 $page = $this->wikiId === WikiAwareEntity::LOCAL ? Title::castFromLinkTarget( $page ) : null;
3038 }
3039 return $this->newRevisionFromConds(
3040 [
3041 'page_namespace' => $page->getNamespace(),
3042 'page_title' => $page->getDBkey()
3043 ],
3044 $flags,
3045 $page,
3046 [
3047 'ORDER BY' => [ 'rev_timestamp ASC', 'rev_id ASC' ],
3048 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3049 ]
3050 );
3051 }
3052
3053 /**
3054 * Get a cache key for use with a row as selected with getQueryInfo( [ 'page', 'user' ] )
3055 * Caching rows without 'page' or 'user' could lead to issues.
3056 * If the format of the rows returned by the query provided by getQueryInfo changes the
3057 * cache key should be updated to avoid conflicts.
3058 *
3059 * @param IReadableDatabase $db
3060 * @param int $pageId
3061 * @param int $revId
3062 * @return string
3063 */
3064 private function getRevisionRowCacheKey( IReadableDatabase $db, $pageId, $revId ) {
3065 return $this->cache->makeGlobalKey(
3066 self::ROW_CACHE_KEY,
3067 $db->getDomainID(),
3068 $pageId,
3069 $revId
3070 );
3071 }
3072
3073 /**
3074 * Asserts that if revision is provided, it's saved and belongs to the page with provided pageId.
3075 * @param string $paramName
3076 * @param int $pageId
3077 * @param RevisionRecord|null $rev
3078 */
3079 private function assertRevisionParameter( $paramName, $pageId, ?RevisionRecord $rev = null ) {
3080 if ( $rev ) {
3081 if ( $rev->getId( $this->wikiId ) === null ) {
3082 throw new InvalidArgumentException( "Unsaved {$paramName} revision passed" );
3083 }
3084 if ( $rev->getPageId( $this->wikiId ) !== $pageId ) {
3085 throw new InvalidArgumentException(
3086 "Revision {$rev->getId( $this->wikiId )} doesn't belong to page {$pageId}"
3087 );
3088 }
3089 }
3090 }
3091
3092 /**
3093 * Converts revision limits to query conditions.
3094 *
3095 * @param ISQLPlatform $dbr
3096 * @param RevisionRecord|null $old Old revision.
3097 * If null is provided, count starting from the first revision (inclusive).
3098 * @param RevisionRecord|null $new New revision.
3099 * If null is provided, count until the last revision (inclusive).
3100 * @param string|array $options Single option, or an array of options:
3101 * RevisionStore::INCLUDE_OLD Include $old in the range; $new is excluded.
3102 * RevisionStore::INCLUDE_NEW Include $new in the range; $old is excluded.
3103 * RevisionStore::INCLUDE_BOTH Include both $old and $new in the range.
3104 * @return array
3105 */
3106 private function getRevisionLimitConditions(
3107 ISQLPlatform $dbr,
3108 ?RevisionRecord $old = null,
3109 ?RevisionRecord $new = null,
3110 $options = []
3111 ) {
3112 $options = (array)$options;
3113 if ( in_array( self::INCLUDE_OLD, $options ) || in_array( self::INCLUDE_BOTH, $options ) ) {
3114 $oldCmp = '>=';
3115 } else {
3116 $oldCmp = '>';
3117 }
3118 if ( in_array( self::INCLUDE_NEW, $options ) || in_array( self::INCLUDE_BOTH, $options ) ) {
3119 $newCmp = '<=';
3120 } else {
3121 $newCmp = '<';
3122 }
3123
3124 $conds = [];
3125 if ( $old ) {
3126 $conds[] = $dbr->buildComparison( $oldCmp, [
3127 'rev_timestamp' => $dbr->timestamp( $old->getTimestamp() ),
3128 'rev_id' => $old->getId( $this->wikiId ),
3129 ] );
3130 }
3131 if ( $new ) {
3132 $conds[] = $dbr->buildComparison( $newCmp, [
3133 'rev_timestamp' => $dbr->timestamp( $new->getTimestamp() ),
3134 'rev_id' => $new->getId( $this->wikiId ),
3135 ] );
3136 }
3137 return $conds;
3138 }
3139
3140 /**
3141 * Get IDs of revisions between the given revisions.
3142 *
3143 * @since 1.36
3144 *
3145 * @param int $pageId The id of the page
3146 * @param RevisionRecord|null $old Old revision.
3147 * If null is provided, count starting from the first revision (inclusive).
3148 * @param RevisionRecord|null $new New revision.
3149 * If null is provided, count until the last revision (inclusive).
3150 * @param int|null $max Limit of Revisions to count, will be incremented by
3151 * one to detect truncations.
3152 * @param string|array $options Single option, or an array of options:
3153 * RevisionStore::INCLUDE_OLD Include $old in the range; $new is excluded.
3154 * RevisionStore::INCLUDE_NEW Include $new in the range; $old is excluded.
3155 * RevisionStore::INCLUDE_BOTH Include both $old and $new in the range.
3156 * @param string|null $order The direction in which the revisions should be sorted.
3157 * Possible values:
3158 * - RevisionStore::ORDER_OLDEST_TO_NEWEST
3159 * - RevisionStore::ORDER_NEWEST_TO_OLDEST
3160 * - null for no specific ordering (default value)
3161 * @param int $flags
3162 * @throws InvalidArgumentException in case either revision is unsaved or
3163 * the revisions do not belong to the same page or unknown option is passed.
3164 * @return int[]
3165 */
3166 public function getRevisionIdsBetween(
3167 int $pageId,
3168 ?RevisionRecord $old = null,
3169 ?RevisionRecord $new = null,
3170 ?int $max = null,
3171 $options = [],
3172 ?string $order = null,
3173 int $flags = IDBAccessObject::READ_NORMAL
3174 ): array {
3175 $this->assertRevisionParameter( 'old', $pageId, $old );
3176 $this->assertRevisionParameter( 'new', $pageId, $new );
3177
3178 $options = (array)$options;
3179 $includeOld = in_array( self::INCLUDE_OLD, $options ) ||
3180 in_array( self::INCLUDE_BOTH, $options );
3181 $includeNew = in_array( self::INCLUDE_NEW, $options ) ||
3182 in_array( self::INCLUDE_BOTH, $options );
3183
3184 // No DB query needed if old and new are the same revision.
3185 // Can't check for consecutive revisions with 'getParentId' for a similar
3186 // optimization as edge cases exist when there are revisions between
3187 // a revision and it's parent. See T185167 for more details.
3188 if ( $old && $new && $new->getId( $this->wikiId ) === $old->getId( $this->wikiId ) ) {
3189 return $includeOld || $includeNew ? [ $new->getId( $this->wikiId ) ] : [];
3190 }
3191
3192 $db = $this->getDBConnectionRefForQueryFlags( $flags );
3193 $queryBuilder = $db->newSelectQueryBuilder()
3194 ->select( 'rev_id' )
3195 ->from( 'revision' )
3196 ->where( [
3197 'rev_page' => $pageId,
3198 $db->bitAnd( 'rev_deleted', RevisionRecord::DELETED_TEXT ) . ' = 0'
3199 ] )
3200 ->andWhere( $this->getRevisionLimitConditions( $db, $old, $new, $options ) );
3201
3202 if ( $order !== null ) {
3203 $queryBuilder->orderBy( [ 'rev_timestamp', 'rev_id' ], $order );
3204 }
3205 if ( $max !== null ) {
3206 // extra to detect truncation
3207 $queryBuilder->limit( $max + 1 );
3208 }
3209
3210 $values = $queryBuilder->caller( __METHOD__ )->fetchFieldValues();
3211 return array_map( 'intval', $values );
3212 }
3213
3214 /**
3215 * Get the authors between the given revisions or revisions.
3216 * Used for diffs and other things that really need it.
3217 *
3218 * @since 1.35
3219 *
3220 * @param int $pageId The id of the page
3221 * @param RevisionRecord|null $old Old revision.
3222 * If null is provided, count starting from the first revision (inclusive).
3223 * @param RevisionRecord|null $new New revision.
3224 * If null is provided, count until the last revision (inclusive).
3225 * @param Authority|null $performer the user whose access rights to apply
3226 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations.
3227 * @param string|array $options Single option, or an array of options:
3228 * RevisionStore::INCLUDE_OLD Include $old in the range; $new is excluded.
3229 * RevisionStore::INCLUDE_NEW Include $new in the range; $old is excluded.
3230 * RevisionStore::INCLUDE_BOTH Include both $old and $new in the range.
3231 * @throws InvalidArgumentException in case either revision is unsaved or
3232 * the revisions do not belong to the same page or unknown option is passed.
3233 * @return UserIdentity[] Names of revision authors in the range
3234 */
3235 public function getAuthorsBetween(
3236 $pageId,
3237 ?RevisionRecord $old = null,
3238 ?RevisionRecord $new = null,
3239 ?Authority $performer = null,
3240 $max = null,
3241 $options = []
3242 ) {
3243 $this->assertRevisionParameter( 'old', $pageId, $old );
3244 $this->assertRevisionParameter( 'new', $pageId, $new );
3245 $options = (array)$options;
3246
3247 // No DB query needed if old and new are the same revision.
3248 // Can't check for consecutive revisions with 'getParentId' for a similar
3249 // optimization as edge cases exist when there are revisions between
3250 //a revision and it's parent. See T185167 for more details.
3251 if ( $old && $new && $new->getId( $this->wikiId ) === $old->getId( $this->wikiId ) ) {
3252 if ( !$options ) {
3253 return [];
3254 } elseif ( $performer ) {
3255 return [ $new->getUser( RevisionRecord::FOR_THIS_USER, $performer ) ];
3256 } else {
3257 return [ $new->getUser() ];
3258 }
3259 }
3260
3261 $dbr = $this->getReplicaConnection();
3262 $queryBuilder = $dbr->newSelectQueryBuilder()
3263 ->select( [
3264 'rev_actor',
3265 'rev_user' => 'revision_actor.actor_user',
3266 'rev_user_text' => 'revision_actor.actor_name',
3267 ] )
3268 ->distinct()
3269 ->from( 'revision' )
3270 ->join( 'actor', 'revision_actor', 'revision_actor.actor_id = rev_actor' )
3271 ->where( [
3272 'rev_page' => $pageId,
3273 $dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . " = 0"
3274 ] )
3275 ->andWhere( $this->getRevisionLimitConditions( $dbr, $old, $new, $options ) )
3276 ->caller( __METHOD__ );
3277 if ( $max !== null ) {
3278 $queryBuilder->limit( $max + 1 );
3279 }
3280
3281 return array_map(
3282 function ( $row ) {
3283 return $this->actorStore->newActorFromRowFields(
3284 $row->rev_user,
3285 $row->rev_user_text,
3286 $row->rev_actor
3287 );
3288 },
3289 iterator_to_array( $queryBuilder->fetchResultSet() )
3290 );
3291 }
3292
3293 /**
3294 * Get the number of authors between the given revisions.
3295 * Used for diffs and other things that really need it.
3296 *
3297 * @since 1.35
3298 *
3299 * @param int $pageId The id of the page
3300 * @param RevisionRecord|null $old Old revision .
3301 * If null is provided, count starting from the first revision (inclusive).
3302 * @param RevisionRecord|null $new New revision.
3303 * If null is provided, count until the last revision (inclusive).
3304 * @param Authority|null $performer the user whose access rights to apply
3305 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations.
3306 * @param string|array $options Single option, or an array of options:
3307 * RevisionStore::INCLUDE_OLD Include $old in the range; $new is excluded.
3308 * RevisionStore::INCLUDE_NEW Include $new in the range; $old is excluded.
3309 * RevisionStore::INCLUDE_BOTH Include both $old and $new in the range.
3310 * @throws InvalidArgumentException in case either revision is unsaved or
3311 * the revisions do not belong to the same page or unknown option is passed.
3312 * @return int Number of revisions authors in the range.
3313 */
3314 public function countAuthorsBetween(
3315 $pageId,
3316 ?RevisionRecord $old = null,
3317 ?RevisionRecord $new = null,
3318 ?Authority $performer = null,
3319 $max = null,
3320 $options = []
3321 ) {
3322 // TODO: Implement with a separate query to avoid cost of selecting unneeded fields
3323 // and creation of UserIdentity stuff.
3324 return count( $this->getAuthorsBetween( $pageId, $old, $new, $performer, $max, $options ) );
3325 }
3326
3327 /**
3328 * Get the number of revisions between the given revisions.
3329 * Used for diffs and other things that really need it.
3330 *
3331 * @since 1.35
3332 *
3333 * @param int $pageId The id of the page
3334 * @param RevisionRecord|null $old Old revision.
3335 * If null is provided, count starting from the first revision (inclusive).
3336 * @param RevisionRecord|null $new New revision.
3337 * If null is provided, count until the last revision (inclusive).
3338 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations.
3339 * @param string|array $options Single option, or an array of options:
3340 * RevisionStore::INCLUDE_OLD Include $old in the range; $new is excluded.
3341 * RevisionStore::INCLUDE_NEW Include $new in the range; $old is excluded.
3342 * RevisionStore::INCLUDE_BOTH Include both $old and $new in the range.
3343 * @throws InvalidArgumentException in case either revision is unsaved or
3344 * the revisions do not belong to the same page.
3345 * @return int Number of revisions between these revisions.
3346 */
3347 public function countRevisionsBetween(
3348 $pageId,
3349 ?RevisionRecord $old = null,
3350 ?RevisionRecord $new = null,
3351 $max = null,
3352 $options = []
3353 ) {
3354 $this->assertRevisionParameter( 'old', $pageId, $old );
3355 $this->assertRevisionParameter( 'new', $pageId, $new );
3356
3357 // No DB query needed if old and new are the same revision.
3358 // Can't check for consecutive revisions with 'getParentId' for a similar
3359 // optimization as edge cases exist when there are revisions between
3360 //a revision and it's parent. See T185167 for more details.
3361 if ( $old && $new && $new->getId( $this->wikiId ) === $old->getId( $this->wikiId ) ) {
3362 return 0;
3363 }
3364
3365 $dbr = $this->getReplicaConnection();
3366 $conds = array_merge(
3367 [
3368 'rev_page' => $pageId,
3369 $dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_TEXT ) . " = 0"
3370 ],
3371 $this->getRevisionLimitConditions( $dbr, $old, $new, $options )
3372 );
3373 if ( $max !== null ) {
3374 return $dbr->newSelectQueryBuilder()
3375 ->select( '1' )
3376 ->from( 'revision' )
3377 ->where( $conds )
3378 ->caller( __METHOD__ )
3379 ->limit( $max + 1 ) // extra to detect truncation
3380 ->fetchRowCount();
3381 } else {
3382 return (int)$dbr->newSelectQueryBuilder()
3383 ->select( 'count(*)' )
3384 ->from( 'revision' )
3385 ->where( $conds )
3386 ->caller( __METHOD__ )->fetchField();
3387 }
3388 }
3389
3390 /**
3391 * Tries to find a revision identical to $revision in $searchLimit most recent revisions
3392 * of this page. The comparison is based on SHA1s of these revisions.
3393 *
3394 * @since 1.37
3395 *
3396 * @param RevisionRecord $revision which revision to compare to
3397 * @param int $searchLimit How many recent revisions should be checked
3398 *
3399 * @return RevisionRecord|null
3400 */
3401 public function findIdenticalRevision(
3402 RevisionRecord $revision,
3403 int $searchLimit
3404 ): ?RevisionRecord {
3405 $revision->assertWiki( $this->wikiId );
3406 $db = $this->getReplicaConnection();
3407 $subquery = $this->newSelectQueryBuilder( $db )
3408 ->joinComment()
3409 ->where( [ 'rev_page' => $revision->getPageId( $this->wikiId ) ] )
3410 // Include 'rev_id' in the ordering in case there are multiple revs with same timestamp
3411 ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_DESC )
3412 // T354015
3413 ->useIndex( [ 'revision' => 'rev_page_timestamp' ] )
3414 ->limit( $searchLimit )
3415 // skip the most recent edit, we can't revert to it anyway
3416 ->offset( 1 )
3417 ->caller( __METHOD__ );
3418
3419 // fetchRow effectively uses LIMIT 1 clause, returning only the first result
3420 $revisionRow = $db->newSelectQueryBuilder()
3421 ->select( '*' )
3422 ->from( $subquery, 'recent_revs' )
3423 ->where( [ 'rev_sha1' => $revision->getSha1() ] )
3424 ->caller( __METHOD__ )->fetchRow();
3425
3426 return $revisionRow ? $this->newRevisionFromRow( $revisionRow ) : null;
3427 }
3428
3429 // TODO: move relevant methods from Title here, e.g. isBigDeletion, etc.
3430 }