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
26 class Revision
implements IDBAccessObject
{
34 protected $mOrigUserText;
36 protected $mMinorEdit;
37 protected $mTimestamp;
56 protected $mContentModel;
57 protected $mContentFormat;
60 * @var Content|null|bool
65 * @var null|ContentHandler
67 protected $mContentHandler;
72 protected $mQueryFlags = 0;
74 // Revision deletion constants
75 const DELETED_TEXT
= 1;
76 const DELETED_COMMENT
= 2;
77 const DELETED_USER
= 4;
78 const DELETED_RESTRICTED
= 8;
79 const SUPPRESSED_USER
= 12; // convenience
81 // Audience options for accessors
83 const FOR_THIS_USER
= 2;
87 * Load a page revision from a given revision ID number.
88 * Returns null if no such revision can be found.
91 * Revision::READ_LATEST : Select the data from the master
92 * Revision::READ_LOCKING : Select & lock the data from the master
95 * @param int $flags (optional)
96 * @return Revision|null
98 public static function newFromId( $id, $flags = 0 ) {
99 return self
::newFromConds( array( 'rev_id' => intval( $id ) ), $flags );
103 * Load either the current, or a specified, revision
104 * that's attached to a given title. If not attached
105 * to that title, will return null.
108 * Revision::READ_LATEST : Select the data from the master
109 * Revision::READ_LOCKING : Select & lock the data from the master
111 * @param Title $title
112 * @param int $id (optional)
113 * @param int $flags Bitfield (optional)
114 * @return Revision|null
116 public static function newFromTitle( $title, $id = 0, $flags = 0 ) {
118 'page_namespace' => $title->getNamespace(),
119 'page_title' => $title->getDBkey()
122 // Use the specified ID
123 $conds['rev_id'] = $id;
124 return self
::newFromConds( $conds, $flags );
126 // Use a join to get the latest revision
127 $conds[] = 'rev_id=page_latest';
128 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
129 return self
::loadFromConds( $db, $conds, $flags );
134 * Load either the current, or a specified, revision
135 * that's attached to a given page ID.
136 * Returns null if no such revision can be found.
139 * Revision::READ_LATEST : Select the data from the master (since 1.20)
140 * Revision::READ_LOCKING : Select & lock the data from the master
143 * @param int $revId (optional)
144 * @param int $flags Bitfield (optional)
145 * @return Revision|null
147 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
148 $conds = array( 'page_id' => $pageId );
150 $conds['rev_id'] = $revId;
151 return self
::newFromConds( $conds, $flags );
153 // Use a join to get the latest revision
154 $conds[] = 'rev_id = page_latest';
155 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
156 return self
::loadFromConds( $db, $conds, $flags );
161 * Make a fake revision object from an archive table row. This is queried
162 * for permissions or even inserted (as in Special:Undelete)
163 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
166 * @param array $overrides
168 * @throws MWException
171 public static function newFromArchiveRow( $row, $overrides = array() ) {
172 global $wgContentHandlerUseDB;
174 $attribs = $overrides +
array(
175 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
176 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
177 'comment' => $row->ar_comment
,
178 'user' => $row->ar_user
,
179 'user_text' => $row->ar_user_text
,
180 'timestamp' => $row->ar_timestamp
,
181 'minor_edit' => $row->ar_minor_edit
,
182 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
183 'deleted' => $row->ar_deleted
,
184 'len' => $row->ar_len
,
185 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
186 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
187 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
190 if ( !$wgContentHandlerUseDB ) {
191 unset( $attribs['content_model'] );
192 unset( $attribs['content_format'] );
195 if ( !isset( $attribs['title'] )
196 && isset( $row->ar_namespace
)
197 && isset( $row->ar_title
)
199 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
202 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
203 // Pre-1.5 ar_text row
204 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
205 if ( $attribs['text'] === false ) {
206 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
209 return new self( $attribs );
218 public static function newFromRow( $row ) {
219 return new self( $row );
223 * Load a page revision from a given revision ID number.
224 * Returns null if no such revision can be found.
226 * @param DatabaseBase $db
228 * @return Revision|null
230 public static function loadFromId( $db, $id ) {
231 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
235 * Load either the current, or a specified, revision
236 * that's attached to a given page. If not attached
237 * to that page, will return null.
239 * @param DatabaseBase $db
242 * @return Revision|null
244 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
245 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
247 $conds['rev_id'] = intval( $id );
249 $conds[] = 'rev_id=page_latest';
251 return self
::loadFromConds( $db, $conds );
255 * Load either the current, or a specified, revision
256 * that's attached to a given page. If not attached
257 * to that page, will return null.
259 * @param DatabaseBase $db
260 * @param Title $title
262 * @return Revision|null
264 public static function loadFromTitle( $db, $title, $id = 0 ) {
266 $matchId = intval( $id );
268 $matchId = 'page_latest';
270 return self
::loadFromConds( $db,
273 'page_namespace' => $title->getNamespace(),
274 'page_title' => $title->getDBkey()
280 * Load the revision for the given title with the given timestamp.
281 * WARNING: Timestamps may in some circumstances not be unique,
282 * so this isn't the best key to use.
284 * @param DatabaseBase $db
285 * @param Title $title
286 * @param string $timestamp
287 * @return Revision|null
289 public static function loadFromTimestamp( $db, $title, $timestamp ) {
290 return self
::loadFromConds( $db,
292 'rev_timestamp' => $db->timestamp( $timestamp ),
293 'page_namespace' => $title->getNamespace(),
294 'page_title' => $title->getDBkey()
300 * Given a set of conditions, fetch a revision
302 * This method is used then a revision ID is qualified and
303 * will incorporate some basic slave/master fallback logic
305 * @param array $conditions
306 * @param int $flags (optional)
307 * @return Revision|null
309 private static function newFromConds( $conditions, $flags = 0 ) {
310 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
312 $rev = self
::loadFromConds( $db, $conditions, $flags );
313 // Make sure new pending/committed revision are visibile later on
314 // within web requests to certain avoid bugs like T93866 and T94407.
316 && !( $flags & self
::READ_LATEST
)
317 && wfGetLB()->getServerCount() > 1
318 && wfGetLB()->hasOrMadeRecentMasterChanges()
320 $flags = self
::READ_LATEST
;
321 $db = wfGetDB( DB_MASTER
);
322 $rev = self
::loadFromConds( $db, $conditions, $flags );
326 $rev->mQueryFlags
= $flags;
333 * Given a set of conditions, fetch a revision from
334 * the given database connection.
336 * @param DatabaseBase $db
337 * @param array $conditions
338 * @param int $flags (optional)
339 * @return Revision|null
341 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
342 $res = self
::fetchFromConds( $db, $conditions, $flags );
344 $row = $res->fetchObject();
346 $ret = new Revision( $row );
355 * Return a wrapper for a series of database rows to
356 * fetch all of a given page's revisions in turn.
357 * Each row can be fed to the constructor to get objects.
359 * @param Title $title
360 * @return ResultWrapper
362 public static function fetchRevision( $title ) {
363 return self
::fetchFromConds(
366 'rev_id=page_latest',
367 'page_namespace' => $title->getNamespace(),
368 'page_title' => $title->getDBkey()
374 * Given a set of conditions, return a ResultWrapper
375 * which will return matching database rows with the
376 * fields necessary to build Revision objects.
378 * @param DatabaseBase $db
379 * @param array $conditions
380 * @param int $flags (optional)
381 * @return ResultWrapper
383 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
384 $fields = array_merge(
385 self
::selectFields(),
386 self
::selectPageFields(),
387 self
::selectUserFields()
389 $options = array( 'LIMIT' => 1 );
390 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
391 $options[] = 'FOR UPDATE';
394 array( 'revision', 'page', 'user' ),
399 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
404 * Return the value of a select() JOIN conds array for the user table.
405 * This will get user table rows for logged-in users.
409 public static function userJoinCond() {
410 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
414 * Return the value of a select() page conds array for the page table.
415 * This will assure that the revision(s) are not orphaned from live pages.
419 public static function pageJoinCond() {
420 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
424 * Return the list of revision fields that should be selected to create
428 public static function selectFields() {
429 global $wgContentHandlerUseDB;
446 if ( $wgContentHandlerUseDB ) {
447 $fields[] = 'rev_content_format';
448 $fields[] = 'rev_content_model';
455 * Return the list of revision fields that should be selected to create
456 * a new revision from an archive row.
459 public static function selectArchiveFields() {
460 global $wgContentHandlerUseDB;
478 if ( $wgContentHandlerUseDB ) {
479 $fields[] = 'ar_content_format';
480 $fields[] = 'ar_content_model';
486 * Return the list of text fields that should be selected to read the
490 public static function selectTextFields() {
498 * Return the list of page fields that should be selected from page table
501 public static function selectPageFields() {
513 * Return the list of user fields that should be selected from user table
516 public static function selectUserFields() {
517 return array( 'user_name' );
521 * Do a batched query to get the parent revision lengths
522 * @param DatabaseBase $db
523 * @param array $revIds
526 public static function getParentLengths( $db, array $revIds ) {
529 return $revLens; // empty
531 $res = $db->select( 'revision',
532 array( 'rev_id', 'rev_len' ),
533 array( 'rev_id' => $revIds ),
535 foreach ( $res as $row ) {
536 $revLens[$row->rev_id
] = $row->rev_len
;
544 * @param object|array $row Either a database row or an array
545 * @throws MWException
548 function __construct( $row ) {
549 if ( is_object( $row ) ) {
550 $this->mId
= intval( $row->rev_id
);
551 $this->mPage
= intval( $row->rev_page
);
552 $this->mTextId
= intval( $row->rev_text_id
);
553 $this->mComment
= $row->rev_comment
;
554 $this->mUser
= intval( $row->rev_user
);
555 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
556 $this->mTimestamp
= $row->rev_timestamp
;
557 $this->mDeleted
= intval( $row->rev_deleted
);
559 if ( !isset( $row->rev_parent_id
) ) {
560 $this->mParentId
= null;
562 $this->mParentId
= intval( $row->rev_parent_id
);
565 if ( !isset( $row->rev_len
) ) {
568 $this->mSize
= intval( $row->rev_len
);
571 if ( !isset( $row->rev_sha1
) ) {
574 $this->mSha1
= $row->rev_sha1
;
577 if ( isset( $row->page_latest
) ) {
578 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
579 $this->mTitle
= Title
::newFromRow( $row );
581 $this->mCurrent
= false;
582 $this->mTitle
= null;
585 if ( !isset( $row->rev_content_model
) ) {
586 $this->mContentModel
= null; # determine on demand if needed
588 $this->mContentModel
= strval( $row->rev_content_model
);
591 if ( !isset( $row->rev_content_format
) ) {
592 $this->mContentFormat
= null; # determine on demand if needed
594 $this->mContentFormat
= strval( $row->rev_content_format
);
597 // Lazy extraction...
599 if ( isset( $row->old_text
) ) {
600 $this->mTextRow
= $row;
602 // 'text' table row entry will be lazy-loaded
603 $this->mTextRow
= null;
606 // Use user_name for users and rev_user_text for IPs...
607 $this->mUserText
= null; // lazy load if left null
608 if ( $this->mUser
== 0 ) {
609 $this->mUserText
= $row->rev_user_text
; // IP user
610 } elseif ( isset( $row->user_name
) ) {
611 $this->mUserText
= $row->user_name
; // logged-in user
613 $this->mOrigUserText
= $row->rev_user_text
;
614 } elseif ( is_array( $row ) ) {
615 // Build a new revision to be saved...
616 global $wgUser; // ugh
618 # if we have a content object, use it to set the model and type
619 if ( !empty( $row['content'] ) ) {
620 // @todo when is that set? test with external store setup! check out insertOn() [dk]
621 if ( !empty( $row['text_id'] ) ) {
622 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
623 "can't serialize content object" );
626 $row['content_model'] = $row['content']->getModel();
627 # note: mContentFormat is initializes later accordingly
628 # note: content is serialized later in this method!
629 # also set text to null?
632 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
633 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
634 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
635 $this->mUserText
= isset( $row['user_text'] )
636 ?
strval( $row['user_text'] ) : $wgUser->getName();
637 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
638 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
639 $this->mTimestamp
= isset( $row['timestamp'] )
640 ?
strval( $row['timestamp'] ) : wfTimestampNow();
641 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
642 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
643 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
644 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
646 $this->mContentModel
= isset( $row['content_model'] )
647 ?
strval( $row['content_model'] ) : null;
648 $this->mContentFormat
= isset( $row['content_format'] )
649 ?
strval( $row['content_format'] ) : null;
651 // Enforce spacing trimming on supplied text
652 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
653 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
654 $this->mTextRow
= null;
656 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
658 // if we have a Content object, override mText and mContentModel
659 if ( !empty( $row['content'] ) ) {
660 if ( !( $row['content'] instanceof Content
) ) {
661 throw new MWException( '`content` field must contain a Content object.' );
664 $handler = $this->getContentHandler();
665 $this->mContent
= $row['content'];
667 $this->mContentModel
= $this->mContent
->getModel();
668 $this->mContentHandler
= null;
670 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
671 } elseif ( $this->mText
!== null ) {
672 $handler = $this->getContentHandler();
673 $this->mContent
= $handler->unserializeContent( $this->mText
);
676 // If we have a Title object, make sure it is consistent with mPage.
677 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
678 if ( $this->mPage
=== null ) {
679 // if the page ID wasn't known, set it now
680 $this->mPage
= $this->mTitle
->getArticleID();
681 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
682 // Got different page IDs. This may be legit (e.g. during undeletion),
683 // but it seems worth mentioning it in the log.
684 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
685 $this->mTitle
->getArticleID() . " provided by the Title object." );
689 $this->mCurrent
= false;
691 // If we still have no length, see it we have the text to figure it out
692 if ( !$this->mSize
&& $this->mContent
!== null ) {
693 $this->mSize
= $this->mContent
->getSize();
697 if ( $this->mSha1
=== null ) {
698 $this->mSha1
= $this->mText
=== null ?
null : self
::base36Sha1( $this->mText
);
702 $this->getContentModel();
703 $this->getContentFormat();
705 throw new MWException( 'Revision constructor passed invalid row format.' );
707 $this->mUnpatrolled
= null;
715 public function getId() {
720 * Set the revision ID
725 public function setId( $id ) {
734 public function getTextId() {
735 return $this->mTextId
;
739 * Get parent revision ID (the original previous page revision)
743 public function getParentId() {
744 return $this->mParentId
;
748 * Returns the length of the text in this revision, or null if unknown.
752 public function getSize() {
757 * Returns the base36 sha1 of the text in this revision, or null if unknown.
759 * @return string|null
761 public function getSha1() {
766 * Returns the title of the page associated with this entry or null.
768 * Will do a query, when title is not set and id is given.
772 public function getTitle() {
773 if ( $this->mTitle
!== null ) {
774 return $this->mTitle
;
776 //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
777 if ( $this->mId
!== null ) {
778 $dbr = wfGetDB( DB_SLAVE
);
779 $row = $dbr->selectRow(
780 array( 'page', 'revision' ),
781 self
::selectPageFields(),
782 array( 'page_id=rev_page',
783 'rev_id' => $this->mId
),
786 $this->mTitle
= Title
::newFromRow( $row );
790 if ( !$this->mTitle
&& $this->mPage
!== null && $this->mPage
> 0 ) {
791 $this->mTitle
= Title
::newFromID( $this->mPage
);
794 return $this->mTitle
;
798 * Set the title of the revision
800 * @param Title $title
802 public function setTitle( $title ) {
803 $this->mTitle
= $title;
811 public function getPage() {
816 * Fetch revision's user id if it's available to the specified audience.
817 * If the specified audience does not have access to it, zero will be
820 * @param int $audience One of:
821 * Revision::FOR_PUBLIC to be displayed to all users
822 * Revision::FOR_THIS_USER to be displayed to the given user
823 * Revision::RAW get the ID regardless of permissions
824 * @param User $user User object to check for, only if FOR_THIS_USER is passed
825 * to the $audience parameter
828 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
829 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
831 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
839 * Fetch revision's user id without regard for the current user's permissions
842 * @deprecated since 1.25, use getUser( Revision::RAW )
844 public function getRawUser() {
845 wfDeprecated( __METHOD__
, '1.25' );
846 return $this->getUser( self
::RAW
);
850 * Fetch revision's username if it's available to the specified audience.
851 * If the specified audience does not have access to the username, an
852 * empty string will be returned.
854 * @param int $audience One of:
855 * Revision::FOR_PUBLIC to be displayed to all users
856 * Revision::FOR_THIS_USER to be displayed to the given user
857 * Revision::RAW get the text regardless of permissions
858 * @param User $user User object to check for, only if FOR_THIS_USER is passed
859 * to the $audience parameter
862 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
863 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
865 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
868 if ( $this->mUserText
=== null ) {
869 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
870 if ( $this->mUserText
=== false ) {
871 # This shouldn't happen, but it can if the wiki was recovered
872 # via importing revs and there is no user table entry yet.
873 $this->mUserText
= $this->mOrigUserText
;
876 return $this->mUserText
;
881 * Fetch revision's username without regard for view restrictions
884 * @deprecated since 1.25, use getUserText( Revision::RAW )
886 public function getRawUserText() {
887 wfDeprecated( __METHOD__
, '1.25' );
888 return $this->getUserText( self
::RAW
);
892 * Fetch revision comment if it's available to the specified audience.
893 * If the specified audience does not have access to the comment, an
894 * empty string will be returned.
896 * @param int $audience One of:
897 * Revision::FOR_PUBLIC to be displayed to all users
898 * Revision::FOR_THIS_USER to be displayed to the given user
899 * Revision::RAW get the text regardless of permissions
900 * @param User $user User object to check for, only if FOR_THIS_USER is passed
901 * to the $audience parameter
904 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
905 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
907 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
910 return $this->mComment
;
915 * Fetch revision comment without regard for the current user's permissions
918 * @deprecated since 1.25, use getComment( Revision::RAW )
920 public function getRawComment() {
921 wfDeprecated( __METHOD__
, '1.25' );
922 return $this->getComment( self
::RAW
);
928 public function isMinor() {
929 return (bool)$this->mMinorEdit
;
933 * @return int Rcid of the unpatrolled row, zero if there isn't one
935 public function isUnpatrolled() {
936 if ( $this->mUnpatrolled
!== null ) {
937 return $this->mUnpatrolled
;
939 $rc = $this->getRecentChange();
940 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
941 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
943 $this->mUnpatrolled
= 0;
945 return $this->mUnpatrolled
;
949 * Get the RC object belonging to the current revision, if there's one
952 * @return RecentChange|null
954 public function getRecentChange() {
955 $dbr = wfGetDB( DB_SLAVE
);
956 return RecentChange
::newFromConds(
958 'rc_user_text' => $this->getUserText( Revision
::RAW
),
959 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
960 'rc_this_oldid' => $this->getId()
967 * @param int $field One of DELETED_* bitfield constants
971 public function isDeleted( $field ) {
972 return ( $this->mDeleted
& $field ) == $field;
976 * Get the deletion bitfield of the revision
980 public function getVisibility() {
981 return (int)$this->mDeleted
;
985 * Fetch revision text if it's available to the specified audience.
986 * If the specified audience does not have the ability to view this
987 * revision, an empty string will be returned.
989 * @param int $audience One of:
990 * Revision::FOR_PUBLIC to be displayed to all users
991 * Revision::FOR_THIS_USER to be displayed to the given user
992 * Revision::RAW get the text regardless of permissions
993 * @param User $user User object to check for, only if FOR_THIS_USER is passed
994 * to the $audience parameter
996 * @deprecated since 1.21, use getContent() instead
997 * @todo Replace usage in core
1000 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1001 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1003 $content = $this->getContent( $audience, $user );
1004 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
1008 * Fetch revision content if it's available to the specified audience.
1009 * If the specified audience does not have the ability to view this
1010 * revision, null will be returned.
1012 * @param int $audience One of:
1013 * Revision::FOR_PUBLIC to be displayed to all users
1014 * Revision::FOR_THIS_USER to be displayed to $wgUser
1015 * Revision::RAW get the text regardless of permissions
1016 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1017 * to the $audience parameter
1019 * @return Content|null
1021 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1022 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1024 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1027 return $this->getContentInternal();
1032 * Fetch revision text without regard for view restrictions
1036 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
1037 * or Revision::getSerializedData() as appropriate.
1039 public function getRawText() {
1040 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1041 return $this->getText( self
::RAW
);
1045 * Fetch original serialized data without regard for view restrictions
1050 public function getSerializedData() {
1051 if ( $this->mText
=== null ) {
1052 $this->mText
= $this->loadText();
1055 return $this->mText
;
1059 * Gets the content object for the revision (or null on failure).
1061 * Note that for mutable Content objects, each call to this method will return a
1065 * @return Content|null The Revision's content, or null on failure.
1067 protected function getContentInternal() {
1068 if ( $this->mContent
=== null ) {
1069 // Revision is immutable. Load on demand:
1070 if ( $this->mText
=== null ) {
1071 $this->mText
= $this->loadText();
1074 if ( $this->mText
!== null && $this->mText
!== false ) {
1075 // Unserialize content
1076 $handler = $this->getContentHandler();
1077 $format = $this->getContentFormat();
1079 $this->mContent
= $handler->unserializeContent( $this->mText
, $format );
1083 // NOTE: copy() will return $this for immutable content objects
1084 return $this->mContent ?
$this->mContent
->copy() : null;
1088 * Returns the content model for this revision.
1090 * If no content model was stored in the database, the default content model for the title is
1091 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1092 * is used as a last resort.
1094 * @return string The content model id associated with this revision,
1095 * see the CONTENT_MODEL_XXX constants.
1097 public function getContentModel() {
1098 if ( !$this->mContentModel
) {
1099 $title = $this->getTitle();
1101 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $title );
1103 $this->mContentModel
= CONTENT_MODEL_WIKITEXT
;
1106 assert( !empty( $this->mContentModel
) );
1109 return $this->mContentModel
;
1113 * Returns the content format for this revision.
1115 * If no content format was stored in the database, the default format for this
1116 * revision's content model is returned.
1118 * @return string The content format id associated with this revision,
1119 * see the CONTENT_FORMAT_XXX constants.
1121 public function getContentFormat() {
1122 if ( !$this->mContentFormat
) {
1123 $handler = $this->getContentHandler();
1124 $this->mContentFormat
= $handler->getDefaultFormat();
1126 assert( !empty( $this->mContentFormat
) );
1129 return $this->mContentFormat
;
1133 * Returns the content handler appropriate for this revision's content model.
1135 * @throws MWException
1136 * @return ContentHandler
1138 public function getContentHandler() {
1139 if ( !$this->mContentHandler
) {
1140 $model = $this->getContentModel();
1141 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1143 $format = $this->getContentFormat();
1145 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1146 throw new MWException( "Oops, the content format $format is not supported for "
1147 . "this content model, $model" );
1151 return $this->mContentHandler
;
1157 public function getTimestamp() {
1158 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1164 public function isCurrent() {
1165 return $this->mCurrent
;
1169 * Get previous revision for this title
1171 * @return Revision|null
1173 public function getPrevious() {
1174 if ( $this->getTitle() ) {
1175 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1177 return self
::newFromTitle( $this->getTitle(), $prev );
1184 * Get next revision for this title
1186 * @return Revision|null
1188 public function getNext() {
1189 if ( $this->getTitle() ) {
1190 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1192 return self
::newFromTitle( $this->getTitle(), $next );
1199 * Get previous revision Id for this page_id
1200 * This is used to populate rev_parent_id on save
1202 * @param DatabaseBase $db
1205 private function getPreviousRevisionId( $db ) {
1206 if ( $this->mPage
=== null ) {
1209 # Use page_latest if ID is not given
1210 if ( !$this->mId
) {
1211 $prevId = $db->selectField( 'page', 'page_latest',
1212 array( 'page_id' => $this->mPage
),
1215 $prevId = $db->selectField( 'revision', 'rev_id',
1216 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1218 array( 'ORDER BY' => 'rev_id DESC' ) );
1220 return intval( $prevId );
1224 * Get revision text associated with an old or archive row
1225 * $row is usually an object from wfFetchRow(), both the flags and the text
1226 * field must be included.
1228 * @param stdClass $row The text data
1229 * @param string $prefix Table prefix (default 'old_')
1230 * @param string|bool $wiki The name of the wiki to load the revision text from
1231 * (same as the the wiki $row was loaded from) or false to indicate the local
1232 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1233 * identifier as understood by the LoadBalancer class.
1234 * @return string Text the text requested or false on failure
1236 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1239 $textField = $prefix . 'text';
1240 $flagsField = $prefix . 'flags';
1242 if ( isset( $row->$flagsField ) ) {
1243 $flags = explode( ',', $row->$flagsField );
1248 if ( isset( $row->$textField ) ) {
1249 $text = $row->$textField;
1254 # Use external methods for external objects, text in table is URL-only then
1255 if ( in_array( 'external', $flags ) ) {
1257 $parts = explode( '://', $url, 2 );
1258 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1261 $text = ExternalStore
::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1264 // If the text was fetched without an error, convert it
1265 if ( $text !== false ) {
1266 $text = self
::decompressRevisionText( $text, $flags );
1272 * If $wgCompressRevisions is enabled, we will compress data.
1273 * The input string is modified in place.
1274 * Return value is the flags field: contains 'gzip' if the
1275 * data is compressed, and 'utf-8' if we're saving in UTF-8
1278 * @param mixed $text Reference to a text
1281 public static function compressRevisionText( &$text ) {
1282 global $wgCompressRevisions;
1285 # Revisions not marked this way will be converted
1286 # on load if $wgLegacyCharset is set in the future.
1289 if ( $wgCompressRevisions ) {
1290 if ( function_exists( 'gzdeflate' ) ) {
1291 $deflated = gzdeflate( $text );
1293 if ( $deflated === false ) {
1294 wfLogWarning( __METHOD__
. ': gzdeflate() failed' );
1300 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1303 return implode( ',', $flags );
1307 * Re-converts revision text according to it's flags.
1309 * @param mixed $text Reference to a text
1310 * @param array $flags Compression flags
1311 * @return string|bool Decompressed text, or false on failure
1313 public static function decompressRevisionText( $text, $flags ) {
1314 if ( in_array( 'gzip', $flags ) ) {
1315 # Deal with optional compression of archived pages.
1316 # This can be done periodically via maintenance/compressOld.php, and
1317 # as pages are saved if $wgCompressRevisions is set.
1318 $text = gzinflate( $text );
1320 if ( $text === false ) {
1321 wfLogWarning( __METHOD__
. ': gzinflate() failed' );
1326 if ( in_array( 'object', $flags ) ) {
1327 # Generic compressed storage
1328 $obj = unserialize( $text );
1329 if ( !is_object( $obj ) ) {
1333 $text = $obj->getText();
1336 global $wgLegacyEncoding;
1337 if ( $text !== false && $wgLegacyEncoding
1338 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1340 # Old revisions kept around in a legacy encoding?
1341 # Upconvert on demand.
1342 # ("utf8" checked for compatibility with some broken
1343 # conversion scripts 2008-12-30)
1345 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1352 * Insert a new revision into the database, returning the new revision ID
1353 * number on success and dies horribly on failure.
1355 * @param DatabaseBase $dbw (master connection)
1356 * @throws MWException
1359 public function insertOn( $dbw ) {
1360 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1362 $this->checkContentModel();
1364 $data = $this->mText
;
1365 $flags = self
::compressRevisionText( $data );
1367 # Write to external storage if required
1368 if ( $wgDefaultExternalStore ) {
1369 // Store and get the URL
1370 $data = ExternalStore
::insertToDefault( $data );
1372 throw new MWException( "Unable to store text to external storage" );
1377 $flags .= 'external';
1380 # Record the text (or external storage URL) to the text table
1381 if ( $this->mTextId
=== null ) {
1382 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1383 $dbw->insert( 'text',
1385 'old_id' => $old_id,
1386 'old_text' => $data,
1387 'old_flags' => $flags,
1390 $this->mTextId
= $dbw->insertId();
1393 if ( $this->mComment
=== null ) {
1394 $this->mComment
= "";
1397 # Record the edit in revisions
1398 $rev_id = $this->mId
!== null
1400 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1402 'rev_id' => $rev_id,
1403 'rev_page' => $this->mPage
,
1404 'rev_text_id' => $this->mTextId
,
1405 'rev_comment' => $this->mComment
,
1406 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1407 'rev_user' => $this->mUser
,
1408 'rev_user_text' => $this->mUserText
,
1409 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1410 'rev_deleted' => $this->mDeleted
,
1411 'rev_len' => $this->mSize
,
1412 'rev_parent_id' => $this->mParentId
=== null
1413 ?
$this->getPreviousRevisionId( $dbw )
1415 'rev_sha1' => $this->mSha1
=== null
1416 ? Revision
::base36Sha1( $this->mText
)
1420 if ( $wgContentHandlerUseDB ) {
1421 //NOTE: Store null for the default model and format, to save space.
1422 //XXX: Makes the DB sensitive to changed defaults.
1423 // Make this behavior optional? Only in miser mode?
1425 $model = $this->getContentModel();
1426 $format = $this->getContentFormat();
1428 $title = $this->getTitle();
1430 if ( $title === null ) {
1431 throw new MWException( "Insufficient information to determine the title of the "
1432 . "revision's page!" );
1435 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1436 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1438 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1439 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1442 $dbw->insert( 'revision', $row, __METHOD__
);
1444 $this->mId
= $rev_id !== null ?
$rev_id : $dbw->insertId();
1446 // Assertion to try to catch T92046
1447 if ( (int)$this->mId
=== 0 ) {
1448 throw new UnexpectedValueException(
1449 'After insert, Revision mId is ' . var_export( $this->mId
, 1 ) . ': ' .
1450 var_export( $row, 1 )
1454 Hooks
::run( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1459 protected function checkContentModel() {
1460 global $wgContentHandlerUseDB;
1462 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1464 $model = $this->getContentModel();
1465 $format = $this->getContentFormat();
1466 $handler = $this->getContentHandler();
1468 if ( !$handler->isSupportedFormat( $format ) ) {
1469 $t = $title->getPrefixedDBkey();
1471 throw new MWException( "Can't use format $format with content model $model on $t" );
1474 if ( !$wgContentHandlerUseDB && $title ) {
1475 // if $wgContentHandlerUseDB is not set,
1476 // all revisions must use the default content model and format.
1478 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1479 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1480 $defaultFormat = $defaultHandler->getDefaultFormat();
1482 if ( $this->getContentModel() != $defaultModel ) {
1483 $t = $title->getPrefixedDBkey();
1485 throw new MWException( "Can't save non-default content model with "
1486 . "\$wgContentHandlerUseDB disabled: model is $model, "
1487 . "default for $t is $defaultModel" );
1490 if ( $this->getContentFormat() != $defaultFormat ) {
1491 $t = $title->getPrefixedDBkey();
1493 throw new MWException( "Can't use non-default content format with "
1494 . "\$wgContentHandlerUseDB disabled: format is $format, "
1495 . "default for $t is $defaultFormat" );
1499 $content = $this->getContent( Revision
::RAW
);
1501 if ( !$content ||
!$content->isValid() ) {
1502 $t = $title->getPrefixedDBkey();
1504 throw new MWException( "Content of $t is not valid! Content model is $model" );
1509 * Get the base 36 SHA-1 value for a string of text
1510 * @param string $text
1513 public static function base36Sha1( $text ) {
1514 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1518 * Lazy-load the revision's text.
1519 * Currently hardcoded to the 'text' table storage engine.
1521 * @return string|bool The revision's text, or false on failure
1523 protected function loadText() {
1524 // Caching may be beneficial for massive use of external storage
1525 global $wgRevisionCacheExpiry, $wgMemc;
1527 $textId = $this->getTextId();
1528 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1529 if ( $wgRevisionCacheExpiry ) {
1530 $text = $wgMemc->get( $key );
1531 if ( is_string( $text ) ) {
1532 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1537 // If we kept data for lazy extraction, use it now...
1538 if ( $this->mTextRow
!== null ) {
1539 $row = $this->mTextRow
;
1540 $this->mTextRow
= null;
1546 // Text data is immutable; check slaves first.
1547 $dbr = wfGetDB( DB_SLAVE
);
1548 $row = $dbr->selectRow( 'text',
1549 array( 'old_text', 'old_flags' ),
1550 array( 'old_id' => $textId ),
1554 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1555 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1556 $forUpdate = ( $this->mQueryFlags
& self
::READ_LOCKING
== self
::READ_LOCKING
);
1557 if ( !$row && ( $forUpdate ||
wfGetLB()->getServerCount() > 1 ) ) {
1558 $dbw = wfGetDB( DB_MASTER
);
1559 $row = $dbw->selectRow( 'text',
1560 array( 'old_text', 'old_flags' ),
1561 array( 'old_id' => $textId ),
1563 $forUpdate ?
array( 'FOR UPDATE' ) : array() );
1567 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1570 $text = self
::getRevisionText( $row );
1571 if ( $row && $text === false ) {
1572 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1575 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1576 if ( $wgRevisionCacheExpiry && $text !== false ) {
1577 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1584 * Create a new null-revision for insertion into a page's
1585 * history. This will not re-save the text, but simply refer
1586 * to the text from the previous version.
1588 * Such revisions can for instance identify page rename
1589 * operations and other such meta-modifications.
1591 * @param DatabaseBase $dbw
1592 * @param int $pageId ID number of the page to read from
1593 * @param string $summary Revision's summary
1594 * @param bool $minor Whether the revision should be considered as minor
1595 * @param User|null $user User object to use or null for $wgUser
1596 * @return Revision|null Revision or null on error
1598 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1599 global $wgContentHandlerUseDB, $wgContLang;
1601 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1602 'rev_text_id', 'rev_len', 'rev_sha1' );
1604 if ( $wgContentHandlerUseDB ) {
1605 $fields[] = 'rev_content_model';
1606 $fields[] = 'rev_content_format';
1609 $current = $dbw->selectRow(
1610 array( 'page', 'revision' ),
1613 'page_id' => $pageId,
1614 'page_latest=rev_id',
1624 // Truncate for whole multibyte characters
1625 $summary = $wgContLang->truncate( $summary, 255 );
1629 'user_text' => $user->getName(),
1630 'user' => $user->getId(),
1631 'comment' => $summary,
1632 'minor_edit' => $minor,
1633 'text_id' => $current->rev_text_id
,
1634 'parent_id' => $current->page_latest
,
1635 'len' => $current->rev_len
,
1636 'sha1' => $current->rev_sha1
1639 if ( $wgContentHandlerUseDB ) {
1640 $row['content_model'] = $current->rev_content_model
;
1641 $row['content_format'] = $current->rev_content_format
;
1644 $revision = new Revision( $row );
1645 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1654 * Determine if the current user is allowed to view a particular
1655 * field of this revision, if it's marked as deleted.
1657 * @param int $field One of self::DELETED_TEXT,
1658 * self::DELETED_COMMENT,
1659 * self::DELETED_USER
1660 * @param User|null $user User object to check, or null to use $wgUser
1663 public function userCan( $field, User
$user = null ) {
1664 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1668 * Determine if the current user is allowed to view a particular
1669 * field of this revision, if it's marked as deleted. This is used
1670 * by various classes to avoid duplication.
1672 * @param int $bitfield Current field
1673 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1674 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1675 * self::DELETED_USER = File::DELETED_USER
1676 * @param User|null $user User object to check, or null to use $wgUser
1677 * @param Title|null $title A Title object to check for per-page restrictions on,
1678 * instead of just plain userrights
1681 public static function userCanBitfield( $bitfield, $field, User
$user = null,
1684 if ( $bitfield & $field ) { // aspect is deleted
1685 if ( $user === null ) {
1689 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1690 $permissions = array( 'suppressrevision', 'viewsuppressed' );
1691 } elseif ( $field & self
::DELETED_TEXT
) {
1692 $permissions = array( 'deletedtext' );
1694 $permissions = array( 'deletedhistory' );
1696 $permissionlist = implode( ', ', $permissions );
1697 if ( $title === null ) {
1698 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1699 return call_user_func_array( array( $user, 'isAllowedAny' ), $permissions );
1701 $text = $title->getPrefixedText();
1702 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1703 foreach ( $permissions as $perm ) {
1704 if ( $title->userCan( $perm, $user ) ) {
1716 * Get rev_timestamp from rev_id, without loading the rest of the row
1718 * @param Title $title
1720 * @return string|bool False if not found
1722 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1723 $db = ( $flags & self
::READ_LATEST
)
1724 ?
wfGetDB( DB_MASTER
)
1725 : wfGetDB( DB_SLAVE
);
1726 // Casting fix for databases that can't take '' for rev_id
1730 $conds = array( 'rev_id' => $id );
1731 $conds['rev_page'] = $title->getArticleID();
1732 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1734 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1738 * Get count of revisions per page...not very efficient
1740 * @param DatabaseBase $db
1741 * @param int $id Page id
1744 static function countByPageId( $db, $id ) {
1745 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1746 array( 'rev_page' => $id ), __METHOD__
);
1748 return $row->revCount
;
1754 * Get count of revisions per page...not very efficient
1756 * @param DatabaseBase $db
1757 * @param Title $title
1760 static function countByTitle( $db, $title ) {
1761 $id = $title->getArticleID();
1763 return self
::countByPageId( $db, $id );
1769 * Check if no edits were made by other users since
1770 * the time a user started editing the page. Limit to
1771 * 50 revisions for the sake of performance.
1774 * @deprecated since 1.24
1776 * @param DatabaseBase|int $db The Database to perform the check on. May be given as a
1777 * Database object or a database identifier usable with wfGetDB.
1778 * @param int $pageId The ID of the page in question
1779 * @param int $userId The ID of the user in question
1780 * @param string $since Look at edits since this time
1782 * @return bool True if the given user was the only one to edit since the given timestamp
1784 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1789 if ( is_int( $db ) ) {
1790 $db = wfGetDB( $db );
1793 $res = $db->select( 'revision',
1796 'rev_page' => $pageId,
1797 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1800 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1801 foreach ( $res as $row ) {
1802 if ( $row->rev_user
!= $userId ) {