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