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\IDatabase
;
24 use MediaWiki\Linker\LinkTarget
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Rdbms\ResultWrapper
;
27 use Wikimedia\Rdbms\FakeResultWrapper
;
32 class Revision
implements IDBAccessObject
{
40 protected $mOrigUserText;
44 protected $mMinorEdit;
46 protected $mTimestamp;
62 protected $mUnpatrolled;
64 /** @var stdClass|null */
67 /** @var null|Title */
72 protected $mContentModel;
74 protected $mContentFormat;
76 /** @var Content|null|bool */
78 /** @var null|ContentHandler */
79 protected $mContentHandler;
82 protected $mQueryFlags = 0;
83 /** @var bool Used for cached values to reload user text and rev_deleted */
84 protected $mRefreshMutableFields = false;
85 /** @var string Wiki ID; false means the current wiki */
86 protected $mWiki = false;
88 // Revision deletion constants
89 const DELETED_TEXT
= 1;
90 const DELETED_COMMENT
= 2;
91 const DELETED_USER
= 4;
92 const DELETED_RESTRICTED
= 8;
93 const SUPPRESSED_USER
= 12; // convenience
94 const SUPPRESSED_ALL
= 15; // convenience
96 // Audience options for accessors
98 const FOR_THIS_USER
= 2;
101 const TEXT_CACHE_GROUP
= 'revisiontext:10'; // process cache name and max key count
104 * Load a page revision from a given revision ID number.
105 * Returns null if no such revision can be found.
108 * Revision::READ_LATEST : Select the data from the master
109 * Revision::READ_LOCKING : Select & lock the data from the master
112 * @param int $flags (optional)
113 * @return Revision|null
115 public static function newFromId( $id, $flags = 0 ) {
116 return self
::newFromConds( [ 'rev_id' => intval( $id ) ], $flags );
120 * Load either the current, or a specified, revision
121 * that's attached to a given link target. If not attached
122 * to that link target, will return null.
125 * Revision::READ_LATEST : Select the data from the master
126 * Revision::READ_LOCKING : Select & lock the data from the master
128 * @param LinkTarget $linkTarget
129 * @param int $id (optional)
130 * @param int $flags Bitfield (optional)
131 * @return Revision|null
133 public static function newFromTitle( LinkTarget
$linkTarget, $id = 0, $flags = 0 ) {
135 'page_namespace' => $linkTarget->getNamespace(),
136 'page_title' => $linkTarget->getDBkey()
139 // Use the specified ID
140 $conds['rev_id'] = $id;
141 return self
::newFromConds( $conds, $flags );
143 // Use a join to get the latest revision
144 $conds[] = 'rev_id=page_latest';
145 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
146 return self
::loadFromConds( $db, $conds, $flags );
151 * Load either the current, or a specified, revision
152 * that's attached to a given page ID.
153 * Returns null if no such revision can be found.
156 * Revision::READ_LATEST : Select the data from the master (since 1.20)
157 * Revision::READ_LOCKING : Select & lock the data from the master
160 * @param int $revId (optional)
161 * @param int $flags Bitfield (optional)
162 * @return Revision|null
164 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
165 $conds = [ 'page_id' => $pageId ];
167 $conds['rev_id'] = $revId;
168 return self
::newFromConds( $conds, $flags );
170 // Use a join to get the latest revision
171 $conds[] = 'rev_id = page_latest';
172 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
173 return self
::loadFromConds( $db, $conds, $flags );
178 * Make a fake revision object from an archive table row. This is queried
179 * for permissions or even inserted (as in Special:Undelete)
180 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
183 * @param array $overrides
185 * @throws MWException
188 public static function newFromArchiveRow( $row, $overrides = [] ) {
189 global $wgContentHandlerUseDB;
191 $attribs = $overrides +
[
192 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
193 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
194 'comment' => $row->ar_comment
,
195 'user' => $row->ar_user
,
196 'user_text' => $row->ar_user_text
,
197 'timestamp' => $row->ar_timestamp
,
198 'minor_edit' => $row->ar_minor_edit
,
199 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
200 'deleted' => $row->ar_deleted
,
201 'len' => $row->ar_len
,
202 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
203 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
204 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
207 if ( !$wgContentHandlerUseDB ) {
208 unset( $attribs['content_model'] );
209 unset( $attribs['content_format'] );
212 if ( !isset( $attribs['title'] )
213 && isset( $row->ar_namespace
)
214 && isset( $row->ar_title
)
216 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
219 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
220 // Pre-1.5 ar_text row
221 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
222 if ( $attribs['text'] === false ) {
223 throw new MWException( 'Unable to load text from archive row (possibly T24624)' );
226 return new self( $attribs );
235 public static function newFromRow( $row ) {
236 return new self( $row );
240 * Load a page revision from a given revision ID number.
241 * Returns null if no such revision can be found.
243 * @param IDatabase $db
245 * @return Revision|null
247 public static function loadFromId( $db, $id ) {
248 return self
::loadFromConds( $db, [ 'rev_id' => intval( $id ) ] );
252 * Load either the current, or a specified, revision
253 * that's attached to a given page. If not attached
254 * to that page, will return null.
256 * @param IDatabase $db
259 * @return Revision|null
261 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
262 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
264 $conds['rev_id'] = intval( $id );
266 $conds[] = 'rev_id=page_latest';
268 return self
::loadFromConds( $db, $conds );
272 * Load either the current, or a specified, revision
273 * that's attached to a given page. If not attached
274 * to that page, will return null.
276 * @param IDatabase $db
277 * @param Title $title
279 * @return Revision|null
281 public static function loadFromTitle( $db, $title, $id = 0 ) {
283 $matchId = intval( $id );
285 $matchId = 'page_latest';
287 return self
::loadFromConds( $db,
290 'page_namespace' => $title->getNamespace(),
291 'page_title' => $title->getDBkey()
297 * Load the revision for the given title with the given timestamp.
298 * WARNING: Timestamps may in some circumstances not be unique,
299 * so this isn't the best key to use.
301 * @param IDatabase $db
302 * @param Title $title
303 * @param string $timestamp
304 * @return Revision|null
306 public static function loadFromTimestamp( $db, $title, $timestamp ) {
307 return self
::loadFromConds( $db,
309 'rev_timestamp' => $db->timestamp( $timestamp ),
310 'page_namespace' => $title->getNamespace(),
311 'page_title' => $title->getDBkey()
317 * Given a set of conditions, fetch a revision
319 * This method is used then a revision ID is qualified and
320 * will incorporate some basic replica DB/master fallback logic
322 * @param array $conditions
323 * @param int $flags (optional)
324 * @return Revision|null
326 private static function newFromConds( $conditions, $flags = 0 ) {
327 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
329 $rev = self
::loadFromConds( $db, $conditions, $flags );
330 // Make sure new pending/committed revision are visibile later on
331 // within web requests to certain avoid bugs like T93866 and T94407.
333 && !( $flags & self
::READ_LATEST
)
334 && wfGetLB()->getServerCount() > 1
335 && wfGetLB()->hasOrMadeRecentMasterChanges()
337 $flags = self
::READ_LATEST
;
338 $db = wfGetDB( DB_MASTER
);
339 $rev = self
::loadFromConds( $db, $conditions, $flags );
343 $rev->mQueryFlags
= $flags;
350 * Given a set of conditions, fetch a revision from
351 * the given database connection.
353 * @param IDatabase $db
354 * @param array $conditions
355 * @param int $flags (optional)
356 * @return Revision|null
358 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
359 $row = self
::fetchFromConds( $db, $conditions, $flags );
361 $rev = new Revision( $row );
362 $rev->mWiki
= $db->getWikiID();
371 * Return a wrapper for a series of database rows to
372 * fetch all of a given page's revisions in turn.
373 * Each row can be fed to the constructor to get objects.
375 * @param LinkTarget $title
376 * @return ResultWrapper
377 * @deprecated Since 1.28
379 public static function fetchRevision( LinkTarget
$title ) {
380 $row = self
::fetchFromConds(
381 wfGetDB( DB_REPLICA
),
383 'rev_id=page_latest',
384 'page_namespace' => $title->getNamespace(),
385 'page_title' => $title->getDBkey()
389 return new FakeResultWrapper( $row ?
[ $row ] : [] );
393 * Given a set of conditions, return a ResultWrapper
394 * which will return matching database rows with the
395 * fields necessary to build Revision objects.
397 * @param IDatabase $db
398 * @param array $conditions
399 * @param int $flags (optional)
402 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
403 $fields = array_merge(
404 self
::selectFields(),
405 self
::selectPageFields(),
406 self
::selectUserFields()
409 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
410 $options[] = 'FOR UPDATE';
412 return $db->selectRow(
413 [ 'revision', 'page', 'user' ],
418 [ 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() ]
423 * Return the value of a select() JOIN conds array for the user table.
424 * This will get user table rows for logged-in users.
428 public static function userJoinCond() {
429 return [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
433 * Return the value of a select() page conds array for the page table.
434 * This will assure that the revision(s) are not orphaned from live pages.
438 public static function pageJoinCond() {
439 return [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
443 * Return the list of revision fields that should be selected to create
447 public static function selectFields() {
448 global $wgContentHandlerUseDB;
465 if ( $wgContentHandlerUseDB ) {
466 $fields[] = 'rev_content_format';
467 $fields[] = 'rev_content_model';
474 * Return the list of revision fields that should be selected to create
475 * a new revision from an archive row.
478 public static function selectArchiveFields() {
479 global $wgContentHandlerUseDB;
497 if ( $wgContentHandlerUseDB ) {
498 $fields[] = 'ar_content_format';
499 $fields[] = 'ar_content_model';
505 * Return the list of text fields that should be selected to read the
509 public static function selectTextFields() {
517 * Return the list of page fields that should be selected from page table
520 public static function selectPageFields() {
532 * Return the list of user fields that should be selected from user table
535 public static function selectUserFields() {
536 return [ 'user_name' ];
540 * Do a batched query to get the parent revision lengths
541 * @param IDatabase $db
542 * @param array $revIds
545 public static function getParentLengths( $db, array $revIds ) {
548 return $revLens; // empty
550 $res = $db->select( 'revision',
551 [ 'rev_id', 'rev_len' ],
552 [ 'rev_id' => $revIds ],
554 foreach ( $res as $row ) {
555 $revLens[$row->rev_id
] = $row->rev_len
;
563 * @param object|array $row Either a database row or an array
564 * @throws MWException
567 function __construct( $row ) {
568 if ( is_object( $row ) ) {
569 $this->mId
= intval( $row->rev_id
);
570 $this->mPage
= intval( $row->rev_page
);
571 $this->mTextId
= intval( $row->rev_text_id
);
572 $this->mComment
= $row->rev_comment
;
573 $this->mUser
= intval( $row->rev_user
);
574 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
575 $this->mTimestamp
= $row->rev_timestamp
;
576 $this->mDeleted
= intval( $row->rev_deleted
);
578 if ( !isset( $row->rev_parent_id
) ) {
579 $this->mParentId
= null;
581 $this->mParentId
= intval( $row->rev_parent_id
);
584 if ( !isset( $row->rev_len
) ) {
587 $this->mSize
= intval( $row->rev_len
);
590 if ( !isset( $row->rev_sha1
) ) {
593 $this->mSha1
= $row->rev_sha1
;
596 if ( isset( $row->page_latest
) ) {
597 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
598 $this->mTitle
= Title
::newFromRow( $row );
600 $this->mCurrent
= false;
601 $this->mTitle
= null;
604 if ( !isset( $row->rev_content_model
) ) {
605 $this->mContentModel
= null; # determine on demand if needed
607 $this->mContentModel
= strval( $row->rev_content_model
);
610 if ( !isset( $row->rev_content_format
) ) {
611 $this->mContentFormat
= null; # determine on demand if needed
613 $this->mContentFormat
= strval( $row->rev_content_format
);
616 // Lazy extraction...
618 if ( isset( $row->old_text
) ) {
619 $this->mTextRow
= $row;
621 // 'text' table row entry will be lazy-loaded
622 $this->mTextRow
= null;
625 // Use user_name for users and rev_user_text for IPs...
626 $this->mUserText
= null; // lazy load if left null
627 if ( $this->mUser
== 0 ) {
628 $this->mUserText
= $row->rev_user_text
; // IP user
629 } elseif ( isset( $row->user_name
) ) {
630 $this->mUserText
= $row->user_name
; // logged-in user
632 $this->mOrigUserText
= $row->rev_user_text
;
633 } elseif ( is_array( $row ) ) {
634 // Build a new revision to be saved...
635 global $wgUser; // ugh
637 # if we have a content object, use it to set the model and type
638 if ( !empty( $row['content'] ) ) {
639 // @todo when is that set? test with external store setup! check out insertOn() [dk]
640 if ( !empty( $row['text_id'] ) ) {
641 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
642 "can't serialize content object" );
645 $row['content_model'] = $row['content']->getModel();
646 # note: mContentFormat is initializes later accordingly
647 # note: content is serialized later in this method!
648 # also set text to null?
651 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
652 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
653 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
654 $this->mUserText
= isset( $row['user_text'] )
655 ?
strval( $row['user_text'] ) : $wgUser->getName();
656 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
657 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
658 $this->mTimestamp
= isset( $row['timestamp'] )
659 ?
strval( $row['timestamp'] ) : wfTimestampNow();
660 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
661 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
662 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
663 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
665 $this->mContentModel
= isset( $row['content_model'] )
666 ?
strval( $row['content_model'] ) : null;
667 $this->mContentFormat
= isset( $row['content_format'] )
668 ?
strval( $row['content_format'] ) : null;
670 // Enforce spacing trimming on supplied text
671 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
672 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
673 $this->mTextRow
= null;
675 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
677 // if we have a Content object, override mText and mContentModel
678 if ( !empty( $row['content'] ) ) {
679 if ( !( $row['content'] instanceof Content
) ) {
680 throw new MWException( '`content` field must contain a Content object.' );
683 $handler = $this->getContentHandler();
684 $this->mContent
= $row['content'];
686 $this->mContentModel
= $this->mContent
->getModel();
687 $this->mContentHandler
= null;
689 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
690 } elseif ( $this->mText
!== null ) {
691 $handler = $this->getContentHandler();
692 $this->mContent
= $handler->unserializeContent( $this->mText
);
695 // If we have a Title object, make sure it is consistent with mPage.
696 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
697 if ( $this->mPage
=== null ) {
698 // if the page ID wasn't known, set it now
699 $this->mPage
= $this->mTitle
->getArticleID();
700 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
701 // Got different page IDs. This may be legit (e.g. during undeletion),
702 // but it seems worth mentioning it in the log.
703 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
704 $this->mTitle
->getArticleID() . " provided by the Title object." );
708 $this->mCurrent
= false;
710 // If we still have no length, see it we have the text to figure it out
711 if ( !$this->mSize
&& $this->mContent
!== null ) {
712 $this->mSize
= $this->mContent
->getSize();
716 if ( $this->mSha1
=== null ) {
717 $this->mSha1
= $this->mText
=== null ?
null : self
::base36Sha1( $this->mText
);
721 $this->getContentModel();
722 $this->getContentFormat();
724 throw new MWException( 'Revision constructor passed invalid row format.' );
726 $this->mUnpatrolled
= null;
734 public function getId() {
739 * Set the revision ID
741 * This should only be used for proposed revisions that turn out to be null edits
746 public function setId( $id ) {
747 $this->mId
= (int)$id;
751 * Set the user ID/name
753 * This should only be used for proposed revisions that turn out to be null edits
756 * @param integer $id User ID
757 * @param string $name User name
759 public function setUserIdAndName( $id, $name ) {
760 $this->mUser
= (int)$id;
761 $this->mUserText
= $name;
762 $this->mOrigUserText
= $name;
770 public function getTextId() {
771 return $this->mTextId
;
775 * Get parent revision ID (the original previous page revision)
779 public function getParentId() {
780 return $this->mParentId
;
784 * Returns the length of the text in this revision, or null if unknown.
788 public function getSize() {
793 * Returns the base36 sha1 of the text in this revision, or null if unknown.
795 * @return string|null
797 public function getSha1() {
802 * Returns the title of the page associated with this entry or null.
804 * Will do a query, when title is not set and id is given.
808 public function getTitle() {
809 if ( $this->mTitle
!== null ) {
810 return $this->mTitle
;
812 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
813 if ( $this->mId
!== null ) {
814 $dbr = wfGetLB( $this->mWiki
)->getConnectionRef( DB_REPLICA
, [], $this->mWiki
);
815 $row = $dbr->selectRow(
816 [ 'page', 'revision' ],
817 self
::selectPageFields(),
818 [ 'page_id=rev_page', 'rev_id' => $this->mId
],
822 // @TODO: better foreign title handling
823 $this->mTitle
= Title
::newFromRow( $row );
827 if ( $this->mWiki
=== false ||
$this->mWiki
=== wfWikiID() ) {
828 // Loading by ID is best, though not possible for foreign titles
829 if ( !$this->mTitle
&& $this->mPage
!== null && $this->mPage
> 0 ) {
830 $this->mTitle
= Title
::newFromID( $this->mPage
);
834 return $this->mTitle
;
838 * Set the title of the revision
840 * @param Title $title
842 public function setTitle( $title ) {
843 $this->mTitle
= $title;
851 public function getPage() {
856 * Fetch revision's user id if it's available to the specified audience.
857 * If the specified audience does not have access to it, zero will be
860 * @param int $audience One of:
861 * Revision::FOR_PUBLIC to be displayed to all users
862 * Revision::FOR_THIS_USER to be displayed to the given user
863 * Revision::RAW get the ID regardless of permissions
864 * @param User $user User object to check for, only if FOR_THIS_USER is passed
865 * to the $audience parameter
868 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
869 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
871 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
879 * Fetch revision's user id without regard for the current user's permissions
882 * @deprecated since 1.25, use getUser( Revision::RAW )
884 public function getRawUser() {
885 wfDeprecated( __METHOD__
, '1.25' );
886 return $this->getUser( self
::RAW
);
890 * Fetch revision's username if it's available to the specified audience.
891 * If the specified audience does not have access to the username, an
892 * empty string will be returned.
894 * @param int $audience One of:
895 * Revision::FOR_PUBLIC to be displayed to all users
896 * Revision::FOR_THIS_USER to be displayed to the given user
897 * Revision::RAW get the text regardless of permissions
898 * @param User $user User object to check for, only if FOR_THIS_USER is passed
899 * to the $audience parameter
902 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
903 $this->loadMutableFields();
905 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
907 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
910 if ( $this->mUserText
=== null ) {
911 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
912 if ( $this->mUserText
=== false ) {
913 # This shouldn't happen, but it can if the wiki was recovered
914 # via importing revs and there is no user table entry yet.
915 $this->mUserText
= $this->mOrigUserText
;
918 return $this->mUserText
;
923 * Fetch revision's username without regard for view restrictions
926 * @deprecated since 1.25, use getUserText( Revision::RAW )
928 public function getRawUserText() {
929 wfDeprecated( __METHOD__
, '1.25' );
930 return $this->getUserText( self
::RAW
);
934 * Fetch revision comment if it's available to the specified audience.
935 * If the specified audience does not have access to the comment, an
936 * empty string will be returned.
938 * @param int $audience One of:
939 * Revision::FOR_PUBLIC to be displayed to all users
940 * Revision::FOR_THIS_USER to be displayed to the given user
941 * Revision::RAW get the text regardless of permissions
942 * @param User $user User object to check for, only if FOR_THIS_USER is passed
943 * to the $audience parameter
946 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
947 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
949 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
952 return $this->mComment
;
957 * Fetch revision comment without regard for the current user's permissions
960 * @deprecated since 1.25, use getComment( Revision::RAW )
962 public function getRawComment() {
963 wfDeprecated( __METHOD__
, '1.25' );
964 return $this->getComment( self
::RAW
);
970 public function isMinor() {
971 return (bool)$this->mMinorEdit
;
975 * @return int Rcid of the unpatrolled row, zero if there isn't one
977 public function isUnpatrolled() {
978 if ( $this->mUnpatrolled
!== null ) {
979 return $this->mUnpatrolled
;
981 $rc = $this->getRecentChange();
982 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
983 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
985 $this->mUnpatrolled
= 0;
987 return $this->mUnpatrolled
;
991 * Get the RC object belonging to the current revision, if there's one
993 * @param int $flags (optional) $flags include:
994 * Revision::READ_LATEST : Select the data from the master
997 * @return RecentChange|null
999 public function getRecentChange( $flags = 0 ) {
1000 $dbr = wfGetDB( DB_REPLICA
);
1002 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
1004 return RecentChange
::newFromConds(
1006 'rc_user_text' => $this->getUserText( Revision
::RAW
),
1007 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
1008 'rc_this_oldid' => $this->getId()
1016 * @param int $field One of DELETED_* bitfield constants
1020 public function isDeleted( $field ) {
1021 if ( $this->isCurrent() && $field === self
::DELETED_TEXT
) {
1022 // Current revisions of pages cannot have the content hidden. Skipping this
1023 // check is very useful for Parser as it fetches templates using newKnownCurrent().
1024 // Calling getVisibility() in that case triggers a verification database query.
1025 return false; // no need to check
1028 return ( $this->getVisibility() & $field ) == $field;
1032 * Get the deletion bitfield of the revision
1036 public function getVisibility() {
1037 $this->loadMutableFields();
1039 return (int)$this->mDeleted
;
1043 * Fetch revision content if it's available to the specified audience.
1044 * If the specified audience does not have the ability to view this
1045 * revision, null will be returned.
1047 * @param int $audience One of:
1048 * Revision::FOR_PUBLIC to be displayed to all users
1049 * Revision::FOR_THIS_USER to be displayed to $wgUser
1050 * Revision::RAW get the text regardless of permissions
1051 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1052 * to the $audience parameter
1054 * @return Content|null
1056 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1057 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1059 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1062 return $this->getContentInternal();
1067 * Get original serialized data (without checking view restrictions)
1072 public function getSerializedData() {
1073 if ( $this->mText
=== null ) {
1074 // Revision is immutable. Load on demand.
1075 $this->mText
= $this->loadText();
1078 return $this->mText
;
1082 * Gets the content object for the revision (or null on failure).
1084 * Note that for mutable Content objects, each call to this method will return a
1088 * @return Content|null The Revision's content, or null on failure.
1090 protected function getContentInternal() {
1091 if ( $this->mContent
=== null ) {
1092 $text = $this->getSerializedData();
1094 if ( $text !== null && $text !== false ) {
1095 // Unserialize content
1096 $handler = $this->getContentHandler();
1097 $format = $this->getContentFormat();
1099 $this->mContent
= $handler->unserializeContent( $text, $format );
1103 // NOTE: copy() will return $this for immutable content objects
1104 return $this->mContent ?
$this->mContent
->copy() : null;
1108 * Returns the content model for this revision.
1110 * If no content model was stored in the database, the default content model for the title is
1111 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1112 * is used as a last resort.
1114 * @return string The content model id associated with this revision,
1115 * see the CONTENT_MODEL_XXX constants.
1117 public function getContentModel() {
1118 if ( !$this->mContentModel
) {
1119 $title = $this->getTitle();
1121 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $title );
1123 $this->mContentModel
= CONTENT_MODEL_WIKITEXT
;
1126 assert( !empty( $this->mContentModel
) );
1129 return $this->mContentModel
;
1133 * Returns the content format for this revision.
1135 * If no content format was stored in the database, the default format for this
1136 * revision's content model is returned.
1138 * @return string The content format id associated with this revision,
1139 * see the CONTENT_FORMAT_XXX constants.
1141 public function getContentFormat() {
1142 if ( !$this->mContentFormat
) {
1143 $handler = $this->getContentHandler();
1144 $this->mContentFormat
= $handler->getDefaultFormat();
1146 assert( !empty( $this->mContentFormat
) );
1149 return $this->mContentFormat
;
1153 * Returns the content handler appropriate for this revision's content model.
1155 * @throws MWException
1156 * @return ContentHandler
1158 public function getContentHandler() {
1159 if ( !$this->mContentHandler
) {
1160 $model = $this->getContentModel();
1161 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1163 $format = $this->getContentFormat();
1165 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1166 throw new MWException( "Oops, the content format $format is not supported for "
1167 . "this content model, $model" );
1171 return $this->mContentHandler
;
1177 public function getTimestamp() {
1178 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1184 public function isCurrent() {
1185 return $this->mCurrent
;
1189 * Get previous revision for this title
1191 * @return Revision|null
1193 public function getPrevious() {
1194 if ( $this->getTitle() ) {
1195 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1197 return self
::newFromTitle( $this->getTitle(), $prev );
1204 * Get next revision for this title
1206 * @return Revision|null
1208 public function getNext() {
1209 if ( $this->getTitle() ) {
1210 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1212 return self
::newFromTitle( $this->getTitle(), $next );
1219 * Get previous revision Id for this page_id
1220 * This is used to populate rev_parent_id on save
1222 * @param IDatabase $db
1225 private function getPreviousRevisionId( $db ) {
1226 if ( $this->mPage
=== null ) {
1229 # Use page_latest if ID is not given
1230 if ( !$this->mId
) {
1231 $prevId = $db->selectField( 'page', 'page_latest',
1232 [ 'page_id' => $this->mPage
],
1235 $prevId = $db->selectField( 'revision', 'rev_id',
1236 [ 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
],
1238 [ 'ORDER BY' => 'rev_id DESC' ] );
1240 return intval( $prevId );
1244 * Get revision text associated with an old or archive row
1246 * Both the flags and the text field must be included. Including the old_id
1247 * field will activate cache usage as long as the $wiki parameter is not set.
1249 * @param stdClass $row The text data
1250 * @param string $prefix Table prefix (default 'old_')
1251 * @param string|bool $wiki The name of the wiki to load the revision text from
1252 * (same as the the wiki $row was loaded from) or false to indicate the local
1253 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1254 * identifier as understood by the LoadBalancer class.
1255 * @return string|false Text the text requested or false on failure
1257 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1258 $textField = $prefix . 'text';
1259 $flagsField = $prefix . 'flags';
1261 if ( isset( $row->$flagsField ) ) {
1262 $flags = explode( ',', $row->$flagsField );
1267 if ( isset( $row->$textField ) ) {
1268 $text = $row->$textField;
1273 // Use external methods for external objects, text in table is URL-only then
1274 if ( in_array( 'external', $flags ) ) {
1276 $parts = explode( '://', $url, 2 );
1277 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1281 if ( isset( $row->old_id
) && $wiki === false ) {
1282 // Make use of the wiki-local revision text cache
1283 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1284 // The cached value should be decompressed, so handle that and return here
1285 return $cache->getWithSetCallback(
1286 $cache->makeKey( 'revisiontext', 'textid', $row->old_id
),
1287 self
::getCacheTTL( $cache ),
1288 function () use ( $url, $wiki, $flags ) {
1289 // No negative caching per Revision::loadText()
1290 $text = ExternalStore
::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1292 return self
::decompressRevisionText( $text, $flags );
1294 [ 'pcGroup' => self
::TEXT_CACHE_GROUP
, 'pcTTL' => $cache::TTL_PROC_LONG
]
1297 $text = ExternalStore
::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1301 return self
::decompressRevisionText( $text, $flags );
1305 * If $wgCompressRevisions is enabled, we will compress data.
1306 * The input string is modified in place.
1307 * Return value is the flags field: contains 'gzip' if the
1308 * data is compressed, and 'utf-8' if we're saving in UTF-8
1311 * @param mixed $text Reference to a text
1314 public static function compressRevisionText( &$text ) {
1315 global $wgCompressRevisions;
1318 # Revisions not marked this way will be converted
1319 # on load if $wgLegacyCharset is set in the future.
1322 if ( $wgCompressRevisions ) {
1323 if ( function_exists( 'gzdeflate' ) ) {
1324 $deflated = gzdeflate( $text );
1326 if ( $deflated === false ) {
1327 wfLogWarning( __METHOD__
. ': gzdeflate() failed' );
1333 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1336 return implode( ',', $flags );
1340 * Re-converts revision text according to it's flags.
1342 * @param mixed $text Reference to a text
1343 * @param array $flags Compression flags
1344 * @return string|bool Decompressed text, or false on failure
1346 public static function decompressRevisionText( $text, $flags ) {
1347 global $wgLegacyEncoding, $wgContLang;
1349 if ( $text === false ) {
1350 // Text failed to be fetched; nothing to do
1354 if ( in_array( 'gzip', $flags ) ) {
1355 # Deal with optional compression of archived pages.
1356 # This can be done periodically via maintenance/compressOld.php, and
1357 # as pages are saved if $wgCompressRevisions is set.
1358 $text = gzinflate( $text );
1360 if ( $text === false ) {
1361 wfLogWarning( __METHOD__
. ': gzinflate() failed' );
1366 if ( in_array( 'object', $flags ) ) {
1367 # Generic compressed storage
1368 $obj = unserialize( $text );
1369 if ( !is_object( $obj ) ) {
1373 $text = $obj->getText();
1376 if ( $text !== false && $wgLegacyEncoding
1377 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1379 # Old revisions kept around in a legacy encoding?
1380 # Upconvert on demand.
1381 # ("utf8" checked for compatibility with some broken
1382 # conversion scripts 2008-12-30)
1383 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1390 * Insert a new revision into the database, returning the new revision ID
1391 * number on success and dies horribly on failure.
1393 * @param IDatabase $dbw (master connection)
1394 * @throws MWException
1397 public function insertOn( $dbw ) {
1398 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1400 // We're inserting a new revision, so we have to use master anyway.
1401 // If it's a null revision, it may have references to rows that
1402 // are not in the replica yet (the text row).
1403 $this->mQueryFlags |
= self
::READ_LATEST
;
1405 // Not allowed to have rev_page equal to 0, false, etc.
1406 if ( !$this->mPage
) {
1407 $title = $this->getTitle();
1408 if ( $title instanceof Title
) {
1409 $titleText = ' for page ' . $title->getPrefixedText();
1413 throw new MWException( "Cannot insert revision$titleText: page ID must be nonzero" );
1416 $this->checkContentModel();
1418 $data = $this->mText
;
1419 $flags = self
::compressRevisionText( $data );
1421 # Write to external storage if required
1422 if ( $wgDefaultExternalStore ) {
1423 // Store and get the URL
1424 $data = ExternalStore
::insertToDefault( $data );
1426 throw new MWException( "Unable to store text to external storage" );
1431 $flags .= 'external';
1434 # Record the text (or external storage URL) to the text table
1435 if ( $this->mTextId
=== null ) {
1436 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1437 $dbw->insert( 'text',
1439 'old_id' => $old_id,
1440 'old_text' => $data,
1441 'old_flags' => $flags,
1444 $this->mTextId
= $dbw->insertId();
1447 if ( $this->mComment
=== null ) {
1448 $this->mComment
= "";
1451 # Record the edit in revisions
1452 $rev_id = $this->mId
!== null
1454 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1456 'rev_id' => $rev_id,
1457 'rev_page' => $this->mPage
,
1458 'rev_text_id' => $this->mTextId
,
1459 'rev_comment' => $this->mComment
,
1460 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1461 'rev_user' => $this->mUser
,
1462 'rev_user_text' => $this->mUserText
,
1463 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1464 'rev_deleted' => $this->mDeleted
,
1465 'rev_len' => $this->mSize
,
1466 'rev_parent_id' => $this->mParentId
=== null
1467 ?
$this->getPreviousRevisionId( $dbw )
1469 'rev_sha1' => $this->mSha1
=== null
1470 ? Revision
::base36Sha1( $this->mText
)
1474 if ( $wgContentHandlerUseDB ) {
1475 // NOTE: Store null for the default model and format, to save space.
1476 // XXX: Makes the DB sensitive to changed defaults.
1477 // Make this behavior optional? Only in miser mode?
1479 $model = $this->getContentModel();
1480 $format = $this->getContentFormat();
1482 $title = $this->getTitle();
1484 if ( $title === null ) {
1485 throw new MWException( "Insufficient information to determine the title of the "
1486 . "revision's page!" );
1489 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1490 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1492 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1493 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1496 $dbw->insert( 'revision', $row, __METHOD__
);
1498 $this->mId
= $rev_id !== null ?
$rev_id : $dbw->insertId();
1500 // Assertion to try to catch T92046
1501 if ( (int)$this->mId
=== 0 ) {
1502 throw new UnexpectedValueException(
1503 'After insert, Revision mId is ' . var_export( $this->mId
, 1 ) . ': ' .
1504 var_export( $row, 1 )
1508 // Avoid PHP 7.1 warning of passing $this by reference
1510 Hooks
::run( 'RevisionInsertComplete', [ &$revision, $data, $flags ] );
1515 protected function checkContentModel() {
1516 global $wgContentHandlerUseDB;
1518 // Note: may return null for revisions that have not yet been inserted
1519 $title = $this->getTitle();
1521 $model = $this->getContentModel();
1522 $format = $this->getContentFormat();
1523 $handler = $this->getContentHandler();
1525 if ( !$handler->isSupportedFormat( $format ) ) {
1526 $t = $title->getPrefixedDBkey();
1528 throw new MWException( "Can't use format $format with content model $model on $t" );
1531 if ( !$wgContentHandlerUseDB && $title ) {
1532 // if $wgContentHandlerUseDB is not set,
1533 // all revisions must use the default content model and format.
1535 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1536 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1537 $defaultFormat = $defaultHandler->getDefaultFormat();
1539 if ( $this->getContentModel() != $defaultModel ) {
1540 $t = $title->getPrefixedDBkey();
1542 throw new MWException( "Can't save non-default content model with "
1543 . "\$wgContentHandlerUseDB disabled: model is $model, "
1544 . "default for $t is $defaultModel" );
1547 if ( $this->getContentFormat() != $defaultFormat ) {
1548 $t = $title->getPrefixedDBkey();
1550 throw new MWException( "Can't use non-default content format with "
1551 . "\$wgContentHandlerUseDB disabled: format is $format, "
1552 . "default for $t is $defaultFormat" );
1556 $content = $this->getContent( Revision
::RAW
);
1557 $prefixedDBkey = $title->getPrefixedDBkey();
1558 $revId = $this->mId
;
1561 throw new MWException(
1562 "Content of revision $revId ($prefixedDBkey) could not be loaded for validation!"
1565 if ( !$content->isValid() ) {
1566 throw new MWException(
1567 "Content of revision $revId ($prefixedDBkey) is not valid! Content model is $model"
1573 * Get the base 36 SHA-1 value for a string of text
1574 * @param string $text
1577 public static function base36Sha1( $text ) {
1578 return Wikimedia\base_convert
( sha1( $text ), 16, 36, 31 );
1582 * Get the text cache TTL
1584 * @param WANObjectCache $cache
1587 private static function getCacheTTL( WANObjectCache
$cache ) {
1588 global $wgRevisionCacheExpiry;
1590 if ( $cache->getQoS( $cache::ATTR_EMULATION
) <= $cache::QOS_EMULATION_SQL
) {
1591 // Do not cache RDBMs blobs in...the RDBMs store
1592 $ttl = $cache::TTL_UNCACHEABLE
;
1594 $ttl = $wgRevisionCacheExpiry ?
: $cache::TTL_UNCACHEABLE
;
1601 * Lazy-load the revision's text.
1602 * Currently hardcoded to the 'text' table storage engine.
1604 * @return string|bool The revision's text, or false on failure
1606 private function loadText() {
1607 $cache = ObjectCache
::getMainWANInstance();
1609 // No negative caching; negative hits on text rows may be due to corrupted replica DBs
1610 return $cache->getWithSetCallback(
1611 $cache->makeKey( 'revisiontext', 'textid', $this->getTextId() ),
1612 self
::getCacheTTL( $cache ),
1614 return $this->fetchText();
1616 [ 'pcGroup' => self
::TEXT_CACHE_GROUP
, 'pcTTL' => $cache::TTL_PROC_LONG
]
1620 private function fetchText() {
1621 $textId = $this->getTextId();
1623 // If we kept data for lazy extraction, use it now...
1624 if ( $this->mTextRow
!== null ) {
1625 $row = $this->mTextRow
;
1626 $this->mTextRow
= null;
1631 // Callers doing updates will pass in READ_LATEST as usual. Since the text/blob tables
1632 // do not normally get rows changed around, set READ_LATEST_IMMUTABLE in those cases.
1633 $flags = $this->mQueryFlags
;
1634 $flags |
= DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
)
1635 ? self
::READ_LATEST_IMMUTABLE
1638 list( $index, $options, $fallbackIndex, $fallbackOptions ) =
1639 DBAccessObjectUtils
::getDBOptions( $flags );
1642 // Text data is immutable; check replica DBs first.
1643 $row = wfGetDB( $index )->selectRow(
1645 [ 'old_text', 'old_flags' ],
1646 [ 'old_id' => $textId ],
1652 // Fallback to DB_MASTER in some cases if the row was not found
1653 if ( !$row && $fallbackIndex !== null ) {
1654 // Use FOR UPDATE if it was used to fetch this revision. This avoids missing the row
1655 // due to REPEATABLE-READ. Also fallback to the master if READ_LATEST is provided.
1656 $row = wfGetDB( $fallbackIndex )->selectRow(
1658 [ 'old_text', 'old_flags' ],
1659 [ 'old_id' => $textId ],
1666 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1669 $text = self
::getRevisionText( $row );
1670 if ( $row && $text === false ) {
1671 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1674 return is_string( $text ) ?
$text : false;
1678 * Create a new null-revision for insertion into a page's
1679 * history. This will not re-save the text, but simply refer
1680 * to the text from the previous version.
1682 * Such revisions can for instance identify page rename
1683 * operations and other such meta-modifications.
1685 * @param IDatabase $dbw
1686 * @param int $pageId ID number of the page to read from
1687 * @param string $summary Revision's summary
1688 * @param bool $minor Whether the revision should be considered as minor
1689 * @param User|null $user User object to use or null for $wgUser
1690 * @return Revision|null Revision or null on error
1692 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1693 global $wgContentHandlerUseDB, $wgContLang;
1695 $fields = [ 'page_latest', 'page_namespace', 'page_title',
1696 'rev_text_id', 'rev_len', 'rev_sha1' ];
1698 if ( $wgContentHandlerUseDB ) {
1699 $fields[] = 'rev_content_model';
1700 $fields[] = 'rev_content_format';
1703 $current = $dbw->selectRow(
1704 [ 'page', 'revision' ],
1707 'page_id' => $pageId,
1708 'page_latest=rev_id',
1711 [ 'FOR UPDATE' ] // T51581
1720 // Truncate for whole multibyte characters
1721 $summary = $wgContLang->truncate( $summary, 255 );
1725 'user_text' => $user->getName(),
1726 'user' => $user->getId(),
1727 'comment' => $summary,
1728 'minor_edit' => $minor,
1729 'text_id' => $current->rev_text_id
,
1730 'parent_id' => $current->page_latest
,
1731 'len' => $current->rev_len
,
1732 'sha1' => $current->rev_sha1
1735 if ( $wgContentHandlerUseDB ) {
1736 $row['content_model'] = $current->rev_content_model
;
1737 $row['content_format'] = $current->rev_content_format
;
1740 $row['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
1742 $revision = new Revision( $row );
1751 * Determine if the current user is allowed to view a particular
1752 * field of this revision, if it's marked as deleted.
1754 * @param int $field One of self::DELETED_TEXT,
1755 * self::DELETED_COMMENT,
1756 * self::DELETED_USER
1757 * @param User|null $user User object to check, or null to use $wgUser
1760 public function userCan( $field, User
$user = null ) {
1761 return self
::userCanBitfield( $this->getVisibility(), $field, $user );
1765 * Determine if the current user is allowed to view a particular
1766 * field of this revision, if it's marked as deleted. This is used
1767 * by various classes to avoid duplication.
1769 * @param int $bitfield Current field
1770 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1771 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1772 * self::DELETED_USER = File::DELETED_USER
1773 * @param User|null $user User object to check, or null to use $wgUser
1774 * @param Title|null $title A Title object to check for per-page restrictions on,
1775 * instead of just plain userrights
1778 public static function userCanBitfield( $bitfield, $field, User
$user = null,
1781 if ( $bitfield & $field ) { // aspect is deleted
1782 if ( $user === null ) {
1786 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1787 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
1788 } elseif ( $field & self
::DELETED_TEXT
) {
1789 $permissions = [ 'deletedtext' ];
1791 $permissions = [ 'deletedhistory' ];
1793 $permissionlist = implode( ', ', $permissions );
1794 if ( $title === null ) {
1795 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1796 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
1798 $text = $title->getPrefixedText();
1799 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1800 foreach ( $permissions as $perm ) {
1801 if ( $title->userCan( $perm, $user ) ) {
1813 * Get rev_timestamp from rev_id, without loading the rest of the row
1815 * @param Title $title
1818 * @return string|bool False if not found
1820 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1821 $db = ( $flags & self
::READ_LATEST
)
1822 ?
wfGetDB( DB_MASTER
)
1823 : wfGetDB( DB_REPLICA
);
1824 // Casting fix for databases that can't take '' for rev_id
1828 $conds = [ 'rev_id' => $id ];
1829 $conds['rev_page'] = $title->getArticleID();
1830 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1832 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1836 * Get count of revisions per page...not very efficient
1838 * @param IDatabase $db
1839 * @param int $id Page id
1842 static function countByPageId( $db, $id ) {
1843 $row = $db->selectRow( 'revision', [ 'revCount' => 'COUNT(*)' ],
1844 [ 'rev_page' => $id ], __METHOD__
);
1846 return $row->revCount
;
1852 * Get count of revisions per page...not very efficient
1854 * @param IDatabase $db
1855 * @param Title $title
1858 static function countByTitle( $db, $title ) {
1859 $id = $title->getArticleID();
1861 return self
::countByPageId( $db, $id );
1867 * Check if no edits were made by other users since
1868 * the time a user started editing the page. Limit to
1869 * 50 revisions for the sake of performance.
1872 * @deprecated since 1.24
1874 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1875 * Database object or a database identifier usable with wfGetDB.
1876 * @param int $pageId The ID of the page in question
1877 * @param int $userId The ID of the user in question
1878 * @param string $since Look at edits since this time
1880 * @return bool True if the given user was the only one to edit since the given timestamp
1882 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1887 if ( is_int( $db ) ) {
1888 $db = wfGetDB( $db );
1891 $res = $db->select( 'revision',
1894 'rev_page' => $pageId,
1895 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1898 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ] );
1899 foreach ( $res as $row ) {
1900 if ( $row->rev_user
!= $userId ) {
1908 * Load a revision based on a known page ID and current revision ID from the DB
1910 * This method allows for the use of caching, though accessing anything that normally
1911 * requires permission checks (aside from the text) will trigger a small DB lookup.
1912 * The title will also be lazy loaded, though setTitle() can be used to preload it.
1914 * @param IDatabase $db
1915 * @param int $pageId Page ID
1916 * @param int $revId Known current revision of this page
1917 * @return Revision|bool Returns false if missing
1920 public static function newKnownCurrent( IDatabase
$db, $pageId, $revId ) {
1921 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1922 return $cache->getWithSetCallback(
1923 // Page/rev IDs passed in from DB to reflect history merges
1924 $cache->makeGlobalKey( 'revision', $db->getWikiID(), $pageId, $revId ),
1926 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1927 $setOpts +
= Database
::getCacheSetOptions( $db );
1929 $rev = Revision
::loadFromPageId( $db, $pageId, $revId );
1930 // Reflect revision deletion and user renames
1932 $rev->mTitle
= null; // mutable; lazy-load
1933 $rev->mRefreshMutableFields
= true;
1936 return $rev ?
: false; // don't cache negatives
1942 * For cached revisions, make sure the user name and rev_deleted is up-to-date
1944 private function loadMutableFields() {
1945 if ( !$this->mRefreshMutableFields
) {
1946 return; // not needed
1949 $this->mRefreshMutableFields
= false;
1950 $dbr = wfGetLB( $this->mWiki
)->getConnectionRef( DB_REPLICA
, [], $this->mWiki
);
1951 $row = $dbr->selectRow(
1952 [ 'revision', 'user' ],
1953 [ 'rev_deleted', 'user_name' ],
1954 [ 'rev_id' => $this->mId
, 'user_id = rev_user' ],
1957 if ( $row ) { // update values
1958 $this->mDeleted
= (int)$row->rev_deleted
;
1959 $this->mUserText
= $row->user_name
;