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