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