Merge "Add support for 'hu-formal'"
[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 stdClass;
51 use Title;
52 use User;
53 use WANObjectCache;
54 use Wikimedia\Assert\Assert;
55 use Wikimedia\Rdbms\Database;
56 use Wikimedia\Rdbms\DBConnRef;
57 use Wikimedia\Rdbms\IDatabase;
58 use Wikimedia\Rdbms\LoadBalancer;
59
60 /**
61 * Service for looking up page revisions.
62 *
63 * @since 1.31
64 *
65 * @note This was written to act as a drop-in replacement for the corresponding
66 * static methods in Revision.
67 */
68 class RevisionStore
69 implements IDBAccessObject, RevisionFactory, RevisionLookup, LoggerAwareInterface {
70
71 /**
72 * @var SqlBlobStore
73 */
74 private $blobStore;
75
76 /**
77 * @var bool|string
78 */
79 private $wikiId;
80
81 /**
82 * @var boolean
83 */
84 private $contentHandlerUseDB = true;
85
86 /**
87 * @var LoadBalancer
88 */
89 private $loadBalancer;
90
91 /**
92 * @var WANObjectCache
93 */
94 private $cache;
95
96 /**
97 * @var CommentStore
98 */
99 private $commentStore;
100
101 /**
102 * @var ActorMigration
103 */
104 private $actorMigration;
105
106 /**
107 * @var LoggerInterface
108 */
109 private $logger;
110
111 /**
112 * @todo $blobStore should be allowed to be any BlobStore!
113 *
114 * @param LoadBalancer $loadBalancer
115 * @param SqlBlobStore $blobStore
116 * @param WANObjectCache $cache
117 * @param CommentStore $commentStore
118 * @param ActorMigration $actorMigration
119 * @param bool|string $wikiId
120 */
121 public function __construct(
122 LoadBalancer $loadBalancer,
123 SqlBlobStore $blobStore,
124 WANObjectCache $cache,
125 CommentStore $commentStore,
126 ActorMigration $actorMigration,
127 $wikiId = false
128 ) {
129 Assert::parameterType( 'string|boolean', $wikiId, '$wikiId' );
130
131 $this->loadBalancer = $loadBalancer;
132 $this->blobStore = $blobStore;
133 $this->cache = $cache;
134 $this->commentStore = $commentStore;
135 $this->actorMigration = $actorMigration;
136 $this->wikiId = $wikiId;
137 $this->logger = new NullLogger();
138 }
139
140 public function setLogger( LoggerInterface $logger ) {
141 $this->logger = $logger;
142 }
143
144 /**
145 * @return bool Whether the store is read-only
146 */
147 public function isReadOnly() {
148 return $this->blobStore->isReadOnly();
149 }
150
151 /**
152 * @return bool
153 */
154 public function getContentHandlerUseDB() {
155 return $this->contentHandlerUseDB;
156 }
157
158 /**
159 * @param bool $contentHandlerUseDB
160 */
161 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
162 $this->contentHandlerUseDB = $contentHandlerUseDB;
163 }
164
165 /**
166 * @return LoadBalancer
167 */
168 private function getDBLoadBalancer() {
169 return $this->loadBalancer;
170 }
171
172 /**
173 * @param int $mode DB_MASTER or DB_REPLICA
174 *
175 * @return IDatabase
176 */
177 private function getDBConnection( $mode ) {
178 $lb = $this->getDBLoadBalancer();
179 return $lb->getConnection( $mode, [], $this->wikiId );
180 }
181
182 /**
183 * @param IDatabase $connection
184 */
185 private function releaseDBConnection( IDatabase $connection ) {
186 $lb = $this->getDBLoadBalancer();
187 $lb->reuseConnection( $connection );
188 }
189
190 /**
191 * @param int $mode DB_MASTER or DB_REPLICA
192 *
193 * @return DBConnRef
194 */
195 private function getDBConnectionRef( $mode ) {
196 $lb = $this->getDBLoadBalancer();
197 return $lb->getConnectionRef( $mode, [], $this->wikiId );
198 }
199
200 /**
201 * Determines the page Title based on the available information.
202 *
203 * MCR migration note: this corresponds to Revision::getTitle
204 *
205 * @note this method should be private, external use should be avoided!
206 *
207 * @param int|null $pageId
208 * @param int|null $revId
209 * @param int $queryFlags
210 *
211 * @return Title
212 * @throws RevisionAccessException
213 */
214 public function getTitle( $pageId, $revId, $queryFlags = self::READ_NORMAL ) {
215 if ( !$pageId && !$revId ) {
216 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
217 }
218
219 // This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
220 // So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
221 if ( DBAccessObjectUtils::hasFlags( $queryFlags, self::READ_LATEST_IMMUTABLE ) ) {
222 $queryFlags = self::READ_NORMAL;
223 }
224
225 $canUseTitleNewFromId = ( $pageId !== null && $pageId > 0 && $this->wikiId === false );
226 list( $dbMode, $dbOptions ) = DBAccessObjectUtils::getDBOptions( $queryFlags );
227 $titleFlags = ( $dbMode == DB_MASTER ? Title::GAID_FOR_UPDATE : 0 );
228
229 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
230 if ( $canUseTitleNewFromId ) {
231 // TODO: better foreign title handling (introduce TitleFactory)
232 $title = Title::newFromID( $pageId, $titleFlags );
233 if ( $title ) {
234 return $title;
235 }
236 }
237
238 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
239 $canUseRevId = ( $revId !== null && $revId > 0 );
240
241 if ( $canUseRevId ) {
242 $dbr = $this->getDBConnectionRef( $dbMode );
243 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
244 $row = $dbr->selectRow(
245 [ 'revision', 'page' ],
246 [
247 'page_namespace',
248 'page_title',
249 'page_id',
250 'page_latest',
251 'page_is_redirect',
252 'page_len',
253 ],
254 [ 'rev_id' => $revId ],
255 __METHOD__,
256 $dbOptions,
257 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
258 );
259 if ( $row ) {
260 // TODO: better foreign title handling (introduce TitleFactory)
261 return Title::newFromRow( $row );
262 }
263 }
264
265 // If we still don't have a title, fallback to master if that wasn't already happening.
266 if ( $dbMode !== DB_MASTER ) {
267 $title = $this->getTitle( $pageId, $revId, self::READ_LATEST );
268 if ( $title ) {
269 $this->logger->info(
270 __METHOD__ . ' fell back to READ_LATEST and got a Title.',
271 [ 'trace' => wfBacktrace() ]
272 );
273 return $title;
274 }
275 }
276
277 throw new RevisionAccessException(
278 "Could not determine title for page ID $pageId and revision ID $revId"
279 );
280 }
281
282 /**
283 * @param mixed $value
284 * @param string $name
285 *
286 * @throw IncompleteRevisionException if $value is null
287 * @return mixed $value, if $value is not null
288 */
289 private function failOnNull( $value, $name ) {
290 if ( $value === null ) {
291 throw new IncompleteRevisionException(
292 "$name must not be " . var_export( $value, true ) . "!"
293 );
294 }
295
296 return $value;
297 }
298
299 /**
300 * @param mixed $value
301 * @param string $name
302 *
303 * @throw IncompleteRevisionException if $value is empty
304 * @return mixed $value, if $value is not null
305 */
306 private function failOnEmpty( $value, $name ) {
307 if ( $value === null || $value === 0 || $value === '' ) {
308 throw new IncompleteRevisionException(
309 "$name must not be " . var_export( $value, true ) . "!"
310 );
311 }
312
313 return $value;
314 }
315
316 /**
317 * Insert a new revision into the database, returning the new revision record
318 * on success and dies horribly on failure.
319 *
320 * MCR migration note: this replaces Revision::insertOn
321 *
322 * @param RevisionRecord $rev
323 * @param IDatabase $dbw (master connection)
324 *
325 * @throws InvalidArgumentException
326 * @return RevisionRecord the new revision record.
327 */
328 public function insertRevisionOn( RevisionRecord $rev, IDatabase $dbw ) {
329 // TODO: pass in a DBTransactionContext instead of a database connection.
330 $this->checkDatabaseWikiId( $dbw );
331
332 if ( !$rev->getSlotRoles() ) {
333 throw new InvalidArgumentException( 'At least one slot needs to be defined!' );
334 }
335
336 if ( $rev->getSlotRoles() !== [ 'main' ] ) {
337 throw new InvalidArgumentException( 'Only the main slot is supported for now!' );
338 }
339
340 // TODO: we shouldn't need an actual Title here.
341 $title = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
342 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
343
344 $parentId = $rev->getParentId() === null
345 ? $this->getPreviousRevisionId( $dbw, $rev )
346 : $rev->getParentId();
347
348 // Record the text (or external storage URL) to the blob store
349 $slot = $rev->getSlot( 'main', RevisionRecord::RAW );
350
351 $size = $this->failOnNull( $rev->getSize(), 'size field' );
352 $sha1 = $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
353
354 if ( !$slot->hasAddress() ) {
355 $content = $slot->getContent();
356 $format = $content->getDefaultFormat();
357 $model = $content->getModel();
358
359 $this->checkContentModel( $content, $title );
360
361 $data = $content->serialize( $format );
362
363 // Hints allow the blob store to optimize by "leaking" application level information to it.
364 // TODO: with the new MCR storage schema, we rev_id have this before storing the blobs.
365 // When we have it, add rev_id as a hint. Can be used with rev_parent_id for
366 // differential storage or compression of subsequent revisions.
367 $blobHints = [
368 BlobStore::DESIGNATION_HINT => 'page-content', // BlobStore may be used for other things too.
369 BlobStore::PAGE_HINT => $pageId,
370 BlobStore::ROLE_HINT => $slot->getRole(),
371 BlobStore::PARENT_HINT => $parentId,
372 BlobStore::SHA1_HINT => $slot->getSha1(),
373 BlobStore::MODEL_HINT => $model,
374 BlobStore::FORMAT_HINT => $format,
375 ];
376
377 $blobAddress = $this->blobStore->storeBlob( $data, $blobHints );
378 } else {
379 $blobAddress = $slot->getAddress();
380 $model = $slot->getModel();
381 $format = $slot->getFormat();
382 }
383
384 $textId = $this->blobStore->getTextIdFromAddress( $blobAddress );
385
386 if ( !$textId ) {
387 throw new LogicException(
388 'Blob address not supported in 1.29 database schema: ' . $blobAddress
389 );
390 }
391
392 // getTextIdFromAddress() is free to insert something into the text table, so $textId
393 // may be a new value, not anything already contained in $blobAddress.
394 $blobAddress = 'tt:' . $textId;
395
396 $comment = $this->failOnNull( $rev->getComment( RevisionRecord::RAW ), 'comment' );
397 $user = $this->failOnNull( $rev->getUser( RevisionRecord::RAW ), 'user' );
398 $timestamp = $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
399
400 // Checks.
401 $this->failOnNull( $user->getId(), 'user field' );
402 $this->failOnEmpty( $user->getName(), 'user_text field' );
403
404 # Record the edit in revisions
405 $row = [
406 'rev_page' => $pageId,
407 'rev_parent_id' => $parentId,
408 'rev_text_id' => $textId,
409 'rev_minor_edit' => $rev->isMinor() ? 1 : 0,
410 'rev_timestamp' => $dbw->timestamp( $timestamp ),
411 'rev_deleted' => $rev->getVisibility(),
412 'rev_len' => $size,
413 'rev_sha1' => $sha1,
414 ];
415
416 if ( $rev->getId() !== null ) {
417 // Needed to restore revisions with their original ID
418 $row['rev_id'] = $rev->getId();
419 }
420
421 list( $commentFields, $commentCallback ) =
422 $this->commentStore->insertWithTempTable( $dbw, 'rev_comment', $comment );
423 $row += $commentFields;
424
425 list( $actorFields, $actorCallback ) =
426 $this->actorMigration->getInsertValuesWithTempTable( $dbw, 'rev_user', $user );
427 $row += $actorFields;
428
429 if ( $this->contentHandlerUseDB ) {
430 // MCR migration note: rev_content_model and rev_content_format will go away
431
432 $defaultModel = ContentHandler::getDefaultModelFor( $title );
433 $defaultFormat = ContentHandler::getForModelID( $defaultModel )->getDefaultFormat();
434
435 $row['rev_content_model'] = ( $model === $defaultModel ) ? null : $model;
436 $row['rev_content_format'] = ( $format === $defaultFormat ) ? null : $format;
437 }
438
439 $dbw->insert( 'revision', $row, __METHOD__ );
440
441 if ( !isset( $row['rev_id'] ) ) {
442 // only if auto-increment was used
443 $row['rev_id'] = intval( $dbw->insertId() );
444 }
445 $commentCallback( $row['rev_id'] );
446 $actorCallback( $row['rev_id'], $row );
447
448 // Insert IP revision into ip_changes for use when querying for a range.
449 if ( $user->getId() === 0 && IP::isValid( $user->getName() ) ) {
450 $ipcRow = [
451 'ipc_rev_id' => $row['rev_id'],
452 'ipc_rev_timestamp' => $row['rev_timestamp'],
453 'ipc_hex' => IP::toHex( $user->getName() ),
454 ];
455 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__ );
456 }
457
458 $newSlot = SlotRecord::newSaved( $row['rev_id'], $blobAddress, $slot );
459 $slots = new RevisionSlots( [ 'main' => $newSlot ] );
460
461 $rev = new RevisionStoreRecord(
462 $title,
463 $user,
464 $comment,
465 (object)$row,
466 $slots,
467 $this->wikiId
468 );
469
470 $newSlot = $rev->getSlot( 'main', RevisionRecord::RAW );
471
472 // sanity checks
473 Assert::postcondition( $rev->getId() > 0, 'revision must have an ID' );
474 Assert::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
475 Assert::postcondition(
476 $rev->getComment( RevisionRecord::RAW ) !== null,
477 'revision must have a comment'
478 );
479 Assert::postcondition(
480 $rev->getUser( RevisionRecord::RAW ) !== null,
481 'revision must have a user'
482 );
483
484 Assert::postcondition( $newSlot !== null, 'revision must have a main slot' );
485 Assert::postcondition(
486 $newSlot->getAddress() !== null,
487 'main slot must have an addess'
488 );
489
490 Hooks::run( 'RevisionRecordInserted', [ $rev ] );
491
492 return $rev;
493 }
494
495 /**
496 * MCR migration note: this corresponds to Revision::checkContentModel
497 *
498 * @param Content $content
499 * @param Title $title
500 *
501 * @throws MWException
502 * @throws MWUnknownContentModelException
503 */
504 private function checkContentModel( Content $content, Title $title ) {
505 // Note: may return null for revisions that have not yet been inserted
506
507 $model = $content->getModel();
508 $format = $content->getDefaultFormat();
509 $handler = $content->getContentHandler();
510
511 $name = "$title";
512
513 if ( !$handler->isSupportedFormat( $format ) ) {
514 throw new MWException( "Can't use format $format with content model $model on $name" );
515 }
516
517 if ( !$this->contentHandlerUseDB ) {
518 // if $wgContentHandlerUseDB is not set,
519 // all revisions must use the default content model and format.
520
521 $defaultModel = ContentHandler::getDefaultModelFor( $title );
522 $defaultHandler = ContentHandler::getForModelID( $defaultModel );
523 $defaultFormat = $defaultHandler->getDefaultFormat();
524
525 if ( $model != $defaultModel ) {
526 throw new MWException( "Can't save non-default content model with "
527 . "\$wgContentHandlerUseDB disabled: model is $model, "
528 . "default for $name is $defaultModel"
529 );
530 }
531
532 if ( $format != $defaultFormat ) {
533 throw new MWException( "Can't use non-default content format with "
534 . "\$wgContentHandlerUseDB disabled: format is $format, "
535 . "default for $name is $defaultFormat"
536 );
537 }
538 }
539
540 if ( !$content->isValid() ) {
541 throw new MWException(
542 "New content for $name is not valid! Content model is $model"
543 );
544 }
545 }
546
547 /**
548 * Create a new null-revision for insertion into a page's
549 * history. This will not re-save the text, but simply refer
550 * to the text from the previous version.
551 *
552 * Such revisions can for instance identify page rename
553 * operations and other such meta-modifications.
554 *
555 * MCR migration note: this replaces Revision::newNullRevision
556 *
557 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
558 * (or go away).
559 *
560 * @param IDatabase $dbw
561 * @param Title $title Title of the page to read from
562 * @param CommentStoreComment $comment RevisionRecord's summary
563 * @param bool $minor Whether the revision should be considered as minor
564 * @param User $user The user to attribute the revision to
565 * @return RevisionRecord|null RevisionRecord or null on error
566 */
567 public function newNullRevision(
568 IDatabase $dbw,
569 Title $title,
570 CommentStoreComment $comment,
571 $minor,
572 User $user
573 ) {
574 $this->checkDatabaseWikiId( $dbw );
575
576 $fields = [ 'page_latest', 'page_namespace', 'page_title',
577 'rev_id', 'rev_text_id', 'rev_len', 'rev_sha1' ];
578
579 if ( $this->contentHandlerUseDB ) {
580 $fields[] = 'rev_content_model';
581 $fields[] = 'rev_content_format';
582 }
583
584 $current = $dbw->selectRow(
585 [ 'page', 'revision' ],
586 $fields,
587 [
588 'page_id' => $title->getArticleID(),
589 'page_latest=rev_id',
590 ],
591 __METHOD__,
592 [ 'FOR UPDATE' ] // T51581
593 );
594
595 if ( $current ) {
596 $fields = [
597 'page' => $title->getArticleID(),
598 'user_text' => $user->getName(),
599 'user' => $user->getId(),
600 'actor' => $user->getActorId(),
601 'comment' => $comment,
602 'minor_edit' => $minor,
603 'text_id' => $current->rev_text_id,
604 'parent_id' => $current->page_latest,
605 'len' => $current->rev_len,
606 'sha1' => $current->rev_sha1
607 ];
608
609 if ( $this->contentHandlerUseDB ) {
610 $fields['content_model'] = $current->rev_content_model;
611 $fields['content_format'] = $current->rev_content_format;
612 }
613
614 $fields['title'] = Title::makeTitle( $current->page_namespace, $current->page_title );
615
616 $mainSlot = $this->emulateMainSlot_1_29( $fields, self::READ_LATEST, $title );
617 $revision = new MutableRevisionRecord( $title, $this->wikiId );
618 $this->initializeMutableRevisionFromArray( $revision, $fields );
619 $revision->setSlot( $mainSlot );
620 } else {
621 $revision = null;
622 }
623
624 return $revision;
625 }
626
627 /**
628 * MCR migration note: this replaces Revision::isUnpatrolled
629 *
630 * @todo This is overly specific, so move or kill this method.
631 *
632 * @param RevisionRecord $rev
633 *
634 * @return int Rcid of the unpatrolled row, zero if there isn't one
635 */
636 public function getRcIdIfUnpatrolled( RevisionRecord $rev ) {
637 $rc = $this->getRecentChange( $rev );
638 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
639 return $rc->getAttribute( 'rc_id' );
640 } else {
641 return 0;
642 }
643 }
644
645 /**
646 * Get the RC object belonging to the current revision, if there's one
647 *
648 * MCR migration note: this replaces Revision::getRecentChange
649 *
650 * @todo move this somewhere else?
651 *
652 * @param RevisionRecord $rev
653 * @param int $flags (optional) $flags include:
654 * IDBAccessObject::READ_LATEST: Select the data from the master
655 *
656 * @return null|RecentChange
657 */
658 public function getRecentChange( RevisionRecord $rev, $flags = 0 ) {
659 $dbr = $this->getDBConnection( DB_REPLICA );
660
661 list( $dbType, ) = DBAccessObjectUtils::getDBOptions( $flags );
662
663 $userIdentity = $rev->getUser( RevisionRecord::RAW );
664
665 if ( !$userIdentity ) {
666 // If the revision has no user identity, chances are it never went
667 // into the database, and doesn't have an RC entry.
668 return null;
669 }
670
671 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
672 $actorWhere = $this->actorMigration->getWhere( $dbr, 'rc_user', $rev->getUser(), false );
673 $rc = RecentChange::newFromConds(
674 [
675 $actorWhere['conds'],
676 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
677 'rc_this_oldid' => $rev->getId()
678 ],
679 __METHOD__,
680 $dbType
681 );
682
683 $this->releaseDBConnection( $dbr );
684
685 // XXX: cache this locally? Glue it to the RevisionRecord?
686 return $rc;
687 }
688
689 /**
690 * Maps fields of the archive row to corresponding revision rows.
691 *
692 * @param object $archiveRow
693 *
694 * @return object a revision row object, corresponding to $archiveRow.
695 */
696 private static function mapArchiveFields( $archiveRow ) {
697 $fieldMap = [
698 // keep with ar prefix:
699 'ar_id' => 'ar_id',
700
701 // not the same suffix:
702 'ar_page_id' => 'rev_page',
703 'ar_rev_id' => 'rev_id',
704
705 // same suffix:
706 'ar_text_id' => 'rev_text_id',
707 'ar_timestamp' => 'rev_timestamp',
708 'ar_user_text' => 'rev_user_text',
709 'ar_user' => 'rev_user',
710 'ar_actor' => 'rev_actor',
711 'ar_minor_edit' => 'rev_minor_edit',
712 'ar_deleted' => 'rev_deleted',
713 'ar_len' => 'rev_len',
714 'ar_parent_id' => 'rev_parent_id',
715 'ar_sha1' => 'rev_sha1',
716 'ar_comment' => 'rev_comment',
717 'ar_comment_cid' => 'rev_comment_cid',
718 'ar_comment_id' => 'rev_comment_id',
719 'ar_comment_text' => 'rev_comment_text',
720 'ar_comment_data' => 'rev_comment_data',
721 'ar_comment_old' => 'rev_comment_old',
722 'ar_content_format' => 'rev_content_format',
723 'ar_content_model' => 'rev_content_model',
724 ];
725
726 if ( empty( $archiveRow->ar_text_id ) ) {
727 $fieldMap['ar_text'] = 'old_text';
728 $fieldMap['ar_flags'] = 'old_flags';
729 }
730
731 $revRow = new stdClass();
732 foreach ( $fieldMap as $arKey => $revKey ) {
733 if ( property_exists( $archiveRow, $arKey ) ) {
734 $revRow->$revKey = $archiveRow->$arKey;
735 }
736 }
737
738 return $revRow;
739 }
740
741 /**
742 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
743 *
744 * @param object|array $row Either a database row or an array
745 * @param int $queryFlags for callbacks
746 * @param Title $title
747 *
748 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
749 * @throws MWException
750 */
751 private function emulateMainSlot_1_29( $row, $queryFlags, Title $title ) {
752 $mainSlotRow = new stdClass();
753 $mainSlotRow->role_name = 'main';
754
755 $content = null;
756 $blobData = null;
757 $blobFlags = null;
758
759 if ( is_object( $row ) ) {
760 // archive row
761 if ( !isset( $row->rev_id ) && ( isset( $row->ar_user ) || isset( $row->ar_actor ) ) ) {
762 $row = $this->mapArchiveFields( $row );
763 }
764
765 if ( isset( $row->rev_text_id ) && $row->rev_text_id > 0 ) {
766 $mainSlotRow->cont_address = 'tt:' . $row->rev_text_id;
767 }
768
769 if ( isset( $row->old_text ) ) {
770 // this happens when the text-table gets joined directly, in the pre-1.30 schema
771 $blobData = isset( $row->old_text ) ? strval( $row->old_text ) : null;
772 // Check against selects that might have not included old_flags
773 if ( !property_exists( $row, 'old_flags' ) ) {
774 throw new InvalidArgumentException( 'old_flags was not set in $row' );
775 }
776 $blobFlags = ( $row->old_flags === null ) ? '' : $row->old_flags;
777 }
778
779 $mainSlotRow->slot_revision = intval( $row->rev_id );
780
781 $mainSlotRow->cont_size = isset( $row->rev_len ) ? intval( $row->rev_len ) : null;
782 $mainSlotRow->cont_sha1 = isset( $row->rev_sha1 ) ? strval( $row->rev_sha1 ) : null;
783 $mainSlotRow->model_name = isset( $row->rev_content_model )
784 ? strval( $row->rev_content_model )
785 : null;
786 // XXX: in the future, we'll probably always use the default format, and drop content_format
787 $mainSlotRow->format_name = isset( $row->rev_content_format )
788 ? strval( $row->rev_content_format )
789 : null;
790 } elseif ( is_array( $row ) ) {
791 $mainSlotRow->slot_revision = isset( $row['id'] ) ? intval( $row['id'] ) : null;
792
793 $mainSlotRow->cont_address = isset( $row['text_id'] )
794 ? 'tt:' . intval( $row['text_id'] )
795 : null;
796 $mainSlotRow->cont_size = isset( $row['len'] ) ? intval( $row['len'] ) : null;
797 $mainSlotRow->cont_sha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
798
799 $mainSlotRow->model_name = isset( $row['content_model'] )
800 ? strval( $row['content_model'] ) : null; // XXX: must be a string!
801 // XXX: in the future, we'll probably always use the default format, and drop content_format
802 $mainSlotRow->format_name = isset( $row['content_format'] )
803 ? strval( $row['content_format'] ) : null;
804 $blobData = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
805 // XXX: If the flags field is not set then $blobFlags should be null so that no
806 // decoding will happen. An empty string will result in default decodings.
807 $blobFlags = isset( $row['flags'] ) ? trim( strval( $row['flags'] ) ) : null;
808
809 // if we have a Content object, override mText and mContentModel
810 if ( !empty( $row['content'] ) ) {
811 if ( !( $row['content'] instanceof Content ) ) {
812 throw new MWException( 'content field must contain a Content object.' );
813 }
814
815 /** @var Content $content */
816 $content = $row['content'];
817 $handler = $content->getContentHandler();
818
819 $mainSlotRow->model_name = $content->getModel();
820
821 // XXX: in the future, we'll probably always use the default format.
822 if ( $mainSlotRow->format_name === null ) {
823 $mainSlotRow->format_name = $handler->getDefaultFormat();
824 }
825 }
826 } else {
827 throw new MWException( 'Revision constructor passed invalid row format.' );
828 }
829
830 // With the old schema, the content changes with every revision.
831 // ...except for null-revisions. Would be nice if we could detect them.
832 $mainSlotRow->slot_inherited = 0;
833
834 if ( $mainSlotRow->model_name === null ) {
835 $mainSlotRow->model_name = function ( SlotRecord $slot ) use ( $title ) {
836 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
837 // TODO: MCR: deprecate $title->getModel().
838 return ContentHandler::getDefaultModelFor( $title );
839 };
840 }
841
842 if ( !$content ) {
843 $content = function ( SlotRecord $slot )
844 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
845 {
846 return $this->loadSlotContent(
847 $slot,
848 $blobData,
849 $blobFlags,
850 $mainSlotRow->format_name,
851 $queryFlags
852 );
853 };
854 }
855
856 return new SlotRecord( $mainSlotRow, $content );
857 }
858
859 /**
860 * Loads a Content object based on a slot row.
861 *
862 * This method does not call $slot->getContent(), and may be used as a callback
863 * called by $slot->getContent().
864 *
865 * MCR migration note: this roughly corresponds to Revision::getContentInternal
866 *
867 * @param SlotRecord $slot The SlotRecord to load content for
868 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
869 * @param string|null $blobFlags Flags indicating how $blobData needs to be processed.
870 * Use null if no processing should happen. That is in constrast to the empty string,
871 * which causes the blob to be decoded according to the configured legacy encoding.
872 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
873 * @param int $queryFlags
874 *
875 * @throw RevisionAccessException
876 * @return Content
877 */
878 private function loadSlotContent(
879 SlotRecord $slot,
880 $blobData = null,
881 $blobFlags = null,
882 $blobFormat = null,
883 $queryFlags = 0
884 ) {
885 if ( $blobData !== null ) {
886 Assert::parameterType( 'string', $blobData, '$blobData' );
887 Assert::parameterType( 'string|null', $blobFlags, '$blobFlags' );
888
889 $cacheKey = $slot->hasAddress() ? $slot->getAddress() : null;
890
891 if ( $blobFlags === null ) {
892 // No blob flags, so use the blob verbatim.
893 $data = $blobData;
894 } else {
895 $data = $this->blobStore->expandBlob( $blobData, $blobFlags, $cacheKey );
896 if ( $data === false ) {
897 throw new RevisionAccessException(
898 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
899 );
900 }
901 }
902
903 } else {
904 $address = $slot->getAddress();
905 try {
906 $data = $this->blobStore->getBlob( $address, $queryFlags );
907 } catch ( BlobAccessException $e ) {
908 throw new RevisionAccessException(
909 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
910 );
911 }
912 }
913
914 // Unserialize content
915 $handler = ContentHandler::getForModelID( $slot->getModel() );
916
917 $content = $handler->unserializeContent( $data, $blobFormat );
918 return $content;
919 }
920
921 /**
922 * Load a page revision from a given revision ID number.
923 * Returns null if no such revision can be found.
924 *
925 * MCR migration note: this replaces Revision::newFromId
926 *
927 * $flags include:
928 * IDBAccessObject::READ_LATEST: Select the data from the master
929 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
930 *
931 * @param int $id
932 * @param int $flags (optional)
933 * @return RevisionRecord|null
934 */
935 public function getRevisionById( $id, $flags = 0 ) {
936 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
937 }
938
939 /**
940 * Load either the current, or a specified, revision
941 * that's attached to a given link target. If not attached
942 * to that link target, will return null.
943 *
944 * MCR migration note: this replaces Revision::newFromTitle
945 *
946 * $flags include:
947 * IDBAccessObject::READ_LATEST: Select the data from the master
948 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
949 *
950 * @param LinkTarget $linkTarget
951 * @param int $revId (optional)
952 * @param int $flags Bitfield (optional)
953 * @return RevisionRecord|null
954 */
955 public function getRevisionByTitle( LinkTarget $linkTarget, $revId = 0, $flags = 0 ) {
956 $conds = [
957 'page_namespace' => $linkTarget->getNamespace(),
958 'page_title' => $linkTarget->getDBkey()
959 ];
960 if ( $revId ) {
961 // Use the specified revision ID.
962 // Note that we use newRevisionFromConds here because we want to retry
963 // and fall back to master if the page is not found on a replica.
964 // Since the caller supplied a revision ID, we are pretty sure the revision is
965 // supposed to exist, so we should try hard to find it.
966 $conds['rev_id'] = $revId;
967 return $this->newRevisionFromConds( $conds, $flags );
968 } else {
969 // Use a join to get the latest revision.
970 // Note that we don't use newRevisionFromConds here because we don't want to retry
971 // and fall back to master. The assumption is that we only want to force the fallback
972 // if we are quite sure the revision exists because the caller supplied a revision ID.
973 // If the page isn't found at all on a replica, it probably simply does not exist.
974 $db = $this->getDBConnection( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
975
976 $conds[] = 'rev_id=page_latest';
977 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
978
979 $this->releaseDBConnection( $db );
980 return $rev;
981 }
982 }
983
984 /**
985 * Load either the current, or a specified, revision
986 * that's attached to a given page ID.
987 * Returns null if no such revision can be found.
988 *
989 * MCR migration note: this replaces Revision::newFromPageId
990 *
991 * $flags include:
992 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
993 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
994 *
995 * @param int $pageId
996 * @param int $revId (optional)
997 * @param int $flags Bitfield (optional)
998 * @return RevisionRecord|null
999 */
1000 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
1001 $conds = [ 'page_id' => $pageId ];
1002 if ( $revId ) {
1003 // Use the specified revision ID.
1004 // Note that we use newRevisionFromConds here because we want to retry
1005 // and fall back to master if the page is not found on a replica.
1006 // Since the caller supplied a revision ID, we are pretty sure the revision is
1007 // supposed to exist, so we should try hard to find it.
1008 $conds['rev_id'] = $revId;
1009 return $this->newRevisionFromConds( $conds, $flags );
1010 } else {
1011 // Use a join to get the latest revision.
1012 // Note that we don't use newRevisionFromConds here because we don't want to retry
1013 // and fall back to master. The assumption is that we only want to force the fallback
1014 // if we are quite sure the revision exists because the caller supplied a revision ID.
1015 // If the page isn't found at all on a replica, it probably simply does not exist.
1016 $db = $this->getDBConnection( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
1017
1018 $conds[] = 'rev_id=page_latest';
1019 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
1020
1021 $this->releaseDBConnection( $db );
1022 return $rev;
1023 }
1024 }
1025
1026 /**
1027 * Load the revision for the given title with the given timestamp.
1028 * WARNING: Timestamps may in some circumstances not be unique,
1029 * so this isn't the best key to use.
1030 *
1031 * MCR migration note: this replaces Revision::loadFromTimestamp
1032 *
1033 * @param Title $title
1034 * @param string $timestamp
1035 * @return RevisionRecord|null
1036 */
1037 public function getRevisionByTimestamp( $title, $timestamp ) {
1038 return $this->newRevisionFromConds(
1039 [
1040 'rev_timestamp' => $timestamp,
1041 'page_namespace' => $title->getNamespace(),
1042 'page_title' => $title->getDBkey()
1043 ],
1044 0,
1045 $title
1046 );
1047 }
1048
1049 /**
1050 * Make a fake revision object from an archive table row. This is queried
1051 * for permissions or even inserted (as in Special:Undelete)
1052 *
1053 * MCR migration note: this replaces Revision::newFromArchiveRow
1054 *
1055 * @param object $row
1056 * @param int $queryFlags
1057 * @param Title|null $title
1058 * @param array $overrides associative array with fields of $row to override. This may be
1059 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
1060 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
1061 * override ar_parent_id.
1062 *
1063 * @return RevisionRecord
1064 * @throws MWException
1065 */
1066 public function newRevisionFromArchiveRow(
1067 $row,
1068 $queryFlags = 0,
1069 Title $title = null,
1070 array $overrides = []
1071 ) {
1072 Assert::parameterType( 'object', $row, '$row' );
1073
1074 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
1075 Assert::parameterType( 'integer', $queryFlags, '$queryFlags' );
1076
1077 if ( !$title && isset( $overrides['title'] ) ) {
1078 if ( !( $overrides['title'] instanceof Title ) ) {
1079 throw new MWException( 'title field override must contain a Title object.' );
1080 }
1081
1082 $title = $overrides['title'];
1083 }
1084
1085 if ( !isset( $title ) ) {
1086 if ( isset( $row->ar_namespace ) && isset( $row->ar_title ) ) {
1087 $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
1088 } else {
1089 throw new InvalidArgumentException(
1090 'A Title or ar_namespace and ar_title must be given'
1091 );
1092 }
1093 }
1094
1095 foreach ( $overrides as $key => $value ) {
1096 $field = "ar_$key";
1097 $row->$field = $value;
1098 }
1099
1100 try {
1101 $user = User::newFromAnyId(
1102 isset( $row->ar_user ) ? $row->ar_user : null,
1103 isset( $row->ar_user_text ) ? $row->ar_user_text : null,
1104 isset( $row->ar_actor ) ? $row->ar_actor : null
1105 );
1106 } catch ( InvalidArgumentException $ex ) {
1107 wfWarn( __METHOD__ . ': ' . $ex->getMessage() );
1108 $user = new UserIdentityValue( 0, '', 0 );
1109 }
1110
1111 $comment = $this->commentStore
1112 // Legacy because $row may have come from self::selectFields()
1113 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA ), 'ar_comment', $row, true );
1114
1115 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1116 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1117
1118 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId );
1119 }
1120
1121 /**
1122 * @see RevisionFactory::newRevisionFromRow_1_29
1123 *
1124 * MCR migration note: this replaces Revision::newFromRow
1125 *
1126 * @param object $row
1127 * @param int $queryFlags
1128 * @param Title|null $title
1129 *
1130 * @return RevisionRecord
1131 * @throws MWException
1132 * @throws RevisionAccessException
1133 */
1134 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title $title = null ) {
1135 Assert::parameterType( 'object', $row, '$row' );
1136
1137 if ( !$title ) {
1138 $pageId = isset( $row->rev_page ) ? $row->rev_page : 0; // XXX: also check page_id?
1139 $revId = isset( $row->rev_id ) ? $row->rev_id : 0;
1140
1141 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1142 }
1143
1144 if ( !isset( $row->page_latest ) ) {
1145 $row->page_latest = $title->getLatestRevID();
1146 if ( $row->page_latest === 0 && $title->exists() ) {
1147 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1148 }
1149 }
1150
1151 try {
1152 $user = User::newFromAnyId(
1153 isset( $row->rev_user ) ? $row->rev_user : null,
1154 isset( $row->rev_user_text ) ? $row->rev_user_text : null,
1155 isset( $row->rev_actor ) ? $row->rev_actor : null
1156 );
1157 } catch ( InvalidArgumentException $ex ) {
1158 wfWarn( __METHOD__ . ': ' . $ex->getMessage() );
1159 $user = new UserIdentityValue( 0, '', 0 );
1160 }
1161
1162 $comment = $this->commentStore
1163 // Legacy because $row may have come from self::selectFields()
1164 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA ), 'rev_comment', $row, true );
1165
1166 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1167 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1168
1169 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId );
1170 }
1171
1172 /**
1173 * @see RevisionFactory::newRevisionFromRow
1174 *
1175 * MCR migration note: this replaces Revision::newFromRow
1176 *
1177 * @param object $row
1178 * @param int $queryFlags
1179 * @param Title|null $title
1180 *
1181 * @return RevisionRecord
1182 */
1183 public function newRevisionFromRow( $row, $queryFlags = 0, Title $title = null ) {
1184 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1185 }
1186
1187 /**
1188 * Constructs a new MutableRevisionRecord based on the given associative array following
1189 * the MW1.29 convention for the Revision constructor.
1190 *
1191 * MCR migration note: this replaces Revision::newFromRow
1192 *
1193 * @param array $fields
1194 * @param int $queryFlags
1195 * @param Title|null $title
1196 *
1197 * @return MutableRevisionRecord
1198 * @throws MWException
1199 * @throws RevisionAccessException
1200 */
1201 public function newMutableRevisionFromArray(
1202 array $fields,
1203 $queryFlags = 0,
1204 Title $title = null
1205 ) {
1206 if ( !$title && isset( $fields['title'] ) ) {
1207 if ( !( $fields['title'] instanceof Title ) ) {
1208 throw new MWException( 'title field must contain a Title object.' );
1209 }
1210
1211 $title = $fields['title'];
1212 }
1213
1214 if ( !$title ) {
1215 $pageId = isset( $fields['page'] ) ? $fields['page'] : 0;
1216 $revId = isset( $fields['id'] ) ? $fields['id'] : 0;
1217
1218 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1219 }
1220
1221 if ( !isset( $fields['page'] ) ) {
1222 $fields['page'] = $title->getArticleID( $queryFlags );
1223 }
1224
1225 // if we have a content object, use it to set the model and type
1226 if ( !empty( $fields['content'] ) ) {
1227 if ( !( $fields['content'] instanceof Content ) ) {
1228 throw new MWException( 'content field must contain a Content object.' );
1229 }
1230
1231 if ( !empty( $fields['text_id'] ) ) {
1232 throw new MWException(
1233 "Text already stored in external store (id {$fields['text_id']}), " .
1234 "can't serialize content object"
1235 );
1236 }
1237 }
1238
1239 if (
1240 isset( $fields['comment'] )
1241 && !( $fields['comment'] instanceof CommentStoreComment )
1242 ) {
1243 $commentData = isset( $fields['comment_data'] ) ? $fields['comment_data'] : null;
1244
1245 if ( $fields['comment'] instanceof Message ) {
1246 $fields['comment'] = CommentStoreComment::newUnsavedComment(
1247 $fields['comment'],
1248 $commentData
1249 );
1250 } else {
1251 $commentText = trim( strval( $fields['comment'] ) );
1252 $fields['comment'] = CommentStoreComment::newUnsavedComment(
1253 $commentText,
1254 $commentData
1255 );
1256 }
1257 }
1258
1259 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1260
1261 $revision = new MutableRevisionRecord( $title, $this->wikiId );
1262 $this->initializeMutableRevisionFromArray( $revision, $fields );
1263 $revision->setSlot( $mainSlot );
1264
1265 return $revision;
1266 }
1267
1268 /**
1269 * @param MutableRevisionRecord $record
1270 * @param array $fields
1271 */
1272 private function initializeMutableRevisionFromArray(
1273 MutableRevisionRecord $record,
1274 array $fields
1275 ) {
1276 /** @var UserIdentity $user */
1277 $user = null;
1278
1279 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity ) ) {
1280 $user = $fields['user'];
1281 } else {
1282 try {
1283 $user = User::newFromAnyId(
1284 isset( $fields['user'] ) ? $fields['user'] : null,
1285 isset( $fields['user_text'] ) ? $fields['user_text'] : null,
1286 isset( $fields['actor'] ) ? $fields['actor'] : null
1287 );
1288 } catch ( InvalidArgumentException $ex ) {
1289 $user = null;
1290 }
1291 }
1292
1293 if ( $user ) {
1294 $record->setUser( $user );
1295 }
1296
1297 $timestamp = isset( $fields['timestamp'] )
1298 ? strval( $fields['timestamp'] )
1299 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1300
1301 $record->setTimestamp( $timestamp );
1302
1303 if ( isset( $fields['page'] ) ) {
1304 $record->setPageId( intval( $fields['page'] ) );
1305 }
1306
1307 if ( isset( $fields['id'] ) ) {
1308 $record->setId( intval( $fields['id'] ) );
1309 }
1310 if ( isset( $fields['parent_id'] ) ) {
1311 $record->setParentId( intval( $fields['parent_id'] ) );
1312 }
1313
1314 if ( isset( $fields['sha1'] ) ) {
1315 $record->setSha1( $fields['sha1'] );
1316 }
1317 if ( isset( $fields['size'] ) ) {
1318 $record->setSize( intval( $fields['size'] ) );
1319 }
1320
1321 if ( isset( $fields['minor_edit'] ) ) {
1322 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1323 }
1324 if ( isset( $fields['deleted'] ) ) {
1325 $record->setVisibility( intval( $fields['deleted'] ) );
1326 }
1327
1328 if ( isset( $fields['comment'] ) ) {
1329 Assert::parameterType(
1330 CommentStoreComment::class,
1331 $fields['comment'],
1332 '$row[\'comment\']'
1333 );
1334 $record->setComment( $fields['comment'] );
1335 }
1336 }
1337
1338 /**
1339 * Load a page revision from a given revision ID number.
1340 * Returns null if no such revision can be found.
1341 *
1342 * MCR migration note: this corresponds to Revision::loadFromId
1343 *
1344 * @note direct use is deprecated!
1345 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1346 *
1347 * @param IDatabase $db
1348 * @param int $id
1349 *
1350 * @return RevisionRecord|null
1351 */
1352 public function loadRevisionFromId( IDatabase $db, $id ) {
1353 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1354 }
1355
1356 /**
1357 * Load either the current, or a specified, revision
1358 * that's attached to a given page. If not attached
1359 * to that page, will return null.
1360 *
1361 * MCR migration note: this replaces Revision::loadFromPageId
1362 *
1363 * @note direct use is deprecated!
1364 * @todo remove when unused!
1365 *
1366 * @param IDatabase $db
1367 * @param int $pageid
1368 * @param int $id
1369 * @return RevisionRecord|null
1370 */
1371 public function loadRevisionFromPageId( IDatabase $db, $pageid, $id = 0 ) {
1372 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1373 if ( $id ) {
1374 $conds['rev_id'] = intval( $id );
1375 } else {
1376 $conds[] = 'rev_id=page_latest';
1377 }
1378 return $this->loadRevisionFromConds( $db, $conds );
1379 }
1380
1381 /**
1382 * Load either the current, or a specified, revision
1383 * that's attached to a given page. If not attached
1384 * to that page, will return null.
1385 *
1386 * MCR migration note: this replaces Revision::loadFromTitle
1387 *
1388 * @note direct use is deprecated!
1389 * @todo remove when unused!
1390 *
1391 * @param IDatabase $db
1392 * @param Title $title
1393 * @param int $id
1394 *
1395 * @return RevisionRecord|null
1396 */
1397 public function loadRevisionFromTitle( IDatabase $db, $title, $id = 0 ) {
1398 if ( $id ) {
1399 $matchId = intval( $id );
1400 } else {
1401 $matchId = 'page_latest';
1402 }
1403
1404 return $this->loadRevisionFromConds(
1405 $db,
1406 [
1407 "rev_id=$matchId",
1408 'page_namespace' => $title->getNamespace(),
1409 'page_title' => $title->getDBkey()
1410 ],
1411 0,
1412 $title
1413 );
1414 }
1415
1416 /**
1417 * Load the revision for the given title with the given timestamp.
1418 * WARNING: Timestamps may in some circumstances not be unique,
1419 * so this isn't the best key to use.
1420 *
1421 * MCR migration note: this replaces Revision::loadFromTimestamp
1422 *
1423 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1424 * @todo remove when unused!
1425 *
1426 * @param IDatabase $db
1427 * @param Title $title
1428 * @param string $timestamp
1429 * @return RevisionRecord|null
1430 */
1431 public function loadRevisionFromTimestamp( IDatabase $db, $title, $timestamp ) {
1432 return $this->loadRevisionFromConds( $db,
1433 [
1434 'rev_timestamp' => $db->timestamp( $timestamp ),
1435 'page_namespace' => $title->getNamespace(),
1436 'page_title' => $title->getDBkey()
1437 ],
1438 0,
1439 $title
1440 );
1441 }
1442
1443 /**
1444 * Given a set of conditions, fetch a revision
1445 *
1446 * This method should be used if we are pretty sure the revision exists.
1447 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1448 * on a replica before hitting the master database.
1449 *
1450 * MCR migration note: this corresponds to Revision::newFromConds
1451 *
1452 * @param array $conditions
1453 * @param int $flags (optional)
1454 * @param Title $title
1455 *
1456 * @return RevisionRecord|null
1457 */
1458 private function newRevisionFromConds( $conditions, $flags = 0, Title $title = null ) {
1459 $db = $this->getDBConnection( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
1460 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1461 $this->releaseDBConnection( $db );
1462
1463 $lb = $this->getDBLoadBalancer();
1464
1465 // Make sure new pending/committed revision are visibile later on
1466 // within web requests to certain avoid bugs like T93866 and T94407.
1467 if ( !$rev
1468 && !( $flags & self::READ_LATEST )
1469 && $lb->getServerCount() > 1
1470 && $lb->hasOrMadeRecentMasterChanges()
1471 ) {
1472 $flags = self::READ_LATEST;
1473 $db = $this->getDBConnection( DB_MASTER );
1474 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1475 $this->releaseDBConnection( $db );
1476 }
1477
1478 return $rev;
1479 }
1480
1481 /**
1482 * Given a set of conditions, fetch a revision from
1483 * the given database connection.
1484 *
1485 * MCR migration note: this corresponds to Revision::loadFromConds
1486 *
1487 * @param IDatabase $db
1488 * @param array $conditions
1489 * @param int $flags (optional)
1490 * @param Title $title
1491 *
1492 * @return RevisionRecord|null
1493 */
1494 private function loadRevisionFromConds(
1495 IDatabase $db,
1496 $conditions,
1497 $flags = 0,
1498 Title $title = null
1499 ) {
1500 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1501 if ( $row ) {
1502 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1503
1504 return $rev;
1505 }
1506
1507 return null;
1508 }
1509
1510 /**
1511 * Throws an exception if the given database connection does not belong to the wiki this
1512 * RevisionStore is bound to.
1513 *
1514 * @param IDatabase $db
1515 * @throws MWException
1516 */
1517 private function checkDatabaseWikiId( IDatabase $db ) {
1518 $storeWiki = $this->wikiId;
1519 $dbWiki = $db->getDomainID();
1520
1521 if ( $dbWiki === $storeWiki ) {
1522 return;
1523 }
1524
1525 // XXX: we really want the default database ID...
1526 $storeWiki = $storeWiki ?: wfWikiID();
1527 $dbWiki = $dbWiki ?: wfWikiID();
1528
1529 if ( $dbWiki === $storeWiki ) {
1530 return;
1531 }
1532
1533 // HACK: counteract encoding imposed by DatabaseDomain
1534 $storeWiki = str_replace( '?h', '-', $storeWiki );
1535 $dbWiki = str_replace( '?h', '-', $dbWiki );
1536
1537 if ( $dbWiki === $storeWiki ) {
1538 return;
1539 }
1540
1541 throw new MWException( "RevisionStore for $storeWiki "
1542 . "cannot be used with a DB connection for $dbWiki" );
1543 }
1544
1545 /**
1546 * Given a set of conditions, return a row with the
1547 * fields necessary to build RevisionRecord objects.
1548 *
1549 * MCR migration note: this corresponds to Revision::fetchFromConds
1550 *
1551 * @param IDatabase $db
1552 * @param array $conditions
1553 * @param int $flags (optional)
1554 *
1555 * @return object|false data row as a raw object
1556 */
1557 private function fetchRevisionRowFromConds( IDatabase $db, $conditions, $flags = 0 ) {
1558 $this->checkDatabaseWikiId( $db );
1559
1560 $revQuery = self::getQueryInfo( [ 'page', 'user' ] );
1561 $options = [];
1562 if ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING ) {
1563 $options[] = 'FOR UPDATE';
1564 }
1565 return $db->selectRow(
1566 $revQuery['tables'],
1567 $revQuery['fields'],
1568 $conditions,
1569 __METHOD__,
1570 $options,
1571 $revQuery['joins']
1572 );
1573 }
1574
1575 /**
1576 * Return the tables, fields, and join conditions to be selected to create
1577 * a new revision object.
1578 *
1579 * MCR migration note: this replaces Revision::getQueryInfo
1580 *
1581 * @since 1.31
1582 *
1583 * @param array $options Any combination of the following strings
1584 * - 'page': Join with the page table, and select fields to identify the page
1585 * - 'user': Join with the user table, and select the user name
1586 * - 'text': Join with the text table, and select fields to load page text
1587 *
1588 * @return array With three keys:
1589 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1590 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1591 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1592 */
1593 public function getQueryInfo( $options = [] ) {
1594 $ret = [
1595 'tables' => [],
1596 'fields' => [],
1597 'joins' => [],
1598 ];
1599
1600 $ret['tables'][] = 'revision';
1601 $ret['fields'] = array_merge( $ret['fields'], [
1602 'rev_id',
1603 'rev_page',
1604 'rev_text_id',
1605 'rev_timestamp',
1606 'rev_minor_edit',
1607 'rev_deleted',
1608 'rev_len',
1609 'rev_parent_id',
1610 'rev_sha1',
1611 ] );
1612
1613 $commentQuery = $this->commentStore->getJoin( 'rev_comment' );
1614 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1615 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1616 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1617
1618 $actorQuery = $this->actorMigration->getJoin( 'rev_user' );
1619 $ret['tables'] = array_merge( $ret['tables'], $actorQuery['tables'] );
1620 $ret['fields'] = array_merge( $ret['fields'], $actorQuery['fields'] );
1621 $ret['joins'] = array_merge( $ret['joins'], $actorQuery['joins'] );
1622
1623 if ( $this->contentHandlerUseDB ) {
1624 $ret['fields'][] = 'rev_content_format';
1625 $ret['fields'][] = 'rev_content_model';
1626 }
1627
1628 if ( in_array( 'page', $options, true ) ) {
1629 $ret['tables'][] = 'page';
1630 $ret['fields'] = array_merge( $ret['fields'], [
1631 'page_namespace',
1632 'page_title',
1633 'page_id',
1634 'page_latest',
1635 'page_is_redirect',
1636 'page_len',
1637 ] );
1638 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1639 }
1640
1641 if ( in_array( 'user', $options, true ) ) {
1642 $ret['tables'][] = 'user';
1643 $ret['fields'] = array_merge( $ret['fields'], [
1644 'user_name',
1645 ] );
1646 $u = $actorQuery['fields']['rev_user'];
1647 $ret['joins']['user'] = [ 'LEFT JOIN', [ "$u != 0", "user_id = $u" ] ];
1648 }
1649
1650 if ( in_array( 'text', $options, true ) ) {
1651 $ret['tables'][] = 'text';
1652 $ret['fields'] = array_merge( $ret['fields'], [
1653 'old_text',
1654 'old_flags'
1655 ] );
1656 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1657 }
1658
1659 return $ret;
1660 }
1661
1662 /**
1663 * Return the tables, fields, and join conditions to be selected to create
1664 * a new archived revision object.
1665 *
1666 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1667 *
1668 * @since 1.31
1669 *
1670 * @return array With three keys:
1671 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1672 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1673 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1674 */
1675 public function getArchiveQueryInfo() {
1676 $commentQuery = $this->commentStore->getJoin( 'ar_comment' );
1677 $actorQuery = $this->actorMigration->getJoin( 'ar_user' );
1678 $ret = [
1679 'tables' => [ 'archive' ] + $commentQuery['tables'] + $actorQuery['tables'],
1680 'fields' => [
1681 'ar_id',
1682 'ar_page_id',
1683 'ar_namespace',
1684 'ar_title',
1685 'ar_rev_id',
1686 'ar_text',
1687 'ar_text_id',
1688 'ar_timestamp',
1689 'ar_minor_edit',
1690 'ar_deleted',
1691 'ar_len',
1692 'ar_parent_id',
1693 'ar_sha1',
1694 ] + $commentQuery['fields'] + $actorQuery['fields'],
1695 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
1696 ];
1697
1698 if ( $this->contentHandlerUseDB ) {
1699 $ret['fields'][] = 'ar_content_format';
1700 $ret['fields'][] = 'ar_content_model';
1701 }
1702
1703 return $ret;
1704 }
1705
1706 /**
1707 * Do a batched query for the sizes of a set of revisions.
1708 *
1709 * MCR migration note: this replaces Revision::getParentLengths
1710 *
1711 * @param int[] $revIds
1712 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1713 * of the corresponding revision.
1714 */
1715 public function getRevisionSizes( array $revIds ) {
1716 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA ), $revIds );
1717 }
1718
1719 /**
1720 * Do a batched query for the sizes of a set of revisions.
1721 *
1722 * MCR migration note: this replaces Revision::getParentLengths
1723 *
1724 * @deprecated use RevisionStore::getRevisionSizes instead.
1725 *
1726 * @param IDatabase $db
1727 * @param int[] $revIds
1728 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1729 * of the corresponding revision.
1730 */
1731 public function listRevisionSizes( IDatabase $db, array $revIds ) {
1732 $this->checkDatabaseWikiId( $db );
1733
1734 $revLens = [];
1735 if ( !$revIds ) {
1736 return $revLens; // empty
1737 }
1738
1739 $res = $db->select(
1740 'revision',
1741 [ 'rev_id', 'rev_len' ],
1742 [ 'rev_id' => $revIds ],
1743 __METHOD__
1744 );
1745
1746 foreach ( $res as $row ) {
1747 $revLens[$row->rev_id] = intval( $row->rev_len );
1748 }
1749
1750 return $revLens;
1751 }
1752
1753 /**
1754 * Get previous revision for this title
1755 *
1756 * MCR migration note: this replaces Revision::getPrevious
1757 *
1758 * @param RevisionRecord $rev
1759 * @param Title $title if known (optional)
1760 *
1761 * @return RevisionRecord|null
1762 */
1763 public function getPreviousRevision( RevisionRecord $rev, Title $title = null ) {
1764 if ( $title === null ) {
1765 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1766 }
1767 $prev = $title->getPreviousRevisionID( $rev->getId() );
1768 if ( $prev ) {
1769 return $this->getRevisionByTitle( $title, $prev );
1770 }
1771 return null;
1772 }
1773
1774 /**
1775 * Get next revision for this title
1776 *
1777 * MCR migration note: this replaces Revision::getNext
1778 *
1779 * @param RevisionRecord $rev
1780 * @param Title $title if known (optional)
1781 *
1782 * @return RevisionRecord|null
1783 */
1784 public function getNextRevision( RevisionRecord $rev, Title $title = null ) {
1785 if ( $title === null ) {
1786 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1787 }
1788 $next = $title->getNextRevisionID( $rev->getId() );
1789 if ( $next ) {
1790 return $this->getRevisionByTitle( $title, $next );
1791 }
1792 return null;
1793 }
1794
1795 /**
1796 * Get previous revision Id for this page_id
1797 * This is used to populate rev_parent_id on save
1798 *
1799 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1800 *
1801 * @param IDatabase $db
1802 * @param RevisionRecord $rev
1803 *
1804 * @return int
1805 */
1806 private function getPreviousRevisionId( IDatabase $db, RevisionRecord $rev ) {
1807 $this->checkDatabaseWikiId( $db );
1808
1809 if ( $rev->getPageId() === null ) {
1810 return 0;
1811 }
1812 # Use page_latest if ID is not given
1813 if ( !$rev->getId() ) {
1814 $prevId = $db->selectField(
1815 'page', 'page_latest',
1816 [ 'page_id' => $rev->getPageId() ],
1817 __METHOD__
1818 );
1819 } else {
1820 $prevId = $db->selectField(
1821 'revision', 'rev_id',
1822 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1823 __METHOD__,
1824 [ 'ORDER BY' => 'rev_id DESC' ]
1825 );
1826 }
1827 return intval( $prevId );
1828 }
1829
1830 /**
1831 * Get rev_timestamp from rev_id, without loading the rest of the row
1832 *
1833 * MCR migration note: this replaces Revision::getTimestampFromId
1834 *
1835 * @param Title $title
1836 * @param int $id
1837 * @param int $flags
1838 * @return string|bool False if not found
1839 */
1840 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1841 $db = $this->getDBConnection(
1842 ( $flags & IDBAccessObject::READ_LATEST ) ? DB_MASTER : DB_REPLICA
1843 );
1844
1845 $conds = [ 'rev_id' => $id ];
1846 $conds['rev_page'] = $title->getArticleID();
1847 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1848
1849 $this->releaseDBConnection( $db );
1850 return ( $timestamp !== false ) ? wfTimestamp( TS_MW, $timestamp ) : false;
1851 }
1852
1853 /**
1854 * Get count of revisions per page...not very efficient
1855 *
1856 * MCR migration note: this replaces Revision::countByPageId
1857 *
1858 * @param IDatabase $db
1859 * @param int $id Page id
1860 * @return int
1861 */
1862 public function countRevisionsByPageId( IDatabase $db, $id ) {
1863 $this->checkDatabaseWikiId( $db );
1864
1865 $row = $db->selectRow( 'revision',
1866 [ 'revCount' => 'COUNT(*)' ],
1867 [ 'rev_page' => $id ],
1868 __METHOD__
1869 );
1870 if ( $row ) {
1871 return intval( $row->revCount );
1872 }
1873 return 0;
1874 }
1875
1876 /**
1877 * Get count of revisions per page...not very efficient
1878 *
1879 * MCR migration note: this replaces Revision::countByTitle
1880 *
1881 * @param IDatabase $db
1882 * @param Title $title
1883 * @return int
1884 */
1885 public function countRevisionsByTitle( IDatabase $db, $title ) {
1886 $id = $title->getArticleID();
1887 if ( $id ) {
1888 return $this->countRevisionsByPageId( $db, $id );
1889 }
1890 return 0;
1891 }
1892
1893 /**
1894 * Check if no edits were made by other users since
1895 * the time a user started editing the page. Limit to
1896 * 50 revisions for the sake of performance.
1897 *
1898 * MCR migration note: this replaces Revision::userWasLastToEdit
1899 *
1900 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1901 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1902 * has been deprecated since 1.24.
1903 *
1904 * @param IDatabase $db The Database to perform the check on.
1905 * @param int $pageId The ID of the page in question
1906 * @param int $userId The ID of the user in question
1907 * @param string $since Look at edits since this time
1908 *
1909 * @return bool True if the given user was the only one to edit since the given timestamp
1910 */
1911 public function userWasLastToEdit( IDatabase $db, $pageId, $userId, $since ) {
1912 $this->checkDatabaseWikiId( $db );
1913
1914 if ( !$userId ) {
1915 return false;
1916 }
1917
1918 $revQuery = self::getQueryInfo();
1919 $res = $db->select(
1920 $revQuery['tables'],
1921 [
1922 'rev_user' => $revQuery['fields']['rev_user'],
1923 ],
1924 [
1925 'rev_page' => $pageId,
1926 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1927 ],
1928 __METHOD__,
1929 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ],
1930 $revQuery['joins']
1931 );
1932 foreach ( $res as $row ) {
1933 if ( $row->rev_user != $userId ) {
1934 return false;
1935 }
1936 }
1937 return true;
1938 }
1939
1940 /**
1941 * Load a revision based on a known page ID and current revision ID from the DB
1942 *
1943 * This method allows for the use of caching, though accessing anything that normally
1944 * requires permission checks (aside from the text) will trigger a small DB lookup.
1945 *
1946 * MCR migration note: this replaces Revision::newKnownCurrent
1947 *
1948 * @param Title $title the associated page title
1949 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1950 *
1951 * @return RevisionRecord|bool Returns false if missing
1952 */
1953 public function getKnownCurrentRevision( Title $title, $revId ) {
1954 $db = $this->getDBConnectionRef( DB_REPLICA );
1955
1956 $pageId = $title->getArticleID();
1957
1958 if ( !$pageId ) {
1959 return false;
1960 }
1961
1962 if ( !$revId ) {
1963 $revId = $title->getLatestRevID();
1964 }
1965
1966 if ( !$revId ) {
1967 wfWarn(
1968 'No latest revision known for page ' . $title->getPrefixedDBkey()
1969 . ' even though it exists with page ID ' . $pageId
1970 );
1971 return false;
1972 }
1973
1974 $row = $this->cache->getWithSetCallback(
1975 // Page/rev IDs passed in from DB to reflect history merges
1976 $this->cache->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1977 WANObjectCache::TTL_WEEK,
1978 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1979 $setOpts += Database::getCacheSetOptions( $db );
1980
1981 $conds = [
1982 'rev_page' => intval( $pageId ),
1983 'page_id' => intval( $pageId ),
1984 'rev_id' => intval( $revId ),
1985 ];
1986
1987 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1988 return $row ?: false; // don't cache negatives
1989 }
1990 );
1991
1992 // Reflect revision deletion and user renames
1993 if ( $row ) {
1994 return $this->newRevisionFromRow( $row, 0, $title );
1995 } else {
1996 return false;
1997 }
1998 }
1999
2000 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.
2001
2002 }