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 = null ) {
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';
101 // Callers assume this will be up-to-date
102 $flags = is_int( $flags ) ?
$flags : self
::READ_LATEST
; // b/c
104 return self
::newFromConds( $conds, (int)$flags );
108 * Load either the current, or a specified, revision
109 * that's attached to a given page ID.
110 * Returns null if no such revision can be found.
113 * Revision::READ_LATEST : Select the data from the master
114 * Revision::READ_LOCKING : Select & lock the data from the master
116 * @param $revId Integer
117 * @param $pageId Integer (optional)
118 * @param $flags Integer Bitfield (optional)
119 * @return Revision or null
121 public static function newFromPageId( $pageId, $revId = 0, $flags = null ) {
122 $conds = array( 'page_id' => $pageId );
124 $conds['rev_id'] = $revId;
126 // Use a join to get the latest revision
127 $conds[] = 'rev_id = page_latest';
128 // Callers assume this will be up-to-date
129 $flags = is_int( $flags ) ?
$flags : self
::READ_LATEST
; // b/c
131 return self
::newFromConds( $conds, (int)$flags );
135 * Make a fake revision object from an archive table row. This is queried
136 * for permissions or even inserted (as in Special:Undelete)
137 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
140 * @param $overrides array
142 * @throws MWException
145 public static function newFromArchiveRow( $row, $overrides = array() ) {
146 global $wgContentHandlerUseDB;
148 $attribs = $overrides +
array(
149 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
150 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
151 'comment' => $row->ar_comment
,
152 'user' => $row->ar_user
,
153 'user_text' => $row->ar_user_text
,
154 'timestamp' => $row->ar_timestamp
,
155 'minor_edit' => $row->ar_minor_edit
,
156 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
157 'deleted' => $row->ar_deleted
,
158 'len' => $row->ar_len
,
159 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
160 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
161 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
164 if ( !$wgContentHandlerUseDB ) {
165 unset( $attribs['content_model'] );
166 unset( $attribs['content_format'] );
169 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
170 // Pre-1.5 ar_text row
171 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
172 if ( $attribs['text'] === false ) {
173 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
176 return new self( $attribs );
185 public static function newFromRow( $row ) {
186 return new self( $row );
190 * Load a page revision from a given revision ID number.
191 * Returns null if no such revision can be found.
193 * @param $db DatabaseBase
195 * @return Revision or null
197 public static function loadFromId( $db, $id ) {
198 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
202 * Load either the current, or a specified, revision
203 * that's attached to a given page. If not attached
204 * to that page, will return null.
206 * @param $db DatabaseBase
207 * @param $pageid Integer
209 * @return Revision or null
211 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
212 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
214 $conds['rev_id'] = intval( $id );
216 $conds[] = 'rev_id=page_latest';
218 return self
::loadFromConds( $db, $conds );
222 * Load either the current, or a specified, revision
223 * that's attached to a given page. If not attached
224 * to that page, will return null.
226 * @param $db DatabaseBase
227 * @param $title Title
229 * @return Revision or null
231 public static function loadFromTitle( $db, $title, $id = 0 ) {
233 $matchId = intval( $id );
235 $matchId = 'page_latest';
237 return self
::loadFromConds( $db,
238 array( "rev_id=$matchId",
239 'page_namespace' => $title->getNamespace(),
240 'page_title' => $title->getDBkey() )
245 * Load the revision for the given title with the given timestamp.
246 * WARNING: Timestamps may in some circumstances not be unique,
247 * so this isn't the best key to use.
249 * @param $db DatabaseBase
250 * @param $title Title
251 * @param $timestamp String
252 * @return Revision or null
254 public static function loadFromTimestamp( $db, $title, $timestamp ) {
255 return self
::loadFromConds( $db,
256 array( 'rev_timestamp' => $db->timestamp( $timestamp ),
257 'page_namespace' => $title->getNamespace(),
258 'page_title' => $title->getDBkey() )
263 * Given a set of conditions, fetch a revision.
265 * @param $conditions Array
266 * @param $flags integer (optional)
267 * @return Revision or null
269 private static function newFromConds( $conditions, $flags = 0 ) {
270 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
271 $rev = self
::loadFromConds( $db, $conditions, $flags );
272 if ( is_null( $rev ) && wfGetLB()->getServerCount() > 1 ) {
273 if ( !( $flags & self
::READ_LATEST
) ) {
274 $dbw = wfGetDB( DB_MASTER
);
275 $rev = self
::loadFromConds( $dbw, $conditions, $flags );
282 * Given a set of conditions, fetch a revision from
283 * the given database connection.
285 * @param $db DatabaseBase
286 * @param $conditions Array
287 * @param $flags integer (optional)
288 * @return Revision or null
290 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
291 $res = self
::fetchFromConds( $db, $conditions, $flags );
293 $row = $res->fetchObject();
295 $ret = new Revision( $row );
304 * Return a wrapper for a series of database rows to
305 * fetch all of a given page's revisions in turn.
306 * Each row can be fed to the constructor to get objects.
308 * @param $title Title
309 * @return ResultWrapper
311 public static function fetchRevision( $title ) {
312 return self
::fetchFromConds(
314 array( 'rev_id=page_latest',
315 'page_namespace' => $title->getNamespace(),
316 'page_title' => $title->getDBkey() )
321 * Given a set of conditions, return a ResultWrapper
322 * which will return matching database rows with the
323 * fields necessary to build Revision objects.
325 * @param $db DatabaseBase
326 * @param $conditions Array
327 * @param $flags integer (optional)
328 * @return ResultWrapper
330 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
331 $fields = array_merge(
332 self
::selectFields(),
333 self
::selectPageFields(),
334 self
::selectUserFields()
336 $options = array( 'LIMIT' => 1 );
337 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
338 $options[] = 'FOR UPDATE';
341 array( 'revision', 'page', 'user' ),
346 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
351 * Return the value of a select() JOIN conds array for the user table.
352 * This will get user table rows for logged-in users.
356 public static function userJoinCond() {
357 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
361 * Return the value of a select() page conds array for the paeg table.
362 * This will assure that the revision(s) are not orphaned from live pages.
366 public static function pageJoinCond() {
367 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
371 * Return the list of revision fields that should be selected to create
375 public static function selectFields() {
376 global $wgContentHandlerUseDB;
393 if ( $wgContentHandlerUseDB ) {
394 $fields[] = 'rev_content_format';
395 $fields[] = 'rev_content_model';
402 * Return the list of text fields that should be selected to read the
406 public static function selectTextFields() {
414 * Return the list of page fields that should be selected from page table
417 public static function selectPageFields() {
429 * Return the list of user fields that should be selected from user table
432 public static function selectUserFields() {
433 return array( 'user_name' );
437 * Do a batched query to get the parent revision lengths
438 * @param $db DatabaseBase
439 * @param $revIds Array
442 public static function getParentLengths( $db, array $revIds ) {
445 return $revLens; // empty
447 wfProfileIn( __METHOD__
);
448 $res = $db->select( 'revision',
449 array( 'rev_id', 'rev_len' ),
450 array( 'rev_id' => $revIds ),
452 foreach ( $res as $row ) {
453 $revLens[$row->rev_id
] = $row->rev_len
;
455 wfProfileOut( __METHOD__
);
462 * @param $row Mixed: either a database row or an array
463 * @throws MWException
466 function __construct( $row ) {
467 if( is_object( $row ) ) {
468 $this->mId
= intval( $row->rev_id
);
469 $this->mPage
= intval( $row->rev_page
);
470 $this->mTextId
= intval( $row->rev_text_id
);
471 $this->mComment
= $row->rev_comment
;
472 $this->mUser
= intval( $row->rev_user
);
473 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
474 $this->mTimestamp
= $row->rev_timestamp
;
475 $this->mDeleted
= intval( $row->rev_deleted
);
477 if( !isset( $row->rev_parent_id
) ) {
478 $this->mParentId
= is_null( $row->rev_parent_id
) ?
null : 0;
480 $this->mParentId
= intval( $row->rev_parent_id
);
483 if( !isset( $row->rev_len
) ||
is_null( $row->rev_len
) ) {
486 $this->mSize
= intval( $row->rev_len
);
489 if ( !isset( $row->rev_sha1
) ) {
492 $this->mSha1
= $row->rev_sha1
;
495 if( isset( $row->page_latest
) ) {
496 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
497 $this->mTitle
= Title
::newFromRow( $row );
499 $this->mCurrent
= false;
500 $this->mTitle
= null;
503 if( !isset( $row->rev_content_model
) ||
is_null( $row->rev_content_model
) ) {
504 $this->mContentModel
= null; # determine on demand if needed
506 $this->mContentModel
= strval( $row->rev_content_model
);
509 if( !isset( $row->rev_content_format
) ||
is_null( $row->rev_content_format
) ) {
510 $this->mContentFormat
= null; # determine on demand if needed
512 $this->mContentFormat
= strval( $row->rev_content_format
);
515 // Lazy extraction...
517 if( isset( $row->old_text
) ) {
518 $this->mTextRow
= $row;
520 // 'text' table row entry will be lazy-loaded
521 $this->mTextRow
= null;
524 // Use user_name for users and rev_user_text for IPs...
525 $this->mUserText
= null; // lazy load if left null
526 if ( $this->mUser
== 0 ) {
527 $this->mUserText
= $row->rev_user_text
; // IP user
528 } elseif ( isset( $row->user_name
) ) {
529 $this->mUserText
= $row->user_name
; // logged-in user
531 $this->mOrigUserText
= $row->rev_user_text
;
532 } elseif( is_array( $row ) ) {
533 // Build a new revision to be saved...
534 global $wgUser; // ugh
537 # if we have a content object, use it to set the model and type
538 if ( !empty( $row['content'] ) ) {
539 //@todo: when is that set? test with external store setup! check out insertOn() [dk]
540 if ( !empty( $row['text_id'] ) ) {
541 throw new MWException( "Text already stored in external store (id {$row['text_id']}), "
542 . "can't serialize content object" );
545 $row['content_model'] = $row['content']->getModel();
546 # note: mContentFormat is initializes later accordingly
547 # note: content is serialized later in this method!
548 # also set text to null?
551 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
552 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
553 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
554 $this->mUserText
= isset( $row['user_text'] ) ?
strval( $row['user_text'] ) : $wgUser->getName();
555 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
556 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
557 $this->mTimestamp
= isset( $row['timestamp'] ) ?
strval( $row['timestamp'] ) : wfTimestampNow();
558 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
559 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
560 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
561 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
563 $this->mContentModel
= isset( $row['content_model'] ) ?
strval( $row['content_model'] ) : null;
564 $this->mContentFormat
= isset( $row['content_format'] ) ?
strval( $row['content_format'] ) : null;
566 // Enforce spacing trimming on supplied text
567 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
568 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
569 $this->mTextRow
= null;
571 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
573 // if we have a Content object, override mText and mContentModel
574 if ( !empty( $row['content'] ) ) {
575 if ( !( $row['content'] instanceof Content
) ) {
576 throw new MWException( '`content` field must contain a Content object.' );
579 $handler = $this->getContentHandler();
580 $this->mContent
= $row['content'];
582 $this->mContentModel
= $this->mContent
->getModel();
583 $this->mContentHandler
= null;
585 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
586 } elseif ( !is_null( $this->mText
) ) {
587 $handler = $this->getContentHandler();
588 $this->mContent
= $handler->unserializeContent( $this->mText
);
591 // if we have a Title object, override mPage. Useful for testing and convenience.
592 if ( isset( $row['title'] ) ) {
593 $this->mTitle
= $row['title'];
594 $this->mPage
= $this->mTitle
->getArticleID();
596 $this->mTitle
= null; // Load on demand if needed
599 // @todo: XXX: really? we are about to create a revision. it will usually then be the current one.
600 $this->mCurrent
= false;
602 // If we still have no length, see it we have the text to figure it out
603 if ( !$this->mSize
) {
604 if ( !is_null( $this->mContent
) ) {
605 $this->mSize
= $this->mContent
->getSize();
607 #NOTE: this should never happen if we have either text or content object!
613 if ( $this->mSha1
=== null ) {
614 $this->mSha1
= is_null( $this->mText
) ?
null : self
::base36Sha1( $this->mText
);
618 $this->getContentModel();
619 $this->getContentFormat();
621 throw new MWException( 'Revision constructor passed invalid row format.' );
623 $this->mUnpatrolled
= null;
629 * @return Integer|null
631 public function getId() {
636 * Set the revision ID
641 public function setId( $id ) {
648 * @return Integer|null
650 public function getTextId() {
651 return $this->mTextId
;
655 * Get parent revision ID (the original previous page revision)
657 * @return Integer|null
659 public function getParentId() {
660 return $this->mParentId
;
664 * Returns the length of the text in this revision, or null if unknown.
666 * @return Integer|null
668 public function getSize() {
673 * Returns the base36 sha1 of the text in this revision, or null if unknown.
675 * @return String|null
677 public function getSha1() {
682 * Returns the title of the page associated with this entry or null.
684 * Will do a query, when title is not set and id is given.
688 public function getTitle() {
689 if( isset( $this->mTitle
) ) {
690 return $this->mTitle
;
692 if( !is_null( $this->mId
) ) { //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
693 $dbr = wfGetDB( DB_SLAVE
);
694 $row = $dbr->selectRow(
695 array( 'page', 'revision' ),
696 self
::selectPageFields(),
697 array( 'page_id=rev_page',
698 'rev_id' => $this->mId
),
701 $this->mTitle
= Title
::newFromRow( $row );
705 if ( !$this->mTitle
&& !is_null( $this->mPage
) && $this->mPage
> 0 ) {
706 $this->mTitle
= Title
::newFromID( $this->mPage
);
709 return $this->mTitle
;
713 * Set the title of the revision
715 * @param $title Title
717 public function setTitle( $title ) {
718 $this->mTitle
= $title;
724 * @return Integer|null
726 public function getPage() {
731 * Fetch revision's user id if it's available to the specified audience.
732 * If the specified audience does not have access to it, zero will be
735 * @param $audience Integer: one of:
736 * Revision::FOR_PUBLIC to be displayed to all users
737 * Revision::FOR_THIS_USER to be displayed to the given user
738 * Revision::RAW get the ID regardless of permissions
739 * @param $user User object to check for, only if FOR_THIS_USER is passed
740 * to the $audience parameter
743 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
744 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
746 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
754 * Fetch revision's user id without regard for the current user's permissions
758 public function getRawUser() {
763 * Fetch revision's username if it's available to the specified audience.
764 * If the specified audience does not have access to the username, an
765 * empty string will be returned.
767 * @param $audience Integer: one of:
768 * Revision::FOR_PUBLIC to be displayed to all users
769 * Revision::FOR_THIS_USER to be displayed to the given user
770 * Revision::RAW get the text regardless of permissions
771 * @param $user User object to check for, only if FOR_THIS_USER is passed
772 * to the $audience parameter
775 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
776 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
778 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
781 return $this->getRawUserText();
786 * Fetch revision's username without regard for view restrictions
790 public function getRawUserText() {
791 if ( $this->mUserText
=== null ) {
792 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
793 if ( $this->mUserText
=== false ) {
794 # This shouldn't happen, but it can if the wiki was recovered
795 # via importing revs and there is no user table entry yet.
796 $this->mUserText
= $this->mOrigUserText
;
799 return $this->mUserText
;
803 * Fetch revision comment if it's available to the specified audience.
804 * If the specified audience does not have access to the comment, an
805 * empty string will be returned.
807 * @param $audience Integer: one of:
808 * Revision::FOR_PUBLIC to be displayed to all users
809 * Revision::FOR_THIS_USER to be displayed to the given user
810 * Revision::RAW get the text regardless of permissions
811 * @param $user User object to check for, only if FOR_THIS_USER is passed
812 * to the $audience parameter
815 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
816 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
818 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
821 return $this->mComment
;
826 * Fetch revision comment without regard for the current user's permissions
830 public function getRawComment() {
831 return $this->mComment
;
837 public function isMinor() {
838 return (bool)$this->mMinorEdit
;
842 * @return Integer rcid of the unpatrolled row, zero if there isn't one
844 public function isUnpatrolled() {
845 if( $this->mUnpatrolled
!== null ) {
846 return $this->mUnpatrolled
;
848 $dbr = wfGetDB( DB_SLAVE
);
849 $this->mUnpatrolled
= $dbr->selectField( 'recentchanges',
851 array( // Add redundant user,timestamp condition so we can use the existing index
852 'rc_user_text' => $this->getRawUserText(),
853 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
854 'rc_this_oldid' => $this->getId(),
859 return (int)$this->mUnpatrolled
;
863 * @param $field int one of DELETED_* bitfield constants
867 public function isDeleted( $field ) {
868 return ( $this->mDeleted
& $field ) == $field;
872 * Get the deletion bitfield of the revision
876 public function getVisibility() {
877 return (int)$this->mDeleted
;
881 * Fetch revision text if it's available to the specified audience.
882 * If the specified audience does not have the ability to view this
883 * revision, an empty string will be returned.
885 * @param $audience Integer: one of:
886 * Revision::FOR_PUBLIC to be displayed to all users
887 * Revision::FOR_THIS_USER to be displayed to the given user
888 * Revision::RAW get the text regardless of permissions
889 * @param $user User object to check for, only if FOR_THIS_USER is passed
890 * to the $audience parameter
892 * @deprecated in 1.21, use getContent() instead
893 * @todo: replace usage in core
896 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
897 wfDeprecated( __METHOD__
, '1.21' );
899 $content = $this->getContent( $audience, $user );
900 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
904 * Fetch revision content if it's available to the specified audience.
905 * If the specified audience does not have the ability to view this
906 * revision, null will be returned.
908 * @param $audience Integer: one of:
909 * Revision::FOR_PUBLIC to be displayed to all users
910 * Revision::FOR_THIS_USER to be displayed to $wgUser
911 * Revision::RAW get the text regardless of permissions
912 * @param $user User object to check for, only if FOR_THIS_USER is passed
913 * to the $audience parameter
917 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
918 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
920 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
923 return $this->getContentInternal();
928 * Alias for getText(Revision::FOR_THIS_USER)
930 * @deprecated since 1.17
933 public function revText() {
934 wfDeprecated( __METHOD__
, '1.17' );
935 return $this->getText( self
::FOR_THIS_USER
);
939 * Fetch revision text without regard for view restrictions
943 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
944 * or Revision::getSerializedData() as appropriate.
946 public function getRawText() {
947 wfDeprecated( __METHOD__
, "1.21" );
949 return $this->getText( self
::RAW
);
953 * Fetch original serialized data without regard for view restrictions
958 public function getSerializedData() {
963 * Gets the content object for the revision
968 protected function getContentInternal() {
969 if( is_null( $this->mContent
) ) {
970 // Revision is immutable. Load on demand:
972 $handler = $this->getContentHandler();
973 $format = $this->getContentFormat();
974 $title = $this->getTitle();
976 if( is_null( $this->mText
) ) {
977 // Load text on demand:
978 $this->mText
= $this->loadText();
981 $this->mContent
= is_null( $this->mText
) ?
null : $handler->unserializeContent( $this->mText
, $format );
984 return $this->mContent
->copy(); // NOTE: copy() will return $this for immutable content objects
988 * Returns the content model for this revision.
990 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
991 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
992 * is used as a last resort.
994 * @return String the content model id associated with this revision, see the CONTENT_MODEL_XXX constants.
996 public function getContentModel() {
997 if ( !$this->mContentModel
) {
998 $title = $this->getTitle();
999 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
1001 assert( !empty( $this->mContentModel
) );
1004 return $this->mContentModel
;
1008 * Returns the content format for this revision.
1010 * If no content format was stored in the database, the default format for this
1011 * revision's content model is returned.
1013 * @return String the content format id associated with this revision, see the CONTENT_FORMAT_XXX constants.
1015 public function getContentFormat() {
1016 if ( !$this->mContentFormat
) {
1017 $handler = $this->getContentHandler();
1018 $this->mContentFormat
= $handler->getDefaultFormat();
1020 assert( !empty( $this->mContentFormat
) );
1023 return $this->mContentFormat
;
1027 * Returns the content handler appropriate for this revision's content model.
1029 * @return ContentHandler
1031 public function getContentHandler() {
1032 if ( !$this->mContentHandler
) {
1033 $model = $this->getContentModel();
1034 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1036 $format = $this->getContentFormat();
1038 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1039 throw new MWException( "Oops, the content format $format is not supported for this content model, $model" );
1043 return $this->mContentHandler
;
1049 public function getTimestamp() {
1050 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1056 public function isCurrent() {
1057 return $this->mCurrent
;
1061 * Get previous revision for this title
1063 * @return Revision or null
1065 public function getPrevious() {
1066 if( $this->getTitle() ) {
1067 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1069 return self
::newFromTitle( $this->getTitle(), $prev );
1076 * Get next revision for this title
1078 * @return Revision or null
1080 public function getNext() {
1081 if( $this->getTitle() ) {
1082 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1084 return self
::newFromTitle( $this->getTitle(), $next );
1091 * Get previous revision Id for this page_id
1092 * This is used to populate rev_parent_id on save
1094 * @param $db DatabaseBase
1097 private function getPreviousRevisionId( $db ) {
1098 if( is_null( $this->mPage
) ) {
1101 # Use page_latest if ID is not given
1103 $prevId = $db->selectField( 'page', 'page_latest',
1104 array( 'page_id' => $this->mPage
),
1107 $prevId = $db->selectField( 'revision', 'rev_id',
1108 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1110 array( 'ORDER BY' => 'rev_id DESC' ) );
1112 return intval( $prevId );
1116 * Get revision text associated with an old or archive row
1117 * $row is usually an object from wfFetchRow(), both the flags and the text
1118 * field must be included
1120 * @param $row Object: the text data
1121 * @param $prefix String: table prefix (default 'old_')
1122 * @return String: text the text requested or false on failure
1124 public static function getRevisionText( $row, $prefix = 'old_' ) {
1125 wfProfileIn( __METHOD__
);
1128 $textField = $prefix . 'text';
1129 $flagsField = $prefix . 'flags';
1131 if( isset( $row->$flagsField ) ) {
1132 $flags = explode( ',', $row->$flagsField );
1137 if( isset( $row->$textField ) ) {
1138 $text = $row->$textField;
1140 wfProfileOut( __METHOD__
);
1144 # Use external methods for external objects, text in table is URL-only then
1145 if ( in_array( 'external', $flags ) ) {
1147 $parts = explode( '://', $url, 2 );
1148 if( count( $parts ) == 1 ||
$parts[1] == '' ) {
1149 wfProfileOut( __METHOD__
);
1152 $text = ExternalStore
::fetchFromURL( $url );
1155 // If the text was fetched without an error, convert it
1156 if ( $text !== false ) {
1157 if( in_array( 'gzip', $flags ) ) {
1158 # Deal with optional compression of archived pages.
1159 # This can be done periodically via maintenance/compressOld.php, and
1160 # as pages are saved if $wgCompressRevisions is set.
1161 $text = gzinflate( $text );
1164 if( in_array( 'object', $flags ) ) {
1165 # Generic compressed storage
1166 $obj = unserialize( $text );
1167 if ( !is_object( $obj ) ) {
1169 wfProfileOut( __METHOD__
);
1172 $text = $obj->getText();
1175 global $wgLegacyEncoding;
1176 if( $text !== false && $wgLegacyEncoding
1177 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
1179 # Old revisions kept around in a legacy encoding?
1180 # Upconvert on demand.
1181 # ("utf8" checked for compatibility with some broken
1182 # conversion scripts 2008-12-30)
1184 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1187 wfProfileOut( __METHOD__
);
1192 * If $wgCompressRevisions is enabled, we will compress data.
1193 * The input string is modified in place.
1194 * Return value is the flags field: contains 'gzip' if the
1195 * data is compressed, and 'utf-8' if we're saving in UTF-8
1198 * @param $text Mixed: reference to a text
1201 public static function compressRevisionText( &$text ) {
1202 global $wgCompressRevisions;
1205 # Revisions not marked this way will be converted
1206 # on load if $wgLegacyCharset is set in the future.
1209 if( $wgCompressRevisions ) {
1210 if( function_exists( 'gzdeflate' ) ) {
1211 $text = gzdeflate( $text );
1214 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1217 return implode( ',', $flags );
1221 * Insert a new revision into the database, returning the new revision ID
1222 * number on success and dies horribly on failure.
1224 * @param $dbw DatabaseBase: (master connection)
1225 * @throws MWException
1228 public function insertOn( $dbw ) {
1229 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1231 wfProfileIn( __METHOD__
);
1233 $this->checkContentModel();
1235 $data = $this->mText
;
1236 $flags = self
::compressRevisionText( $data );
1238 # Write to external storage if required
1239 if( $wgDefaultExternalStore ) {
1240 // Store and get the URL
1241 $data = ExternalStore
::insertToDefault( $data );
1243 throw new MWException( "Unable to store text to external storage" );
1248 $flags .= 'external';
1251 # Record the text (or external storage URL) to the text table
1252 if( !isset( $this->mTextId
) ) {
1253 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1254 $dbw->insert( 'text',
1256 'old_id' => $old_id,
1257 'old_text' => $data,
1258 'old_flags' => $flags,
1261 $this->mTextId
= $dbw->insertId();
1264 if ( $this->mComment
=== null ) $this->mComment
= "";
1266 # Record the edit in revisions
1267 $rev_id = isset( $this->mId
)
1269 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1271 'rev_id' => $rev_id,
1272 'rev_page' => $this->mPage
,
1273 'rev_text_id' => $this->mTextId
,
1274 'rev_comment' => $this->mComment
,
1275 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1276 'rev_user' => $this->mUser
,
1277 'rev_user_text' => $this->mUserText
,
1278 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1279 'rev_deleted' => $this->mDeleted
,
1280 'rev_len' => $this->mSize
,
1281 'rev_parent_id' => is_null( $this->mParentId
)
1282 ?
$this->getPreviousRevisionId( $dbw )
1284 'rev_sha1' => is_null( $this->mSha1
)
1285 ? Revision
::base36Sha1( $this->mText
)
1289 if ( $wgContentHandlerUseDB ) {
1290 //NOTE: Store null for the default model and format, to save space.
1291 //XXX: Makes the DB sensitive to changed defaults. Make this behaviour optional? Only in miser mode?
1293 $model = $this->getContentModel();
1294 $format = $this->getContentFormat();
1296 $title = $this->getTitle();
1298 if ( $title === null ) {
1299 throw new MWException( "Insufficient information to determine the title of the revision's page!" );
1302 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1303 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1305 $row[ 'rev_content_model' ] = ( $model === $defaultModel ) ?
null : $model;
1306 $row[ 'rev_content_format' ] = ( $format === $defaultFormat ) ?
null : $format;
1309 $dbw->insert( 'revision', $row, __METHOD__
);
1311 $this->mId
= !is_null( $rev_id ) ?
$rev_id : $dbw->insertId();
1313 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1315 wfProfileOut( __METHOD__
);
1319 protected function checkContentModel() {
1320 global $wgContentHandlerUseDB;
1322 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1324 $model = $this->getContentModel();
1325 $format = $this->getContentFormat();
1326 $handler = $this->getContentHandler();
1328 if ( !$handler->isSupportedFormat( $format ) ) {
1329 $t = $title->getPrefixedDBkey();
1331 throw new MWException( "Can't use format $format with content model $model on $t" );
1334 if ( !$wgContentHandlerUseDB && $title ) {
1335 // if $wgContentHandlerUseDB is not set, all revisions must use the default content model and format.
1337 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1338 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1339 $defaultFormat = $defaultHandler->getDefaultFormat();
1341 if ( $this->getContentModel() != $defaultModel ) {
1342 $t = $title->getPrefixedDBkey();
1344 throw new MWException( "Can't save non-default content model with \$wgContentHandlerUseDB disabled: "
1345 . "model is $model , default for $t is $defaultModel" );
1348 if ( $this->getContentFormat() != $defaultFormat ) {
1349 $t = $title->getPrefixedDBkey();
1351 throw new MWException( "Can't use non-default content format with \$wgContentHandlerUseDB disabled: "
1352 . "format is $format, default for $t is $defaultFormat" );
1356 $content = $this->getContent( Revision
::RAW
);
1358 if ( !$content->isValid() ) {
1359 $t = $title->getPrefixedDBkey();
1361 throw new MWException( "Content of $t is not valid! Content model is $model" );
1366 * Get the base 36 SHA-1 value for a string of text
1367 * @param $text String
1370 public static function base36Sha1( $text ) {
1371 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1375 * Lazy-load the revision's text.
1376 * Currently hardcoded to the 'text' table storage engine.
1380 protected function loadText() {
1381 wfProfileIn( __METHOD__
);
1383 // Caching may be beneficial for massive use of external storage
1384 global $wgRevisionCacheExpiry, $wgMemc;
1385 $textId = $this->getTextId();
1386 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1387 if( $wgRevisionCacheExpiry ) {
1388 $text = $wgMemc->get( $key );
1389 if( is_string( $text ) ) {
1390 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1391 wfProfileOut( __METHOD__
);
1396 // If we kept data for lazy extraction, use it now...
1397 if ( isset( $this->mTextRow
) ) {
1398 $row = $this->mTextRow
;
1399 $this->mTextRow
= null;
1405 // Text data is immutable; check slaves first.
1406 $dbr = wfGetDB( DB_SLAVE
);
1407 $row = $dbr->selectRow( 'text',
1408 array( 'old_text', 'old_flags' ),
1409 array( 'old_id' => $this->getTextId() ),
1413 if( !$row && wfGetLB()->getServerCount() > 1 ) {
1414 // Possible slave lag!
1415 $dbw = wfGetDB( DB_MASTER
);
1416 $row = $dbw->selectRow( 'text',
1417 array( 'old_text', 'old_flags' ),
1418 array( 'old_id' => $this->getTextId() ),
1422 $text = self
::getRevisionText( $row );
1424 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1425 if( $wgRevisionCacheExpiry && $text !== false ) {
1426 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1429 wfProfileOut( __METHOD__
);
1435 * Create a new null-revision for insertion into a page's
1436 * history. This will not re-save the text, but simply refer
1437 * to the text from the previous version.
1439 * Such revisions can for instance identify page rename
1440 * operations and other such meta-modifications.
1442 * @param $dbw DatabaseBase
1443 * @param $pageId Integer: ID number of the page to read from
1444 * @param $summary String: revision's summary
1445 * @param $minor Boolean: whether the revision should be considered as minor
1446 * @return Revision|null on error
1448 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1449 global $wgContentHandlerUseDB;
1451 wfProfileIn( __METHOD__
);
1453 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1454 'rev_text_id', 'rev_len', 'rev_sha1' );
1456 if ( $wgContentHandlerUseDB ) {
1457 $fields[] = 'rev_content_model';
1458 $fields[] = 'rev_content_format';
1461 $current = $dbw->selectRow(
1462 array( 'page', 'revision' ),
1465 'page_id' => $pageId,
1466 'page_latest=rev_id',
1473 'comment' => $summary,
1474 'minor_edit' => $minor,
1475 'text_id' => $current->rev_text_id
,
1476 'parent_id' => $current->page_latest
,
1477 'len' => $current->rev_len
,
1478 'sha1' => $current->rev_sha1
1481 if ( $wgContentHandlerUseDB ) {
1482 $row[ 'content_model' ] = $current->rev_content_model
;
1483 $row[ 'content_format' ] = $current->rev_content_format
;
1486 $revision = new Revision( $row );
1487 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1492 wfProfileOut( __METHOD__
);
1497 * Determine if the current user is allowed to view a particular
1498 * field of this revision, if it's marked as deleted.
1500 * @param $field Integer:one of self::DELETED_TEXT,
1501 * self::DELETED_COMMENT,
1502 * self::DELETED_USER
1503 * @param $user User object to check, or null to use $wgUser
1506 public function userCan( $field, User
$user = null ) {
1507 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1511 * Determine if the current user is allowed to view a particular
1512 * field of this revision, if it's marked as deleted. This is used
1513 * by various classes to avoid duplication.
1515 * @param $bitfield Integer: current field
1516 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1517 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1518 * self::DELETED_USER = File::DELETED_USER
1519 * @param $user User object to check, or null to use $wgUser
1522 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
1523 if( $bitfield & $field ) { // aspect is deleted
1524 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1525 $permission = 'suppressrevision';
1526 } elseif ( $field & self
::DELETED_TEXT
) {
1527 $permission = 'deletedtext';
1529 $permission = 'deletedhistory';
1531 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1532 if ( $user === null ) {
1536 return $user->isAllowed( $permission );
1543 * Get rev_timestamp from rev_id, without loading the rest of the row
1545 * @param $title Title
1546 * @param $id Integer
1549 static function getTimestampFromId( $title, $id ) {
1550 $dbr = wfGetDB( DB_SLAVE
);
1551 // Casting fix for DB2
1555 $conds = array( 'rev_id' => $id );
1556 $conds['rev_page'] = $title->getArticleID();
1557 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1558 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1559 # Not in slave, try master
1560 $dbw = wfGetDB( DB_MASTER
);
1561 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1563 return wfTimestamp( TS_MW
, $timestamp );
1567 * Get count of revisions per page...not very efficient
1569 * @param $db DatabaseBase
1570 * @param $id Integer: page id
1573 static function countByPageId( $db, $id ) {
1574 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1575 array( 'rev_page' => $id ), __METHOD__
);
1577 return $row->revCount
;
1583 * Get count of revisions per page...not very efficient
1585 * @param $db DatabaseBase
1586 * @param $title Title
1589 static function countByTitle( $db, $title ) {
1590 $id = $title->getArticleID();
1592 return self
::countByPageId( $db, $id );
1598 * Check if no edits were made by other users since
1599 * the time a user started editing the page. Limit to
1600 * 50 revisions for the sake of performance.
1604 * @param DatabaseBase|int $db the Database to perform the check on. May be given as a Database object or
1605 * a database identifier usable with wfGetDB.
1606 * @param int $pageId the ID of the page in question
1607 * @param int $userId the ID of the user in question
1608 * @param string $since look at edits since this time
1610 * @return bool True if the given user was the only one to edit since the given timestamp
1612 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1613 if ( !$userId ) return false;
1615 if ( is_int( $db ) ) {
1616 $db = wfGetDB( $db );
1619 $res = $db->select( 'revision',
1622 'rev_page' => $pageId,
1623 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1626 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1627 foreach ( $res as $row ) {
1628 if ( $row->rev_user
!= $userId ) {