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
22 use MediaWiki\Linker\LinkTarget
;
23 use MediaWiki\MediaWikiServices
;
28 class Revision
implements IDBAccessObject
{
36 protected $mOrigUserText;
40 protected $mMinorEdit;
42 protected $mTimestamp;
58 protected $mUnpatrolled;
60 /** @var stdClass|null */
63 /** @var null|Title */
68 protected $mContentModel;
70 protected $mContentFormat;
72 /** @var Content|null|bool */
74 /** @var null|ContentHandler */
75 protected $mContentHandler;
78 protected $mQueryFlags = 0;
79 /** @var bool Used for cached values to reload user text and rev_deleted */
80 protected $mRefreshMutableFields = false;
81 /** @var string Wiki ID; false means the current wiki */
82 protected $mWiki = false;
84 // Revision deletion constants
85 const DELETED_TEXT
= 1;
86 const DELETED_COMMENT
= 2;
87 const DELETED_USER
= 4;
88 const DELETED_RESTRICTED
= 8;
89 const SUPPRESSED_USER
= 12; // convenience
91 // Audience options for accessors
93 const FOR_THIS_USER
= 2;
96 const TEXT_CACHE_GROUP
= 'revisiontext:10'; // process cache name and max key count
99 * Load a page revision from a given revision ID number.
100 * Returns null if no such revision can be found.
103 * Revision::READ_LATEST : Select the data from the master
104 * Revision::READ_LOCKING : Select & lock the data from the master
107 * @param int $flags (optional)
108 * @return Revision|null
110 public static function newFromId( $id, $flags = 0 ) {
111 return self
::newFromConds( [ 'rev_id' => intval( $id ) ], $flags );
115 * Load either the current, or a specified, revision
116 * that's attached to a given link target. If not attached
117 * to that link target, will return null.
120 * Revision::READ_LATEST : Select the data from the master
121 * Revision::READ_LOCKING : Select & lock the data from the master
123 * @param LinkTarget $linkTarget
124 * @param int $id (optional)
125 * @param int $flags Bitfield (optional)
126 * @return Revision|null
128 public static function newFromTitle( LinkTarget
$linkTarget, $id = 0, $flags = 0 ) {
130 'page_namespace' => $linkTarget->getNamespace(),
131 'page_title' => $linkTarget->getDBkey()
134 // Use the specified ID
135 $conds['rev_id'] = $id;
136 return self
::newFromConds( $conds, $flags );
138 // Use a join to get the latest revision
139 $conds[] = 'rev_id=page_latest';
140 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
141 return self
::loadFromConds( $db, $conds, $flags );
146 * Load either the current, or a specified, revision
147 * that's attached to a given page ID.
148 * Returns null if no such revision can be found.
151 * Revision::READ_LATEST : Select the data from the master (since 1.20)
152 * Revision::READ_LOCKING : Select & lock the data from the master
155 * @param int $revId (optional)
156 * @param int $flags Bitfield (optional)
157 * @return Revision|null
159 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
160 $conds = [ 'page_id' => $pageId ];
162 $conds['rev_id'] = $revId;
163 return self
::newFromConds( $conds, $flags );
165 // Use a join to get the latest revision
166 $conds[] = 'rev_id = page_latest';
167 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
168 return self
::loadFromConds( $db, $conds, $flags );
173 * Make a fake revision object from an archive table row. This is queried
174 * for permissions or even inserted (as in Special:Undelete)
175 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
178 * @param array $overrides
180 * @throws MWException
183 public static function newFromArchiveRow( $row, $overrides = [] ) {
184 global $wgContentHandlerUseDB;
186 $attribs = $overrides +
[
187 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
188 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
189 'comment' => $row->ar_comment
,
190 'user' => $row->ar_user
,
191 'user_text' => $row->ar_user_text
,
192 'timestamp' => $row->ar_timestamp
,
193 'minor_edit' => $row->ar_minor_edit
,
194 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
195 'deleted' => $row->ar_deleted
,
196 'len' => $row->ar_len
,
197 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
198 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
199 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
202 if ( !$wgContentHandlerUseDB ) {
203 unset( $attribs['content_model'] );
204 unset( $attribs['content_format'] );
207 if ( !isset( $attribs['title'] )
208 && isset( $row->ar_namespace
)
209 && isset( $row->ar_title
)
211 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
214 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
215 // Pre-1.5 ar_text row
216 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
217 if ( $attribs['text'] === false ) {
218 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
221 return new self( $attribs );
230 public static function newFromRow( $row ) {
231 return new self( $row );
235 * Load a page revision from a given revision ID number.
236 * Returns null if no such revision can be found.
238 * @param IDatabase $db
240 * @return Revision|null
242 public static function loadFromId( $db, $id ) {
243 return self
::loadFromConds( $db, [ 'rev_id' => intval( $id ) ] );
247 * Load either the current, or a specified, revision
248 * that's attached to a given page. If not attached
249 * to that page, will return null.
251 * @param IDatabase $db
254 * @return Revision|null
256 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
257 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
259 $conds['rev_id'] = intval( $id );
261 $conds[] = 'rev_id=page_latest';
263 return self
::loadFromConds( $db, $conds );
267 * Load either the current, or a specified, revision
268 * that's attached to a given page. If not attached
269 * to that page, will return null.
271 * @param IDatabase $db
272 * @param Title $title
274 * @return Revision|null
276 public static function loadFromTitle( $db, $title, $id = 0 ) {
278 $matchId = intval( $id );
280 $matchId = 'page_latest';
282 return self
::loadFromConds( $db,
285 'page_namespace' => $title->getNamespace(),
286 'page_title' => $title->getDBkey()
292 * Load the revision for the given title with the given timestamp.
293 * WARNING: Timestamps may in some circumstances not be unique,
294 * so this isn't the best key to use.
296 * @param IDatabase $db
297 * @param Title $title
298 * @param string $timestamp
299 * @return Revision|null
301 public static function loadFromTimestamp( $db, $title, $timestamp ) {
302 return self
::loadFromConds( $db,
304 'rev_timestamp' => $db->timestamp( $timestamp ),
305 'page_namespace' => $title->getNamespace(),
306 'page_title' => $title->getDBkey()
312 * Given a set of conditions, fetch a revision
314 * This method is used then a revision ID is qualified and
315 * will incorporate some basic replica DB/master fallback logic
317 * @param array $conditions
318 * @param int $flags (optional)
319 * @return Revision|null
321 private static function newFromConds( $conditions, $flags = 0 ) {
322 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
324 $rev = self
::loadFromConds( $db, $conditions, $flags );
325 // Make sure new pending/committed revision are visibile later on
326 // within web requests to certain avoid bugs like T93866 and T94407.
328 && !( $flags & self
::READ_LATEST
)
329 && wfGetLB()->getServerCount() > 1
330 && wfGetLB()->hasOrMadeRecentMasterChanges()
332 $flags = self
::READ_LATEST
;
333 $db = wfGetDB( DB_MASTER
);
334 $rev = self
::loadFromConds( $db, $conditions, $flags );
338 $rev->mQueryFlags
= $flags;
345 * Given a set of conditions, fetch a revision from
346 * the given database connection.
348 * @param IDatabase $db
349 * @param array $conditions
350 * @param int $flags (optional)
351 * @return Revision|null
353 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
354 $row = self
::fetchFromConds( $db, $conditions, $flags );
356 $rev = new Revision( $row );
357 $rev->mWiki
= $db->getWikiID();
366 * Return a wrapper for a series of database rows to
367 * fetch all of a given page's revisions in turn.
368 * Each row can be fed to the constructor to get objects.
370 * @param LinkTarget $title
371 * @return ResultWrapper
372 * @deprecated Since 1.28
374 public static function fetchRevision( LinkTarget
$title ) {
375 $row = self
::fetchFromConds(
376 wfGetDB( DB_REPLICA
),
378 'rev_id=page_latest',
379 'page_namespace' => $title->getNamespace(),
380 'page_title' => $title->getDBkey()
384 return new FakeResultWrapper( $row ?
[ $row ] : [] );
388 * Given a set of conditions, return a ResultWrapper
389 * which will return matching database rows with the
390 * fields necessary to build Revision objects.
392 * @param IDatabase $db
393 * @param array $conditions
394 * @param int $flags (optional)
397 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
398 $fields = array_merge(
399 self
::selectFields(),
400 self
::selectPageFields(),
401 self
::selectUserFields()
404 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
405 $options[] = 'FOR UPDATE';
407 return $db->selectRow(
408 [ 'revision', 'page', 'user' ],
413 [ 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() ]
418 * Return the value of a select() JOIN conds array for the user table.
419 * This will get user table rows for logged-in users.
423 public static function userJoinCond() {
424 return [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
428 * Return the value of a select() page conds array for the page table.
429 * This will assure that the revision(s) are not orphaned from live pages.
433 public static function pageJoinCond() {
434 return [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
438 * Return the list of revision fields that should be selected to create
442 public static function selectFields() {
443 global $wgContentHandlerUseDB;
460 if ( $wgContentHandlerUseDB ) {
461 $fields[] = 'rev_content_format';
462 $fields[] = 'rev_content_model';
469 * Return the list of revision fields that should be selected to create
470 * a new revision from an archive row.
473 public static function selectArchiveFields() {
474 global $wgContentHandlerUseDB;
492 if ( $wgContentHandlerUseDB ) {
493 $fields[] = 'ar_content_format';
494 $fields[] = 'ar_content_model';
500 * Return the list of text fields that should be selected to read the
504 public static function selectTextFields() {
512 * Return the list of page fields that should be selected from page table
515 public static function selectPageFields() {
527 * Return the list of user fields that should be selected from user table
530 public static function selectUserFields() {
531 return [ 'user_name' ];
535 * Do a batched query to get the parent revision lengths
536 * @param IDatabase $db
537 * @param array $revIds
540 public static function getParentLengths( $db, array $revIds ) {
543 return $revLens; // empty
545 $res = $db->select( 'revision',
546 [ 'rev_id', 'rev_len' ],
547 [ 'rev_id' => $revIds ],
549 foreach ( $res as $row ) {
550 $revLens[$row->rev_id
] = $row->rev_len
;
558 * @param object|array $row Either a database row or an array
559 * @throws MWException
562 function __construct( $row ) {
563 if ( is_object( $row ) ) {
564 $this->mId
= intval( $row->rev_id
);
565 $this->mPage
= intval( $row->rev_page
);
566 $this->mTextId
= intval( $row->rev_text_id
);
567 $this->mComment
= $row->rev_comment
;
568 $this->mUser
= intval( $row->rev_user
);
569 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
570 $this->mTimestamp
= $row->rev_timestamp
;
571 $this->mDeleted
= intval( $row->rev_deleted
);
573 if ( !isset( $row->rev_parent_id
) ) {
574 $this->mParentId
= null;
576 $this->mParentId
= intval( $row->rev_parent_id
);
579 if ( !isset( $row->rev_len
) ) {
582 $this->mSize
= intval( $row->rev_len
);
585 if ( !isset( $row->rev_sha1
) ) {
588 $this->mSha1
= $row->rev_sha1
;
591 if ( isset( $row->page_latest
) ) {
592 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
593 $this->mTitle
= Title
::newFromRow( $row );
595 $this->mCurrent
= false;
596 $this->mTitle
= null;
599 if ( !isset( $row->rev_content_model
) ) {
600 $this->mContentModel
= null; # determine on demand if needed
602 $this->mContentModel
= strval( $row->rev_content_model
);
605 if ( !isset( $row->rev_content_format
) ) {
606 $this->mContentFormat
= null; # determine on demand if needed
608 $this->mContentFormat
= strval( $row->rev_content_format
);
611 // Lazy extraction...
613 if ( isset( $row->old_text
) ) {
614 $this->mTextRow
= $row;
616 // 'text' table row entry will be lazy-loaded
617 $this->mTextRow
= null;
620 // Use user_name for users and rev_user_text for IPs...
621 $this->mUserText
= null; // lazy load if left null
622 if ( $this->mUser
== 0 ) {
623 $this->mUserText
= $row->rev_user_text
; // IP user
624 } elseif ( isset( $row->user_name
) ) {
625 $this->mUserText
= $row->user_name
; // logged-in user
627 $this->mOrigUserText
= $row->rev_user_text
;
628 } elseif ( is_array( $row ) ) {
629 // Build a new revision to be saved...
630 global $wgUser; // ugh
632 # if we have a content object, use it to set the model and type
633 if ( !empty( $row['content'] ) ) {
634 // @todo when is that set? test with external store setup! check out insertOn() [dk]
635 if ( !empty( $row['text_id'] ) ) {
636 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
637 "can't serialize content object" );
640 $row['content_model'] = $row['content']->getModel();
641 # note: mContentFormat is initializes later accordingly
642 # note: content is serialized later in this method!
643 # also set text to null?
646 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
647 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
648 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
649 $this->mUserText
= isset( $row['user_text'] )
650 ?
strval( $row['user_text'] ) : $wgUser->getName();
651 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
652 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
653 $this->mTimestamp
= isset( $row['timestamp'] )
654 ?
strval( $row['timestamp'] ) : wfTimestampNow();
655 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
656 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
657 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
658 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
660 $this->mContentModel
= isset( $row['content_model'] )
661 ?
strval( $row['content_model'] ) : null;
662 $this->mContentFormat
= isset( $row['content_format'] )
663 ?
strval( $row['content_format'] ) : null;
665 // Enforce spacing trimming on supplied text
666 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
667 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
668 $this->mTextRow
= null;
670 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
672 // if we have a Content object, override mText and mContentModel
673 if ( !empty( $row['content'] ) ) {
674 if ( !( $row['content'] instanceof Content
) ) {
675 throw new MWException( '`content` field must contain a Content object.' );
678 $handler = $this->getContentHandler();
679 $this->mContent
= $row['content'];
681 $this->mContentModel
= $this->mContent
->getModel();
682 $this->mContentHandler
= null;
684 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
685 } elseif ( $this->mText
!== null ) {
686 $handler = $this->getContentHandler();
687 $this->mContent
= $handler->unserializeContent( $this->mText
);
690 // If we have a Title object, make sure it is consistent with mPage.
691 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
692 if ( $this->mPage
=== null ) {
693 // if the page ID wasn't known, set it now
694 $this->mPage
= $this->mTitle
->getArticleID();
695 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
696 // Got different page IDs. This may be legit (e.g. during undeletion),
697 // but it seems worth mentioning it in the log.
698 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
699 $this->mTitle
->getArticleID() . " provided by the Title object." );
703 $this->mCurrent
= false;
705 // If we still have no length, see it we have the text to figure it out
706 if ( !$this->mSize
&& $this->mContent
!== null ) {
707 $this->mSize
= $this->mContent
->getSize();
711 if ( $this->mSha1
=== null ) {
712 $this->mSha1
= $this->mText
=== null ?
null : self
::base36Sha1( $this->mText
);
716 $this->getContentModel();
717 $this->getContentFormat();
719 throw new MWException( 'Revision constructor passed invalid row format.' );
721 $this->mUnpatrolled
= null;
729 public function getId() {
734 * Set the revision ID
736 * This should only be used for proposed revisions that turn out to be null edits
741 public function setId( $id ) {
742 $this->mId
= (int)$id;
746 * Set the user ID/name
748 * This should only be used for proposed revisions that turn out to be null edits
751 * @param integer $id User ID
752 * @param string $name User name
754 public function setUserIdAndName( $id, $name ) {
755 $this->mUser
= (int)$id;
756 $this->mUserText
= $name;
757 $this->mOrigUserText
= $name;
765 public function getTextId() {
766 return $this->mTextId
;
770 * Get parent revision ID (the original previous page revision)
774 public function getParentId() {
775 return $this->mParentId
;
779 * Returns the length of the text in this revision, or null if unknown.
783 public function getSize() {
788 * Returns the base36 sha1 of the text in this revision, or null if unknown.
790 * @return string|null
792 public function getSha1() {
797 * Returns the title of the page associated with this entry or null.
799 * Will do a query, when title is not set and id is given.
803 public function getTitle() {
804 if ( $this->mTitle
!== null ) {
805 return $this->mTitle
;
807 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
808 if ( $this->mId
!== null ) {
809 $dbr = wfGetLB( $this->mWiki
)->getConnectionRef( DB_REPLICA
, [], $this->mWiki
);
810 $row = $dbr->selectRow(
811 [ 'page', 'revision' ],
812 self
::selectPageFields(),
813 [ 'page_id=rev_page', 'rev_id' => $this->mId
],
817 // @TODO: better foreign title handling
818 $this->mTitle
= Title
::newFromRow( $row );
822 if ( $this->mWiki
=== false ||
$this->mWiki
=== wfWikiID() ) {
823 // Loading by ID is best, though not possible for foreign titles
824 if ( !$this->mTitle
&& $this->mPage
!== null && $this->mPage
> 0 ) {
825 $this->mTitle
= Title
::newFromID( $this->mPage
);
829 return $this->mTitle
;
833 * Set the title of the revision
835 * @param Title $title
837 public function setTitle( $title ) {
838 $this->mTitle
= $title;
846 public function getPage() {
851 * Fetch revision's user id if it's available to the specified audience.
852 * If the specified audience does not have access to it, zero will be
855 * @param int $audience One of:
856 * Revision::FOR_PUBLIC to be displayed to all users
857 * Revision::FOR_THIS_USER to be displayed to the given user
858 * Revision::RAW get the ID regardless of permissions
859 * @param User $user User object to check for, only if FOR_THIS_USER is passed
860 * to the $audience parameter
863 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
864 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
866 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
874 * Fetch revision's user id without regard for the current user's permissions
877 * @deprecated since 1.25, use getUser( Revision::RAW )
879 public function getRawUser() {
880 wfDeprecated( __METHOD__
, '1.25' );
881 return $this->getUser( self
::RAW
);
885 * Fetch revision's username if it's available to the specified audience.
886 * If the specified audience does not have access to the username, an
887 * empty string will be returned.
889 * @param int $audience One of:
890 * Revision::FOR_PUBLIC to be displayed to all users
891 * Revision::FOR_THIS_USER to be displayed to the given user
892 * Revision::RAW get the text regardless of permissions
893 * @param User $user User object to check for, only if FOR_THIS_USER is passed
894 * to the $audience parameter
897 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
898 $this->loadMutableFields();
900 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
902 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
905 if ( $this->mUserText
=== null ) {
906 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
907 if ( $this->mUserText
=== false ) {
908 # This shouldn't happen, but it can if the wiki was recovered
909 # via importing revs and there is no user table entry yet.
910 $this->mUserText
= $this->mOrigUserText
;
913 return $this->mUserText
;
918 * Fetch revision's username without regard for view restrictions
921 * @deprecated since 1.25, use getUserText( Revision::RAW )
923 public function getRawUserText() {
924 wfDeprecated( __METHOD__
, '1.25' );
925 return $this->getUserText( self
::RAW
);
929 * Fetch revision comment if it's available to the specified audience.
930 * If the specified audience does not have access to the comment, an
931 * empty string will be returned.
933 * @param int $audience One of:
934 * Revision::FOR_PUBLIC to be displayed to all users
935 * Revision::FOR_THIS_USER to be displayed to the given user
936 * Revision::RAW get the text regardless of permissions
937 * @param User $user User object to check for, only if FOR_THIS_USER is passed
938 * to the $audience parameter
941 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
942 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
944 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
947 return $this->mComment
;
952 * Fetch revision comment without regard for the current user's permissions
955 * @deprecated since 1.25, use getComment( Revision::RAW )
957 public function getRawComment() {
958 wfDeprecated( __METHOD__
, '1.25' );
959 return $this->getComment( self
::RAW
);
965 public function isMinor() {
966 return (bool)$this->mMinorEdit
;
970 * @return int Rcid of the unpatrolled row, zero if there isn't one
972 public function isUnpatrolled() {
973 if ( $this->mUnpatrolled
!== null ) {
974 return $this->mUnpatrolled
;
976 $rc = $this->getRecentChange();
977 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
978 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
980 $this->mUnpatrolled
= 0;
982 return $this->mUnpatrolled
;
986 * Get the RC object belonging to the current revision, if there's one
988 * @param int $flags (optional) $flags include:
989 * Revision::READ_LATEST : Select the data from the master
992 * @return RecentChange|null
994 public function getRecentChange( $flags = 0 ) {
995 $dbr = wfGetDB( DB_REPLICA
);
997 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
999 return RecentChange
::newFromConds(
1001 'rc_user_text' => $this->getUserText( Revision
::RAW
),
1002 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
1003 'rc_this_oldid' => $this->getId()
1011 * @param int $field One of DELETED_* bitfield constants
1015 public function isDeleted( $field ) {
1016 if ( $this->isCurrent() && $field === self
::DELETED_TEXT
) {
1017 // Current revisions of pages cannot have the content hidden. Skipping this
1018 // check is very useful for Parser as it fetches templates using newKnownCurrent().
1019 // Calling getVisibility() in that case triggers a verification database query.
1020 return false; // no need to check
1023 return ( $this->getVisibility() & $field ) == $field;
1027 * Get the deletion bitfield of the revision
1031 public function getVisibility() {
1032 $this->loadMutableFields();
1034 return (int)$this->mDeleted
;
1038 * Fetch revision text if it's available to the specified audience.
1039 * If the specified audience does not have the ability to view this
1040 * revision, an empty string will be returned.
1042 * @param int $audience One of:
1043 * Revision::FOR_PUBLIC to be displayed to all users
1044 * Revision::FOR_THIS_USER to be displayed to the given user
1045 * Revision::RAW get the text regardless of permissions
1046 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1047 * to the $audience parameter
1049 * @deprecated since 1.21, use getContent() instead
1052 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1053 wfDeprecated( __METHOD__
, '1.21' );
1055 $content = $this->getContent( $audience, $user );
1056 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
1060 * Fetch revision content if it's available to the specified audience.
1061 * If the specified audience does not have the ability to view this
1062 * revision, null will be returned.
1064 * @param int $audience One of:
1065 * Revision::FOR_PUBLIC to be displayed to all users
1066 * Revision::FOR_THIS_USER to be displayed to $wgUser
1067 * Revision::RAW get the text regardless of permissions
1068 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1069 * to the $audience parameter
1071 * @return Content|null
1073 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1074 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1076 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1079 return $this->getContentInternal();
1084 * Get original serialized data (without checking view restrictions)
1089 public function getSerializedData() {
1090 if ( $this->mText
=== null ) {
1091 // Revision is immutable. Load on demand.
1092 $this->mText
= $this->loadText();
1095 return $this->mText
;
1099 * Gets the content object for the revision (or null on failure).
1101 * Note that for mutable Content objects, each call to this method will return a
1105 * @return Content|null The Revision's content, or null on failure.
1107 protected function getContentInternal() {
1108 if ( $this->mContent
=== null ) {
1109 $text = $this->getSerializedData();
1111 if ( $text !== null && $text !== false ) {
1112 // Unserialize content
1113 $handler = $this->getContentHandler();
1114 $format = $this->getContentFormat();
1116 $this->mContent
= $handler->unserializeContent( $text, $format );
1120 // NOTE: copy() will return $this for immutable content objects
1121 return $this->mContent ?
$this->mContent
->copy() : null;
1125 * Returns the content model for this revision.
1127 * If no content model was stored in the database, the default content model for the title is
1128 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1129 * is used as a last resort.
1131 * @return string The content model id associated with this revision,
1132 * see the CONTENT_MODEL_XXX constants.
1134 public function getContentModel() {
1135 if ( !$this->mContentModel
) {
1136 $title = $this->getTitle();
1138 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $title );
1140 $this->mContentModel
= CONTENT_MODEL_WIKITEXT
;
1143 assert( !empty( $this->mContentModel
) );
1146 return $this->mContentModel
;
1150 * Returns the content format for this revision.
1152 * If no content format was stored in the database, the default format for this
1153 * revision's content model is returned.
1155 * @return string The content format id associated with this revision,
1156 * see the CONTENT_FORMAT_XXX constants.
1158 public function getContentFormat() {
1159 if ( !$this->mContentFormat
) {
1160 $handler = $this->getContentHandler();
1161 $this->mContentFormat
= $handler->getDefaultFormat();
1163 assert( !empty( $this->mContentFormat
) );
1166 return $this->mContentFormat
;
1170 * Returns the content handler appropriate for this revision's content model.
1172 * @throws MWException
1173 * @return ContentHandler
1175 public function getContentHandler() {
1176 if ( !$this->mContentHandler
) {
1177 $model = $this->getContentModel();
1178 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1180 $format = $this->getContentFormat();
1182 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1183 throw new MWException( "Oops, the content format $format is not supported for "
1184 . "this content model, $model" );
1188 return $this->mContentHandler
;
1194 public function getTimestamp() {
1195 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1201 public function isCurrent() {
1202 return $this->mCurrent
;
1206 * Get previous revision for this title
1208 * @return Revision|null
1210 public function getPrevious() {
1211 if ( $this->getTitle() ) {
1212 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1214 return self
::newFromTitle( $this->getTitle(), $prev );
1221 * Get next revision for this title
1223 * @return Revision|null
1225 public function getNext() {
1226 if ( $this->getTitle() ) {
1227 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1229 return self
::newFromTitle( $this->getTitle(), $next );
1236 * Get previous revision Id for this page_id
1237 * This is used to populate rev_parent_id on save
1239 * @param IDatabase $db
1242 private function getPreviousRevisionId( $db ) {
1243 if ( $this->mPage
=== null ) {
1246 # Use page_latest if ID is not given
1247 if ( !$this->mId
) {
1248 $prevId = $db->selectField( 'page', 'page_latest',
1249 [ 'page_id' => $this->mPage
],
1252 $prevId = $db->selectField( 'revision', 'rev_id',
1253 [ 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
],
1255 [ 'ORDER BY' => 'rev_id DESC' ] );
1257 return intval( $prevId );
1261 * Get revision text associated with an old or archive row
1262 * $row is usually an object from wfFetchRow(), both the flags and the text
1263 * field must be included.
1265 * @param stdClass $row The text data
1266 * @param string $prefix Table prefix (default 'old_')
1267 * @param string|bool $wiki The name of the wiki to load the revision text from
1268 * (same as the the wiki $row was loaded from) or false to indicate the local
1269 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1270 * identifier as understood by the LoadBalancer class.
1271 * @return string Text the text requested or false on failure
1273 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1276 $textField = $prefix . 'text';
1277 $flagsField = $prefix . 'flags';
1279 if ( isset( $row->$flagsField ) ) {
1280 $flags = explode( ',', $row->$flagsField );
1285 if ( isset( $row->$textField ) ) {
1286 $text = $row->$textField;
1291 # Use external methods for external objects, text in table is URL-only then
1292 if ( in_array( 'external', $flags ) ) {
1294 $parts = explode( '://', $url, 2 );
1295 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1298 $text = ExternalStore
::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1301 // If the text was fetched without an error, convert it
1302 if ( $text !== false ) {
1303 $text = self
::decompressRevisionText( $text, $flags );
1309 * If $wgCompressRevisions is enabled, we will compress data.
1310 * The input string is modified in place.
1311 * Return value is the flags field: contains 'gzip' if the
1312 * data is compressed, and 'utf-8' if we're saving in UTF-8
1315 * @param mixed $text Reference to a text
1318 public static function compressRevisionText( &$text ) {
1319 global $wgCompressRevisions;
1322 # Revisions not marked this way will be converted
1323 # on load if $wgLegacyCharset is set in the future.
1326 if ( $wgCompressRevisions ) {
1327 if ( function_exists( 'gzdeflate' ) ) {
1328 $deflated = gzdeflate( $text );
1330 if ( $deflated === false ) {
1331 wfLogWarning( __METHOD__
. ': gzdeflate() failed' );
1337 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1340 return implode( ',', $flags );
1344 * Re-converts revision text according to it's flags.
1346 * @param mixed $text Reference to a text
1347 * @param array $flags Compression flags
1348 * @return string|bool Decompressed text, or false on failure
1350 public static function decompressRevisionText( $text, $flags ) {
1351 if ( in_array( 'gzip', $flags ) ) {
1352 # Deal with optional compression of archived pages.
1353 # This can be done periodically via maintenance/compressOld.php, and
1354 # as pages are saved if $wgCompressRevisions is set.
1355 $text = gzinflate( $text );
1357 if ( $text === false ) {
1358 wfLogWarning( __METHOD__
. ': gzinflate() failed' );
1363 if ( in_array( 'object', $flags ) ) {
1364 # Generic compressed storage
1365 $obj = unserialize( $text );
1366 if ( !is_object( $obj ) ) {
1370 $text = $obj->getText();
1373 global $wgLegacyEncoding;
1374 if ( $text !== false && $wgLegacyEncoding
1375 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1377 # Old revisions kept around in a legacy encoding?
1378 # Upconvert on demand.
1379 # ("utf8" checked for compatibility with some broken
1380 # conversion scripts 2008-12-30)
1382 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1389 * Insert a new revision into the database, returning the new revision ID
1390 * number on success and dies horribly on failure.
1392 * @param IDatabase $dbw (master connection)
1393 * @throws MWException
1396 public function insertOn( $dbw ) {
1397 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1399 // We're inserting a new revision, so we have to use master anyway.
1400 // If it's a null revision, it may have references to rows that
1401 // are not in the replica yet (the text row).
1402 $this->mQueryFlags |
= self
::READ_LATEST
;
1404 // Not allowed to have rev_page equal to 0, false, etc.
1405 if ( !$this->mPage
) {
1406 $title = $this->getTitle();
1407 if ( $title instanceof Title
) {
1408 $titleText = ' for page ' . $title->getPrefixedText();
1412 throw new MWException( "Cannot insert revision$titleText: page ID must be nonzero" );
1415 $this->checkContentModel();
1417 $data = $this->mText
;
1418 $flags = self
::compressRevisionText( $data );
1420 # Write to external storage if required
1421 if ( $wgDefaultExternalStore ) {
1422 // Store and get the URL
1423 $data = ExternalStore
::insertToDefault( $data );
1425 throw new MWException( "Unable to store text to external storage" );
1430 $flags .= 'external';
1433 # Record the text (or external storage URL) to the text table
1434 if ( $this->mTextId
=== null ) {
1435 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1436 $dbw->insert( 'text',
1438 'old_id' => $old_id,
1439 'old_text' => $data,
1440 'old_flags' => $flags,
1443 $this->mTextId
= $dbw->insertId();
1446 if ( $this->mComment
=== null ) {
1447 $this->mComment
= "";
1450 # Record the edit in revisions
1451 $rev_id = $this->mId
!== null
1453 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1455 'rev_id' => $rev_id,
1456 'rev_page' => $this->mPage
,
1457 'rev_text_id' => $this->mTextId
,
1458 'rev_comment' => $this->mComment
,
1459 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1460 'rev_user' => $this->mUser
,
1461 'rev_user_text' => $this->mUserText
,
1462 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1463 'rev_deleted' => $this->mDeleted
,
1464 'rev_len' => $this->mSize
,
1465 'rev_parent_id' => $this->mParentId
=== null
1466 ?
$this->getPreviousRevisionId( $dbw )
1468 'rev_sha1' => $this->mSha1
=== null
1469 ? Revision
::base36Sha1( $this->mText
)
1473 if ( $wgContentHandlerUseDB ) {
1474 // NOTE: Store null for the default model and format, to save space.
1475 // XXX: Makes the DB sensitive to changed defaults.
1476 // Make this behavior optional? Only in miser mode?
1478 $model = $this->getContentModel();
1479 $format = $this->getContentFormat();
1481 $title = $this->getTitle();
1483 if ( $title === null ) {
1484 throw new MWException( "Insufficient information to determine the title of the "
1485 . "revision's page!" );
1488 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1489 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1491 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1492 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1495 $dbw->insert( 'revision', $row, __METHOD__
);
1497 $this->mId
= $rev_id !== null ?
$rev_id : $dbw->insertId();
1499 // Assertion to try to catch T92046
1500 if ( (int)$this->mId
=== 0 ) {
1501 throw new UnexpectedValueException(
1502 'After insert, Revision mId is ' . var_export( $this->mId
, 1 ) . ': ' .
1503 var_export( $row, 1 )
1507 Hooks
::run( 'RevisionInsertComplete', [ &$this, $data, $flags ] );
1512 protected function checkContentModel() {
1513 global $wgContentHandlerUseDB;
1515 // Note: may return null for revisions that have not yet been inserted
1516 $title = $this->getTitle();
1518 $model = $this->getContentModel();
1519 $format = $this->getContentFormat();
1520 $handler = $this->getContentHandler();
1522 if ( !$handler->isSupportedFormat( $format ) ) {
1523 $t = $title->getPrefixedDBkey();
1525 throw new MWException( "Can't use format $format with content model $model on $t" );
1528 if ( !$wgContentHandlerUseDB && $title ) {
1529 // if $wgContentHandlerUseDB is not set,
1530 // all revisions must use the default content model and format.
1532 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1533 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1534 $defaultFormat = $defaultHandler->getDefaultFormat();
1536 if ( $this->getContentModel() != $defaultModel ) {
1537 $t = $title->getPrefixedDBkey();
1539 throw new MWException( "Can't save non-default content model with "
1540 . "\$wgContentHandlerUseDB disabled: model is $model, "
1541 . "default for $t is $defaultModel" );
1544 if ( $this->getContentFormat() != $defaultFormat ) {
1545 $t = $title->getPrefixedDBkey();
1547 throw new MWException( "Can't use non-default content format with "
1548 . "\$wgContentHandlerUseDB disabled: format is $format, "
1549 . "default for $t is $defaultFormat" );
1553 $content = $this->getContent( Revision
::RAW
);
1554 $prefixedDBkey = $title->getPrefixedDBkey();
1555 $revId = $this->mId
;
1558 throw new MWException(
1559 "Content of revision $revId ($prefixedDBkey) could not be loaded for validation!"
1562 if ( !$content->isValid() ) {
1563 throw new MWException(
1564 "Content of revision $revId ($prefixedDBkey) is not valid! Content model is $model"
1570 * Get the base 36 SHA-1 value for a string of text
1571 * @param string $text
1574 public static function base36Sha1( $text ) {
1575 return Wikimedia\base_convert
( sha1( $text ), 16, 36, 31 );
1579 * Lazy-load the revision's text.
1580 * Currently hardcoded to the 'text' table storage engine.
1582 * @return string|bool The revision's text, or false on failure
1584 private function loadText() {
1585 global $wgRevisionCacheExpiry;
1587 $cache = ObjectCache
::getMainWANInstance();
1588 if ( $cache->getQoS( $cache::ATTR_EMULATION
) <= $cache::QOS_EMULATION_SQL
) {
1589 // Do not cache RDBMs blobs in...the RDBMs store
1590 $ttl = $cache::TTL_UNCACHEABLE
;
1592 $ttl = $wgRevisionCacheExpiry ?
: $cache::TTL_UNCACHEABLE
;
1595 // No negative caching; negative hits on text rows may be due to corrupted replica DBs
1596 return $cache->getWithSetCallback(
1597 $cache->makeKey( 'revisiontext', 'textid', $this->getTextId() ),
1600 return $this->fetchText();
1602 [ 'pcGroup' => self
::TEXT_CACHE_GROUP
, 'pcTTL' => $cache::TTL_PROC_LONG
]
1606 private function fetchText() {
1607 $textId = $this->getTextId();
1609 // If we kept data for lazy extraction, use it now...
1610 if ( $this->mTextRow
!== null ) {
1611 $row = $this->mTextRow
;
1612 $this->mTextRow
= null;
1617 // Callers doing updates will pass in READ_LATEST as usual. Since the text/blob tables
1618 // do not normally get rows changed around, set READ_LATEST_IMMUTABLE in those cases.
1619 $flags = $this->mQueryFlags
;
1620 $flags |
= DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
)
1621 ? self
::READ_LATEST_IMMUTABLE
1624 list( $index, $options, $fallbackIndex, $fallbackOptions ) =
1625 DBAccessObjectUtils
::getDBOptions( $flags );
1628 // Text data is immutable; check replica DBs first.
1629 $row = wfGetDB( $index )->selectRow(
1631 [ 'old_text', 'old_flags' ],
1632 [ 'old_id' => $textId ],
1638 // Fallback to DB_MASTER in some cases if the row was not found
1639 if ( !$row && $fallbackIndex !== null ) {
1640 // Use FOR UPDATE if it was used to fetch this revision. This avoids missing the row
1641 // due to REPEATABLE-READ. Also fallback to the master if READ_LATEST is provided.
1642 $row = wfGetDB( $fallbackIndex )->selectRow(
1644 [ 'old_text', 'old_flags' ],
1645 [ 'old_id' => $textId ],
1652 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1655 $text = self
::getRevisionText( $row );
1656 if ( $row && $text === false ) {
1657 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1660 return is_string( $text ) ?
$text : false;
1664 * Create a new null-revision for insertion into a page's
1665 * history. This will not re-save the text, but simply refer
1666 * to the text from the previous version.
1668 * Such revisions can for instance identify page rename
1669 * operations and other such meta-modifications.
1671 * @param IDatabase $dbw
1672 * @param int $pageId ID number of the page to read from
1673 * @param string $summary Revision's summary
1674 * @param bool $minor Whether the revision should be considered as minor
1675 * @param User|null $user User object to use or null for $wgUser
1676 * @return Revision|null Revision or null on error
1678 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1679 global $wgContentHandlerUseDB, $wgContLang;
1681 $fields = [ 'page_latest', 'page_namespace', 'page_title',
1682 'rev_text_id', 'rev_len', 'rev_sha1' ];
1684 if ( $wgContentHandlerUseDB ) {
1685 $fields[] = 'rev_content_model';
1686 $fields[] = 'rev_content_format';
1689 $current = $dbw->selectRow(
1690 [ 'page', 'revision' ],
1693 'page_id' => $pageId,
1694 'page_latest=rev_id',
1697 [ 'FOR UPDATE' ] // T51581
1706 // Truncate for whole multibyte characters
1707 $summary = $wgContLang->truncate( $summary, 255 );
1711 'user_text' => $user->getName(),
1712 'user' => $user->getId(),
1713 'comment' => $summary,
1714 'minor_edit' => $minor,
1715 'text_id' => $current->rev_text_id
,
1716 'parent_id' => $current->page_latest
,
1717 'len' => $current->rev_len
,
1718 'sha1' => $current->rev_sha1
1721 if ( $wgContentHandlerUseDB ) {
1722 $row['content_model'] = $current->rev_content_model
;
1723 $row['content_format'] = $current->rev_content_format
;
1726 $row['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
1728 $revision = new Revision( $row );
1737 * Determine if the current user is allowed to view a particular
1738 * field of this revision, if it's marked as deleted.
1740 * @param int $field One of self::DELETED_TEXT,
1741 * self::DELETED_COMMENT,
1742 * self::DELETED_USER
1743 * @param User|null $user User object to check, or null to use $wgUser
1746 public function userCan( $field, User
$user = null ) {
1747 return self
::userCanBitfield( $this->getVisibility(), $field, $user );
1751 * Determine if the current user is allowed to view a particular
1752 * field of this revision, if it's marked as deleted. This is used
1753 * by various classes to avoid duplication.
1755 * @param int $bitfield Current field
1756 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1757 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1758 * self::DELETED_USER = File::DELETED_USER
1759 * @param User|null $user User object to check, or null to use $wgUser
1760 * @param Title|null $title A Title object to check for per-page restrictions on,
1761 * instead of just plain userrights
1764 public static function userCanBitfield( $bitfield, $field, User
$user = null,
1767 if ( $bitfield & $field ) { // aspect is deleted
1768 if ( $user === null ) {
1772 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1773 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
1774 } elseif ( $field & self
::DELETED_TEXT
) {
1775 $permissions = [ 'deletedtext' ];
1777 $permissions = [ 'deletedhistory' ];
1779 $permissionlist = implode( ', ', $permissions );
1780 if ( $title === null ) {
1781 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1782 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
1784 $text = $title->getPrefixedText();
1785 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1786 foreach ( $permissions as $perm ) {
1787 if ( $title->userCan( $perm, $user ) ) {
1799 * Get rev_timestamp from rev_id, without loading the rest of the row
1801 * @param Title $title
1803 * @return string|bool False if not found
1805 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1806 $db = ( $flags & self
::READ_LATEST
)
1807 ?
wfGetDB( DB_MASTER
)
1808 : wfGetDB( DB_REPLICA
);
1809 // Casting fix for databases that can't take '' for rev_id
1813 $conds = [ 'rev_id' => $id ];
1814 $conds['rev_page'] = $title->getArticleID();
1815 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1817 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1821 * Get count of revisions per page...not very efficient
1823 * @param IDatabase $db
1824 * @param int $id Page id
1827 static function countByPageId( $db, $id ) {
1828 $row = $db->selectRow( 'revision', [ 'revCount' => 'COUNT(*)' ],
1829 [ 'rev_page' => $id ], __METHOD__
);
1831 return $row->revCount
;
1837 * Get count of revisions per page...not very efficient
1839 * @param IDatabase $db
1840 * @param Title $title
1843 static function countByTitle( $db, $title ) {
1844 $id = $title->getArticleID();
1846 return self
::countByPageId( $db, $id );
1852 * Check if no edits were made by other users since
1853 * the time a user started editing the page. Limit to
1854 * 50 revisions for the sake of performance.
1857 * @deprecated since 1.24
1859 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1860 * Database object or a database identifier usable with wfGetDB.
1861 * @param int $pageId The ID of the page in question
1862 * @param int $userId The ID of the user in question
1863 * @param string $since Look at edits since this time
1865 * @return bool True if the given user was the only one to edit since the given timestamp
1867 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1872 if ( is_int( $db ) ) {
1873 $db = wfGetDB( $db );
1876 $res = $db->select( 'revision',
1879 'rev_page' => $pageId,
1880 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1883 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ] );
1884 foreach ( $res as $row ) {
1885 if ( $row->rev_user
!= $userId ) {
1893 * Load a revision based on a known page ID and current revision ID from the DB
1895 * This method allows for the use of caching, though accessing anything that normally
1896 * requires permission checks (aside from the text) will trigger a small DB lookup.
1897 * The title will also be lazy loaded, though setTitle() can be used to preload it.
1899 * @param IDatabase $db
1900 * @param int $pageId Page ID
1901 * @param int $revId Known current revision of this page
1902 * @return Revision|bool Returns false if missing
1905 public static function newKnownCurrent( IDatabase
$db, $pageId, $revId ) {
1906 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1907 return $cache->getWithSetCallback(
1908 // Page/rev IDs passed in from DB to reflect history merges
1909 $cache->makeGlobalKey( 'revision', $db->getWikiID(), $pageId, $revId ),
1911 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1912 $setOpts +
= Database
::getCacheSetOptions( $db );
1914 $rev = Revision
::loadFromPageId( $db, $pageId, $revId );
1915 // Reflect revision deletion and user renames
1917 $rev->mTitle
= null; // mutable; lazy-load
1918 $rev->mRefreshMutableFields
= true;
1921 return $rev ?
: false; // don't cache negatives
1927 * For cached revisions, make sure the user name and rev_deleted is up-to-date
1929 private function loadMutableFields() {
1930 if ( !$this->mRefreshMutableFields
) {
1931 return; // not needed
1934 $this->mRefreshMutableFields
= false;
1935 $dbr = wfGetLB( $this->mWiki
)->getConnectionRef( DB_REPLICA
, [], $this->mWiki
);
1936 $row = $dbr->selectRow(
1937 [ 'revision', 'user' ],
1938 [ 'rev_deleted', 'user_name' ],
1939 [ 'rev_id' => $this->mId
, 'user_id = rev_user' ],
1942 if ( $row ) { // update values
1943 $this->mDeleted
= (int)$row->rev_deleted
;
1944 $this->mUserText
= $row->user_name
;