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
{
30 protected $mOrigUserText;
32 protected $mMinorEdit;
33 protected $mTimestamp;
43 protected $mContentModel;
44 protected $mContentFormat;
46 protected $mContentHandler;
48 // Revision deletion constants
49 const DELETED_TEXT
= 1;
50 const DELETED_COMMENT
= 2;
51 const DELETED_USER
= 4;
52 const DELETED_RESTRICTED
= 8;
53 const SUPPRESSED_USER
= 12; // convenience
55 // Audience options for accessors
57 const FOR_THIS_USER
= 2;
61 * Load a page revision from a given revision ID number.
62 * Returns null if no such revision can be found.
65 * Revision::READ_LATEST : Select the data from the master
66 * Revision::READ_LOCKING : Select & lock the data from the master
69 * @param $flags Integer (optional)
70 * @return Revision or null
72 public static function newFromId( $id, $flags = 0 ) {
73 return self
::newFromConds( array( 'rev_id' => intval( $id ) ), $flags );
77 * Load either the current, or a specified, revision
78 * that's attached to a given title. If not attached
79 * to that title, will return null.
82 * Revision::READ_LATEST : Select the data from the master
83 * Revision::READ_LOCKING : Select & lock the data from the master
86 * @param $id Integer (optional)
87 * @param $flags Integer Bitfield (optional)
88 * @return Revision or null
90 public static function newFromTitle( $title, $id = 0, $flags = 0 ) {
92 'page_namespace' => $title->getNamespace(),
93 'page_title' => $title->getDBkey()
96 // Use the specified ID
97 $conds['rev_id'] = $id;
99 // Use a join to get the latest revision
100 $conds[] = 'rev_id=page_latest';
102 return self
::newFromConds( $conds, (int)$flags );
106 * Load either the current, or a specified, revision
107 * that's attached to a given page ID.
108 * Returns null if no such revision can be found.
111 * Revision::READ_LATEST : Select the data from the master
112 * Revision::READ_LOCKING : Select & lock the data from the master
114 * @param $revId Integer
115 * @param $pageId Integer (optional)
116 * @param $flags Integer Bitfield (optional)
117 * @return Revision or null
119 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
120 $conds = array( 'page_id' => $pageId );
122 $conds['rev_id'] = $revId;
124 // Use a join to get the latest revision
125 $conds[] = 'rev_id = page_latest';
127 return self
::newFromConds( $conds, (int)$flags );
131 * Make a fake revision object from an archive table row. This is queried
132 * for permissions or even inserted (as in Special:Undelete)
133 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
136 * @param $overrides array
138 * @throws MWException
141 public static function newFromArchiveRow( $row, $overrides = array() ) {
142 global $wgContentHandlerUseDB;
144 $attribs = $overrides +
array(
145 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
146 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
147 'comment' => $row->ar_comment
,
148 'user' => $row->ar_user
,
149 'user_text' => $row->ar_user_text
,
150 'timestamp' => $row->ar_timestamp
,
151 'minor_edit' => $row->ar_minor_edit
,
152 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
153 'deleted' => $row->ar_deleted
,
154 'len' => $row->ar_len
,
155 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
156 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
157 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
160 if ( !$wgContentHandlerUseDB ) {
161 unset( $attribs['content_model'] );
162 unset( $attribs['content_format'] );
165 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
166 // Pre-1.5 ar_text row
167 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
168 if ( $attribs['text'] === false ) {
169 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
172 return new self( $attribs );
181 public static function newFromRow( $row ) {
182 return new self( $row );
186 * Load a page revision from a given revision ID number.
187 * Returns null if no such revision can be found.
189 * @param $db DatabaseBase
191 * @return Revision or null
193 public static function loadFromId( $db, $id ) {
194 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
198 * Load either the current, or a specified, revision
199 * that's attached to a given page. If not attached
200 * to that page, will return null.
202 * @param $db DatabaseBase
203 * @param $pageid Integer
205 * @return Revision or null
207 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
208 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
210 $conds['rev_id'] = intval( $id );
212 $conds[] = 'rev_id=page_latest';
214 return self
::loadFromConds( $db, $conds );
218 * Load either the current, or a specified, revision
219 * that's attached to a given page. If not attached
220 * to that page, will return null.
222 * @param $db DatabaseBase
223 * @param $title Title
225 * @return Revision or null
227 public static function loadFromTitle( $db, $title, $id = 0 ) {
229 $matchId = intval( $id );
231 $matchId = 'page_latest';
233 return self
::loadFromConds( $db,
234 array( "rev_id=$matchId",
235 'page_namespace' => $title->getNamespace(),
236 'page_title' => $title->getDBkey() )
241 * Load the revision for the given title with the given timestamp.
242 * WARNING: Timestamps may in some circumstances not be unique,
243 * so this isn't the best key to use.
245 * @param $db DatabaseBase
246 * @param $title Title
247 * @param $timestamp String
248 * @return Revision or null
250 public static function loadFromTimestamp( $db, $title, $timestamp ) {
251 return self
::loadFromConds( $db,
252 array( 'rev_timestamp' => $db->timestamp( $timestamp ),
253 'page_namespace' => $title->getNamespace(),
254 'page_title' => $title->getDBkey() )
259 * Given a set of conditions, fetch a revision.
261 * @param $conditions Array
262 * @param $flags integer (optional)
263 * @return Revision or null
265 private static function newFromConds( $conditions, $flags = 0 ) {
266 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
267 $rev = self
::loadFromConds( $db, $conditions, $flags );
268 if ( is_null( $rev ) && wfGetLB()->getServerCount() > 1 ) {
269 if ( !( $flags & self
::READ_LATEST
) ) {
270 $dbw = wfGetDB( DB_MASTER
);
271 $rev = self
::loadFromConds( $dbw, $conditions, $flags );
278 * Given a set of conditions, fetch a revision from
279 * the given database connection.
281 * @param $db DatabaseBase
282 * @param $conditions Array
283 * @param $flags integer (optional)
284 * @return Revision or null
286 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
287 $res = self
::fetchFromConds( $db, $conditions, $flags );
289 $row = $res->fetchObject();
291 $ret = new Revision( $row );
300 * Return a wrapper for a series of database rows to
301 * fetch all of a given page's revisions in turn.
302 * Each row can be fed to the constructor to get objects.
304 * @param $title Title
305 * @return ResultWrapper
307 public static function fetchRevision( $title ) {
308 return self
::fetchFromConds(
310 array( 'rev_id=page_latest',
311 'page_namespace' => $title->getNamespace(),
312 'page_title' => $title->getDBkey() )
317 * Given a set of conditions, return a ResultWrapper
318 * which will return matching database rows with the
319 * fields necessary to build Revision objects.
321 * @param $db DatabaseBase
322 * @param $conditions Array
323 * @param $flags integer (optional)
324 * @return ResultWrapper
326 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
327 $fields = array_merge(
328 self
::selectFields(),
329 self
::selectPageFields(),
330 self
::selectUserFields()
332 $options = array( 'LIMIT' => 1 );
333 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
334 $options[] = 'FOR UPDATE';
337 array( 'revision', 'page', 'user' ),
342 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
347 * Return the value of a select() JOIN conds array for the user table.
348 * This will get user table rows for logged-in users.
352 public static function userJoinCond() {
353 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
357 * Return the value of a select() page conds array for the paeg table.
358 * This will assure that the revision(s) are not orphaned from live pages.
362 public static function pageJoinCond() {
363 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
367 * Return the list of revision fields that should be selected to create
371 public static function selectFields() {
372 global $wgContentHandlerUseDB;
389 if ( $wgContentHandlerUseDB ) {
390 $fields[] = 'rev_content_format';
391 $fields[] = 'rev_content_model';
398 * Return the list of text fields that should be selected to read the
402 public static function selectTextFields() {
410 * Return the list of page fields that should be selected from page table
413 public static function selectPageFields() {
425 * Return the list of user fields that should be selected from user table
428 public static function selectUserFields() {
429 return array( 'user_name' );
433 * Do a batched query to get the parent revision lengths
434 * @param $db DatabaseBase
435 * @param $revIds Array
438 public static function getParentLengths( $db, array $revIds ) {
441 return $revLens; // empty
443 wfProfileIn( __METHOD__
);
444 $res = $db->select( 'revision',
445 array( 'rev_id', 'rev_len' ),
446 array( 'rev_id' => $revIds ),
448 foreach ( $res as $row ) {
449 $revLens[$row->rev_id
] = $row->rev_len
;
451 wfProfileOut( __METHOD__
);
458 * @param $row Mixed: either a database row or an array
459 * @throws MWException
462 function __construct( $row ) {
463 if( is_object( $row ) ) {
464 $this->mId
= intval( $row->rev_id
);
465 $this->mPage
= intval( $row->rev_page
);
466 $this->mTextId
= intval( $row->rev_text_id
);
467 $this->mComment
= $row->rev_comment
;
468 $this->mUser
= intval( $row->rev_user
);
469 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
470 $this->mTimestamp
= $row->rev_timestamp
;
471 $this->mDeleted
= intval( $row->rev_deleted
);
473 if( !isset( $row->rev_parent_id
) ) {
474 $this->mParentId
= is_null( $row->rev_parent_id
) ?
null : 0;
476 $this->mParentId
= intval( $row->rev_parent_id
);
479 if( !isset( $row->rev_len
) ||
is_null( $row->rev_len
) ) {
482 $this->mSize
= intval( $row->rev_len
);
485 if ( !isset( $row->rev_sha1
) ) {
488 $this->mSha1
= $row->rev_sha1
;
491 if( isset( $row->page_latest
) ) {
492 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
493 $this->mTitle
= Title
::newFromRow( $row );
495 $this->mCurrent
= false;
496 $this->mTitle
= null;
499 if( !isset( $row->rev_content_model
) ||
is_null( $row->rev_content_model
) ) {
500 $this->mContentModel
= null; # determine on demand if needed
502 $this->mContentModel
= strval( $row->rev_content_model
);
505 if( !isset( $row->rev_content_format
) ||
is_null( $row->rev_content_format
) ) {
506 $this->mContentFormat
= null; # determine on demand if needed
508 $this->mContentFormat
= strval( $row->rev_content_format
);
511 // Lazy extraction...
513 if( isset( $row->old_text
) ) {
514 $this->mTextRow
= $row;
516 // 'text' table row entry will be lazy-loaded
517 $this->mTextRow
= null;
520 // Use user_name for users and rev_user_text for IPs...
521 $this->mUserText
= null; // lazy load if left null
522 if ( $this->mUser
== 0 ) {
523 $this->mUserText
= $row->rev_user_text
; // IP user
524 } elseif ( isset( $row->user_name
) ) {
525 $this->mUserText
= $row->user_name
; // logged-in user
527 $this->mOrigUserText
= $row->rev_user_text
;
528 } elseif( is_array( $row ) ) {
529 // Build a new revision to be saved...
530 global $wgUser; // ugh
533 # if we have a content object, use it to set the model and type
534 if ( !empty( $row['content'] ) ) {
535 //@todo: when is that set? test with external store setup! check out insertOn() [dk]
536 if ( !empty( $row['text_id'] ) ) {
537 throw new MWException( "Text already stored in external store (id {$row['text_id']}), "
538 . "can't serialize content object" );
541 $row['content_model'] = $row['content']->getModel();
542 # note: mContentFormat is initializes later accordingly
543 # note: content is serialized later in this method!
544 # also set text to null?
547 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
548 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
549 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
550 $this->mUserText
= isset( $row['user_text'] ) ?
strval( $row['user_text'] ) : $wgUser->getName();
551 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
552 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
553 $this->mTimestamp
= isset( $row['timestamp'] ) ?
strval( $row['timestamp'] ) : wfTimestampNow();
554 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
555 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
556 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
557 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
559 $this->mContentModel
= isset( $row['content_model'] ) ?
strval( $row['content_model'] ) : null;
560 $this->mContentFormat
= isset( $row['content_format'] ) ?
strval( $row['content_format'] ) : null;
562 // Enforce spacing trimming on supplied text
563 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
564 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
565 $this->mTextRow
= null;
567 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
569 // if we have a Content object, override mText and mContentModel
570 if ( !empty( $row['content'] ) ) {
571 if ( !( $row['content'] instanceof Content
) ) {
572 throw new MWException( '`content` field must contain a Content object.' );
575 $handler = $this->getContentHandler();
576 $this->mContent
= $row['content'];
578 $this->mContentModel
= $this->mContent
->getModel();
579 $this->mContentHandler
= null;
581 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
582 } elseif ( !is_null( $this->mText
) ) {
583 $handler = $this->getContentHandler();
584 $this->mContent
= $handler->unserializeContent( $this->mText
);
587 // if we have a Title object, override mPage. Useful for testing and convenience.
588 if ( isset( $row['title'] ) ) {
589 $this->mTitle
= $row['title'];
590 $this->mPage
= $this->mTitle
->getArticleID();
592 $this->mTitle
= null; // Load on demand if needed
595 // @todo: XXX: really? we are about to create a revision. it will usually then be the current one.
596 $this->mCurrent
= false;
598 // If we still have no length, see it we have the text to figure it out
599 if ( !$this->mSize
) {
600 if ( !is_null( $this->mContent
) ) {
601 $this->mSize
= $this->mContent
->getSize();
603 #NOTE: this should never happen if we have either text or content object!
609 if ( $this->mSha1
=== null ) {
610 $this->mSha1
= is_null( $this->mText
) ?
null : self
::base36Sha1( $this->mText
);
614 $this->getContentModel();
615 $this->getContentFormat();
617 throw new MWException( 'Revision constructor passed invalid row format.' );
619 $this->mUnpatrolled
= null;
625 * @return Integer|null
627 public function getId() {
632 * Set the revision ID
637 public function setId( $id ) {
644 * @return Integer|null
646 public function getTextId() {
647 return $this->mTextId
;
651 * Get parent revision ID (the original previous page revision)
653 * @return Integer|null
655 public function getParentId() {
656 return $this->mParentId
;
660 * Returns the length of the text in this revision, or null if unknown.
662 * @return Integer|null
664 public function getSize() {
669 * Returns the base36 sha1 of the text in this revision, or null if unknown.
671 * @return String|null
673 public function getSha1() {
678 * Returns the title of the page associated with this entry or null.
680 * Will do a query, when title is not set and id is given.
684 public function getTitle() {
685 if( isset( $this->mTitle
) ) {
686 return $this->mTitle
;
688 if( !is_null( $this->mId
) ) { //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
689 $dbr = wfGetDB( DB_SLAVE
);
690 $row = $dbr->selectRow(
691 array( 'page', 'revision' ),
692 self
::selectPageFields(),
693 array( 'page_id=rev_page',
694 'rev_id' => $this->mId
),
697 $this->mTitle
= Title
::newFromRow( $row );
701 if ( !$this->mTitle
&& !is_null( $this->mPage
) && $this->mPage
> 0 ) {
702 $this->mTitle
= Title
::newFromID( $this->mPage
);
705 return $this->mTitle
;
709 * Set the title of the revision
711 * @param $title Title
713 public function setTitle( $title ) {
714 $this->mTitle
= $title;
720 * @return Integer|null
722 public function getPage() {
727 * Fetch revision's user id if it's available to the specified audience.
728 * If the specified audience does not have access to it, zero will be
731 * @param $audience Integer: one of:
732 * Revision::FOR_PUBLIC to be displayed to all users
733 * Revision::FOR_THIS_USER to be displayed to the given user
734 * Revision::RAW get the ID regardless of permissions
735 * @param $user User object to check for, only if FOR_THIS_USER is passed
736 * to the $audience parameter
739 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
740 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
742 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
750 * Fetch revision's user id without regard for the current user's permissions
754 public function getRawUser() {
759 * Fetch revision's username if it's available to the specified audience.
760 * If the specified audience does not have access to the username, an
761 * empty string will be returned.
763 * @param $audience Integer: one of:
764 * Revision::FOR_PUBLIC to be displayed to all users
765 * Revision::FOR_THIS_USER to be displayed to the given user
766 * Revision::RAW get the text regardless of permissions
767 * @param $user User object to check for, only if FOR_THIS_USER is passed
768 * to the $audience parameter
771 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
772 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
774 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
777 return $this->getRawUserText();
782 * Fetch revision's username without regard for view restrictions
786 public function getRawUserText() {
787 if ( $this->mUserText
=== null ) {
788 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
789 if ( $this->mUserText
=== false ) {
790 # This shouldn't happen, but it can if the wiki was recovered
791 # via importing revs and there is no user table entry yet.
792 $this->mUserText
= $this->mOrigUserText
;
795 return $this->mUserText
;
799 * Fetch revision comment if it's available to the specified audience.
800 * If the specified audience does not have access to the comment, an
801 * empty string will be returned.
803 * @param $audience Integer: one of:
804 * Revision::FOR_PUBLIC to be displayed to all users
805 * Revision::FOR_THIS_USER to be displayed to the given user
806 * Revision::RAW get the text regardless of permissions
807 * @param $user User object to check for, only if FOR_THIS_USER is passed
808 * to the $audience parameter
811 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
812 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
814 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
817 return $this->mComment
;
822 * Fetch revision comment without regard for the current user's permissions
826 public function getRawComment() {
827 return $this->mComment
;
833 public function isMinor() {
834 return (bool)$this->mMinorEdit
;
838 * @return Integer rcid of the unpatrolled row, zero if there isn't one
840 public function isUnpatrolled() {
841 if( $this->mUnpatrolled
!== null ) {
842 return $this->mUnpatrolled
;
844 $dbr = wfGetDB( DB_SLAVE
);
845 $this->mUnpatrolled
= $dbr->selectField( 'recentchanges',
847 array( // Add redundant user,timestamp condition so we can use the existing index
848 'rc_user_text' => $this->getRawUserText(),
849 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
850 'rc_this_oldid' => $this->getId(),
855 return (int)$this->mUnpatrolled
;
859 * @param $field int one of DELETED_* bitfield constants
863 public function isDeleted( $field ) {
864 return ( $this->mDeleted
& $field ) == $field;
868 * Get the deletion bitfield of the revision
872 public function getVisibility() {
873 return (int)$this->mDeleted
;
877 * Fetch revision text if it's available to the specified audience.
878 * If the specified audience does not have the ability to view this
879 * revision, an empty string will be returned.
881 * @param $audience Integer: one of:
882 * Revision::FOR_PUBLIC to be displayed to all users
883 * Revision::FOR_THIS_USER to be displayed to the given user
884 * Revision::RAW get the text regardless of permissions
885 * @param $user User object to check for, only if FOR_THIS_USER is passed
886 * to the $audience parameter
888 * @deprecated in 1.21, use getContent() instead
889 * @todo: replace usage in core
892 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
893 ContentHandler
::deprecated( __METHOD__
, '1.21' );
895 $content = $this->getContent( $audience, $user );
896 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
900 * Fetch revision content if it's available to the specified audience.
901 * If the specified audience does not have the ability to view this
902 * revision, null will be returned.
904 * @param $audience Integer: one of:
905 * Revision::FOR_PUBLIC to be displayed to all users
906 * Revision::FOR_THIS_USER to be displayed to $wgUser
907 * Revision::RAW get the text regardless of permissions
908 * @param $user User object to check for, only if FOR_THIS_USER is passed
909 * to the $audience parameter
913 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
914 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
916 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
919 return $this->getContentInternal();
924 * Alias for getText(Revision::FOR_THIS_USER)
926 * @deprecated since 1.17
929 public function revText() {
930 wfDeprecated( __METHOD__
, '1.17' );
931 return $this->getText( self
::FOR_THIS_USER
);
935 * Fetch revision text without regard for view restrictions
939 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
940 * or Revision::getSerializedData() as appropriate.
942 public function getRawText() {
943 ContentHandler
::deprecated( __METHOD__
, "1.21" );
945 return $this->getText( self
::RAW
);
949 * Fetch original serialized data without regard for view restrictions
954 public function getSerializedData() {
959 * Gets the content object for the revision
964 protected function getContentInternal() {
965 if( is_null( $this->mContent
) ) {
966 // Revision is immutable. Load on demand:
968 $handler = $this->getContentHandler();
969 $format = $this->getContentFormat();
970 $title = $this->getTitle();
972 if( is_null( $this->mText
) ) {
973 // Load text on demand:
974 $this->mText
= $this->loadText();
977 $this->mContent
= is_null( $this->mText
) ?
null : $handler->unserializeContent( $this->mText
, $format );
980 return $this->mContent
->copy(); // NOTE: copy() will return $this for immutable content objects
984 * Returns the content model for this revision.
986 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
987 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
988 * is used as a last resort.
990 * @return String the content model id associated with this revision, see the CONTENT_MODEL_XXX constants.
992 public function getContentModel() {
993 if ( !$this->mContentModel
) {
994 $title = $this->getTitle();
995 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
997 assert( !empty( $this->mContentModel
) );
1000 return $this->mContentModel
;
1004 * Returns the content format for this revision.
1006 * If no content format was stored in the database, the default format for this
1007 * revision's content model is returned.
1009 * @return String the content format id associated with this revision, see the CONTENT_FORMAT_XXX constants.
1011 public function getContentFormat() {
1012 if ( !$this->mContentFormat
) {
1013 $handler = $this->getContentHandler();
1014 $this->mContentFormat
= $handler->getDefaultFormat();
1016 assert( !empty( $this->mContentFormat
) );
1019 return $this->mContentFormat
;
1023 * Returns the content handler appropriate for this revision's content model.
1025 * @return ContentHandler
1027 public function getContentHandler() {
1028 if ( !$this->mContentHandler
) {
1029 $model = $this->getContentModel();
1030 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1032 $format = $this->getContentFormat();
1034 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1035 throw new MWException( "Oops, the content format $format is not supported for this content model, $model" );
1039 return $this->mContentHandler
;
1045 public function getTimestamp() {
1046 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1052 public function isCurrent() {
1053 return $this->mCurrent
;
1057 * Get previous revision for this title
1059 * @return Revision or null
1061 public function getPrevious() {
1062 if( $this->getTitle() ) {
1063 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1065 return self
::newFromTitle( $this->getTitle(), $prev );
1072 * Get next revision for this title
1074 * @return Revision or null
1076 public function getNext() {
1077 if( $this->getTitle() ) {
1078 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1080 return self
::newFromTitle( $this->getTitle(), $next );
1087 * Get previous revision Id for this page_id
1088 * This is used to populate rev_parent_id on save
1090 * @param $db DatabaseBase
1093 private function getPreviousRevisionId( $db ) {
1094 if( is_null( $this->mPage
) ) {
1097 # Use page_latest if ID is not given
1099 $prevId = $db->selectField( 'page', 'page_latest',
1100 array( 'page_id' => $this->mPage
),
1103 $prevId = $db->selectField( 'revision', 'rev_id',
1104 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1106 array( 'ORDER BY' => 'rev_id DESC' ) );
1108 return intval( $prevId );
1112 * Get revision text associated with an old or archive row
1113 * $row is usually an object from wfFetchRow(), both the flags and the text
1114 * field must be included
1116 * @param $row Object: the text data
1117 * @param $prefix String: table prefix (default 'old_')
1118 * @return String: text the text requested or false on failure
1120 public static function getRevisionText( $row, $prefix = 'old_' ) {
1121 wfProfileIn( __METHOD__
);
1124 $textField = $prefix . 'text';
1125 $flagsField = $prefix . 'flags';
1127 if( isset( $row->$flagsField ) ) {
1128 $flags = explode( ',', $row->$flagsField );
1133 if( isset( $row->$textField ) ) {
1134 $text = $row->$textField;
1136 wfProfileOut( __METHOD__
);
1140 # Use external methods for external objects, text in table is URL-only then
1141 if ( in_array( 'external', $flags ) ) {
1143 $parts = explode( '://', $url, 2 );
1144 if( count( $parts ) == 1 ||
$parts[1] == '' ) {
1145 wfProfileOut( __METHOD__
);
1148 $text = ExternalStore
::fetchFromURL( $url );
1151 // If the text was fetched without an error, convert it
1152 if ( $text !== false ) {
1153 if( in_array( 'gzip', $flags ) ) {
1154 # Deal with optional compression of archived pages.
1155 # This can be done periodically via maintenance/compressOld.php, and
1156 # as pages are saved if $wgCompressRevisions is set.
1157 $text = gzinflate( $text );
1160 if( in_array( 'object', $flags ) ) {
1161 # Generic compressed storage
1162 $obj = unserialize( $text );
1163 if ( !is_object( $obj ) ) {
1165 wfProfileOut( __METHOD__
);
1168 $text = $obj->getText();
1171 global $wgLegacyEncoding;
1172 if( $text !== false && $wgLegacyEncoding
1173 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
1175 # Old revisions kept around in a legacy encoding?
1176 # Upconvert on demand.
1177 # ("utf8" checked for compatibility with some broken
1178 # conversion scripts 2008-12-30)
1180 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1183 wfProfileOut( __METHOD__
);
1188 * If $wgCompressRevisions is enabled, we will compress data.
1189 * The input string is modified in place.
1190 * Return value is the flags field: contains 'gzip' if the
1191 * data is compressed, and 'utf-8' if we're saving in UTF-8
1194 * @param $text Mixed: reference to a text
1197 public static function compressRevisionText( &$text ) {
1198 global $wgCompressRevisions;
1201 # Revisions not marked this way will be converted
1202 # on load if $wgLegacyCharset is set in the future.
1205 if( $wgCompressRevisions ) {
1206 if( function_exists( 'gzdeflate' ) ) {
1207 $text = gzdeflate( $text );
1210 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1213 return implode( ',', $flags );
1217 * Insert a new revision into the database, returning the new revision ID
1218 * number on success and dies horribly on failure.
1220 * @param $dbw DatabaseBase: (master connection)
1221 * @throws MWException
1224 public function insertOn( $dbw ) {
1225 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1227 wfProfileIn( __METHOD__
);
1229 $this->checkContentModel();
1231 $data = $this->mText
;
1232 $flags = self
::compressRevisionText( $data );
1234 # Write to external storage if required
1235 if( $wgDefaultExternalStore ) {
1236 // Store and get the URL
1237 $data = ExternalStore
::insertToDefault( $data );
1239 throw new MWException( "Unable to store text to external storage" );
1244 $flags .= 'external';
1247 # Record the text (or external storage URL) to the text table
1248 if( !isset( $this->mTextId
) ) {
1249 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1250 $dbw->insert( 'text',
1252 'old_id' => $old_id,
1253 'old_text' => $data,
1254 'old_flags' => $flags,
1257 $this->mTextId
= $dbw->insertId();
1260 if ( $this->mComment
=== null ) $this->mComment
= "";
1262 # Record the edit in revisions
1263 $rev_id = isset( $this->mId
)
1265 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1267 'rev_id' => $rev_id,
1268 'rev_page' => $this->mPage
,
1269 'rev_text_id' => $this->mTextId
,
1270 'rev_comment' => $this->mComment
,
1271 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1272 'rev_user' => $this->mUser
,
1273 'rev_user_text' => $this->mUserText
,
1274 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1275 'rev_deleted' => $this->mDeleted
,
1276 'rev_len' => $this->mSize
,
1277 'rev_parent_id' => is_null( $this->mParentId
)
1278 ?
$this->getPreviousRevisionId( $dbw )
1280 'rev_sha1' => is_null( $this->mSha1
)
1281 ? Revision
::base36Sha1( $this->mText
)
1285 if ( $wgContentHandlerUseDB ) {
1286 //NOTE: Store null for the default model and format, to save space.
1287 //XXX: Makes the DB sensitive to changed defaults. Make this behaviour optional? Only in miser mode?
1289 $model = $this->getContentModel();
1290 $format = $this->getContentFormat();
1292 $title = $this->getTitle();
1294 if ( $title === null ) {
1295 throw new MWException( "Insufficient information to determine the title of the revision's page!" );
1298 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1299 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1301 $row[ 'rev_content_model' ] = ( $model === $defaultModel ) ?
null : $model;
1302 $row[ 'rev_content_format' ] = ( $format === $defaultFormat ) ?
null : $format;
1305 $dbw->insert( 'revision', $row, __METHOD__
);
1307 $this->mId
= !is_null( $rev_id ) ?
$rev_id : $dbw->insertId();
1309 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1311 wfProfileOut( __METHOD__
);
1315 protected function checkContentModel() {
1316 global $wgContentHandlerUseDB;
1318 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1320 $model = $this->getContentModel();
1321 $format = $this->getContentFormat();
1322 $handler = $this->getContentHandler();
1324 if ( !$handler->isSupportedFormat( $format ) ) {
1325 $t = $title->getPrefixedDBkey();
1327 throw new MWException( "Can't use format $format with content model $model on $t" );
1330 if ( !$wgContentHandlerUseDB && $title ) {
1331 // if $wgContentHandlerUseDB is not set, all revisions must use the default content model and format.
1333 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1334 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1335 $defaultFormat = $defaultHandler->getDefaultFormat();
1337 if ( $this->getContentModel() != $defaultModel ) {
1338 $t = $title->getPrefixedDBkey();
1340 throw new MWException( "Can't save non-default content model with \$wgContentHandlerUseDB disabled: "
1341 . "model is $model , default for $t is $defaultModel" );
1344 if ( $this->getContentFormat() != $defaultFormat ) {
1345 $t = $title->getPrefixedDBkey();
1347 throw new MWException( "Can't use non-default content format with \$wgContentHandlerUseDB disabled: "
1348 . "format is $format, default for $t is $defaultFormat" );
1352 $content = $this->getContent( Revision
::RAW
);
1354 if ( !$content->isValid() ) {
1355 $t = $title->getPrefixedDBkey();
1357 throw new MWException( "Content of $t is not valid! Content model is $model" );
1362 * Get the base 36 SHA-1 value for a string of text
1363 * @param $text String
1366 public static function base36Sha1( $text ) {
1367 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1371 * Lazy-load the revision's text.
1372 * Currently hardcoded to the 'text' table storage engine.
1376 protected function loadText() {
1377 wfProfileIn( __METHOD__
);
1379 // Caching may be beneficial for massive use of external storage
1380 global $wgRevisionCacheExpiry, $wgMemc;
1381 $textId = $this->getTextId();
1382 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1383 if( $wgRevisionCacheExpiry ) {
1384 $text = $wgMemc->get( $key );
1385 if( is_string( $text ) ) {
1386 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1387 wfProfileOut( __METHOD__
);
1392 // If we kept data for lazy extraction, use it now...
1393 if ( isset( $this->mTextRow
) ) {
1394 $row = $this->mTextRow
;
1395 $this->mTextRow
= null;
1401 // Text data is immutable; check slaves first.
1402 $dbr = wfGetDB( DB_SLAVE
);
1403 $row = $dbr->selectRow( 'text',
1404 array( 'old_text', 'old_flags' ),
1405 array( 'old_id' => $this->getTextId() ),
1409 if( !$row && wfGetLB()->getServerCount() > 1 ) {
1410 // Possible slave lag!
1411 $dbw = wfGetDB( DB_MASTER
);
1412 $row = $dbw->selectRow( 'text',
1413 array( 'old_text', 'old_flags' ),
1414 array( 'old_id' => $this->getTextId() ),
1418 $text = self
::getRevisionText( $row );
1420 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1421 if( $wgRevisionCacheExpiry && $text !== false ) {
1422 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1425 wfProfileOut( __METHOD__
);
1431 * Create a new null-revision for insertion into a page's
1432 * history. This will not re-save the text, but simply refer
1433 * to the text from the previous version.
1435 * Such revisions can for instance identify page rename
1436 * operations and other such meta-modifications.
1438 * @param $dbw DatabaseBase
1439 * @param $pageId Integer: ID number of the page to read from
1440 * @param $summary String: revision's summary
1441 * @param $minor Boolean: whether the revision should be considered as minor
1442 * @return Revision|null on error
1444 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1445 global $wgContentHandlerUseDB;
1447 wfProfileIn( __METHOD__
);
1449 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1450 'rev_text_id', 'rev_len', 'rev_sha1' );
1452 if ( $wgContentHandlerUseDB ) {
1453 $fields[] = 'rev_content_model';
1454 $fields[] = 'rev_content_format';
1457 $current = $dbw->selectRow(
1458 array( 'page', 'revision' ),
1461 'page_id' => $pageId,
1462 'page_latest=rev_id',
1469 'comment' => $summary,
1470 'minor_edit' => $minor,
1471 'text_id' => $current->rev_text_id
,
1472 'parent_id' => $current->page_latest
,
1473 'len' => $current->rev_len
,
1474 'sha1' => $current->rev_sha1
1477 if ( $wgContentHandlerUseDB ) {
1478 $row[ 'content_model' ] = $current->rev_content_model
;
1479 $row[ 'content_format' ] = $current->rev_content_format
;
1482 $revision = new Revision( $row );
1483 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1488 wfProfileOut( __METHOD__
);
1493 * Determine if the current user is allowed to view a particular
1494 * field of this revision, if it's marked as deleted.
1496 * @param $field Integer:one of self::DELETED_TEXT,
1497 * self::DELETED_COMMENT,
1498 * self::DELETED_USER
1499 * @param $user User object to check, or null to use $wgUser
1502 public function userCan( $field, User
$user = null ) {
1503 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1507 * Determine if the current user is allowed to view a particular
1508 * field of this revision, if it's marked as deleted. This is used
1509 * by various classes to avoid duplication.
1511 * @param $bitfield Integer: current field
1512 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1513 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1514 * self::DELETED_USER = File::DELETED_USER
1515 * @param $user User object to check, or null to use $wgUser
1518 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
1519 if( $bitfield & $field ) { // aspect is deleted
1520 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1521 $permission = 'suppressrevision';
1522 } elseif ( $field & self
::DELETED_TEXT
) {
1523 $permission = 'deletedtext';
1525 $permission = 'deletedhistory';
1527 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1528 if ( $user === null ) {
1532 return $user->isAllowed( $permission );
1539 * Get rev_timestamp from rev_id, without loading the rest of the row
1541 * @param $title Title
1542 * @param $id Integer
1545 static function getTimestampFromId( $title, $id ) {
1546 $dbr = wfGetDB( DB_SLAVE
);
1547 // Casting fix for DB2
1551 $conds = array( 'rev_id' => $id );
1552 $conds['rev_page'] = $title->getArticleID();
1553 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1554 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1555 # Not in slave, try master
1556 $dbw = wfGetDB( DB_MASTER
);
1557 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1559 return wfTimestamp( TS_MW
, $timestamp );
1563 * Get count of revisions per page...not very efficient
1565 * @param $db DatabaseBase
1566 * @param $id Integer: page id
1569 static function countByPageId( $db, $id ) {
1570 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1571 array( 'rev_page' => $id ), __METHOD__
);
1573 return $row->revCount
;
1579 * Get count of revisions per page...not very efficient
1581 * @param $db DatabaseBase
1582 * @param $title Title
1585 static function countByTitle( $db, $title ) {
1586 $id = $title->getArticleID();
1588 return self
::countByPageId( $db, $id );
1594 * Check if no edits were made by other users since
1595 * the time a user started editing the page. Limit to
1596 * 50 revisions for the sake of performance.
1600 * @param DatabaseBase|int $db the Database to perform the check on. May be given as a Database object or
1601 * a database identifier usable with wfGetDB.
1602 * @param int $pageId the ID of the page in question
1603 * @param int $userId the ID of the user in question
1604 * @param string $since look at edits since this time
1606 * @return bool True if the given user was the only one to edit since the given timestamp
1608 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1609 if ( !$userId ) return false;
1611 if ( is_int( $db ) ) {
1612 $db = wfGetDB( $db );
1615 $res = $db->select( 'revision',
1618 'rev_page' => $pageId,
1619 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1622 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1623 foreach ( $res as $row ) {
1624 if ( $row->rev_user
!= $userId ) {