Merge "Use WikiMap methods for wiki ID logic in more places"
[lhc/web/wiklou.git] / includes / Revision.php
1 <?php
2 /**
3 * Representation of a page version.
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 * @file
21 */
22
23 use MediaWiki\Revision\MutableRevisionRecord;
24 use MediaWiki\Revision\RevisionAccessException;
25 use MediaWiki\Revision\RevisionFactory;
26 use MediaWiki\Revision\RevisionLookup;
27 use MediaWiki\Revision\RevisionRecord;
28 use MediaWiki\Revision\RevisionStore;
29 use MediaWiki\Revision\RevisionStoreRecord;
30 use MediaWiki\Revision\SlotRecord;
31 use MediaWiki\Storage\SqlBlobStore;
32 use Wikimedia\Rdbms\IDatabase;
33 use MediaWiki\Linker\LinkTarget;
34 use MediaWiki\MediaWikiServices;
35 use Wikimedia\Rdbms\ResultWrapper;
36 use Wikimedia\Rdbms\FakeResultWrapper;
37
38 /**
39 * @deprecated since 1.31, use RevisionRecord, RevisionStore, and BlobStore instead.
40 */
41 class Revision implements IDBAccessObject {
42
43 /** @var RevisionRecord */
44 protected $mRecord;
45
46 // Revision deletion constants
47 const DELETED_TEXT = RevisionRecord::DELETED_TEXT;
48 const DELETED_COMMENT = RevisionRecord::DELETED_COMMENT;
49 const DELETED_USER = RevisionRecord::DELETED_USER;
50 const DELETED_RESTRICTED = RevisionRecord::DELETED_RESTRICTED;
51 const SUPPRESSED_USER = RevisionRecord::SUPPRESSED_USER;
52 const SUPPRESSED_ALL = RevisionRecord::SUPPRESSED_ALL;
53
54 // Audience options for accessors
55 const FOR_PUBLIC = RevisionRecord::FOR_PUBLIC;
56 const FOR_THIS_USER = RevisionRecord::FOR_THIS_USER;
57 const RAW = RevisionRecord::RAW;
58
59 const TEXT_CACHE_GROUP = SqlBlobStore::TEXT_CACHE_GROUP;
60
61 /**
62 * @return RevisionStore
63 */
64 protected static function getRevisionStore( $wiki = false ) {
65 if ( $wiki ) {
66 return MediaWikiServices::getInstance()->getRevisionStoreFactory()
67 ->getRevisionStore( $wiki );
68 } else {
69 return MediaWikiServices::getInstance()->getRevisionStore();
70 }
71 }
72
73 /**
74 * @return RevisionLookup
75 */
76 protected static function getRevisionLookup() {
77 return MediaWikiServices::getInstance()->getRevisionLookup();
78 }
79
80 /**
81 * @return RevisionFactory
82 */
83 protected static function getRevisionFactory() {
84 return MediaWikiServices::getInstance()->getRevisionFactory();
85 }
86
87 /**
88 * @param bool|string $wiki The ID of the target wiki database. Use false for the local wiki.
89 *
90 * @return SqlBlobStore
91 */
92 protected static function getBlobStore( $wiki = false ) {
93 $store = MediaWikiServices::getInstance()
94 ->getBlobStoreFactory()
95 ->newSqlBlobStore( $wiki );
96
97 if ( !$store instanceof SqlBlobStore ) {
98 throw new RuntimeException(
99 'The backwards compatibility code in Revision currently requires the BlobStore '
100 . 'service to be an SqlBlobStore instance, but it is a ' . get_class( $store )
101 );
102 }
103
104 return $store;
105 }
106
107 /**
108 * Load a page revision from a given revision ID number.
109 * Returns null if no such revision can be found.
110 *
111 * $flags include:
112 * Revision::READ_LATEST : Select the data from the master
113 * Revision::READ_LOCKING : Select & lock the data from the master
114 *
115 * @param int $id
116 * @param int $flags (optional)
117 * @return Revision|null
118 */
119 public static function newFromId( $id, $flags = 0 ) {
120 $rec = self::getRevisionLookup()->getRevisionById( $id, $flags );
121 return $rec === null ? null : new Revision( $rec, $flags );
122 }
123
124 /**
125 * Load either the current, or a specified, revision
126 * that's attached to a given link target. If not attached
127 * to that link target, will return null.
128 *
129 * $flags include:
130 * Revision::READ_LATEST : Select the data from the master
131 * Revision::READ_LOCKING : Select & lock the data from the master
132 *
133 * @param LinkTarget $linkTarget
134 * @param int $id (optional)
135 * @param int $flags Bitfield (optional)
136 * @return Revision|null
137 */
138 public static function newFromTitle( LinkTarget $linkTarget, $id = 0, $flags = 0 ) {
139 $rec = self::getRevisionLookup()->getRevisionByTitle( $linkTarget, $id, $flags );
140 return $rec === null ? null : new Revision( $rec, $flags );
141 }
142
143 /**
144 * Load either the current, or a specified, revision
145 * that's attached to a given page ID.
146 * Returns null if no such revision can be found.
147 *
148 * $flags include:
149 * Revision::READ_LATEST : Select the data from the master (since 1.20)
150 * Revision::READ_LOCKING : Select & lock the data from the master
151 *
152 * @param int $pageId
153 * @param int $revId (optional)
154 * @param int $flags Bitfield (optional)
155 * @return Revision|null
156 */
157 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
158 $rec = self::getRevisionLookup()->getRevisionByPageId( $pageId, $revId, $flags );
159 return $rec === null ? null : new Revision( $rec, $flags );
160 }
161
162 /**
163 * Make a fake revision object from an archive table row. This is queried
164 * for permissions or even inserted (as in Special:Undelete)
165 *
166 * @param object $row
167 * @param array $overrides
168 *
169 * @throws MWException
170 * @return Revision
171 */
172 public static function newFromArchiveRow( $row, $overrides = [] ) {
173 /**
174 * MCR Migration: https://phabricator.wikimedia.org/T183564
175 * This method used to overwrite attributes, then passed to Revision::__construct
176 * RevisionStore::newRevisionFromArchiveRow instead overrides row field names
177 * So do a conversion here.
178 */
179 if ( array_key_exists( 'page', $overrides ) ) {
180 $overrides['page_id'] = $overrides['page'];
181 unset( $overrides['page'] );
182 }
183
184 /**
185 * We require a Title for both the Revision object and the RevisionRecord.
186 * Below is duplicated logic from RevisionStore::newRevisionFromArchiveRow
187 * to fetch a title in order pass it into the Revision object.
188 */
189 $title = null;
190 if ( isset( $overrides['title'] ) ) {
191 if ( !( $overrides['title'] instanceof Title ) ) {
192 throw new MWException( 'title field override must contain a Title object.' );
193 }
194
195 $title = $overrides['title'];
196 }
197 if ( $title !== null ) {
198 if ( isset( $row->ar_namespace ) && isset( $row->ar_title ) ) {
199 $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
200 } else {
201 throw new InvalidArgumentException(
202 'A Title or ar_namespace and ar_title must be given'
203 );
204 }
205 }
206
207 $rec = self::getRevisionFactory()->newRevisionFromArchiveRow( $row, 0, $title, $overrides );
208 return new Revision( $rec, self::READ_NORMAL, $title );
209 }
210
211 /**
212 * @since 1.19
213 *
214 * MCR migration note: replaced by RevisionStore::newRevisionFromRow(). Note that
215 * newFromRow() also accepts arrays, while newRevisionFromRow() does not. Instead,
216 * a MutableRevisionRecord should be constructed directly.
217 * RevisionStore::newMutableRevisionFromArray() can be used as a temporary replacement,
218 * but should be avoided.
219 *
220 * @param object|array $row
221 * @return Revision
222 */
223 public static function newFromRow( $row ) {
224 if ( is_array( $row ) ) {
225 $rec = self::getRevisionFactory()->newMutableRevisionFromArray( $row );
226 } else {
227 $rec = self::getRevisionFactory()->newRevisionFromRow( $row );
228 }
229
230 return new Revision( $rec );
231 }
232
233 /**
234 * Load a page revision from a given revision ID number.
235 * Returns null if no such revision can be found.
236 *
237 * @deprecated since 1.31, use RevisionStore::getRevisionById() instead.
238 *
239 * @param IDatabase $db
240 * @param int $id
241 * @return Revision|null
242 */
243 public static function loadFromId( $db, $id ) {
244 wfDeprecated( __METHOD__, '1.31' ); // no known callers
245 $rec = self::getRevisionStore()->loadRevisionFromId( $db, $id );
246 return $rec === null ? null : new Revision( $rec );
247 }
248
249 /**
250 * Load either the current, or a specified, revision
251 * that's attached to a given page. If not attached
252 * to that page, will return null.
253 *
254 * @deprecated since 1.31, use RevisionStore::getRevisionByPageId() instead.
255 *
256 * @param IDatabase $db
257 * @param int $pageid
258 * @param int $id
259 * @return Revision|null
260 */
261 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
262 $rec = self::getRevisionStore()->loadRevisionFromPageId( $db, $pageid, $id );
263 return $rec === null ? null : new Revision( $rec );
264 }
265
266 /**
267 * Load either the current, or a specified, revision
268 * that's attached to a given page. If not attached
269 * to that page, will return null.
270 *
271 * @deprecated since 1.31, use RevisionStore::getRevisionByTitle() instead.
272 *
273 * @param IDatabase $db
274 * @param Title $title
275 * @param int $id
276 * @return Revision|null
277 */
278 public static function loadFromTitle( $db, $title, $id = 0 ) {
279 $rec = self::getRevisionStore()->loadRevisionFromTitle( $db, $title, $id );
280 return $rec === null ? null : new Revision( $rec );
281 }
282
283 /**
284 * Load the revision for the given title with the given timestamp.
285 * WARNING: Timestamps may in some circumstances not be unique,
286 * so this isn't the best key to use.
287 *
288 * @deprecated since 1.31, use RevisionStore::getRevisionByTimestamp()
289 * or RevisionStore::loadRevisionFromTimestamp() instead.
290 *
291 * @param IDatabase $db
292 * @param Title $title
293 * @param string $timestamp
294 * @return Revision|null
295 */
296 public static function loadFromTimestamp( $db, $title, $timestamp ) {
297 $rec = self::getRevisionStore()->loadRevisionFromTimestamp( $db, $title, $timestamp );
298 return $rec === null ? null : new Revision( $rec );
299 }
300
301 /**
302 * Return a wrapper for a series of database rows to
303 * fetch all of a given page's revisions in turn.
304 * Each row can be fed to the constructor to get objects.
305 *
306 * @param LinkTarget $title
307 * @return ResultWrapper
308 * @deprecated Since 1.28, no callers in core nor in known extensions. No-op since 1.31.
309 */
310 public static function fetchRevision( LinkTarget $title ) {
311 wfDeprecated( __METHOD__, '1.31' );
312 return new FakeResultWrapper( [] );
313 }
314
315 /**
316 * Return the value of a select() JOIN conds array for the user table.
317 * This will get user table rows for logged-in users.
318 * @since 1.19
319 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'user' ] ) instead.
320 * @return array
321 */
322 public static function userJoinCond() {
323 global $wgActorTableSchemaMigrationStage;
324
325 wfDeprecated( __METHOD__, '1.31' );
326 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
327 // If code is using this instead of self::getQueryInfo(), there's
328 // no way the join it's trying to do can work once the old fields
329 // aren't being used anymore.
330 throw new BadMethodCallException(
331 'Cannot use ' . __METHOD__
332 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
333 );
334 }
335
336 return [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
337 }
338
339 /**
340 * Return the value of a select() page conds array for the page table.
341 * This will assure that the revision(s) are not orphaned from live pages.
342 * @since 1.19
343 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'page' ] ) instead.
344 * @return array
345 */
346 public static function pageJoinCond() {
347 wfDeprecated( __METHOD__, '1.31' );
348 return [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
349 }
350
351 /**
352 * Return the list of revision fields that should be selected to create
353 * a new revision.
354 * @deprecated since 1.31, use RevisionStore::getQueryInfo() instead.
355 * @return array
356 */
357 public static function selectFields() {
358 global $wgContentHandlerUseDB, $wgActorTableSchemaMigrationStage;
359 global $wgMultiContentRevisionSchemaMigrationStage;
360
361 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
362 // If code is using this instead of self::getQueryInfo(), there's a
363 // decent chance it's going to try to directly access
364 // $row->rev_user or $row->rev_user_text and we can't give it
365 // useful values here once those aren't being used anymore.
366 throw new BadMethodCallException(
367 'Cannot use ' . __METHOD__
368 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
369 );
370 }
371
372 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
373 // If code is using this instead of self::getQueryInfo(), there's a
374 // decent chance it's going to try to directly access
375 // $row->rev_text_id or $row->rev_content_model and we can't give it
376 // useful values here once those aren't being written anymore,
377 // and may not exist at all.
378 throw new BadMethodCallException(
379 'Cannot use ' . __METHOD__ . ' when $wgMultiContentRevisionSchemaMigrationStage '
380 . 'does not have SCHEMA_COMPAT_WRITE_OLD set.'
381 );
382 }
383
384 wfDeprecated( __METHOD__, '1.31' );
385
386 $fields = [
387 'rev_id',
388 'rev_page',
389 'rev_text_id',
390 'rev_timestamp',
391 'rev_user_text',
392 'rev_user',
393 'rev_actor' => 'NULL',
394 'rev_minor_edit',
395 'rev_deleted',
396 'rev_len',
397 'rev_parent_id',
398 'rev_sha1',
399 ];
400
401 $fields += CommentStore::getStore()->getFields( 'rev_comment' );
402
403 if ( $wgContentHandlerUseDB ) {
404 $fields[] = 'rev_content_format';
405 $fields[] = 'rev_content_model';
406 }
407
408 return $fields;
409 }
410
411 /**
412 * Return the list of revision fields that should be selected to create
413 * a new revision from an archive row.
414 * @deprecated since 1.31, use RevisionStore::getArchiveQueryInfo() instead.
415 * @return array
416 */
417 public static function selectArchiveFields() {
418 global $wgContentHandlerUseDB, $wgActorTableSchemaMigrationStage;
419 global $wgMultiContentRevisionSchemaMigrationStage;
420
421 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
422 // If code is using this instead of self::getQueryInfo(), there's a
423 // decent chance it's going to try to directly access
424 // $row->ar_user or $row->ar_user_text and we can't give it
425 // useful values here once those aren't being used anymore.
426 throw new BadMethodCallException(
427 'Cannot use ' . __METHOD__
428 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
429 );
430 }
431
432 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
433 // If code is using this instead of self::getQueryInfo(), there's a
434 // decent chance it's going to try to directly access
435 // $row->ar_text_id or $row->ar_content_model and we can't give it
436 // useful values here once those aren't being written anymore,
437 // and may not exist at all.
438 throw new BadMethodCallException(
439 'Cannot use ' . __METHOD__ . ' when $wgMultiContentRevisionSchemaMigrationStage '
440 . 'does not have SCHEMA_COMPAT_WRITE_OLD set.'
441 );
442 }
443
444 wfDeprecated( __METHOD__, '1.31' );
445
446 $fields = [
447 'ar_id',
448 'ar_page_id',
449 'ar_rev_id',
450 'ar_text_id',
451 'ar_timestamp',
452 'ar_user_text',
453 'ar_user',
454 'ar_actor' => 'NULL',
455 'ar_minor_edit',
456 'ar_deleted',
457 'ar_len',
458 'ar_parent_id',
459 'ar_sha1',
460 ];
461
462 $fields += CommentStore::getStore()->getFields( 'ar_comment' );
463
464 if ( $wgContentHandlerUseDB ) {
465 $fields[] = 'ar_content_format';
466 $fields[] = 'ar_content_model';
467 }
468 return $fields;
469 }
470
471 /**
472 * Return the list of text fields that should be selected to read the
473 * revision text
474 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'text' ] ) instead.
475 * @return array
476 */
477 public static function selectTextFields() {
478 wfDeprecated( __METHOD__, '1.31' );
479 return [
480 'old_text',
481 'old_flags'
482 ];
483 }
484
485 /**
486 * Return the list of page fields that should be selected from page table
487 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'page' ] ) instead.
488 * @return array
489 */
490 public static function selectPageFields() {
491 wfDeprecated( __METHOD__, '1.31' );
492 return [
493 'page_namespace',
494 'page_title',
495 'page_id',
496 'page_latest',
497 'page_is_redirect',
498 'page_len',
499 ];
500 }
501
502 /**
503 * Return the list of user fields that should be selected from user table
504 * @deprecated since 1.31, use RevisionStore::getQueryInfo( [ 'user' ] ) instead.
505 * @return array
506 */
507 public static function selectUserFields() {
508 wfDeprecated( __METHOD__, '1.31' );
509 return [ 'user_name' ];
510 }
511
512 /**
513 * Return the tables, fields, and join conditions to be selected to create
514 * a new revision object.
515 * @since 1.31
516 * @deprecated since 1.31, use RevisionStore::getQueryInfo() instead.
517 * @param array $options Any combination of the following strings
518 * - 'page': Join with the page table, and select fields to identify the page
519 * - 'user': Join with the user table, and select the user name
520 * - 'text': Join with the text table, and select fields to load page text
521 * @return array With three keys:
522 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
523 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
524 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
525 */
526 public static function getQueryInfo( $options = [] ) {
527 return self::getRevisionStore()->getQueryInfo( $options );
528 }
529
530 /**
531 * Return the tables, fields, and join conditions to be selected to create
532 * a new archived revision object.
533 * @since 1.31
534 * @deprecated since 1.31, use RevisionStore::getArchiveQueryInfo() instead.
535 * @return array With three keys:
536 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
537 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
538 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
539 */
540 public static function getArchiveQueryInfo() {
541 return self::getRevisionStore()->getArchiveQueryInfo();
542 }
543
544 /**
545 * Do a batched query to get the parent revision lengths
546 *
547 * @deprecated in 1.31, use RevisionStore::getRevisionSizes instead.
548 *
549 * @param IDatabase $db
550 * @param array $revIds
551 * @return array
552 */
553 public static function getParentLengths( $db, array $revIds ) {
554 return self::getRevisionStore()->listRevisionSizes( $db, $revIds );
555 }
556
557 /**
558 * @param object|array|RevisionRecord $row Either a database row or an array
559 * @param int $queryFlags
560 * @param Title|null $title
561 *
562 * @access private
563 */
564 function __construct( $row, $queryFlags = 0, Title $title = null ) {
565 global $wgUser;
566
567 if ( $row instanceof RevisionRecord ) {
568 $this->mRecord = $row;
569 } elseif ( is_array( $row ) ) {
570 // If no user is specified, fall back to using the global user object, to stay
571 // compatible with pre-1.31 behavior.
572 if ( !isset( $row['user'] ) && !isset( $row['user_text'] ) ) {
573 $row['user'] = $wgUser;
574 }
575
576 $this->mRecord = self::getRevisionFactory()->newMutableRevisionFromArray(
577 $row,
578 $queryFlags,
579 $this->ensureTitle( $row, $queryFlags, $title )
580 );
581 } elseif ( is_object( $row ) ) {
582 $this->mRecord = self::getRevisionFactory()->newRevisionFromRow(
583 $row,
584 $queryFlags,
585 $this->ensureTitle( $row, $queryFlags, $title )
586 );
587 } else {
588 throw new InvalidArgumentException(
589 '$row must be a row object, an associative array, or a RevisionRecord'
590 );
591 }
592 }
593
594 /**
595 * Make sure we have *some* Title object for use by the constructor.
596 * For B/C, the constructor shouldn't fail even for a bad page ID or bad revision ID.
597 *
598 * @param array|object $row
599 * @param int $queryFlags
600 * @param Title|null $title
601 *
602 * @return Title $title if not null, or a Title constructed from information in $row.
603 */
604 private function ensureTitle( $row, $queryFlags, $title = null ) {
605 if ( $title ) {
606 return $title;
607 }
608
609 if ( is_array( $row ) ) {
610 if ( isset( $row['title'] ) ) {
611 if ( !( $row['title'] instanceof Title ) ) {
612 throw new MWException( 'title field must contain a Title object.' );
613 }
614
615 return $row['title'];
616 }
617
618 $pageId = $row['page'] ?? 0;
619 $revId = $row['id'] ?? 0;
620 } else {
621 $pageId = $row->rev_page ?? 0;
622 $revId = $row->rev_id ?? 0;
623 }
624
625 try {
626 $title = self::getRevisionStore()->getTitle( $pageId, $revId, $queryFlags );
627 } catch ( RevisionAccessException $ex ) {
628 // construct a dummy title!
629 wfLogWarning( __METHOD__ . ': ' . $ex->getMessage() );
630
631 // NOTE: this Title will only be used inside RevisionRecord
632 $title = Title::makeTitleSafe( NS_SPECIAL, "Badtitle/ID=$pageId" );
633 $title->resetArticleID( $pageId );
634 }
635
636 return $title;
637 }
638
639 /**
640 * @return RevisionRecord
641 */
642 public function getRevisionRecord() {
643 return $this->mRecord;
644 }
645
646 /**
647 * Get revision ID
648 *
649 * @return int|null
650 */
651 public function getId() {
652 return $this->mRecord->getId();
653 }
654
655 /**
656 * Set the revision ID
657 *
658 * This should only be used for proposed revisions that turn out to be null edits.
659 *
660 * @note Only supported on Revisions that were constructed based on associative arrays,
661 * since they are mutable.
662 *
663 * @since 1.19
664 * @param int|string $id
665 * @throws MWException
666 */
667 public function setId( $id ) {
668 if ( $this->mRecord instanceof MutableRevisionRecord ) {
669 $this->mRecord->setId( intval( $id ) );
670 } else {
671 throw new MWException( __METHOD__ . ' is not supported on this instance' );
672 }
673 }
674
675 /**
676 * Set the user ID/name
677 *
678 * This should only be used for proposed revisions that turn out to be null edits
679 *
680 * @note Only supported on Revisions that were constructed based on associative arrays,
681 * since they are mutable.
682 *
683 * @since 1.28
684 * @deprecated since 1.31, please reuse old Revision object
685 * @param int $id User ID
686 * @param string $name User name
687 * @throws MWException
688 */
689 public function setUserIdAndName( $id, $name ) {
690 if ( $this->mRecord instanceof MutableRevisionRecord ) {
691 $user = User::newFromAnyId( intval( $id ), $name, null );
692 $this->mRecord->setUser( $user );
693 } else {
694 throw new MWException( __METHOD__ . ' is not supported on this instance' );
695 }
696 }
697
698 /**
699 * @return SlotRecord
700 */
701 private function getMainSlotRaw() {
702 return $this->mRecord->getSlot( SlotRecord::MAIN, RevisionRecord::RAW );
703 }
704
705 /**
706 * Get the ID of the row of the text table that contains the content of the
707 * revision's main slot, if that content is stored in the text table.
708 *
709 * If the content is stored elsewhere, this returns null.
710 *
711 * @deprecated since 1.31, use RevisionRecord()->getSlot()->getContentAddress() to
712 * get that actual address that can be used with BlobStore::getBlob(); or use
713 * RevisionRecord::hasSameContent() to check if two revisions have the same content.
714 *
715 * @return int|null
716 */
717 public function getTextId() {
718 $slot = $this->getMainSlotRaw();
719 return $slot->hasAddress()
720 ? self::getBlobStore()->getTextIdFromAddress( $slot->getAddress() )
721 : null;
722 }
723
724 /**
725 * Get parent revision ID (the original previous page revision)
726 *
727 * @return int|null The ID of the parent revision. 0 indicates that there is no
728 * parent revision. Null indicates that the parent revision is not known.
729 */
730 public function getParentId() {
731 return $this->mRecord->getParentId();
732 }
733
734 /**
735 * Returns the length of the text in this revision, or null if unknown.
736 *
737 * @return int|null
738 */
739 public function getSize() {
740 try {
741 return $this->mRecord->getSize();
742 } catch ( RevisionAccessException $ex ) {
743 return null;
744 }
745 }
746
747 /**
748 * Returns the base36 sha1 of the content in this revision, or null if unknown.
749 *
750 * @return string|null
751 */
752 public function getSha1() {
753 try {
754 return $this->mRecord->getSha1();
755 } catch ( RevisionAccessException $ex ) {
756 return null;
757 }
758 }
759
760 /**
761 * Returns the title of the page associated with this entry.
762 * Since 1.31, this will never return null.
763 *
764 * Will do a query, when title is not set and id is given.
765 *
766 * @return Title
767 */
768 public function getTitle() {
769 $linkTarget = $this->mRecord->getPageAsLinkTarget();
770 return Title::newFromLinkTarget( $linkTarget );
771 }
772
773 /**
774 * Set the title of the revision
775 *
776 * @deprecated since 1.31, this is now a noop. Pass the Title to the constructor instead.
777 *
778 * @param Title $title
779 */
780 public function setTitle( $title ) {
781 if ( !$title->equals( $this->getTitle() ) ) {
782 throw new InvalidArgumentException(
783 $title->getPrefixedText()
784 . ' is not the same as '
785 . $this->mRecord->getPageAsLinkTarget()->__toString()
786 );
787 }
788 }
789
790 /**
791 * Get the page ID
792 *
793 * @return int|null
794 */
795 public function getPage() {
796 return $this->mRecord->getPageId();
797 }
798
799 /**
800 * Fetch revision's user id if it's available to the specified audience.
801 * If the specified audience does not have access to it, zero will be
802 * returned.
803 *
804 * @param int $audience One of:
805 * Revision::FOR_PUBLIC to be displayed to all users
806 * Revision::FOR_THIS_USER to be displayed to the given user
807 * Revision::RAW get the ID regardless of permissions
808 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
809 * to the $audience parameter
810 * @return int
811 */
812 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
813 global $wgUser;
814
815 if ( $audience === self::FOR_THIS_USER && !$user ) {
816 $user = $wgUser;
817 }
818
819 $user = $this->mRecord->getUser( $audience, $user );
820 return $user ? $user->getId() : 0;
821 }
822
823 /**
824 * Fetch revision's username if it's available to the specified audience.
825 * If the specified audience does not have access to the username, an
826 * empty string will be returned.
827 *
828 * @param int $audience One of:
829 * Revision::FOR_PUBLIC to be displayed to all users
830 * Revision::FOR_THIS_USER to be displayed to the given user
831 * Revision::RAW get the text regardless of permissions
832 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
833 * to the $audience parameter
834 * @return string
835 */
836 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
837 global $wgUser;
838
839 if ( $audience === self::FOR_THIS_USER && !$user ) {
840 $user = $wgUser;
841 }
842
843 $user = $this->mRecord->getUser( $audience, $user );
844 return $user ? $user->getName() : '';
845 }
846 /**
847 * Fetch revision comment if it's available to the specified audience.
848 * If the specified audience does not have access to the comment, an
849 * empty string will be returned.
850 *
851 * @param int $audience One of:
852 * Revision::FOR_PUBLIC to be displayed to all users
853 * Revision::FOR_THIS_USER to be displayed to the given user
854 * Revision::RAW get the text regardless of permissions
855 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
856 * to the $audience parameter
857 * @return string
858 */
859 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
860 global $wgUser;
861
862 if ( $audience === self::FOR_THIS_USER && !$user ) {
863 $user = $wgUser;
864 }
865
866 $comment = $this->mRecord->getComment( $audience, $user );
867 return $comment === null ? null : $comment->text;
868 }
869
870 /**
871 * @return bool
872 */
873 public function isMinor() {
874 return $this->mRecord->isMinor();
875 }
876
877 /**
878 * @return int Rcid of the unpatrolled row, zero if there isn't one
879 */
880 public function isUnpatrolled() {
881 return self::getRevisionStore()->getRcIdIfUnpatrolled( $this->mRecord );
882 }
883
884 /**
885 * Get the RC object belonging to the current revision, if there's one
886 *
887 * @param int $flags (optional) $flags include:
888 * Revision::READ_LATEST : Select the data from the master
889 *
890 * @since 1.22
891 * @return RecentChange|null
892 */
893 public function getRecentChange( $flags = 0 ) {
894 return self::getRevisionStore()->getRecentChange( $this->mRecord, $flags );
895 }
896
897 /**
898 * @param int $field One of DELETED_* bitfield constants
899 *
900 * @return bool
901 */
902 public function isDeleted( $field ) {
903 return $this->mRecord->isDeleted( $field );
904 }
905
906 /**
907 * Get the deletion bitfield of the revision
908 *
909 * @return int
910 */
911 public function getVisibility() {
912 return $this->mRecord->getVisibility();
913 }
914
915 /**
916 * Fetch revision content if it's available to the specified audience.
917 * If the specified audience does not have the ability to view this
918 * revision, or the content could not be loaded, null will be returned.
919 *
920 * @param int $audience One of:
921 * Revision::FOR_PUBLIC to be displayed to all users
922 * Revision::FOR_THIS_USER to be displayed to $user
923 * Revision::RAW get the text regardless of permissions
924 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
925 * to the $audience parameter
926 * @since 1.21
927 * @return Content|null
928 */
929 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
930 global $wgUser;
931
932 if ( $audience === self::FOR_THIS_USER && !$user ) {
933 $user = $wgUser;
934 }
935
936 try {
937 return $this->mRecord->getContent( SlotRecord::MAIN, $audience, $user );
938 }
939 catch ( RevisionAccessException $e ) {
940 return null;
941 }
942 }
943
944 /**
945 * Get original serialized data (without checking view restrictions)
946 *
947 * @since 1.21
948 * @deprecated since 1.31, use BlobStore::getBlob instead.
949 *
950 * @return string
951 */
952 public function getSerializedData() {
953 $slot = $this->getMainSlotRaw();
954 return $slot->getContent()->serialize();
955 }
956
957 /**
958 * Returns the content model for the main slot of this revision.
959 *
960 * If no content model was stored in the database, the default content model for the title is
961 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
962 * is used as a last resort.
963 *
964 * @todo drop this, with MCR, there no longer is a single model associated with a revision.
965 *
966 * @return string The content model id associated with this revision,
967 * see the CONTENT_MODEL_XXX constants.
968 */
969 public function getContentModel() {
970 return $this->getMainSlotRaw()->getModel();
971 }
972
973 /**
974 * Returns the content format for the main slot of this revision.
975 *
976 * If no content format was stored in the database, the default format for this
977 * revision's content model is returned.
978 *
979 * @todo drop this, the format is irrelevant to the revision!
980 *
981 * @return string The content format id associated with this revision,
982 * see the CONTENT_FORMAT_XXX constants.
983 */
984 public function getContentFormat() {
985 $format = $this->getMainSlotRaw()->getFormat();
986
987 if ( $format === null ) {
988 // if no format was stored along with the blob, fall back to default format
989 $format = $this->getContentHandler()->getDefaultFormat();
990 }
991
992 return $format;
993 }
994
995 /**
996 * Returns the content handler appropriate for this revision's content model.
997 *
998 * @throws MWException
999 * @return ContentHandler
1000 */
1001 public function getContentHandler() {
1002 return ContentHandler::getForModelID( $this->getContentModel() );
1003 }
1004
1005 /**
1006 * @return string
1007 */
1008 public function getTimestamp() {
1009 return $this->mRecord->getTimestamp();
1010 }
1011
1012 /**
1013 * @return bool
1014 */
1015 public function isCurrent() {
1016 return ( $this->mRecord instanceof RevisionStoreRecord ) && $this->mRecord->isCurrent();
1017 }
1018
1019 /**
1020 * Get previous revision for this title
1021 *
1022 * @return Revision|null
1023 */
1024 public function getPrevious() {
1025 $title = $this->getTitle();
1026 $rec = self::getRevisionLookup()->getPreviousRevision( $this->mRecord, $title );
1027 return $rec === null ? null : new Revision( $rec, self::READ_NORMAL, $title );
1028 }
1029
1030 /**
1031 * Get next revision for this title
1032 *
1033 * @return Revision|null
1034 */
1035 public function getNext() {
1036 $title = $this->getTitle();
1037 $rec = self::getRevisionLookup()->getNextRevision( $this->mRecord, $title );
1038 return $rec === null ? null : new Revision( $rec, self::READ_NORMAL, $title );
1039 }
1040
1041 /**
1042 * Get revision text associated with an old or archive row
1043 *
1044 * If the text field is not included, this uses RevisionStore to load the appropriate slot
1045 * and return its serialized content. This is the default backwards-compatibility behavior
1046 * when reading from the MCR aware database schema is enabled. For this to work, either
1047 * the revision ID or the page ID must be included in the row.
1048 *
1049 * When using the old text field, the flags field must also be set. Including the old_id
1050 * field will activate cache usage as long as the $wiki parameter is not set.
1051 *
1052 * @deprecated since 1.32, use RevisionStore::newRevisionFromRow instead.
1053 *
1054 * @param stdClass $row The text data. If a falsy value is passed instead, false is returned.
1055 * @param string $prefix Table prefix (default 'old_')
1056 * @param string|bool $wiki The name of the wiki to load the revision text from
1057 * (same as the wiki $row was loaded from) or false to indicate the local
1058 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1059 * identifier as understood by the LoadBalancer class.
1060 * @return string|false Text the text requested or false on failure
1061 */
1062 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1063 global $wgMultiContentRevisionSchemaMigrationStage;
1064
1065 if ( !$row ) {
1066 return false;
1067 }
1068
1069 $textField = $prefix . 'text';
1070 $flagsField = $prefix . 'flags';
1071
1072 if ( isset( $row->$textField ) ) {
1073 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
1074 // The text field was read, but it's no longer being populated!
1075 // We could gloss over this by using the text when it's there and loading
1076 // if when it's not, but it seems preferable to complain loudly about a
1077 // query that is no longer guaranteed to work reliably.
1078 throw new LogicException(
1079 'Cannot use ' . __METHOD__ . ' with the ' . $textField . ' field when'
1080 . ' $wgMultiContentRevisionSchemaMigrationStage does not include'
1081 . ' SCHEMA_COMPAT_WRITE_OLD. The field may not be populated for all revisions!'
1082 );
1083 }
1084
1085 $text = $row->$textField;
1086 } else {
1087 // Missing text field, we are probably looking at the MCR-enabled DB schema.
1088
1089 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
1090 // This method should no longer be used with the new schema. Ideally, we
1091 // would already trigger a deprecation warning when SCHEMA_COMPAT_READ_NEW is set.
1092 wfDeprecated( __METHOD__ . ' (MCR without SCHEMA_COMPAT_WRITE_OLD)', '1.32' );
1093 }
1094
1095 $store = self::getRevisionStore( $wiki );
1096 $rev = $prefix === 'ar_'
1097 ? $store->newRevisionFromArchiveRow( $row )
1098 : $store->newRevisionFromRow( $row );
1099
1100 $content = $rev->getContent( SlotRecord::MAIN );
1101 return $content ? $content->serialize() : false;
1102 }
1103
1104 if ( isset( $row->$flagsField ) ) {
1105 $flags = explode( ',', $row->$flagsField );
1106 } else {
1107 $flags = [];
1108 }
1109
1110 $cacheKey = isset( $row->old_id )
1111 ? SqlBlobStore::makeAddressFromTextId( $row->old_id )
1112 : null;
1113
1114 $revisionText = self::getBlobStore( $wiki )->expandBlob( $text, $flags, $cacheKey );
1115
1116 if ( $revisionText === false ) {
1117 if ( isset( $row->old_id ) ) {
1118 wfLogWarning( __METHOD__ . ": Bad data in text row {$row->old_id}! " );
1119 } else {
1120 wfLogWarning( __METHOD__ . ": Bad data in text row! " );
1121 }
1122 return false;
1123 }
1124
1125 return $revisionText;
1126 }
1127
1128 /**
1129 * If $wgCompressRevisions is enabled, we will compress data.
1130 * The input string is modified in place.
1131 * Return value is the flags field: contains 'gzip' if the
1132 * data is compressed, and 'utf-8' if we're saving in UTF-8
1133 * mode.
1134 *
1135 * @param mixed &$text Reference to a text
1136 * @return string
1137 */
1138 public static function compressRevisionText( &$text ) {
1139 return self::getBlobStore()->compressData( $text );
1140 }
1141
1142 /**
1143 * Re-converts revision text according to it's flags.
1144 *
1145 * @param mixed $text Reference to a text
1146 * @param array $flags Compression flags
1147 * @return string|bool Decompressed text, or false on failure
1148 */
1149 public static function decompressRevisionText( $text, $flags ) {
1150 if ( $text === false ) {
1151 // Text failed to be fetched; nothing to do
1152 return false;
1153 }
1154
1155 return self::getBlobStore()->decompressData( $text, $flags );
1156 }
1157
1158 /**
1159 * Insert a new revision into the database, returning the new revision ID
1160 * number on success and dies horribly on failure.
1161 *
1162 * @param IDatabase $dbw (master connection)
1163 * @throws MWException
1164 * @return int The revision ID
1165 */
1166 public function insertOn( $dbw ) {
1167 global $wgUser;
1168
1169 // Note that $this->mRecord->getId() will typically return null here, but not always,
1170 // e.g. not when restoring a revision.
1171
1172 if ( $this->mRecord->getUser( RevisionRecord::RAW ) === null ) {
1173 if ( $this->mRecord instanceof MutableRevisionRecord ) {
1174 $this->mRecord->setUser( $wgUser );
1175 } else {
1176 throw new MWException( 'Cannot insert revision with no associated user.' );
1177 }
1178 }
1179
1180 $rec = self::getRevisionStore()->insertRevisionOn( $this->mRecord, $dbw );
1181
1182 $this->mRecord = $rec;
1183
1184 // Avoid PHP 7.1 warning of passing $this by reference
1185 $revision = $this;
1186
1187 return $rec->getId();
1188 }
1189
1190 /**
1191 * Get the base 36 SHA-1 value for a string of text
1192 * @param string $text
1193 * @return string
1194 */
1195 public static function base36Sha1( $text ) {
1196 return SlotRecord::base36Sha1( $text );
1197 }
1198
1199 /**
1200 * Create a new null-revision for insertion into a page's
1201 * history. This will not re-save the text, but simply refer
1202 * to the text from the previous version.
1203 *
1204 * Such revisions can for instance identify page rename
1205 * operations and other such meta-modifications.
1206 *
1207 * @param IDatabase $dbw
1208 * @param int $pageId ID number of the page to read from
1209 * @param string $summary Revision's summary
1210 * @param bool $minor Whether the revision should be considered as minor
1211 * @param User|null $user User object to use or null for $wgUser
1212 * @return Revision|null Revision or null on error
1213 */
1214 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1215 global $wgUser;
1216 if ( !$user ) {
1217 $user = $wgUser;
1218 }
1219
1220 $comment = CommentStoreComment::newUnsavedComment( $summary, null );
1221
1222 $title = Title::newFromID( $pageId, Title::GAID_FOR_UPDATE );
1223 if ( $title === null ) {
1224 return null;
1225 }
1226
1227 $rec = self::getRevisionStore()->newNullRevision( $dbw, $title, $comment, $minor, $user );
1228
1229 return $rec ? new Revision( $rec ) : null;
1230 }
1231
1232 /**
1233 * Determine if the current user is allowed to view a particular
1234 * field of this revision, if it's marked as deleted.
1235 *
1236 * @param int $field One of self::DELETED_TEXT,
1237 * self::DELETED_COMMENT,
1238 * self::DELETED_USER
1239 * @param User|null $user User object to check, or null to use $wgUser
1240 * @return bool
1241 */
1242 public function userCan( $field, User $user = null ) {
1243 return self::userCanBitfield( $this->getVisibility(), $field, $user );
1244 }
1245
1246 /**
1247 * Determine if the current user is allowed to view a particular
1248 * field of this revision, if it's marked as deleted. This is used
1249 * by various classes to avoid duplication.
1250 *
1251 * @param int $bitfield Current field
1252 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1253 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1254 * self::DELETED_USER = File::DELETED_USER
1255 * @param User|null $user User object to check, or null to use $wgUser
1256 * @param Title|null $title A Title object to check for per-page restrictions on,
1257 * instead of just plain userrights
1258 * @return bool
1259 */
1260 public static function userCanBitfield( $bitfield, $field, User $user = null,
1261 Title $title = null
1262 ) {
1263 global $wgUser;
1264
1265 if ( !$user ) {
1266 $user = $wgUser;
1267 }
1268
1269 return RevisionRecord::userCanBitfield( $bitfield, $field, $user, $title );
1270 }
1271
1272 /**
1273 * Get rev_timestamp from rev_id, without loading the rest of the row
1274 *
1275 * @param Title $title
1276 * @param int $id
1277 * @param int $flags
1278 * @return string|bool False if not found
1279 */
1280 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1281 return self::getRevisionStore()->getTimestampFromId( $title, $id, $flags );
1282 }
1283
1284 /**
1285 * Get count of revisions per page...not very efficient
1286 *
1287 * @param IDatabase $db
1288 * @param int $id Page id
1289 * @return int
1290 */
1291 static function countByPageId( $db, $id ) {
1292 return self::getRevisionStore()->countRevisionsByPageId( $db, $id );
1293 }
1294
1295 /**
1296 * Get count of revisions per page...not very efficient
1297 *
1298 * @param IDatabase $db
1299 * @param Title $title
1300 * @return int
1301 */
1302 static function countByTitle( $db, $title ) {
1303 return self::getRevisionStore()->countRevisionsByTitle( $db, $title );
1304 }
1305
1306 /**
1307 * Check if no edits were made by other users since
1308 * the time a user started editing the page. Limit to
1309 * 50 revisions for the sake of performance.
1310 *
1311 * @since 1.20
1312 * @deprecated since 1.24
1313 *
1314 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1315 * Database object or a database identifier usable with wfGetDB.
1316 * @param int $pageId The ID of the page in question
1317 * @param int $userId The ID of the user in question
1318 * @param string $since Look at edits since this time
1319 *
1320 * @return bool True if the given user was the only one to edit since the given timestamp
1321 */
1322 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1323 if ( is_int( $db ) ) {
1324 $db = wfGetDB( $db );
1325 }
1326
1327 return self::getRevisionStore()->userWasLastToEdit( $db, $pageId, $userId, $since );
1328 }
1329
1330 /**
1331 * Load a revision based on a known page ID and current revision ID from the DB
1332 *
1333 * This method allows for the use of caching, though accessing anything that normally
1334 * requires permission checks (aside from the text) will trigger a small DB lookup.
1335 * The title will also be loaded if $pageIdOrTitle is an integer ID.
1336 *
1337 * @param IDatabase $db ignored!
1338 * @param int|Title $pageIdOrTitle Page ID or Title object
1339 * @param int $revId Known current revision of this page. Determined automatically if not given.
1340 * @return Revision|bool Returns false if missing
1341 * @since 1.28
1342 */
1343 public static function newKnownCurrent( IDatabase $db, $pageIdOrTitle, $revId = 0 ) {
1344 $title = $pageIdOrTitle instanceof Title
1345 ? $pageIdOrTitle
1346 : Title::newFromID( $pageIdOrTitle );
1347
1348 if ( !$title ) {
1349 return false;
1350 }
1351
1352 $record = self::getRevisionLookup()->getKnownCurrentRevision( $title, $revId );
1353 return $record ? new Revision( $record ) : false;
1354 }
1355 }