Make Revision::__construct work with bad page ID
[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 = '';
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 $blobFlags = isset( $row->old_flags ) ? strval( $row->old_flags ) : '';
710 }
711
712 $mainSlotRow->slot_revision = intval( $row->rev_id );
713
714 $mainSlotRow->cont_size = isset( $row->rev_len ) ? intval( $row->rev_len ) : null;
715 $mainSlotRow->cont_sha1 = isset( $row->rev_sha1 ) ? strval( $row->rev_sha1 ) : null;
716 $mainSlotRow->model_name = isset( $row->rev_content_model )
717 ? strval( $row->rev_content_model )
718 : null;
719 // XXX: in the future, we'll probably always use the default format, and drop content_format
720 $mainSlotRow->format_name = isset( $row->rev_content_format )
721 ? strval( $row->rev_content_format )
722 : null;
723 } elseif ( is_array( $row ) ) {
724 $mainSlotRow->slot_revision = isset( $row['id'] ) ? intval( $row['id'] ) : null;
725
726 $mainSlotRow->cont_address = isset( $row['text_id'] )
727 ? 'tt:' . intval( $row['text_id'] )
728 : null;
729 $mainSlotRow->cont_size = isset( $row['len'] ) ? intval( $row['len'] ) : null;
730 $mainSlotRow->cont_sha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
731
732 $mainSlotRow->model_name = isset( $row['content_model'] )
733 ? strval( $row['content_model'] ) : null; // XXX: must be a string!
734 // XXX: in the future, we'll probably always use the default format, and drop content_format
735 $mainSlotRow->format_name = isset( $row['content_format'] )
736 ? strval( $row['content_format'] ) : null;
737 $blobData = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
738 $blobFlags = isset( $row['flags'] ) ? trim( strval( $row['flags'] ) ) : '';
739
740 // if we have a Content object, override mText and mContentModel
741 if ( !empty( $row['content'] ) ) {
742 if ( !( $row['content'] instanceof Content ) ) {
743 throw new MWException( 'content field must contain a Content object.' );
744 }
745
746 /** @var Content $content */
747 $content = $row['content'];
748 $handler = $content->getContentHandler();
749
750 $mainSlotRow->model_name = $content->getModel();
751
752 // XXX: in the future, we'll probably always use the default format.
753 if ( $mainSlotRow->format_name === null ) {
754 $mainSlotRow->format_name = $handler->getDefaultFormat();
755 }
756 }
757 } else {
758 throw new MWException( 'Revision constructor passed invalid row format.' );
759 }
760
761 // With the old schema, the content changes with every revision.
762 // ...except for null-revisions. Would be nice if we could detect them.
763 $mainSlotRow->slot_inherited = 0;
764
765 if ( $mainSlotRow->model_name === null ) {
766 $mainSlotRow->model_name = function ( SlotRecord $slot ) use ( $title ) {
767 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
768 // TODO: MCR: deprecate $title->getModel().
769 return ContentHandler::getDefaultModelFor( $title );
770 };
771 }
772
773 if ( !$content ) {
774 $content = function ( SlotRecord $slot )
775 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
776 {
777 return $this->loadSlotContent(
778 $slot,
779 $blobData,
780 $blobFlags,
781 $mainSlotRow->format_name,
782 $queryFlags
783 );
784 };
785 }
786
787 return new SlotRecord( $mainSlotRow, $content );
788 }
789
790 /**
791 * Loads a Content object based on a slot row.
792 *
793 * This method does not call $slot->getContent(), and may be used as a callback
794 * called by $slot->getContent().
795 *
796 * MCR migration note: this roughly corresponds to Revision::getContentInternal
797 *
798 * @param SlotRecord $slot The SlotRecord to load content for
799 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
800 * @param string $blobFlags Flags indicating how $blobData needs to be processed
801 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
802 * @param int $queryFlags
803 *
804 * @throw RevisionAccessException
805 * @return Content
806 */
807 private function loadSlotContent(
808 SlotRecord $slot,
809 $blobData = null,
810 $blobFlags = '',
811 $blobFormat = null,
812 $queryFlags = 0
813 ) {
814 if ( $blobData !== null ) {
815 Assert::parameterType( 'string', $blobData, '$blobData' );
816 Assert::parameterType( 'string', $blobFlags, '$blobFlags' );
817
818 $cacheKey = $slot->hasAddress() ? $slot->getAddress() : null;
819
820 $data = $this->blobStore->expandBlob( $blobData, $blobFlags, $cacheKey );
821
822 if ( $data === false ) {
823 throw new RevisionAccessException(
824 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
825 );
826 }
827 } else {
828 $address = $slot->getAddress();
829 try {
830 $data = $this->blobStore->getBlob( $address, $queryFlags );
831 } catch ( BlobAccessException $e ) {
832 throw new RevisionAccessException(
833 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
834 );
835 }
836 }
837
838 // Unserialize content
839 $handler = ContentHandler::getForModelID( $slot->getModel() );
840
841 $content = $handler->unserializeContent( $data, $blobFormat );
842 return $content;
843 }
844
845 /**
846 * Load a page revision from a given revision ID number.
847 * Returns null if no such revision can be found.
848 *
849 * MCR migration note: this replaces Revision::newFromId
850 *
851 * $flags include:
852 * IDBAccessObject::READ_LATEST: Select the data from the master
853 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
854 *
855 * @param int $id
856 * @param int $flags (optional)
857 * @return RevisionRecord|null
858 */
859 public function getRevisionById( $id, $flags = 0 ) {
860 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
861 }
862
863 /**
864 * Load either the current, or a specified, revision
865 * that's attached to a given link target. If not attached
866 * to that link target, will return null.
867 *
868 * MCR migration note: this replaces Revision::newFromTitle
869 *
870 * $flags include:
871 * IDBAccessObject::READ_LATEST: Select the data from the master
872 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
873 *
874 * @param LinkTarget $linkTarget
875 * @param int $revId (optional)
876 * @param int $flags Bitfield (optional)
877 * @return RevisionRecord|null
878 */
879 public function getRevisionByTitle( LinkTarget $linkTarget, $revId = 0, $flags = 0 ) {
880 $conds = [
881 'page_namespace' => $linkTarget->getNamespace(),
882 'page_title' => $linkTarget->getDBkey()
883 ];
884 if ( $revId ) {
885 // Use the specified revision ID.
886 // Note that we use newRevisionFromConds here because we want to retry
887 // and fall back to master if the page is not found on a replica.
888 // Since the caller supplied a revision ID, we are pretty sure the revision is
889 // supposed to exist, so we should try hard to find it.
890 $conds['rev_id'] = $revId;
891 return $this->newRevisionFromConds( $conds, $flags );
892 } else {
893 // Use a join to get the latest revision.
894 // Note that we don't use newRevisionFromConds here because we don't want to retry
895 // and fall back to master. The assumption is that we only want to force the fallback
896 // if we are quite sure the revision exists because the caller supplied a revision ID.
897 // If the page isn't found at all on a replica, it probably simply does not exist.
898 $db = $this->getDBConnection( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
899
900 $conds[] = 'rev_id=page_latest';
901 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
902
903 $this->releaseDBConnection( $db );
904 return $rev;
905 }
906 }
907
908 /**
909 * Load either the current, or a specified, revision
910 * that's attached to a given page ID.
911 * Returns null if no such revision can be found.
912 *
913 * MCR migration note: this replaces Revision::newFromPageId
914 *
915 * $flags include:
916 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
917 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
918 *
919 * @param int $pageId
920 * @param int $revId (optional)
921 * @param int $flags Bitfield (optional)
922 * @return RevisionRecord|null
923 */
924 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
925 $conds = [ 'page_id' => $pageId ];
926 if ( $revId ) {
927 // Use the specified revision ID.
928 // Note that we use newRevisionFromConds here because we want to retry
929 // and fall back to master if the page is not found on a replica.
930 // Since the caller supplied a revision ID, we are pretty sure the revision is
931 // supposed to exist, so we should try hard to find it.
932 $conds['rev_id'] = $revId;
933 return $this->newRevisionFromConds( $conds, $flags );
934 } else {
935 // Use a join to get the latest revision.
936 // Note that we don't use newRevisionFromConds here because we don't want to retry
937 // and fall back to master. The assumption is that we only want to force the fallback
938 // if we are quite sure the revision exists because the caller supplied a revision ID.
939 // If the page isn't found at all on a replica, it probably simply does not exist.
940 $db = $this->getDBConnection( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
941
942 $conds[] = 'rev_id=page_latest';
943 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
944
945 $this->releaseDBConnection( $db );
946 return $rev;
947 }
948 }
949
950 /**
951 * Load the revision for the given title with the given timestamp.
952 * WARNING: Timestamps may in some circumstances not be unique,
953 * so this isn't the best key to use.
954 *
955 * MCR migration note: this replaces Revision::loadFromTimestamp
956 *
957 * @param Title $title
958 * @param string $timestamp
959 * @return RevisionRecord|null
960 */
961 public function getRevisionByTimestamp( $title, $timestamp ) {
962 return $this->newRevisionFromConds(
963 [
964 'rev_timestamp' => $timestamp,
965 'page_namespace' => $title->getNamespace(),
966 'page_title' => $title->getDBkey()
967 ],
968 0,
969 $title
970 );
971 }
972
973 /**
974 * Make a fake revision object from an archive table row. This is queried
975 * for permissions or even inserted (as in Special:Undelete)
976 *
977 * MCR migration note: this replaces Revision::newFromArchiveRow
978 *
979 * @param object $row
980 * @param int $queryFlags
981 * @param Title|null $title
982 * @param array $overrides associative array with fields of $row to override. This may be
983 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
984 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
985 * override ar_parent_id.
986 *
987 * @return RevisionRecord
988 * @throws MWException
989 */
990 public function newRevisionFromArchiveRow(
991 $row,
992 $queryFlags = 0,
993 Title $title = null,
994 array $overrides = []
995 ) {
996 Assert::parameterType( 'object', $row, '$row' );
997
998 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
999 Assert::parameterType( 'integer', $queryFlags, '$queryFlags' );
1000
1001 if ( !$title && isset( $overrides['title'] ) ) {
1002 if ( !( $overrides['title'] instanceof Title ) ) {
1003 throw new MWException( 'title field override must contain a Title object.' );
1004 }
1005
1006 $title = $overrides['title'];
1007 }
1008
1009 if ( !isset( $title ) ) {
1010 if ( isset( $row->ar_namespace ) && isset( $row->ar_title ) ) {
1011 $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
1012 } else {
1013 throw new InvalidArgumentException(
1014 'A Title or ar_namespace and ar_title must be given'
1015 );
1016 }
1017 }
1018
1019 foreach ( $overrides as $key => $value ) {
1020 $field = "ar_$key";
1021 $row->$field = $value;
1022 }
1023
1024 $user = $this->getUserIdentityFromRowObject( $row, 'ar_' );
1025
1026 $comment = CommentStore::newKey( 'ar_comment' )
1027 // Legacy because $row may have come from self::selectFields()
1028 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA ), $row, true );
1029
1030 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1031 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1032
1033 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId );
1034 }
1035
1036 /**
1037 * @param object $row
1038 * @param string $prefix Field prefix, such as 'rev_' or 'ar_'.
1039 *
1040 * @return UserIdentityValue
1041 */
1042 private function getUserIdentityFromRowObject( $row, $prefix = 'rev_' ) {
1043 $idField = "{$prefix}user";
1044 $nameField = "{$prefix}user_text";
1045
1046 $userId = intval( $row->$idField );
1047
1048 if ( isset( $row->user_name ) ) {
1049 $userName = $row->user_name;
1050 } elseif ( isset( $row->$nameField ) ) {
1051 $userName = $row->$nameField;
1052 } else {
1053 $userName = User::whoIs( $userId );
1054 }
1055
1056 if ( $userName === false ) {
1057 wfWarn( __METHOD__ . ': Cannot determine user name for user ID ' . $userId );
1058 $userName = '';
1059 }
1060
1061 return new UserIdentityValue( $userId, $userName );
1062 }
1063
1064 /**
1065 * @see RevisionFactory::newRevisionFromRow_1_29
1066 *
1067 * MCR migration note: this replaces Revision::newFromRow
1068 *
1069 * @param object $row
1070 * @param int $queryFlags
1071 * @param Title|null $title
1072 *
1073 * @return RevisionRecord
1074 * @throws MWException
1075 * @throws RevisionAccessException
1076 */
1077 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title $title = null ) {
1078 Assert::parameterType( 'object', $row, '$row' );
1079
1080 if ( !$title ) {
1081 $pageId = isset( $row->rev_page ) ? $row->rev_page : 0; // XXX: also check page_id?
1082 $revId = isset( $row->rev_id ) ? $row->rev_id : 0;
1083
1084 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1085 }
1086
1087 if ( !isset( $row->page_latest ) ) {
1088 $row->page_latest = $title->getLatestRevID();
1089 if ( $row->page_latest === 0 && $title->exists() ) {
1090 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1091 }
1092 }
1093
1094 $user = $this->getUserIdentityFromRowObject( $row );
1095
1096 $comment = CommentStore::newKey( 'rev_comment' )
1097 // Legacy because $row may have come from self::selectFields()
1098 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA ), $row, true );
1099
1100 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1101 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1102
1103 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId );
1104 }
1105
1106 /**
1107 * @see RevisionFactory::newRevisionFromRow
1108 *
1109 * MCR migration note: this replaces Revision::newFromRow
1110 *
1111 * @param object $row
1112 * @param int $queryFlags
1113 * @param Title|null $title
1114 *
1115 * @return RevisionRecord
1116 */
1117 public function newRevisionFromRow( $row, $queryFlags = 0, Title $title = null ) {
1118 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1119 }
1120
1121 /**
1122 * Constructs a new MutableRevisionRecord based on the given associative array following
1123 * the MW1.29 convention for the Revision constructor.
1124 *
1125 * MCR migration note: this replaces Revision::newFromRow
1126 *
1127 * @param array $fields
1128 * @param int $queryFlags
1129 * @param Title|null $title
1130 *
1131 * @return MutableRevisionRecord
1132 * @throws MWException
1133 * @throws RevisionAccessException
1134 */
1135 public function newMutableRevisionFromArray(
1136 array $fields,
1137 $queryFlags = 0,
1138 Title $title = null
1139 ) {
1140 if ( !$title && isset( $fields['title'] ) ) {
1141 if ( !( $fields['title'] instanceof Title ) ) {
1142 throw new MWException( 'title field must contain a Title object.' );
1143 }
1144
1145 $title = $fields['title'];
1146 }
1147
1148 if ( !$title ) {
1149 $pageId = isset( $fields['page'] ) ? $fields['page'] : 0;
1150 $revId = isset( $fields['id'] ) ? $fields['id'] : 0;
1151
1152 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1153 }
1154
1155 if ( !isset( $fields['page'] ) ) {
1156 $fields['page'] = $title->getArticleID( $queryFlags );
1157 }
1158
1159 // if we have a content object, use it to set the model and type
1160 if ( !empty( $fields['content'] ) ) {
1161 if ( !( $fields['content'] instanceof Content ) ) {
1162 throw new MWException( 'content field must contain a Content object.' );
1163 }
1164
1165 if ( !empty( $fields['text_id'] ) ) {
1166 throw new MWException(
1167 "Text already stored in external store (id {$fields['text_id']}), " .
1168 "can't serialize content object"
1169 );
1170 }
1171 }
1172
1173 // Replaces old lazy loading logic in Revision::getUserText.
1174 if ( !isset( $fields['user_text'] ) && isset( $fields['user'] ) ) {
1175 if ( $fields['user'] instanceof UserIdentity ) {
1176 /** @var User $user */
1177 $user = $fields['user'];
1178 $fields['user_text'] = $user->getName();
1179 $fields['user'] = $user->getId();
1180 } else {
1181 // TODO: wrap this in a callback to make it lazy again.
1182 $name = $fields['user'] === 0 ? false : User::whoIs( $fields['user'] );
1183
1184 if ( $name === false ) {
1185 throw new MWException(
1186 'user_text not given, and unknown user ID ' . $fields['user']
1187 );
1188 }
1189
1190 $fields['user_text'] = $name;
1191 }
1192 }
1193
1194 if (
1195 isset( $fields['comment'] )
1196 && !( $fields['comment'] instanceof CommentStoreComment )
1197 ) {
1198 $commentData = isset( $fields['comment_data'] ) ? $fields['comment_data'] : null;
1199
1200 if ( $fields['comment'] instanceof Message ) {
1201 $fields['comment'] = CommentStoreComment::newUnsavedComment(
1202 $fields['comment'],
1203 $commentData
1204 );
1205 } else {
1206 $commentText = trim( strval( $fields['comment'] ) );
1207 $fields['comment'] = CommentStoreComment::newUnsavedComment(
1208 $commentText,
1209 $commentData
1210 );
1211 }
1212 }
1213
1214 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1215
1216 $revision = new MutableRevisionRecord( $title, $this->wikiId );
1217 $this->initializeMutableRevisionFromArray( $revision, $fields );
1218 $revision->setSlot( $mainSlot );
1219
1220 return $revision;
1221 }
1222
1223 /**
1224 * @param MutableRevisionRecord $record
1225 * @param array $fields
1226 */
1227 private function initializeMutableRevisionFromArray(
1228 MutableRevisionRecord $record,
1229 array $fields
1230 ) {
1231 /** @var UserIdentity $user */
1232 $user = null;
1233
1234 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity ) ) {
1235 $user = $fields['user'];
1236 } elseif ( isset( $fields['user'] ) && isset( $fields['user_text'] ) ) {
1237 $user = new UserIdentityValue( intval( $fields['user'] ), $fields['user_text'] );
1238 } elseif ( isset( $fields['user'] ) ) {
1239 $user = User::newFromId( intval( $fields['user'] ) );
1240 } elseif ( isset( $fields['user_text'] ) ) {
1241 $user = User::newFromName( $fields['user_text'] );
1242
1243 // User::newFromName will return false for IP addresses (and invalid names)
1244 if ( $user == false ) {
1245 $user = new UserIdentityValue( 0, $fields['user_text'] );
1246 }
1247 }
1248
1249 if ( $user ) {
1250 $record->setUser( $user );
1251 }
1252
1253 $timestamp = isset( $fields['timestamp'] )
1254 ? strval( $fields['timestamp'] )
1255 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1256
1257 $record->setTimestamp( $timestamp );
1258
1259 if ( isset( $fields['page'] ) ) {
1260 $record->setPageId( intval( $fields['page'] ) );
1261 }
1262
1263 if ( isset( $fields['id'] ) ) {
1264 $record->setId( intval( $fields['id'] ) );
1265 }
1266 if ( isset( $fields['parent_id'] ) ) {
1267 $record->setParentId( intval( $fields['parent_id'] ) );
1268 }
1269
1270 if ( isset( $fields['sha1'] ) ) {
1271 $record->setSha1( $fields['sha1'] );
1272 }
1273 if ( isset( $fields['size'] ) ) {
1274 $record->setSize( intval( $fields['size'] ) );
1275 }
1276
1277 if ( isset( $fields['minor_edit'] ) ) {
1278 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1279 }
1280 if ( isset( $fields['deleted'] ) ) {
1281 $record->setVisibility( intval( $fields['deleted'] ) );
1282 }
1283
1284 if ( isset( $fields['comment'] ) ) {
1285 Assert::parameterType(
1286 CommentStoreComment::class,
1287 $fields['comment'],
1288 '$row[\'comment\']'
1289 );
1290 $record->setComment( $fields['comment'] );
1291 }
1292 }
1293
1294 /**
1295 * Load a page revision from a given revision ID number.
1296 * Returns null if no such revision can be found.
1297 *
1298 * MCR migration note: this corresponds to Revision::loadFromId
1299 *
1300 * @note direct use is deprecated!
1301 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1302 *
1303 * @param IDatabase $db
1304 * @param int $id
1305 *
1306 * @return RevisionRecord|null
1307 */
1308 public function loadRevisionFromId( IDatabase $db, $id ) {
1309 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1310 }
1311
1312 /**
1313 * Load either the current, or a specified, revision
1314 * that's attached to a given page. If not attached
1315 * to that page, will return null.
1316 *
1317 * MCR migration note: this replaces Revision::loadFromPageId
1318 *
1319 * @note direct use is deprecated!
1320 * @todo remove when unused!
1321 *
1322 * @param IDatabase $db
1323 * @param int $pageid
1324 * @param int $id
1325 * @return RevisionRecord|null
1326 */
1327 public function loadRevisionFromPageId( IDatabase $db, $pageid, $id = 0 ) {
1328 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1329 if ( $id ) {
1330 $conds['rev_id'] = intval( $id );
1331 } else {
1332 $conds[] = 'rev_id=page_latest';
1333 }
1334 return $this->loadRevisionFromConds( $db, $conds );
1335 }
1336
1337 /**
1338 * Load either the current, or a specified, revision
1339 * that's attached to a given page. If not attached
1340 * to that page, will return null.
1341 *
1342 * MCR migration note: this replaces Revision::loadFromTitle
1343 *
1344 * @note direct use is deprecated!
1345 * @todo remove when unused!
1346 *
1347 * @param IDatabase $db
1348 * @param Title $title
1349 * @param int $id
1350 *
1351 * @return RevisionRecord|null
1352 */
1353 public function loadRevisionFromTitle( IDatabase $db, $title, $id = 0 ) {
1354 if ( $id ) {
1355 $matchId = intval( $id );
1356 } else {
1357 $matchId = 'page_latest';
1358 }
1359
1360 return $this->loadRevisionFromConds(
1361 $db,
1362 [
1363 "rev_id=$matchId",
1364 'page_namespace' => $title->getNamespace(),
1365 'page_title' => $title->getDBkey()
1366 ],
1367 0,
1368 $title
1369 );
1370 }
1371
1372 /**
1373 * Load the revision for the given title with the given timestamp.
1374 * WARNING: Timestamps may in some circumstances not be unique,
1375 * so this isn't the best key to use.
1376 *
1377 * MCR migration note: this replaces Revision::loadFromTimestamp
1378 *
1379 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1380 * @todo remove when unused!
1381 *
1382 * @param IDatabase $db
1383 * @param Title $title
1384 * @param string $timestamp
1385 * @return RevisionRecord|null
1386 */
1387 public function loadRevisionFromTimestamp( IDatabase $db, $title, $timestamp ) {
1388 return $this->loadRevisionFromConds( $db,
1389 [
1390 'rev_timestamp' => $db->timestamp( $timestamp ),
1391 'page_namespace' => $title->getNamespace(),
1392 'page_title' => $title->getDBkey()
1393 ],
1394 0,
1395 $title
1396 );
1397 }
1398
1399 /**
1400 * Given a set of conditions, fetch a revision
1401 *
1402 * This method should be used if we are pretty sure the revision exists.
1403 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1404 * on a replica before hitting the master database.
1405 *
1406 * MCR migration note: this corresponds to Revision::newFromConds
1407 *
1408 * @param array $conditions
1409 * @param int $flags (optional)
1410 * @param Title $title
1411 *
1412 * @return RevisionRecord|null
1413 */
1414 private function newRevisionFromConds( $conditions, $flags = 0, Title $title = null ) {
1415 $db = $this->getDBConnection( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
1416 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1417 $this->releaseDBConnection( $db );
1418
1419 $lb = $this->getDBLoadBalancer();
1420
1421 // Make sure new pending/committed revision are visibile later on
1422 // within web requests to certain avoid bugs like T93866 and T94407.
1423 if ( !$rev
1424 && !( $flags & self::READ_LATEST )
1425 && $lb->getServerCount() > 1
1426 && $lb->hasOrMadeRecentMasterChanges()
1427 ) {
1428 $flags = self::READ_LATEST;
1429 $db = $this->getDBConnection( DB_MASTER );
1430 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1431 $this->releaseDBConnection( $db );
1432 }
1433
1434 return $rev;
1435 }
1436
1437 /**
1438 * Given a set of conditions, fetch a revision from
1439 * the given database connection.
1440 *
1441 * MCR migration note: this corresponds to Revision::loadFromConds
1442 *
1443 * @param IDatabase $db
1444 * @param array $conditions
1445 * @param int $flags (optional)
1446 * @param Title $title
1447 *
1448 * @return RevisionRecord|null
1449 */
1450 private function loadRevisionFromConds(
1451 IDatabase $db,
1452 $conditions,
1453 $flags = 0,
1454 Title $title = null
1455 ) {
1456 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1457 if ( $row ) {
1458 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1459
1460 return $rev;
1461 }
1462
1463 return null;
1464 }
1465
1466 /**
1467 * Throws an exception if the given database connection does not belong to the wiki this
1468 * RevisionStore is bound to.
1469 *
1470 * @param IDatabase $db
1471 * @throws MWException
1472 */
1473 private function checkDatabaseWikiId( IDatabase $db ) {
1474 $storeWiki = $this->wikiId;
1475 $dbWiki = $db->getDomainID();
1476
1477 if ( $dbWiki === $storeWiki ) {
1478 return;
1479 }
1480
1481 // XXX: we really want the default database ID...
1482 $storeWiki = $storeWiki ?: wfWikiID();
1483 $dbWiki = $dbWiki ?: wfWikiID();
1484
1485 if ( $dbWiki === $storeWiki ) {
1486 return;
1487 }
1488
1489 // HACK: counteract encoding imposed by DatabaseDomain
1490 $storeWiki = str_replace( '?h', '-', $storeWiki );
1491 $dbWiki = str_replace( '?h', '-', $dbWiki );
1492
1493 if ( $dbWiki === $storeWiki ) {
1494 return;
1495 }
1496
1497 throw new MWException( "RevisionStore for $storeWiki "
1498 . "cannot be used with a DB connection for $dbWiki" );
1499 }
1500
1501 /**
1502 * Given a set of conditions, return a row with the
1503 * fields necessary to build RevisionRecord objects.
1504 *
1505 * MCR migration note: this corresponds to Revision::fetchFromConds
1506 *
1507 * @param IDatabase $db
1508 * @param array $conditions
1509 * @param int $flags (optional)
1510 *
1511 * @return object|false data row as a raw object
1512 */
1513 private function fetchRevisionRowFromConds( IDatabase $db, $conditions, $flags = 0 ) {
1514 $this->checkDatabaseWikiId( $db );
1515
1516 $revQuery = self::getQueryInfo( [ 'page', 'user' ] );
1517 $options = [];
1518 if ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING ) {
1519 $options[] = 'FOR UPDATE';
1520 }
1521 return $db->selectRow(
1522 $revQuery['tables'],
1523 $revQuery['fields'],
1524 $conditions,
1525 __METHOD__,
1526 $options,
1527 $revQuery['joins']
1528 );
1529 }
1530
1531 /**
1532 * Return the tables, fields, and join conditions to be selected to create
1533 * a new revision object.
1534 *
1535 * MCR migration note: this replaces Revision::getQueryInfo
1536 *
1537 * @since 1.31
1538 *
1539 * @param array $options Any combination of the following strings
1540 * - 'page': Join with the page table, and select fields to identify the page
1541 * - 'user': Join with the user table, and select the user name
1542 * - 'text': Join with the text table, and select fields to load page text
1543 *
1544 * @return array With three keys:
1545 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1546 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1547 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1548 */
1549 public function getQueryInfo( $options = [] ) {
1550 $ret = [
1551 'tables' => [],
1552 'fields' => [],
1553 'joins' => [],
1554 ];
1555
1556 $ret['tables'][] = 'revision';
1557 $ret['fields'] = array_merge( $ret['fields'], [
1558 'rev_id',
1559 'rev_page',
1560 'rev_text_id',
1561 'rev_timestamp',
1562 'rev_user_text',
1563 'rev_user',
1564 'rev_minor_edit',
1565 'rev_deleted',
1566 'rev_len',
1567 'rev_parent_id',
1568 'rev_sha1',
1569 ] );
1570
1571 $commentQuery = CommentStore::newKey( 'rev_comment' )->getJoin();
1572 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1573 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1574 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1575
1576 if ( $this->contentHandlerUseDB ) {
1577 $ret['fields'][] = 'rev_content_format';
1578 $ret['fields'][] = 'rev_content_model';
1579 }
1580
1581 if ( in_array( 'page', $options, true ) ) {
1582 $ret['tables'][] = 'page';
1583 $ret['fields'] = array_merge( $ret['fields'], [
1584 'page_namespace',
1585 'page_title',
1586 'page_id',
1587 'page_latest',
1588 'page_is_redirect',
1589 'page_len',
1590 ] );
1591 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1592 }
1593
1594 if ( in_array( 'user', $options, true ) ) {
1595 $ret['tables'][] = 'user';
1596 $ret['fields'] = array_merge( $ret['fields'], [
1597 'user_name',
1598 ] );
1599 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
1600 }
1601
1602 if ( in_array( 'text', $options, true ) ) {
1603 $ret['tables'][] = 'text';
1604 $ret['fields'] = array_merge( $ret['fields'], [
1605 'old_text',
1606 'old_flags'
1607 ] );
1608 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1609 }
1610
1611 return $ret;
1612 }
1613
1614 /**
1615 * Return the tables, fields, and join conditions to be selected to create
1616 * a new archived revision object.
1617 *
1618 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1619 *
1620 * @since 1.31
1621 *
1622 * @return array With three keys:
1623 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1624 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1625 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1626 */
1627 public function getArchiveQueryInfo() {
1628 $commentQuery = CommentStore::newKey( 'ar_comment' )->getJoin();
1629 $ret = [
1630 'tables' => [ 'archive' ] + $commentQuery['tables'],
1631 'fields' => [
1632 'ar_id',
1633 'ar_page_id',
1634 'ar_namespace',
1635 'ar_title',
1636 'ar_rev_id',
1637 'ar_text',
1638 'ar_text_id',
1639 'ar_timestamp',
1640 'ar_user_text',
1641 'ar_user',
1642 'ar_minor_edit',
1643 'ar_deleted',
1644 'ar_len',
1645 'ar_parent_id',
1646 'ar_sha1',
1647 ] + $commentQuery['fields'],
1648 'joins' => $commentQuery['joins'],
1649 ];
1650
1651 if ( $this->contentHandlerUseDB ) {
1652 $ret['fields'][] = 'ar_content_format';
1653 $ret['fields'][] = 'ar_content_model';
1654 }
1655
1656 return $ret;
1657 }
1658
1659 /**
1660 * Do a batched query for the sizes of a set of revisions.
1661 *
1662 * MCR migration note: this replaces Revision::getParentLengths
1663 *
1664 * @param int[] $revIds
1665 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1666 * of the corresponding revision.
1667 */
1668 public function getRevisionSizes( array $revIds ) {
1669 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA ), $revIds );
1670 }
1671
1672 /**
1673 * Do a batched query for the sizes of a set of revisions.
1674 *
1675 * MCR migration note: this replaces Revision::getParentLengths
1676 *
1677 * @deprecated use RevisionStore::getRevisionSizes instead.
1678 *
1679 * @param IDatabase $db
1680 * @param int[] $revIds
1681 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1682 * of the corresponding revision.
1683 */
1684 public function listRevisionSizes( IDatabase $db, array $revIds ) {
1685 $this->checkDatabaseWikiId( $db );
1686
1687 $revLens = [];
1688 if ( !$revIds ) {
1689 return $revLens; // empty
1690 }
1691
1692 $res = $db->select(
1693 'revision',
1694 [ 'rev_id', 'rev_len' ],
1695 [ 'rev_id' => $revIds ],
1696 __METHOD__
1697 );
1698
1699 foreach ( $res as $row ) {
1700 $revLens[$row->rev_id] = intval( $row->rev_len );
1701 }
1702
1703 return $revLens;
1704 }
1705
1706 /**
1707 * Get previous revision for this title
1708 *
1709 * MCR migration note: this replaces Revision::getPrevious
1710 *
1711 * @param RevisionRecord $rev
1712 * @param Title $title if known (optional)
1713 *
1714 * @return RevisionRecord|null
1715 */
1716 public function getPreviousRevision( RevisionRecord $rev, Title $title = null ) {
1717 if ( $title === null ) {
1718 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1719 }
1720 $prev = $title->getPreviousRevisionID( $rev->getId() );
1721 if ( $prev ) {
1722 return $this->getRevisionByTitle( $title, $prev );
1723 }
1724 return null;
1725 }
1726
1727 /**
1728 * Get next revision for this title
1729 *
1730 * MCR migration note: this replaces Revision::getNext
1731 *
1732 * @param RevisionRecord $rev
1733 * @param Title $title if known (optional)
1734 *
1735 * @return RevisionRecord|null
1736 */
1737 public function getNextRevision( RevisionRecord $rev, Title $title = null ) {
1738 if ( $title === null ) {
1739 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1740 }
1741 $next = $title->getNextRevisionID( $rev->getId() );
1742 if ( $next ) {
1743 return $this->getRevisionByTitle( $title, $next );
1744 }
1745 return null;
1746 }
1747
1748 /**
1749 * Get previous revision Id for this page_id
1750 * This is used to populate rev_parent_id on save
1751 *
1752 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1753 *
1754 * @param IDatabase $db
1755 * @param RevisionRecord $rev
1756 *
1757 * @return int
1758 */
1759 private function getPreviousRevisionId( IDatabase $db, RevisionRecord $rev ) {
1760 $this->checkDatabaseWikiId( $db );
1761
1762 if ( $rev->getPageId() === null ) {
1763 return 0;
1764 }
1765 # Use page_latest if ID is not given
1766 if ( !$rev->getId() ) {
1767 $prevId = $db->selectField(
1768 'page', 'page_latest',
1769 [ 'page_id' => $rev->getPageId() ],
1770 __METHOD__
1771 );
1772 } else {
1773 $prevId = $db->selectField(
1774 'revision', 'rev_id',
1775 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1776 __METHOD__,
1777 [ 'ORDER BY' => 'rev_id DESC' ]
1778 );
1779 }
1780 return intval( $prevId );
1781 }
1782
1783 /**
1784 * Get rev_timestamp from rev_id, without loading the rest of the row
1785 *
1786 * MCR migration note: this replaces Revision::getTimestampFromId
1787 *
1788 * @param Title $title
1789 * @param int $id
1790 * @param int $flags
1791 * @return string|bool False if not found
1792 */
1793 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1794 $db = $this->getDBConnection(
1795 ( $flags & IDBAccessObject::READ_LATEST ) ? DB_MASTER : DB_REPLICA
1796 );
1797
1798 $conds = [ 'rev_id' => $id ];
1799 $conds['rev_page'] = $title->getArticleID();
1800 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1801
1802 $this->releaseDBConnection( $db );
1803 return ( $timestamp !== false ) ? wfTimestamp( TS_MW, $timestamp ) : false;
1804 }
1805
1806 /**
1807 * Get count of revisions per page...not very efficient
1808 *
1809 * MCR migration note: this replaces Revision::countByPageId
1810 *
1811 * @param IDatabase $db
1812 * @param int $id Page id
1813 * @return int
1814 */
1815 public function countRevisionsByPageId( IDatabase $db, $id ) {
1816 $this->checkDatabaseWikiId( $db );
1817
1818 $row = $db->selectRow( 'revision',
1819 [ 'revCount' => 'COUNT(*)' ],
1820 [ 'rev_page' => $id ],
1821 __METHOD__
1822 );
1823 if ( $row ) {
1824 return intval( $row->revCount );
1825 }
1826 return 0;
1827 }
1828
1829 /**
1830 * Get count of revisions per page...not very efficient
1831 *
1832 * MCR migration note: this replaces Revision::countByTitle
1833 *
1834 * @param IDatabase $db
1835 * @param Title $title
1836 * @return int
1837 */
1838 public function countRevisionsByTitle( IDatabase $db, $title ) {
1839 $id = $title->getArticleID();
1840 if ( $id ) {
1841 return $this->countRevisionsByPageId( $db, $id );
1842 }
1843 return 0;
1844 }
1845
1846 /**
1847 * Check if no edits were made by other users since
1848 * the time a user started editing the page. Limit to
1849 * 50 revisions for the sake of performance.
1850 *
1851 * MCR migration note: this replaces Revision::userWasLastToEdit
1852 *
1853 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1854 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1855 * has been deprecated since 1.24.
1856 *
1857 * @param IDatabase $db The Database to perform the check on.
1858 * @param int $pageId The ID of the page in question
1859 * @param int $userId The ID of the user in question
1860 * @param string $since Look at edits since this time
1861 *
1862 * @return bool True if the given user was the only one to edit since the given timestamp
1863 */
1864 public function userWasLastToEdit( IDatabase $db, $pageId, $userId, $since ) {
1865 $this->checkDatabaseWikiId( $db );
1866
1867 if ( !$userId ) {
1868 return false;
1869 }
1870
1871 $res = $db->select(
1872 'revision',
1873 'rev_user',
1874 [
1875 'rev_page' => $pageId,
1876 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1877 ],
1878 __METHOD__,
1879 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ]
1880 );
1881 foreach ( $res as $row ) {
1882 if ( $row->rev_user != $userId ) {
1883 return false;
1884 }
1885 }
1886 return true;
1887 }
1888
1889 /**
1890 * Load a revision based on a known page ID and current revision ID from the DB
1891 *
1892 * This method allows for the use of caching, though accessing anything that normally
1893 * requires permission checks (aside from the text) will trigger a small DB lookup.
1894 *
1895 * MCR migration note: this replaces Revision::newKnownCurrent
1896 *
1897 * @param Title $title the associated page title
1898 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1899 *
1900 * @return RevisionRecord|bool Returns false if missing
1901 */
1902 public function getKnownCurrentRevision( Title $title, $revId ) {
1903 $db = $this->getDBConnectionRef( DB_REPLICA );
1904
1905 $pageId = $title->getArticleID();
1906
1907 if ( !$pageId ) {
1908 return false;
1909 }
1910
1911 if ( !$revId ) {
1912 $revId = $title->getLatestRevID();
1913 }
1914
1915 if ( !$revId ) {
1916 wfWarn(
1917 'No latest revision known for page ' . $title->getPrefixedDBkey()
1918 . ' even though it exists with page ID ' . $pageId
1919 );
1920 return false;
1921 }
1922
1923 $row = $this->cache->getWithSetCallback(
1924 // Page/rev IDs passed in from DB to reflect history merges
1925 $this->cache->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1926 WANObjectCache::TTL_WEEK,
1927 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1928 $setOpts += Database::getCacheSetOptions( $db );
1929
1930 $conds = [
1931 'rev_page' => intval( $pageId ),
1932 'page_id' => intval( $pageId ),
1933 'rev_id' => intval( $revId ),
1934 ];
1935
1936 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1937 return $row ?: false; // don't cache negatives
1938 }
1939 );
1940
1941 // Reflect revision deletion and user renames
1942 if ( $row ) {
1943 return $this->newRevisionFromRow( $row, 0, $title );
1944 } else {
1945 return false;
1946 }
1947 }
1948
1949 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.
1950
1951 }