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