Revision: Assert that $mRecord is never null in Revision
[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 * Fetch revision comment if it's available to the specified audience.
851 * If the specified audience does not have access to the comment, an
852 * empty string will be returned.
853 *
854 * @param int $audience One of:
855 * Revision::FOR_PUBLIC to be displayed to all users
856 * Revision::FOR_THIS_USER to be displayed to the given user
857 * Revision::RAW get the text regardless of permissions
858 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
859 * to the $audience parameter
860 * @return string
861 */
862 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
863 global $wgUser;
864
865 if ( $audience === self::FOR_THIS_USER && !$user ) {
866 $user = $wgUser;
867 }
868
869 $comment = $this->mRecord->getComment( $audience, $user );
870 return $comment === null ? null : $comment->text;
871 }
872
873 /**
874 * @return bool
875 */
876 public function isMinor() {
877 return $this->mRecord->isMinor();
878 }
879
880 /**
881 * @return int Rcid of the unpatrolled row, zero if there isn't one
882 */
883 public function isUnpatrolled() {
884 return self::getRevisionStore()->getRcIdIfUnpatrolled( $this->mRecord );
885 }
886
887 /**
888 * Get the RC object belonging to the current revision, if there's one
889 *
890 * @param int $flags (optional) $flags include:
891 * Revision::READ_LATEST : Select the data from the master
892 *
893 * @since 1.22
894 * @return RecentChange|null
895 */
896 public function getRecentChange( $flags = 0 ) {
897 return self::getRevisionStore()->getRecentChange( $this->mRecord, $flags );
898 }
899
900 /**
901 * @param int $field One of DELETED_* bitfield constants
902 *
903 * @return bool
904 */
905 public function isDeleted( $field ) {
906 return $this->mRecord->isDeleted( $field );
907 }
908
909 /**
910 * Get the deletion bitfield of the revision
911 *
912 * @return int
913 */
914 public function getVisibility() {
915 return $this->mRecord->getVisibility();
916 }
917
918 /**
919 * Fetch revision content if it's available to the specified audience.
920 * If the specified audience does not have the ability to view this
921 * revision, or the content could not be loaded, null will be returned.
922 *
923 * @param int $audience One of:
924 * Revision::FOR_PUBLIC to be displayed to all users
925 * Revision::FOR_THIS_USER to be displayed to $user
926 * Revision::RAW get the text regardless of permissions
927 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
928 * to the $audience parameter
929 * @since 1.21
930 * @return Content|null
931 */
932 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
933 global $wgUser;
934
935 if ( $audience === self::FOR_THIS_USER && !$user ) {
936 $user = $wgUser;
937 }
938
939 try {
940 return $this->mRecord->getContent( SlotRecord::MAIN, $audience, $user );
941 }
942 catch ( RevisionAccessException $e ) {
943 return null;
944 }
945 }
946
947 /**
948 * Get original serialized data (without checking view restrictions)
949 *
950 * @since 1.21
951 * @deprecated since 1.31, use BlobStore::getBlob instead.
952 *
953 * @return string
954 */
955 public function getSerializedData() {
956 $slot = $this->getMainSlotRaw();
957 return $slot->getContent()->serialize();
958 }
959
960 /**
961 * Returns the content model for the main slot of this revision.
962 *
963 * If no content model was stored in the database, the default content model for the title is
964 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
965 * is used as a last resort.
966 *
967 * @todo drop this, with MCR, there no longer is a single model associated with a revision.
968 *
969 * @return string The content model id associated with this revision,
970 * see the CONTENT_MODEL_XXX constants.
971 */
972 public function getContentModel() {
973 return $this->getMainSlotRaw()->getModel();
974 }
975
976 /**
977 * Returns the content format for the main slot of this revision.
978 *
979 * If no content format was stored in the database, the default format for this
980 * revision's content model is returned.
981 *
982 * @todo drop this, the format is irrelevant to the revision!
983 *
984 * @return string The content format id associated with this revision,
985 * see the CONTENT_FORMAT_XXX constants.
986 */
987 public function getContentFormat() {
988 $format = $this->getMainSlotRaw()->getFormat();
989
990 if ( $format === null ) {
991 // if no format was stored along with the blob, fall back to default format
992 $format = $this->getContentHandler()->getDefaultFormat();
993 }
994
995 return $format;
996 }
997
998 /**
999 * Returns the content handler appropriate for this revision's content model.
1000 *
1001 * @throws MWException
1002 * @return ContentHandler
1003 */
1004 public function getContentHandler() {
1005 return ContentHandler::getForModelID( $this->getContentModel() );
1006 }
1007
1008 /**
1009 * @return string
1010 */
1011 public function getTimestamp() {
1012 return $this->mRecord->getTimestamp();
1013 }
1014
1015 /**
1016 * @return bool
1017 */
1018 public function isCurrent() {
1019 return ( $this->mRecord instanceof RevisionStoreRecord ) && $this->mRecord->isCurrent();
1020 }
1021
1022 /**
1023 * Get previous revision for this title
1024 *
1025 * @return Revision|null
1026 */
1027 public function getPrevious() {
1028 $title = $this->getTitle();
1029 $rec = self::getRevisionLookup()->getPreviousRevision( $this->mRecord, $title );
1030 return $rec === null ? null : new Revision( $rec, self::READ_NORMAL, $title );
1031 }
1032
1033 /**
1034 * Get next revision for this title
1035 *
1036 * @return Revision|null
1037 */
1038 public function getNext() {
1039 $title = $this->getTitle();
1040 $rec = self::getRevisionLookup()->getNextRevision( $this->mRecord, $title );
1041 return $rec === null ? null : new Revision( $rec, self::READ_NORMAL, $title );
1042 }
1043
1044 /**
1045 * Get revision text associated with an old or archive row
1046 *
1047 * If the text field is not included, this uses RevisionStore to load the appropriate slot
1048 * and return its serialized content. This is the default backwards-compatibility behavior
1049 * when reading from the MCR aware database schema is enabled. For this to work, either
1050 * the revision ID or the page ID must be included in the row.
1051 *
1052 * When using the old text field, the flags field must also be set. Including the old_id
1053 * field will activate cache usage as long as the $wiki parameter is not set.
1054 *
1055 * @deprecated since 1.32, use RevisionStore::newRevisionFromRow instead.
1056 *
1057 * @param stdClass $row The text data. If a falsy value is passed instead, false is returned.
1058 * @param string $prefix Table prefix (default 'old_')
1059 * @param string|bool $wiki The name of the wiki to load the revision text from
1060 * (same as the wiki $row was loaded from) or false to indicate the local
1061 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1062 * identifier as understood by the LoadBalancer class.
1063 * @return string|false Text the text requested or false on failure
1064 */
1065 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1066 global $wgMultiContentRevisionSchemaMigrationStage;
1067
1068 if ( !$row ) {
1069 return false;
1070 }
1071
1072 $textField = $prefix . 'text';
1073 $flagsField = $prefix . 'flags';
1074
1075 if ( isset( $row->$textField ) ) {
1076 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
1077 // The text field was read, but it's no longer being populated!
1078 // We could gloss over this by using the text when it's there and loading
1079 // if when it's not, but it seems preferable to complain loudly about a
1080 // query that is no longer guaranteed to work reliably.
1081 throw new LogicException(
1082 'Cannot use ' . __METHOD__ . ' with the ' . $textField . ' field when'
1083 . ' $wgMultiContentRevisionSchemaMigrationStage does not include'
1084 . ' SCHEMA_COMPAT_WRITE_OLD. The field may not be populated for all revisions!'
1085 );
1086 }
1087
1088 $text = $row->$textField;
1089 } else {
1090 // Missing text field, we are probably looking at the MCR-enabled DB schema.
1091
1092 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
1093 // This method should no longer be used with the new schema. Ideally, we
1094 // would already trigger a deprecation warning when SCHEMA_COMPAT_READ_NEW is set.
1095 wfDeprecated( __METHOD__ . ' (MCR without SCHEMA_COMPAT_WRITE_OLD)', '1.32' );
1096 }
1097
1098 $store = self::getRevisionStore( $wiki );
1099 $rev = $prefix === 'ar_'
1100 ? $store->newRevisionFromArchiveRow( $row )
1101 : $store->newRevisionFromRow( $row );
1102
1103 $content = $rev->getContent( SlotRecord::MAIN );
1104 return $content ? $content->serialize() : false;
1105 }
1106
1107 if ( isset( $row->$flagsField ) ) {
1108 $flags = explode( ',', $row->$flagsField );
1109 } else {
1110 $flags = [];
1111 }
1112
1113 $cacheKey = isset( $row->old_id )
1114 ? SqlBlobStore::makeAddressFromTextId( $row->old_id )
1115 : null;
1116
1117 $revisionText = self::getBlobStore( $wiki )->expandBlob( $text, $flags, $cacheKey );
1118
1119 if ( $revisionText === false ) {
1120 if ( isset( $row->old_id ) ) {
1121 wfLogWarning( __METHOD__ . ": Bad data in text row {$row->old_id}! " );
1122 } else {
1123 wfLogWarning( __METHOD__ . ": Bad data in text row! " );
1124 }
1125 return false;
1126 }
1127
1128 return $revisionText;
1129 }
1130
1131 /**
1132 * If $wgCompressRevisions is enabled, we will compress data.
1133 * The input string is modified in place.
1134 * Return value is the flags field: contains 'gzip' if the
1135 * data is compressed, and 'utf-8' if we're saving in UTF-8
1136 * mode.
1137 *
1138 * @param mixed &$text Reference to a text
1139 * @return string
1140 */
1141 public static function compressRevisionText( &$text ) {
1142 return self::getBlobStore()->compressData( $text );
1143 }
1144
1145 /**
1146 * Re-converts revision text according to it's flags.
1147 *
1148 * @param mixed $text Reference to a text
1149 * @param array $flags Compression flags
1150 * @return string|bool Decompressed text, or false on failure
1151 */
1152 public static function decompressRevisionText( $text, $flags ) {
1153 if ( $text === false ) {
1154 // Text failed to be fetched; nothing to do
1155 return false;
1156 }
1157
1158 return self::getBlobStore()->decompressData( $text, $flags );
1159 }
1160
1161 /**
1162 * Insert a new revision into the database, returning the new revision ID
1163 * number on success and dies horribly on failure.
1164 *
1165 * @param IDatabase $dbw (master connection)
1166 * @throws MWException
1167 * @return int The revision ID
1168 */
1169 public function insertOn( $dbw ) {
1170 global $wgUser;
1171
1172 // Note that $this->mRecord->getId() will typically return null here, but not always,
1173 // e.g. not when restoring a revision.
1174
1175 if ( $this->mRecord->getUser( RevisionRecord::RAW ) === null ) {
1176 if ( $this->mRecord instanceof MutableRevisionRecord ) {
1177 $this->mRecord->setUser( $wgUser );
1178 } else {
1179 throw new MWException( 'Cannot insert revision with no associated user.' );
1180 }
1181 }
1182
1183 $rec = self::getRevisionStore()->insertRevisionOn( $this->mRecord, $dbw );
1184
1185 $this->mRecord = $rec;
1186 Assert::postcondition( $this->mRecord !== null, 'Failed to acquire a RevisionRecord' );
1187
1188 return $rec->getId();
1189 }
1190
1191 /**
1192 * Get the base 36 SHA-1 value for a string of text
1193 * @param string $text
1194 * @return string
1195 */
1196 public static function base36Sha1( $text ) {
1197 return SlotRecord::base36Sha1( $text );
1198 }
1199
1200 /**
1201 * Create a new null-revision for insertion into a page's
1202 * history. This will not re-save the text, but simply refer
1203 * to the text from the previous version.
1204 *
1205 * Such revisions can for instance identify page rename
1206 * operations and other such meta-modifications.
1207 *
1208 * @param IDatabase $dbw
1209 * @param int $pageId ID number of the page to read from
1210 * @param string $summary Revision's summary
1211 * @param bool $minor Whether the revision should be considered as minor
1212 * @param User|null $user User object to use or null for $wgUser
1213 * @return Revision|null Revision or null on error
1214 */
1215 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1216 global $wgUser;
1217 if ( !$user ) {
1218 $user = $wgUser;
1219 }
1220
1221 $comment = CommentStoreComment::newUnsavedComment( $summary, null );
1222
1223 $title = Title::newFromID( $pageId, Title::GAID_FOR_UPDATE );
1224 if ( $title === null ) {
1225 return null;
1226 }
1227
1228 $rec = self::getRevisionStore()->newNullRevision( $dbw, $title, $comment, $minor, $user );
1229
1230 return $rec ? new Revision( $rec ) : null;
1231 }
1232
1233 /**
1234 * Determine if the current user is allowed to view a particular
1235 * field of this revision, if it's marked as deleted.
1236 *
1237 * @param int $field One of self::DELETED_TEXT,
1238 * self::DELETED_COMMENT,
1239 * self::DELETED_USER
1240 * @param User|null $user User object to check, or null to use $wgUser
1241 * @return bool
1242 */
1243 public function userCan( $field, User $user = null ) {
1244 return self::userCanBitfield( $this->getVisibility(), $field, $user );
1245 }
1246
1247 /**
1248 * Determine if the current user is allowed to view a particular
1249 * field of this revision, if it's marked as deleted. This is used
1250 * by various classes to avoid duplication.
1251 *
1252 * @param int $bitfield Current field
1253 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1254 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1255 * self::DELETED_USER = File::DELETED_USER
1256 * @param User|null $user User object to check, or null to use $wgUser
1257 * @param Title|null $title A Title object to check for per-page restrictions on,
1258 * instead of just plain userrights
1259 * @return bool
1260 */
1261 public static function userCanBitfield( $bitfield, $field, User $user = null,
1262 Title $title = null
1263 ) {
1264 global $wgUser;
1265
1266 if ( !$user ) {
1267 $user = $wgUser;
1268 }
1269
1270 return RevisionRecord::userCanBitfield( $bitfield, $field, $user, $title );
1271 }
1272
1273 /**
1274 * Get rev_timestamp from rev_id, without loading the rest of the row
1275 *
1276 * @param Title $title
1277 * @param int $id
1278 * @param int $flags
1279 * @return string|bool False if not found
1280 */
1281 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1282 return self::getRevisionStore()->getTimestampFromId( $title, $id, $flags );
1283 }
1284
1285 /**
1286 * Get count of revisions per page...not very efficient
1287 *
1288 * @param IDatabase $db
1289 * @param int $id Page id
1290 * @return int
1291 */
1292 static function countByPageId( $db, $id ) {
1293 return self::getRevisionStore()->countRevisionsByPageId( $db, $id );
1294 }
1295
1296 /**
1297 * Get count of revisions per page...not very efficient
1298 *
1299 * @param IDatabase $db
1300 * @param Title $title
1301 * @return int
1302 */
1303 static function countByTitle( $db, $title ) {
1304 return self::getRevisionStore()->countRevisionsByTitle( $db, $title );
1305 }
1306
1307 /**
1308 * Check if no edits were made by other users since
1309 * the time a user started editing the page. Limit to
1310 * 50 revisions for the sake of performance.
1311 *
1312 * @since 1.20
1313 * @deprecated since 1.24
1314 *
1315 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1316 * Database object or a database identifier usable with wfGetDB.
1317 * @param int $pageId The ID of the page in question
1318 * @param int $userId The ID of the user in question
1319 * @param string $since Look at edits since this time
1320 *
1321 * @return bool True if the given user was the only one to edit since the given timestamp
1322 */
1323 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1324 if ( is_int( $db ) ) {
1325 $db = wfGetDB( $db );
1326 }
1327
1328 return self::getRevisionStore()->userWasLastToEdit( $db, $pageId, $userId, $since );
1329 }
1330
1331 /**
1332 * Load a revision based on a known page ID and current revision ID from the DB
1333 *
1334 * This method allows for the use of caching, though accessing anything that normally
1335 * requires permission checks (aside from the text) will trigger a small DB lookup.
1336 * The title will also be loaded if $pageIdOrTitle is an integer ID.
1337 *
1338 * @param IDatabase $db ignored!
1339 * @param int|Title $pageIdOrTitle Page ID or Title object
1340 * @param int $revId Known current revision of this page. Determined automatically if not given.
1341 * @return Revision|bool Returns false if missing
1342 * @since 1.28
1343 */
1344 public static function newKnownCurrent( IDatabase $db, $pageIdOrTitle, $revId = 0 ) {
1345 $title = $pageIdOrTitle instanceof Title
1346 ? $pageIdOrTitle
1347 : Title::newFromID( $pageIdOrTitle );
1348
1349 if ( !$title ) {
1350 return false;
1351 }
1352
1353 $record = self::getRevisionLookup()->getKnownCurrentRevision( $title, $revId );
1354 return $record ? new Revision( $record ) : false;
1355 }
1356 }