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