3 * Representation of a page version.
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.
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.
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
23 use Wikimedia\Rdbms\Database
;
24 use Wikimedia\Rdbms\IDatabase
;
25 use MediaWiki\Linker\LinkTarget
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\Rdbms\ResultWrapper
;
28 use Wikimedia\Rdbms\FakeResultWrapper
;
33 class Revision
implements IDBAccessObject
{
41 protected $mOrigUserText;
45 protected $mMinorEdit;
47 protected $mTimestamp;
63 protected $mUnpatrolled;
65 /** @var stdClass|null */
68 /** @var null|Title */
73 protected $mContentModel;
75 protected $mContentFormat;
77 /** @var Content|null|bool */
79 /** @var null|ContentHandler */
80 protected $mContentHandler;
83 protected $mQueryFlags = 0;
84 /** @var bool Used for cached values to reload user text and rev_deleted */
85 protected $mRefreshMutableFields = false;
86 /** @var string Wiki ID; false means the current wiki */
87 protected $mWiki = false;
89 // Revision deletion constants
90 const DELETED_TEXT
= 1;
91 const DELETED_COMMENT
= 2;
92 const DELETED_USER
= 4;
93 const DELETED_RESTRICTED
= 8;
94 const SUPPRESSED_USER
= 12; // convenience
95 const SUPPRESSED_ALL
= 15; // convenience
97 // Audience options for accessors
99 const FOR_THIS_USER
= 2;
102 const TEXT_CACHE_GROUP
= 'revisiontext:10'; // process cache name and max key count
105 * Load a page revision from a given revision ID number.
106 * Returns null if no such revision can be found.
109 * Revision::READ_LATEST : Select the data from the master
110 * Revision::READ_LOCKING : Select & lock the data from the master
113 * @param int $flags (optional)
114 * @return Revision|null
116 public static function newFromId( $id, $flags = 0 ) {
117 return self
::newFromConds( [ 'rev_id' => intval( $id ) ], $flags );
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.
126 * Revision::READ_LATEST : Select the data from the master
127 * Revision::READ_LOCKING : Select & lock the data from the master
129 * @param LinkTarget $linkTarget
130 * @param int $id (optional)
131 * @param int $flags Bitfield (optional)
132 * @return Revision|null
134 public static function newFromTitle( LinkTarget
$linkTarget, $id = 0, $flags = 0 ) {
136 'page_namespace' => $linkTarget->getNamespace(),
137 'page_title' => $linkTarget->getDBkey()
140 // Use the specified ID
141 $conds['rev_id'] = $id;
142 return self
::newFromConds( $conds, $flags );
144 // Use a join to get the latest revision
145 $conds[] = 'rev_id=page_latest';
146 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
147 return self
::loadFromConds( $db, $conds, $flags );
152 * Load either the current, or a specified, revision
153 * that's attached to a given page ID.
154 * Returns null if no such revision can be found.
157 * Revision::READ_LATEST : Select the data from the master (since 1.20)
158 * Revision::READ_LOCKING : Select & lock the data from the master
161 * @param int $revId (optional)
162 * @param int $flags Bitfield (optional)
163 * @return Revision|null
165 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
166 $conds = [ 'page_id' => $pageId ];
168 $conds['rev_id'] = $revId;
169 return self
::newFromConds( $conds, $flags );
171 // Use a join to get the latest revision
172 $conds[] = 'rev_id = page_latest';
173 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
174 return self
::loadFromConds( $db, $conds, $flags );
179 * Make a fake revision object from an archive table row. This is queried
180 * for permissions or even inserted (as in Special:Undelete)
181 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
184 * @param array $overrides
186 * @throws MWException
189 public static function newFromArchiveRow( $row, $overrides = [] ) {
190 global $wgContentHandlerUseDB;
192 $attribs = $overrides +
[
193 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
194 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
195 'comment' => CommentStore
::newKey( 'ar_comment' )
196 // Legacy because $row may have come from self::selectArchiveFields()
197 ->getCommentLegacy( wfGetDB( DB_REPLICA
), $row, true )->text
,
198 'user' => $row->ar_user
,
199 'user_text' => $row->ar_user_text
,
200 'timestamp' => $row->ar_timestamp
,
201 'minor_edit' => $row->ar_minor_edit
,
202 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
203 'deleted' => $row->ar_deleted
,
204 'len' => $row->ar_len
,
205 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
206 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
207 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
210 if ( !$wgContentHandlerUseDB ) {
211 unset( $attribs['content_model'] );
212 unset( $attribs['content_format'] );
215 if ( !isset( $attribs['title'] )
216 && isset( $row->ar_namespace
)
217 && isset( $row->ar_title
)
219 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
222 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
223 // Pre-1.5 ar_text row
224 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
225 if ( $attribs['text'] === false ) {
226 throw new MWException( 'Unable to load text from archive row (possibly T24624)' );
229 return new self( $attribs );
238 public static function newFromRow( $row ) {
239 return new self( $row );
243 * Load a page revision from a given revision ID number.
244 * Returns null if no such revision can be found.
246 * @param IDatabase $db
248 * @return Revision|null
250 public static function loadFromId( $db, $id ) {
251 return self
::loadFromConds( $db, [ 'rev_id' => intval( $id ) ] );
255 * Load either the current, or a specified, revision
256 * that's attached to a given page. If not attached
257 * to that page, will return null.
259 * @param IDatabase $db
262 * @return Revision|null
264 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
265 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
267 $conds['rev_id'] = intval( $id );
269 $conds[] = 'rev_id=page_latest';
271 return self
::loadFromConds( $db, $conds );
275 * Load either the current, or a specified, revision
276 * that's attached to a given page. If not attached
277 * to that page, will return null.
279 * @param IDatabase $db
280 * @param Title $title
282 * @return Revision|null
284 public static function loadFromTitle( $db, $title, $id = 0 ) {
286 $matchId = intval( $id );
288 $matchId = 'page_latest';
290 return self
::loadFromConds( $db,
293 'page_namespace' => $title->getNamespace(),
294 'page_title' => $title->getDBkey()
300 * Load the revision for the given title with the given timestamp.
301 * WARNING: Timestamps may in some circumstances not be unique,
302 * so this isn't the best key to use.
304 * @param IDatabase $db
305 * @param Title $title
306 * @param string $timestamp
307 * @return Revision|null
309 public static function loadFromTimestamp( $db, $title, $timestamp ) {
310 return self
::loadFromConds( $db,
312 'rev_timestamp' => $db->timestamp( $timestamp ),
313 'page_namespace' => $title->getNamespace(),
314 'page_title' => $title->getDBkey()
320 * Given a set of conditions, fetch a revision
322 * This method is used then a revision ID is qualified and
323 * will incorporate some basic replica DB/master fallback logic
325 * @param array $conditions
326 * @param int $flags (optional)
327 * @return Revision|null
329 private static function newFromConds( $conditions, $flags = 0 ) {
330 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
332 $rev = self
::loadFromConds( $db, $conditions, $flags );
333 // Make sure new pending/committed revision are visibile later on
334 // within web requests to certain avoid bugs like T93866 and T94407.
336 && !( $flags & self
::READ_LATEST
)
337 && wfGetLB()->getServerCount() > 1
338 && wfGetLB()->hasOrMadeRecentMasterChanges()
340 $flags = self
::READ_LATEST
;
341 $db = wfGetDB( DB_MASTER
);
342 $rev = self
::loadFromConds( $db, $conditions, $flags );
346 $rev->mQueryFlags
= $flags;
353 * Given a set of conditions, fetch a revision from
354 * the given database connection.
356 * @param IDatabase $db
357 * @param array $conditions
358 * @param int $flags (optional)
359 * @return Revision|null
361 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
362 $row = self
::fetchFromConds( $db, $conditions, $flags );
364 $rev = new Revision( $row );
365 $rev->mWiki
= $db->getDomainID();
374 * Return a wrapper for a series of database rows to
375 * fetch all of a given page's revisions in turn.
376 * Each row can be fed to the constructor to get objects.
378 * @param LinkTarget $title
379 * @return ResultWrapper
380 * @deprecated Since 1.28
382 public static function fetchRevision( LinkTarget
$title ) {
383 $row = self
::fetchFromConds(
384 wfGetDB( DB_REPLICA
),
386 'rev_id=page_latest',
387 'page_namespace' => $title->getNamespace(),
388 'page_title' => $title->getDBkey()
392 return new FakeResultWrapper( $row ?
[ $row ] : [] );
396 * Given a set of conditions, return a ResultWrapper
397 * which will return matching database rows with the
398 * fields necessary to build Revision objects.
400 * @param IDatabase $db
401 * @param array $conditions
402 * @param int $flags (optional)
405 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
406 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
408 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
409 $options[] = 'FOR UPDATE';
411 return $db->selectRow(
422 * Return the value of a select() JOIN conds array for the user table.
423 * This will get user table rows for logged-in users.
425 * @deprecated since 1.31, use self::getQueryInfo( [ 'user' ] ) instead.
428 public static function userJoinCond() {
429 wfDeprecated( __METHOD__
, '1.31' );
430 return [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
434 * Return the value of a select() page conds array for the page table.
435 * This will assure that the revision(s) are not orphaned from live pages.
437 * @deprecated since 1.31, use self::getQueryInfo( [ 'page' ] ) instead.
440 public static function pageJoinCond() {
441 wfDeprecated( __METHOD__
, '1.31' );
442 return [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
446 * Return the list of revision fields that should be selected to create
448 * @deprecated since 1.31, use self::getQueryInfo() instead.
451 public static function selectFields() {
452 global $wgContentHandlerUseDB;
454 wfDeprecated( __METHOD__
, '1.31' );
470 $fields +
= CommentStore
::newKey( 'rev_comment' )->getFields();
472 if ( $wgContentHandlerUseDB ) {
473 $fields[] = 'rev_content_format';
474 $fields[] = 'rev_content_model';
481 * Return the list of revision fields that should be selected to create
482 * a new revision from an archive row.
483 * @deprecated since 1.31, use self::getArchiveQueryInfo() instead.
486 public static function selectArchiveFields() {
487 global $wgContentHandlerUseDB;
489 wfDeprecated( __METHOD__
, '1.31' );
507 $fields +
= CommentStore
::newKey( 'ar_comment' )->getFields();
509 if ( $wgContentHandlerUseDB ) {
510 $fields[] = 'ar_content_format';
511 $fields[] = 'ar_content_model';
517 * Return the list of text fields that should be selected to read the
519 * @deprecated since 1.31, use self::getQueryInfo( [ 'text' ] ) instead.
522 public static function selectTextFields() {
523 wfDeprecated( __METHOD__
, '1.31' );
531 * Return the list of page fields that should be selected from page table
532 * @deprecated since 1.31, use self::getQueryInfo( [ 'page' ] ) instead.
535 public static function selectPageFields() {
536 wfDeprecated( __METHOD__
, '1.31' );
548 * Return the list of user fields that should be selected from user table
549 * @deprecated since 1.31, use self::getQueryInfo( [ 'user' ] ) instead.
552 public static function selectUserFields() {
553 wfDeprecated( __METHOD__
, '1.31' );
554 return [ 'user_name' ];
558 * Return the tables, fields, and join conditions to be selected to create
559 * a new revision object.
561 * @param array $options Any combination of the following strings
562 * - 'page': Join with the page table, and select fields to identify the page
563 * - 'user': Join with the user table, and select the user name
564 * - 'text': Join with the text table, and select fields to load page text
565 * @return array With three keys:
566 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
567 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
568 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
570 public static function getQueryInfo( $options = [] ) {
571 global $wgContentHandlerUseDB;
573 $commentQuery = CommentStore
::newKey( 'rev_comment' )->getJoin();
575 'tables' => [ 'revision' ] +
$commentQuery['tables'],
588 ] +
$commentQuery['fields'],
589 'joins' => $commentQuery['joins'],
592 if ( $wgContentHandlerUseDB ) {
593 $ret['fields'][] = 'rev_content_format';
594 $ret['fields'][] = 'rev_content_model';
597 if ( in_array( 'page', $options, true ) ) {
598 $ret['tables'][] = 'page';
599 $ret['fields'] = array_merge( $ret['fields'], [
607 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
610 if ( in_array( 'user', $options, true ) ) {
611 $ret['tables'][] = 'user';
612 $ret['fields'] = array_merge( $ret['fields'], [
615 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
618 if ( in_array( 'text', $options, true ) ) {
619 $ret['tables'][] = 'text';
620 $ret['fields'] = array_merge( $ret['fields'], [
624 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
631 * Return the tables, fields, and join conditions to be selected to create
632 * a new archived revision object.
634 * @return array With three keys:
635 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
636 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
637 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
639 public static function getArchiveQueryInfo() {
640 global $wgContentHandlerUseDB;
642 $commentQuery = CommentStore
::newKey( 'ar_comment' )->getJoin();
644 'tables' => [ 'archive' ] +
$commentQuery['tables'],
659 ] +
$commentQuery['fields'],
660 'joins' => $commentQuery['joins'],
663 if ( $wgContentHandlerUseDB ) {
664 $ret['fields'][] = 'ar_content_format';
665 $ret['fields'][] = 'ar_content_model';
672 * Do a batched query to get the parent revision lengths
673 * @param IDatabase $db
674 * @param array $revIds
677 public static function getParentLengths( $db, array $revIds ) {
680 return $revLens; // empty
682 $res = $db->select( 'revision',
683 [ 'rev_id', 'rev_len' ],
684 [ 'rev_id' => $revIds ],
686 foreach ( $res as $row ) {
687 $revLens[$row->rev_id
] = $row->rev_len
;
693 * @param object|array $row Either a database row or an array
694 * @throws MWException
697 public function __construct( $row ) {
698 if ( is_object( $row ) ) {
699 $this->constructFromDbRowObject( $row );
700 } elseif ( is_array( $row ) ) {
701 $this->constructFromRowArray( $row );
703 throw new MWException( 'Revision constructor passed invalid row format.' );
705 $this->mUnpatrolled
= null;
711 private function constructFromDbRowObject( $row ) {
712 $this->mId
= intval( $row->rev_id
);
713 $this->mPage
= intval( $row->rev_page
);
714 $this->mTextId
= intval( $row->rev_text_id
);
715 $this->mComment
= CommentStore
::newKey( 'rev_comment' )
716 // Legacy because $row may have come from self::selectFields()
717 ->getCommentLegacy( wfGetDB( DB_REPLICA
), $row, true )->text
;
718 $this->mUser
= intval( $row->rev_user
);
719 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
720 $this->mTimestamp
= $row->rev_timestamp
;
721 $this->mDeleted
= intval( $row->rev_deleted
);
723 if ( !isset( $row->rev_parent_id
) ) {
724 $this->mParentId
= null;
726 $this->mParentId
= intval( $row->rev_parent_id
);
729 if ( !isset( $row->rev_len
) ) {
732 $this->mSize
= intval( $row->rev_len
);
735 if ( !isset( $row->rev_sha1
) ) {
738 $this->mSha1
= $row->rev_sha1
;
741 if ( isset( $row->page_latest
) ) {
742 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
743 $this->mTitle
= Title
::newFromRow( $row );
745 $this->mCurrent
= false;
746 $this->mTitle
= null;
749 if ( !isset( $row->rev_content_model
) ) {
750 $this->mContentModel
= null; # determine on demand if needed
752 $this->mContentModel
= strval( $row->rev_content_model
);
755 if ( !isset( $row->rev_content_format
) ) {
756 $this->mContentFormat
= null; # determine on demand if needed
758 $this->mContentFormat
= strval( $row->rev_content_format
);
761 // Lazy extraction...
763 if ( isset( $row->old_text
) ) {
764 $this->mTextRow
= $row;
766 // 'text' table row entry will be lazy-loaded
767 $this->mTextRow
= null;
770 // Use user_name for users and rev_user_text for IPs...
771 $this->mUserText
= null; // lazy load if left null
772 if ( $this->mUser
== 0 ) {
773 $this->mUserText
= $row->rev_user_text
; // IP user
774 } elseif ( isset( $row->user_name
) ) {
775 $this->mUserText
= $row->user_name
; // logged-in user
777 $this->mOrigUserText
= $row->rev_user_text
;
783 * @throws MWException
785 private function constructFromRowArray( array $row ) {
786 // Build a new revision to be saved...
787 global $wgUser; // ugh
789 # if we have a content object, use it to set the model and type
790 if ( !empty( $row['content'] ) ) {
791 if ( !( $row['content'] instanceof Content
) ) {
792 throw new MWException( '`content` field must contain a Content object.' );
795 // @todo when is that set? test with external store setup! check out insertOn() [dk]
796 if ( !empty( $row['text_id'] ) ) {
797 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
798 "can't serialize content object" );
801 $row['content_model'] = $row['content']->getModel();
802 # note: mContentFormat is initializes later accordingly
803 # note: content is serialized later in this method!
804 # also set text to null?
807 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
808 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
809 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
810 $this->mUserText
= isset( $row['user_text'] )
811 ?
strval( $row['user_text'] ) : $wgUser->getName();
812 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
813 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
814 $this->mTimestamp
= isset( $row['timestamp'] )
815 ?
strval( $row['timestamp'] ) : wfTimestampNow();
816 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
817 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
818 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
819 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
821 $this->mContentModel
= isset( $row['content_model'] )
822 ?
strval( $row['content_model'] ) : null;
823 $this->mContentFormat
= isset( $row['content_format'] )
824 ?
strval( $row['content_format'] ) : null;
826 // Enforce spacing trimming on supplied text
827 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
828 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
829 $this->mTextRow
= null;
831 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
833 // if we have a Content object, override mText and mContentModel
834 if ( !empty( $row['content'] ) ) {
835 $handler = $this->getContentHandler();
836 $this->mContent
= $row['content'];
838 $this->mContentModel
= $this->mContent
->getModel();
839 $this->mContentHandler
= null;
841 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
842 } elseif ( $this->mText
!== null ) {
843 $handler = $this->getContentHandler();
844 $this->mContent
= $handler->unserializeContent( $this->mText
);
847 // If we have a Title object, make sure it is consistent with mPage.
848 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
849 if ( $this->mPage
=== null ) {
850 // if the page ID wasn't known, set it now
851 $this->mPage
= $this->mTitle
->getArticleID();
852 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
853 // Got different page IDs. This may be legit (e.g. during undeletion),
854 // but it seems worth mentioning it in the log.
855 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
856 $this->mTitle
->getArticleID() . " provided by the Title object." );
860 $this->mCurrent
= false;
862 // If we still have no length, see it we have the text to figure it out
863 if ( !$this->mSize
&& $this->mContent
!== null ) {
864 $this->mSize
= $this->mContent
->getSize();
868 if ( $this->mSha1
=== null ) {
869 $this->mSha1
= $this->mText
=== null ?
null : self
::base36Sha1( $this->mText
);
873 $this->getContentModel();
874 $this->getContentFormat();
882 public function getId() {
887 * Set the revision ID
889 * This should only be used for proposed revisions that turn out to be null edits
894 public function setId( $id ) {
895 $this->mId
= (int)$id;
899 * Set the user ID/name
901 * This should only be used for proposed revisions that turn out to be null edits
904 * @param int $id User ID
905 * @param string $name User name
907 public function setUserIdAndName( $id, $name ) {
908 $this->mUser
= (int)$id;
909 $this->mUserText
= $name;
910 $this->mOrigUserText
= $name;
918 public function getTextId() {
919 return $this->mTextId
;
923 * Get parent revision ID (the original previous page revision)
927 public function getParentId() {
928 return $this->mParentId
;
932 * Returns the length of the text in this revision, or null if unknown.
936 public function getSize() {
941 * Returns the base36 sha1 of the text in this revision, or null if unknown.
943 * @return string|null
945 public function getSha1() {
950 * Returns the title of the page associated with this entry or null.
952 * Will do a query, when title is not set and id is given.
956 public function getTitle() {
957 if ( $this->mTitle
!== null ) {
958 return $this->mTitle
;
960 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
961 if ( $this->mId
!== null ) {
962 $dbr = wfGetLB( $this->mWiki
)->getConnectionRef( DB_REPLICA
, [], $this->mWiki
);
963 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
964 $row = $dbr->selectRow(
965 [ 'revision', 'page' ],
974 [ 'rev_id' => $this->mId
],
977 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
980 // @TODO: better foreign title handling
981 $this->mTitle
= Title
::newFromRow( $row );
985 if ( $this->mWiki
=== false ||
$this->mWiki
=== wfWikiID() ) {
986 // Loading by ID is best, though not possible for foreign titles
987 if ( !$this->mTitle
&& $this->mPage
!== null && $this->mPage
> 0 ) {
988 $this->mTitle
= Title
::newFromID( $this->mPage
);
992 return $this->mTitle
;
996 * Set the title of the revision
998 * @param Title $title
1000 public function setTitle( $title ) {
1001 $this->mTitle
= $title;
1009 public function getPage() {
1010 return $this->mPage
;
1014 * Fetch revision's user id if it's available to the specified audience.
1015 * If the specified audience does not have access to it, zero will be
1018 * @param int $audience One of:
1019 * Revision::FOR_PUBLIC to be displayed to all users
1020 * Revision::FOR_THIS_USER to be displayed to the given user
1021 * Revision::RAW get the ID regardless of permissions
1022 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
1023 * to the $audience parameter
1026 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1027 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
1029 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
1032 return $this->mUser
;
1037 * Fetch revision's user id without regard for the current user's permissions
1040 * @deprecated since 1.25, use getUser( Revision::RAW )
1042 public function getRawUser() {
1043 wfDeprecated( __METHOD__
, '1.25' );
1044 return $this->getUser( self
::RAW
);
1048 * Fetch revision's username if it's available to the specified audience.
1049 * If the specified audience does not have access to the username, an
1050 * empty string will be returned.
1052 * @param int $audience One of:
1053 * Revision::FOR_PUBLIC to be displayed to all users
1054 * Revision::FOR_THIS_USER to be displayed to the given user
1055 * Revision::RAW get the text regardless of permissions
1056 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
1057 * to the $audience parameter
1060 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1061 $this->loadMutableFields();
1063 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
1065 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
1068 if ( $this->mUserText
=== null ) {
1069 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
1070 if ( $this->mUserText
=== false ) {
1071 # This shouldn't happen, but it can if the wiki was recovered
1072 # via importing revs and there is no user table entry yet.
1073 $this->mUserText
= $this->mOrigUserText
;
1076 return $this->mUserText
;
1081 * Fetch revision's username without regard for view restrictions
1084 * @deprecated since 1.25, use getUserText( Revision::RAW )
1086 public function getRawUserText() {
1087 wfDeprecated( __METHOD__
, '1.25' );
1088 return $this->getUserText( self
::RAW
);
1092 * Fetch revision comment if it's available to the specified audience.
1093 * If the specified audience does not have access to the comment, an
1094 * empty string will be returned.
1096 * @param int $audience One of:
1097 * Revision::FOR_PUBLIC to be displayed to all users
1098 * Revision::FOR_THIS_USER to be displayed to the given user
1099 * Revision::RAW get the text regardless of permissions
1100 * @param User|null $user User object to check for, only if FOR_THIS_USER is passed
1101 * to the $audience parameter
1104 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1105 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1107 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
1110 return $this->mComment
;
1115 * Fetch revision comment without regard for the current user's permissions
1118 * @deprecated since 1.25, use getComment( Revision::RAW )
1120 public function getRawComment() {
1121 wfDeprecated( __METHOD__
, '1.25' );
1122 return $this->getComment( self
::RAW
);
1128 public function isMinor() {
1129 return (bool)$this->mMinorEdit
;
1133 * @return int Rcid of the unpatrolled row, zero if there isn't one
1135 public function isUnpatrolled() {
1136 if ( $this->mUnpatrolled
!== null ) {
1137 return $this->mUnpatrolled
;
1139 $rc = $this->getRecentChange();
1140 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
1141 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
1143 $this->mUnpatrolled
= 0;
1145 return $this->mUnpatrolled
;
1149 * Get the RC object belonging to the current revision, if there's one
1151 * @param int $flags (optional) $flags include:
1152 * Revision::READ_LATEST : Select the data from the master
1155 * @return RecentChange|null
1157 public function getRecentChange( $flags = 0 ) {
1158 $dbr = wfGetDB( DB_REPLICA
);
1160 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
1162 return RecentChange
::newFromConds(
1164 'rc_user_text' => $this->getUserText( self
::RAW
),
1165 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
1166 'rc_this_oldid' => $this->getId()
1174 * @param int $field One of DELETED_* bitfield constants
1178 public function isDeleted( $field ) {
1179 if ( $this->isCurrent() && $field === self
::DELETED_TEXT
) {
1180 // Current revisions of pages cannot have the content hidden. Skipping this
1181 // check is very useful for Parser as it fetches templates using newKnownCurrent().
1182 // Calling getVisibility() in that case triggers a verification database query.
1183 return false; // no need to check
1186 return ( $this->getVisibility() & $field ) == $field;
1190 * Get the deletion bitfield of the revision
1194 public function getVisibility() {
1195 $this->loadMutableFields();
1197 return (int)$this->mDeleted
;
1201 * Fetch revision content if it's available to the specified audience.
1202 * If the specified audience does not have the ability to view this
1203 * revision, null will be returned.
1205 * @param int $audience One of:
1206 * Revision::FOR_PUBLIC to be displayed to all users
1207 * Revision::FOR_THIS_USER to be displayed to $wgUser
1208 * Revision::RAW get the text regardless of permissions
1209 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1210 * to the $audience parameter
1212 * @return Content|null
1214 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1215 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1217 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1220 return $this->getContentInternal();
1225 * Get original serialized data (without checking view restrictions)
1230 public function getSerializedData() {
1231 if ( $this->mText
=== null ) {
1232 // Revision is immutable. Load on demand.
1233 $this->mText
= $this->loadText();
1236 return $this->mText
;
1240 * Gets the content object for the revision (or null on failure).
1242 * Note that for mutable Content objects, each call to this method will return a
1246 * @return Content|null The Revision's content, or null on failure.
1248 protected function getContentInternal() {
1249 if ( $this->mContent
=== null ) {
1250 $text = $this->getSerializedData();
1252 if ( $text !== null && $text !== false ) {
1253 // Unserialize content
1254 $handler = $this->getContentHandler();
1255 $format = $this->getContentFormat();
1257 $this->mContent
= $handler->unserializeContent( $text, $format );
1261 // NOTE: copy() will return $this for immutable content objects
1262 return $this->mContent ?
$this->mContent
->copy() : null;
1266 * Returns the content model for this revision.
1268 * If no content model was stored in the database, the default content model for the title is
1269 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1270 * is used as a last resort.
1272 * @return string The content model id associated with this revision,
1273 * see the CONTENT_MODEL_XXX constants.
1275 public function getContentModel() {
1276 if ( !$this->mContentModel
) {
1277 $title = $this->getTitle();
1279 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $title );
1281 $this->mContentModel
= CONTENT_MODEL_WIKITEXT
;
1284 assert( !empty( $this->mContentModel
) );
1287 return $this->mContentModel
;
1291 * Returns the content format for this revision.
1293 * If no content format was stored in the database, the default format for this
1294 * revision's content model is returned.
1296 * @return string The content format id associated with this revision,
1297 * see the CONTENT_FORMAT_XXX constants.
1299 public function getContentFormat() {
1300 if ( !$this->mContentFormat
) {
1301 $handler = $this->getContentHandler();
1302 $this->mContentFormat
= $handler->getDefaultFormat();
1304 assert( !empty( $this->mContentFormat
) );
1307 return $this->mContentFormat
;
1311 * Returns the content handler appropriate for this revision's content model.
1313 * @throws MWException
1314 * @return ContentHandler
1316 public function getContentHandler() {
1317 if ( !$this->mContentHandler
) {
1318 $model = $this->getContentModel();
1319 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1321 $format = $this->getContentFormat();
1323 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1324 throw new MWException( "Oops, the content format $format is not supported for "
1325 . "this content model, $model" );
1329 return $this->mContentHandler
;
1335 public function getTimestamp() {
1336 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1342 public function isCurrent() {
1343 return $this->mCurrent
;
1347 * Get previous revision for this title
1349 * @return Revision|null
1351 public function getPrevious() {
1352 if ( $this->getTitle() ) {
1353 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1355 return self
::newFromTitle( $this->getTitle(), $prev );
1362 * Get next revision for this title
1364 * @return Revision|null
1366 public function getNext() {
1367 if ( $this->getTitle() ) {
1368 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1370 return self
::newFromTitle( $this->getTitle(), $next );
1377 * Get previous revision Id for this page_id
1378 * This is used to populate rev_parent_id on save
1380 * @param IDatabase $db
1383 private function getPreviousRevisionId( $db ) {
1384 if ( $this->mPage
=== null ) {
1387 # Use page_latest if ID is not given
1388 if ( !$this->mId
) {
1389 $prevId = $db->selectField( 'page', 'page_latest',
1390 [ 'page_id' => $this->mPage
],
1393 $prevId = $db->selectField( 'revision', 'rev_id',
1394 [ 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
],
1396 [ 'ORDER BY' => 'rev_id DESC' ] );
1398 return intval( $prevId );
1402 * Get revision text associated with an old or archive row
1404 * Both the flags and the text field must be included. Including the old_id
1405 * field will activate cache usage as long as the $wiki parameter is not set.
1407 * @param stdClass $row The text data
1408 * @param string $prefix Table prefix (default 'old_')
1409 * @param string|bool $wiki The name of the wiki to load the revision text from
1410 * (same as the the wiki $row was loaded from) or false to indicate the local
1411 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1412 * identifier as understood by the LoadBalancer class.
1413 * @return string|false Text the text requested or false on failure
1415 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1416 $textField = $prefix . 'text';
1417 $flagsField = $prefix . 'flags';
1419 if ( isset( $row->$flagsField ) ) {
1420 $flags = explode( ',', $row->$flagsField );
1425 if ( isset( $row->$textField ) ) {
1426 $text = $row->$textField;
1431 // Use external methods for external objects, text in table is URL-only then
1432 if ( in_array( 'external', $flags ) ) {
1434 $parts = explode( '://', $url, 2 );
1435 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1439 if ( isset( $row->old_id
) && $wiki === false ) {
1440 // Make use of the wiki-local revision text cache
1441 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1442 // The cached value should be decompressed, so handle that and return here
1443 return $cache->getWithSetCallback(
1444 $cache->makeKey( 'revisiontext', 'textid', $row->old_id
),
1445 self
::getCacheTTL( $cache ),
1446 function () use ( $url, $wiki, $flags ) {
1447 // No negative caching per Revision::loadText()
1448 $text = ExternalStore
::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1450 return self
::decompressRevisionText( $text, $flags );
1452 [ 'pcGroup' => self
::TEXT_CACHE_GROUP
, 'pcTTL' => $cache::TTL_PROC_LONG
]
1455 $text = ExternalStore
::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1459 return self
::decompressRevisionText( $text, $flags );
1463 * If $wgCompressRevisions is enabled, we will compress data.
1464 * The input string is modified in place.
1465 * Return value is the flags field: contains 'gzip' if the
1466 * data is compressed, and 'utf-8' if we're saving in UTF-8
1469 * @param mixed &$text Reference to a text
1472 public static function compressRevisionText( &$text ) {
1473 global $wgCompressRevisions;
1476 # Revisions not marked this way will be converted
1477 # on load if $wgLegacyCharset is set in the future.
1480 if ( $wgCompressRevisions ) {
1481 if ( function_exists( 'gzdeflate' ) ) {
1482 $deflated = gzdeflate( $text );
1484 if ( $deflated === false ) {
1485 wfLogWarning( __METHOD__
. ': gzdeflate() failed' );
1491 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1494 return implode( ',', $flags );
1498 * Re-converts revision text according to it's flags.
1500 * @param mixed $text Reference to a text
1501 * @param array $flags Compression flags
1502 * @return string|bool Decompressed text, or false on failure
1504 public static function decompressRevisionText( $text, $flags ) {
1505 global $wgLegacyEncoding, $wgContLang;
1507 if ( $text === false ) {
1508 // Text failed to be fetched; nothing to do
1512 if ( in_array( 'gzip', $flags ) ) {
1513 # Deal with optional compression of archived pages.
1514 # This can be done periodically via maintenance/compressOld.php, and
1515 # as pages are saved if $wgCompressRevisions is set.
1516 $text = gzinflate( $text );
1518 if ( $text === false ) {
1519 wfLogWarning( __METHOD__
. ': gzinflate() failed' );
1524 if ( in_array( 'object', $flags ) ) {
1525 # Generic compressed storage
1526 $obj = unserialize( $text );
1527 if ( !is_object( $obj ) ) {
1531 $text = $obj->getText();
1534 if ( $text !== false && $wgLegacyEncoding
1535 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1537 # Old revisions kept around in a legacy encoding?
1538 # Upconvert on demand.
1539 # ("utf8" checked for compatibility with some broken
1540 # conversion scripts 2008-12-30)
1541 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1548 * Insert a new revision into the database, returning the new revision ID
1549 * number on success and dies horribly on failure.
1551 * @param IDatabase $dbw (master connection)
1552 * @throws MWException
1553 * @return int The revision ID
1555 public function insertOn( $dbw ) {
1556 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1558 // We're inserting a new revision, so we have to use master anyway.
1559 // If it's a null revision, it may have references to rows that
1560 // are not in the replica yet (the text row).
1561 $this->mQueryFlags |
= self
::READ_LATEST
;
1563 // Not allowed to have rev_page equal to 0, false, etc.
1564 if ( !$this->mPage
) {
1565 $title = $this->getTitle();
1566 if ( $title instanceof Title
) {
1567 $titleText = ' for page ' . $title->getPrefixedText();
1571 throw new MWException( "Cannot insert revision$titleText: page ID must be nonzero" );
1574 $this->checkContentModel();
1576 $data = $this->mText
;
1577 $flags = self
::compressRevisionText( $data );
1579 # Write to external storage if required
1580 if ( $wgDefaultExternalStore ) {
1581 // Store and get the URL
1582 $data = ExternalStore
::insertToDefault( $data );
1584 throw new MWException( "Unable to store text to external storage" );
1589 $flags .= 'external';
1592 # Record the text (or external storage URL) to the text table
1593 if ( $this->mTextId
=== null ) {
1594 $dbw->insert( 'text',
1596 'old_text' => $data,
1597 'old_flags' => $flags,
1600 $this->mTextId
= $dbw->insertId();
1603 if ( $this->mComment
=== null ) {
1604 $this->mComment
= "";
1607 # Record the edit in revisions
1609 'rev_page' => $this->mPage
,
1610 'rev_text_id' => $this->mTextId
,
1611 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1612 'rev_user' => $this->mUser
,
1613 'rev_user_text' => $this->mUserText
,
1614 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1615 'rev_deleted' => $this->mDeleted
,
1616 'rev_len' => $this->mSize
,
1617 'rev_parent_id' => $this->mParentId
=== null
1618 ?
$this->getPreviousRevisionId( $dbw )
1620 'rev_sha1' => $this->mSha1
=== null
1621 ? self
::base36Sha1( $this->mText
)
1624 if ( $this->mId
!== null ) {
1625 $row['rev_id'] = $this->mId
;
1628 list( $commentFields, $commentCallback ) =
1629 CommentStore
::newKey( 'rev_comment' )->insertWithTempTable( $dbw, $this->mComment
);
1630 $row +
= $commentFields;
1632 if ( $wgContentHandlerUseDB ) {
1633 // NOTE: Store null for the default model and format, to save space.
1634 // XXX: Makes the DB sensitive to changed defaults.
1635 // Make this behavior optional? Only in miser mode?
1637 $model = $this->getContentModel();
1638 $format = $this->getContentFormat();
1640 $title = $this->getTitle();
1642 if ( $title === null ) {
1643 throw new MWException( "Insufficient information to determine the title of the "
1644 . "revision's page!" );
1647 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1648 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1650 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1651 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1654 $dbw->insert( 'revision', $row, __METHOD__
);
1656 if ( $this->mId
=== null ) {
1657 // Only if auto-increment was used
1658 $this->mId
= $dbw->insertId();
1660 $commentCallback( $this->mId
);
1662 // Assertion to try to catch T92046
1663 if ( (int)$this->mId
=== 0 ) {
1664 throw new UnexpectedValueException(
1665 'After insert, Revision mId is ' . var_export( $this->mId
, 1 ) . ': ' .
1666 var_export( $row, 1 )
1670 // Insert IP revision into ip_changes for use when querying for a range.
1671 if ( $this->mUser
=== 0 && IP
::isValid( $this->mUserText
) ) {
1673 'ipc_rev_id' => $this->mId
,
1674 'ipc_rev_timestamp' => $row['rev_timestamp'],
1675 'ipc_hex' => IP
::toHex( $row['rev_user_text'] ),
1677 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
1680 // Avoid PHP 7.1 warning of passing $this by reference
1682 Hooks
::run( 'RevisionInsertComplete', [ &$revision, $data, $flags ] );
1687 protected function checkContentModel() {
1688 global $wgContentHandlerUseDB;
1690 // Note: may return null for revisions that have not yet been inserted
1691 $title = $this->getTitle();
1693 $model = $this->getContentModel();
1694 $format = $this->getContentFormat();
1695 $handler = $this->getContentHandler();
1697 if ( !$handler->isSupportedFormat( $format ) ) {
1698 $t = $title->getPrefixedDBkey();
1700 throw new MWException( "Can't use format $format with content model $model on $t" );
1703 if ( !$wgContentHandlerUseDB && $title ) {
1704 // if $wgContentHandlerUseDB is not set,
1705 // all revisions must use the default content model and format.
1707 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1708 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1709 $defaultFormat = $defaultHandler->getDefaultFormat();
1711 if ( $this->getContentModel() != $defaultModel ) {
1712 $t = $title->getPrefixedDBkey();
1714 throw new MWException( "Can't save non-default content model with "
1715 . "\$wgContentHandlerUseDB disabled: model is $model, "
1716 . "default for $t is $defaultModel" );
1719 if ( $this->getContentFormat() != $defaultFormat ) {
1720 $t = $title->getPrefixedDBkey();
1722 throw new MWException( "Can't use non-default content format with "
1723 . "\$wgContentHandlerUseDB disabled: format is $format, "
1724 . "default for $t is $defaultFormat" );
1728 $content = $this->getContent( self
::RAW
);
1729 $prefixedDBkey = $title->getPrefixedDBkey();
1730 $revId = $this->mId
;
1733 throw new MWException(
1734 "Content of revision $revId ($prefixedDBkey) could not be loaded for validation!"
1737 if ( !$content->isValid() ) {
1738 throw new MWException(
1739 "Content of revision $revId ($prefixedDBkey) is not valid! Content model is $model"
1745 * Get the base 36 SHA-1 value for a string of text
1746 * @param string $text
1749 public static function base36Sha1( $text ) {
1750 return Wikimedia\base_convert
( sha1( $text ), 16, 36, 31 );
1754 * Get the text cache TTL
1756 * @param WANObjectCache $cache
1759 private static function getCacheTTL( WANObjectCache
$cache ) {
1760 global $wgRevisionCacheExpiry;
1762 if ( $cache->getQoS( $cache::ATTR_EMULATION
) <= $cache::QOS_EMULATION_SQL
) {
1763 // Do not cache RDBMs blobs in...the RDBMs store
1764 $ttl = $cache::TTL_UNCACHEABLE
;
1766 $ttl = $wgRevisionCacheExpiry ?
: $cache::TTL_UNCACHEABLE
;
1773 * Lazy-load the revision's text.
1774 * Currently hardcoded to the 'text' table storage engine.
1776 * @return string|bool The revision's text, or false on failure
1778 private function loadText() {
1779 $cache = ObjectCache
::getMainWANInstance();
1781 // No negative caching; negative hits on text rows may be due to corrupted replica DBs
1782 return $cache->getWithSetCallback(
1783 $cache->makeKey( 'revisiontext', 'textid', $this->getTextId() ),
1784 self
::getCacheTTL( $cache ),
1786 return $this->fetchText();
1788 [ 'pcGroup' => self
::TEXT_CACHE_GROUP
, 'pcTTL' => $cache::TTL_PROC_LONG
]
1792 private function fetchText() {
1793 $textId = $this->getTextId();
1795 // If we kept data for lazy extraction, use it now...
1796 if ( $this->mTextRow
!== null ) {
1797 $row = $this->mTextRow
;
1798 $this->mTextRow
= null;
1803 // Callers doing updates will pass in READ_LATEST as usual. Since the text/blob tables
1804 // do not normally get rows changed around, set READ_LATEST_IMMUTABLE in those cases.
1805 $flags = $this->mQueryFlags
;
1806 $flags |
= DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
)
1807 ? self
::READ_LATEST_IMMUTABLE
1810 list( $index, $options, $fallbackIndex, $fallbackOptions ) =
1811 DBAccessObjectUtils
::getDBOptions( $flags );
1814 // Text data is immutable; check replica DBs first.
1815 $row = wfGetDB( $index )->selectRow(
1817 [ 'old_text', 'old_flags' ],
1818 [ 'old_id' => $textId ],
1824 // Fallback to DB_MASTER in some cases if the row was not found
1825 if ( !$row && $fallbackIndex !== null ) {
1826 // Use FOR UPDATE if it was used to fetch this revision. This avoids missing the row
1827 // due to REPEATABLE-READ. Also fallback to the master if READ_LATEST is provided.
1828 $row = wfGetDB( $fallbackIndex )->selectRow(
1830 [ 'old_text', 'old_flags' ],
1831 [ 'old_id' => $textId ],
1838 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1841 $text = self
::getRevisionText( $row );
1842 if ( $row && $text === false ) {
1843 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1846 return is_string( $text ) ?
$text : false;
1850 * Create a new null-revision for insertion into a page's
1851 * history. This will not re-save the text, but simply refer
1852 * to the text from the previous version.
1854 * Such revisions can for instance identify page rename
1855 * operations and other such meta-modifications.
1857 * @param IDatabase $dbw
1858 * @param int $pageId ID number of the page to read from
1859 * @param string $summary Revision's summary
1860 * @param bool $minor Whether the revision should be considered as minor
1861 * @param User|null $user User object to use or null for $wgUser
1862 * @return Revision|null Revision or null on error
1864 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1865 global $wgContentHandlerUseDB;
1867 $fields = [ 'page_latest', 'page_namespace', 'page_title',
1868 'rev_text_id', 'rev_len', 'rev_sha1' ];
1870 if ( $wgContentHandlerUseDB ) {
1871 $fields[] = 'rev_content_model';
1872 $fields[] = 'rev_content_format';
1875 $current = $dbw->selectRow(
1876 [ 'page', 'revision' ],
1879 'page_id' => $pageId,
1880 'page_latest=rev_id',
1883 [ 'FOR UPDATE' ] // T51581
1894 'user_text' => $user->getName(),
1895 'user' => $user->getId(),
1896 'comment' => $summary,
1897 'minor_edit' => $minor,
1898 'text_id' => $current->rev_text_id
,
1899 'parent_id' => $current->page_latest
,
1900 'len' => $current->rev_len
,
1901 'sha1' => $current->rev_sha1
1904 if ( $wgContentHandlerUseDB ) {
1905 $row['content_model'] = $current->rev_content_model
;
1906 $row['content_format'] = $current->rev_content_format
;
1909 $row['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
1911 $revision = new Revision( $row );
1920 * Determine if the current user is allowed to view a particular
1921 * field of this revision, if it's marked as deleted.
1923 * @param int $field One of self::DELETED_TEXT,
1924 * self::DELETED_COMMENT,
1925 * self::DELETED_USER
1926 * @param User|null $user User object to check, or null to use $wgUser
1929 public function userCan( $field, User
$user = null ) {
1930 return self
::userCanBitfield( $this->getVisibility(), $field, $user );
1934 * Determine if the current user is allowed to view a particular
1935 * field of this revision, if it's marked as deleted. This is used
1936 * by various classes to avoid duplication.
1938 * @param int $bitfield Current field
1939 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1940 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1941 * self::DELETED_USER = File::DELETED_USER
1942 * @param User|null $user User object to check, or null to use $wgUser
1943 * @param Title|null $title A Title object to check for per-page restrictions on,
1944 * instead of just plain userrights
1947 public static function userCanBitfield( $bitfield, $field, User
$user = null,
1950 if ( $bitfield & $field ) { // aspect is deleted
1951 if ( $user === null ) {
1955 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1956 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
1957 } elseif ( $field & self
::DELETED_TEXT
) {
1958 $permissions = [ 'deletedtext' ];
1960 $permissions = [ 'deletedhistory' ];
1962 $permissionlist = implode( ', ', $permissions );
1963 if ( $title === null ) {
1964 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1965 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
1967 $text = $title->getPrefixedText();
1968 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1969 foreach ( $permissions as $perm ) {
1970 if ( $title->userCan( $perm, $user ) ) {
1982 * Get rev_timestamp from rev_id, without loading the rest of the row
1984 * @param Title $title
1987 * @return string|bool False if not found
1989 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1990 $db = ( $flags & self
::READ_LATEST
)
1991 ?
wfGetDB( DB_MASTER
)
1992 : wfGetDB( DB_REPLICA
);
1993 // Casting fix for databases that can't take '' for rev_id
1997 $conds = [ 'rev_id' => $id ];
1998 $conds['rev_page'] = $title->getArticleID();
1999 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
2001 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
2005 * Get count of revisions per page...not very efficient
2007 * @param IDatabase $db
2008 * @param int $id Page id
2011 static function countByPageId( $db, $id ) {
2012 $row = $db->selectRow( 'revision', [ 'revCount' => 'COUNT(*)' ],
2013 [ 'rev_page' => $id ], __METHOD__
);
2015 return $row->revCount
;
2021 * Get count of revisions per page...not very efficient
2023 * @param IDatabase $db
2024 * @param Title $title
2027 static function countByTitle( $db, $title ) {
2028 $id = $title->getArticleID();
2030 return self
::countByPageId( $db, $id );
2036 * Check if no edits were made by other users since
2037 * the time a user started editing the page. Limit to
2038 * 50 revisions for the sake of performance.
2041 * @deprecated since 1.24
2043 * @param IDatabase|int $db The Database to perform the check on. May be given as a
2044 * Database object or a database identifier usable with wfGetDB.
2045 * @param int $pageId The ID of the page in question
2046 * @param int $userId The ID of the user in question
2047 * @param string $since Look at edits since this time
2049 * @return bool True if the given user was the only one to edit since the given timestamp
2051 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
2056 if ( is_int( $db ) ) {
2057 $db = wfGetDB( $db );
2060 $res = $db->select( 'revision',
2063 'rev_page' => $pageId,
2064 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
2067 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ] );
2068 foreach ( $res as $row ) {
2069 if ( $row->rev_user
!= $userId ) {
2077 * Load a revision based on a known page ID and current revision ID from the DB
2079 * This method allows for the use of caching, though accessing anything that normally
2080 * requires permission checks (aside from the text) will trigger a small DB lookup.
2081 * The title will also be lazy loaded, though setTitle() can be used to preload it.
2083 * @param IDatabase $db
2084 * @param int $pageId Page ID
2085 * @param int $revId Known current revision of this page
2086 * @return Revision|bool Returns false if missing
2089 public static function newKnownCurrent( IDatabase
$db, $pageId, $revId ) {
2090 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2091 return $cache->getWithSetCallback(
2092 // Page/rev IDs passed in from DB to reflect history merges
2093 $cache->makeGlobalKey( 'revision', $db->getDomainID(), $pageId, $revId ),
2095 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
2096 $setOpts +
= Database
::getCacheSetOptions( $db );
2098 $rev = Revision
::loadFromPageId( $db, $pageId, $revId );
2099 // Reflect revision deletion and user renames
2101 $rev->mTitle
= null; // mutable; lazy-load
2102 $rev->mRefreshMutableFields
= true;
2105 return $rev ?
: false; // don't cache negatives
2111 * For cached revisions, make sure the user name and rev_deleted is up-to-date
2113 private function loadMutableFields() {
2114 if ( !$this->mRefreshMutableFields
) {
2115 return; // not needed
2118 $this->mRefreshMutableFields
= false;
2119 $dbr = wfGetLB( $this->mWiki
)->getConnectionRef( DB_REPLICA
, [], $this->mWiki
);
2120 $row = $dbr->selectRow(
2121 [ 'revision', 'user' ],
2122 [ 'rev_deleted', 'user_name' ],
2123 [ 'rev_id' => $this->mId
, 'user_id = rev_user' ],
2126 if ( $row ) { // update values
2127 $this->mDeleted
= (int)$row->rev_deleted
;
2128 $this->mUserText
= $row->user_name
;