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