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;
51 protected $mContentModel;
52 protected $mContentFormat;
55 * @var Content|null|bool
60 * @var null|ContentHandler
62 protected $mContentHandler;
64 // Revision deletion constants
65 const DELETED_TEXT
= 1;
66 const DELETED_COMMENT
= 2;
67 const DELETED_USER
= 4;
68 const DELETED_RESTRICTED
= 8;
69 const SUPPRESSED_USER
= 12; // convenience
71 // Audience options for accessors
73 const FOR_THIS_USER
= 2;
77 * Load a page revision from a given revision ID number.
78 * Returns null if no such revision can be found.
81 * Revision::READ_LATEST : Select the data from the master
82 * Revision::READ_LOCKING : Select & lock the data from the master
85 * @param $flags Integer (optional)
86 * @return Revision or null
88 public static function newFromId( $id, $flags = 0 ) {
89 return self
::newFromConds( array( 'rev_id' => intval( $id ) ), $flags );
93 * Load either the current, or a specified, revision
94 * that's attached to a given title. If not attached
95 * to that title, will return null.
98 * Revision::READ_LATEST : Select the data from the master
99 * Revision::READ_LOCKING : Select & lock the data from the master
101 * @param $title Title
102 * @param $id Integer (optional)
103 * @param $flags Integer Bitfield (optional)
104 * @return Revision or null
106 public static function newFromTitle( $title, $id = 0, $flags = 0 ) {
108 'page_namespace' => $title->getNamespace(),
109 'page_title' => $title->getDBkey()
112 // Use the specified ID
113 $conds['rev_id'] = $id;
115 // Use a join to get the latest revision
116 $conds[] = 'rev_id=page_latest';
118 return self
::newFromConds( $conds, (int)$flags );
122 * Load either the current, or a specified, revision
123 * that's attached to a given page ID.
124 * Returns null if no such revision can be found.
127 * Revision::READ_LATEST : Select the data from the master (since 1.20)
128 * Revision::READ_LOCKING : Select & lock the data from the master
130 * @param $revId Integer
131 * @param $pageId Integer (optional)
132 * @param $flags Integer Bitfield (optional)
133 * @return Revision or null
135 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
136 $conds = array( 'page_id' => $pageId );
138 $conds['rev_id'] = $revId;
140 // Use a join to get the latest revision
141 $conds[] = 'rev_id = page_latest';
143 return self
::newFromConds( $conds, (int)$flags );
147 * Make a fake revision object from an archive table row. This is queried
148 * for permissions or even inserted (as in Special:Undelete)
149 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
152 * @param $overrides array
154 * @throws MWException
157 public static function newFromArchiveRow( $row, $overrides = array() ) {
158 global $wgContentHandlerUseDB;
160 $attribs = $overrides +
array(
161 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
162 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
163 'comment' => $row->ar_comment
,
164 'user' => $row->ar_user
,
165 'user_text' => $row->ar_user_text
,
166 'timestamp' => $row->ar_timestamp
,
167 'minor_edit' => $row->ar_minor_edit
,
168 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
169 'deleted' => $row->ar_deleted
,
170 'len' => $row->ar_len
,
171 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
172 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
173 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
176 if ( !$wgContentHandlerUseDB ) {
177 unset( $attribs['content_model'] );
178 unset( $attribs['content_format'] );
181 if ( !isset( $attribs['title'] )
182 && isset( $row->ar_namespace
)
183 && isset( $row->ar_title
) ) {
185 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
188 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
189 // Pre-1.5 ar_text row
190 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
191 if ( $attribs['text'] === false ) {
192 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
195 return new self( $attribs );
204 public static function newFromRow( $row ) {
205 return new self( $row );
209 * Load a page revision from a given revision ID number.
210 * Returns null if no such revision can be found.
212 * @param $db DatabaseBase
214 * @return Revision or null
216 public static function loadFromId( $db, $id ) {
217 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
221 * Load either the current, or a specified, revision
222 * that's attached to a given page. If not attached
223 * to that page, will return null.
225 * @param $db DatabaseBase
226 * @param $pageid Integer
228 * @return Revision or null
230 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
231 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
233 $conds['rev_id'] = intval( $id );
235 $conds[] = 'rev_id=page_latest';
237 return self
::loadFromConds( $db, $conds );
241 * Load either the current, or a specified, revision
242 * that's attached to a given page. If not attached
243 * to that page, will return null.
245 * @param $db DatabaseBase
246 * @param $title Title
248 * @return Revision or null
250 public static function loadFromTitle( $db, $title, $id = 0 ) {
252 $matchId = intval( $id );
254 $matchId = 'page_latest';
256 return self
::loadFromConds( $db,
259 'page_namespace' => $title->getNamespace(),
260 'page_title' => $title->getDBkey()
266 * Load the revision for the given title with the given timestamp.
267 * WARNING: Timestamps may in some circumstances not be unique,
268 * so this isn't the best key to use.
270 * @param $db DatabaseBase
271 * @param $title Title
272 * @param $timestamp String
273 * @return Revision or null
275 public static function loadFromTimestamp( $db, $title, $timestamp ) {
276 return self
::loadFromConds( $db,
278 'rev_timestamp' => $db->timestamp( $timestamp ),
279 'page_namespace' => $title->getNamespace(),
280 'page_title' => $title->getDBkey()
286 * Given a set of conditions, fetch a revision.
288 * @param $conditions Array
289 * @param $flags integer (optional)
290 * @return Revision or null
292 private static function newFromConds( $conditions, $flags = 0 ) {
293 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
294 $rev = self
::loadFromConds( $db, $conditions, $flags );
295 if ( is_null( $rev ) && wfGetLB()->getServerCount() > 1 ) {
296 if ( !( $flags & self
::READ_LATEST
) ) {
297 $dbw = wfGetDB( DB_MASTER
);
298 $rev = self
::loadFromConds( $dbw, $conditions, $flags );
305 * Given a set of conditions, fetch a revision from
306 * the given database connection.
308 * @param $db DatabaseBase
309 * @param $conditions Array
310 * @param $flags integer (optional)
311 * @return Revision or null
313 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
314 $res = self
::fetchFromConds( $db, $conditions, $flags );
316 $row = $res->fetchObject();
318 $ret = new Revision( $row );
327 * Return a wrapper for a series of database rows to
328 * fetch all of a given page's revisions in turn.
329 * Each row can be fed to the constructor to get objects.
331 * @param $title Title
332 * @return ResultWrapper
334 public static function fetchRevision( $title ) {
335 return self
::fetchFromConds(
338 'rev_id=page_latest',
339 'page_namespace' => $title->getNamespace(),
340 'page_title' => $title->getDBkey()
346 * Given a set of conditions, return a ResultWrapper
347 * which will return matching database rows with the
348 * fields necessary to build Revision objects.
350 * @param $db DatabaseBase
351 * @param $conditions Array
352 * @param $flags integer (optional)
353 * @return ResultWrapper
355 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
356 $fields = array_merge(
357 self
::selectFields(),
358 self
::selectPageFields(),
359 self
::selectUserFields()
361 $options = array( 'LIMIT' => 1 );
362 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
363 $options[] = 'FOR UPDATE';
366 array( 'revision', 'page', 'user' ),
371 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
376 * Return the value of a select() JOIN conds array for the user table.
377 * This will get user table rows for logged-in users.
381 public static function userJoinCond() {
382 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
386 * Return the value of a select() page conds array for the paeg table.
387 * This will assure that the revision(s) are not orphaned from live pages.
391 public static function pageJoinCond() {
392 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
396 * Return the list of revision fields that should be selected to create
400 public static function selectFields() {
401 global $wgContentHandlerUseDB;
418 if ( $wgContentHandlerUseDB ) {
419 $fields[] = 'rev_content_format';
420 $fields[] = 'rev_content_model';
427 * Return the list of text fields that should be selected to read the
431 public static function selectTextFields() {
439 * Return the list of page fields that should be selected from page table
442 public static function selectPageFields() {
454 * Return the list of user fields that should be selected from user table
457 public static function selectUserFields() {
458 return array( 'user_name' );
462 * Do a batched query to get the parent revision lengths
463 * @param $db DatabaseBase
464 * @param $revIds Array
467 public static function getParentLengths( $db, array $revIds ) {
470 return $revLens; // empty
472 wfProfileIn( __METHOD__
);
473 $res = $db->select( 'revision',
474 array( 'rev_id', 'rev_len' ),
475 array( 'rev_id' => $revIds ),
477 foreach ( $res as $row ) {
478 $revLens[$row->rev_id
] = $row->rev_len
;
480 wfProfileOut( __METHOD__
);
487 * @param $row Mixed: either a database row or an array
488 * @throws MWException
491 function __construct( $row ) {
492 if( is_object( $row ) ) {
493 $this->mId
= intval( $row->rev_id
);
494 $this->mPage
= intval( $row->rev_page
);
495 $this->mTextId
= intval( $row->rev_text_id
);
496 $this->mComment
= $row->rev_comment
;
497 $this->mUser
= intval( $row->rev_user
);
498 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
499 $this->mTimestamp
= $row->rev_timestamp
;
500 $this->mDeleted
= intval( $row->rev_deleted
);
502 if ( !isset( $row->rev_parent_id
) ) {
503 $this->mParentId
= null;
505 $this->mParentId
= intval( $row->rev_parent_id
);
508 if ( !isset( $row->rev_len
) ) {
511 $this->mSize
= intval( $row->rev_len
);
514 if ( !isset( $row->rev_sha1
) ) {
517 $this->mSha1
= $row->rev_sha1
;
520 if( isset( $row->page_latest
) ) {
521 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
522 $this->mTitle
= Title
::newFromRow( $row );
524 $this->mCurrent
= false;
525 $this->mTitle
= null;
528 if( !isset( $row->rev_content_model
) ||
is_null( $row->rev_content_model
) ) {
529 $this->mContentModel
= null; # determine on demand if needed
531 $this->mContentModel
= strval( $row->rev_content_model
);
534 if( !isset( $row->rev_content_format
) ||
is_null( $row->rev_content_format
) ) {
535 $this->mContentFormat
= null; # determine on demand if needed
537 $this->mContentFormat
= strval( $row->rev_content_format
);
540 // Lazy extraction...
542 if( isset( $row->old_text
) ) {
543 $this->mTextRow
= $row;
545 // 'text' table row entry will be lazy-loaded
546 $this->mTextRow
= null;
549 // Use user_name for users and rev_user_text for IPs...
550 $this->mUserText
= null; // lazy load if left null
551 if ( $this->mUser
== 0 ) {
552 $this->mUserText
= $row->rev_user_text
; // IP user
553 } elseif ( isset( $row->user_name
) ) {
554 $this->mUserText
= $row->user_name
; // logged-in user
556 $this->mOrigUserText
= $row->rev_user_text
;
557 } elseif( is_array( $row ) ) {
558 // Build a new revision to be saved...
559 global $wgUser; // ugh
562 # if we have a content object, use it to set the model and type
563 if ( !empty( $row['content'] ) ) {
564 //@todo: when is that set? test with external store setup! check out insertOn() [dk]
565 if ( !empty( $row['text_id'] ) ) {
566 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
567 "can't serialize content object" );
570 $row['content_model'] = $row['content']->getModel();
571 # note: mContentFormat is initializes later accordingly
572 # note: content is serialized later in this method!
573 # also set text to null?
576 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
577 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
578 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
579 $this->mUserText
= isset( $row['user_text'] ) ?
strval( $row['user_text'] ) : $wgUser->getName();
580 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
581 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
582 $this->mTimestamp
= isset( $row['timestamp'] ) ?
strval( $row['timestamp'] ) : wfTimestampNow();
583 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
584 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
585 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
586 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
588 $this->mContentModel
= isset( $row['content_model'] ) ?
strval( $row['content_model'] ) : null;
589 $this->mContentFormat
= isset( $row['content_format'] ) ?
strval( $row['content_format'] ) : null;
591 // Enforce spacing trimming on supplied text
592 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
593 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
594 $this->mTextRow
= null;
596 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
598 // if we have a Content object, override mText and mContentModel
599 if ( !empty( $row['content'] ) ) {
600 if ( !( $row['content'] instanceof Content
) ) {
601 throw new MWException( '`content` field must contain a Content object.' );
604 $handler = $this->getContentHandler();
605 $this->mContent
= $row['content'];
607 $this->mContentModel
= $this->mContent
->getModel();
608 $this->mContentHandler
= null;
610 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
611 } elseif ( !is_null( $this->mText
) ) {
612 $handler = $this->getContentHandler();
613 $this->mContent
= $handler->unserializeContent( $this->mText
);
616 // If we have a Title object, make sure it is consistent with mPage.
617 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
618 if ( $this->mPage
=== null ) {
619 // if the page ID wasn't known, set it now
620 $this->mPage
= $this->mTitle
->getArticleID();
621 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
622 // Got different page IDs. This may be legit (e.g. during undeletion),
623 // but it seems worth mentioning it in the log.
624 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
625 $this->mTitle
->getArticleID() . " provided by the Title object." );
629 $this->mCurrent
= false;
631 // If we still have no length, see it we have the text to figure it out
632 if ( !$this->mSize
) {
633 if ( !is_null( $this->mContent
) ) {
634 $this->mSize
= $this->mContent
->getSize();
636 #NOTE: this should never happen if we have either text or content object!
642 if ( $this->mSha1
=== null ) {
643 $this->mSha1
= is_null( $this->mText
) ?
null : self
::base36Sha1( $this->mText
);
647 $this->getContentModel();
648 $this->getContentFormat();
650 throw new MWException( 'Revision constructor passed invalid row format.' );
652 $this->mUnpatrolled
= null;
658 * @return Integer|null
660 public function getId() {
665 * Set the revision ID
670 public function setId( $id ) {
677 * @return Integer|null
679 public function getTextId() {
680 return $this->mTextId
;
684 * Get parent revision ID (the original previous page revision)
686 * @return Integer|null
688 public function getParentId() {
689 return $this->mParentId
;
693 * Returns the length of the text in this revision, or null if unknown.
695 * @return Integer|null
697 public function getSize() {
702 * Returns the base36 sha1 of the text in this revision, or null if unknown.
704 * @return String|null
706 public function getSha1() {
711 * Returns the title of the page associated with this entry or null.
713 * Will do a query, when title is not set and id is given.
717 public function getTitle() {
718 if( isset( $this->mTitle
) ) {
719 return $this->mTitle
;
721 if( !is_null( $this->mId
) ) { //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
722 $dbr = wfGetDB( DB_SLAVE
);
723 $row = $dbr->selectRow(
724 array( 'page', 'revision' ),
725 self
::selectPageFields(),
726 array( 'page_id=rev_page',
727 'rev_id' => $this->mId
),
730 $this->mTitle
= Title
::newFromRow( $row );
734 if ( !$this->mTitle
&& !is_null( $this->mPage
) && $this->mPage
> 0 ) {
735 $this->mTitle
= Title
::newFromID( $this->mPage
);
738 return $this->mTitle
;
742 * Set the title of the revision
744 * @param $title Title
746 public function setTitle( $title ) {
747 $this->mTitle
= $title;
753 * @return Integer|null
755 public function getPage() {
760 * Fetch revision's user id if it's available to the specified audience.
761 * If the specified audience does not have access to it, zero will be
764 * @param $audience Integer: one of:
765 * Revision::FOR_PUBLIC to be displayed to all users
766 * Revision::FOR_THIS_USER to be displayed to the given user
767 * Revision::RAW get the ID regardless of permissions
768 * @param $user User object to check for, only if FOR_THIS_USER is passed
769 * to the $audience parameter
772 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
773 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
775 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
783 * Fetch revision's user id without regard for the current user's permissions
787 public function getRawUser() {
792 * Fetch revision's username if it's available to the specified audience.
793 * If the specified audience does not have access to the username, an
794 * empty string will be returned.
796 * @param $audience Integer: one of:
797 * Revision::FOR_PUBLIC to be displayed to all users
798 * Revision::FOR_THIS_USER to be displayed to the given user
799 * Revision::RAW get the text regardless of permissions
800 * @param $user User object to check for, only if FOR_THIS_USER is passed
801 * to the $audience parameter
804 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
805 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
807 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
810 return $this->getRawUserText();
815 * Fetch revision's username without regard for view restrictions
819 public function getRawUserText() {
820 if ( $this->mUserText
=== null ) {
821 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
822 if ( $this->mUserText
=== false ) {
823 # This shouldn't happen, but it can if the wiki was recovered
824 # via importing revs and there is no user table entry yet.
825 $this->mUserText
= $this->mOrigUserText
;
828 return $this->mUserText
;
832 * Fetch revision comment if it's available to the specified audience.
833 * If the specified audience does not have access to the comment, an
834 * empty string will be returned.
836 * @param $audience Integer: one of:
837 * Revision::FOR_PUBLIC to be displayed to all users
838 * Revision::FOR_THIS_USER to be displayed to the given user
839 * Revision::RAW get the text regardless of permissions
840 * @param $user User object to check for, only if FOR_THIS_USER is passed
841 * to the $audience parameter
844 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
845 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
847 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
850 return $this->mComment
;
855 * Fetch revision comment without regard for the current user's permissions
859 public function getRawComment() {
860 return $this->mComment
;
866 public function isMinor() {
867 return (bool)$this->mMinorEdit
;
871 * @return Integer rcid of the unpatrolled row, zero if there isn't one
873 public function isUnpatrolled() {
874 if( $this->mUnpatrolled
!== null ) {
875 return $this->mUnpatrolled
;
877 $dbr = wfGetDB( DB_SLAVE
);
878 $this->mUnpatrolled
= $dbr->selectField( 'recentchanges',
880 array( // Add redundant user,timestamp condition so we can use the existing index
881 'rc_user_text' => $this->getRawUserText(),
882 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
883 'rc_this_oldid' => $this->getId(),
888 return (int)$this->mUnpatrolled
;
892 * @param $field int one of DELETED_* bitfield constants
896 public function isDeleted( $field ) {
897 return ( $this->mDeleted
& $field ) == $field;
901 * Get the deletion bitfield of the revision
905 public function getVisibility() {
906 return (int)$this->mDeleted
;
910 * Fetch revision text if it's available to the specified audience.
911 * If the specified audience does not have the ability to view this
912 * revision, an empty string will be returned.
914 * @param $audience Integer: one of:
915 * Revision::FOR_PUBLIC to be displayed to all users
916 * Revision::FOR_THIS_USER to be displayed to the given user
917 * Revision::RAW get the text regardless of permissions
918 * @param $user User object to check for, only if FOR_THIS_USER is passed
919 * to the $audience parameter
921 * @deprecated in 1.21, use getContent() instead
922 * @todo: replace usage in core
925 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
926 ContentHandler
::deprecated( __METHOD__
, '1.21' );
928 $content = $this->getContent( $audience, $user );
929 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
933 * Fetch revision content if it's available to the specified audience.
934 * If the specified audience does not have the ability to view this
935 * revision, null will be returned.
937 * @param $audience Integer: one of:
938 * Revision::FOR_PUBLIC to be displayed to all users
939 * Revision::FOR_THIS_USER to be displayed to $wgUser
940 * Revision::RAW get the text regardless of permissions
941 * @param $user User object to check for, only if FOR_THIS_USER is passed
942 * to the $audience parameter
944 * @return Content|null
946 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
947 if( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
949 } elseif( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
952 return $this->getContentInternal();
957 * Alias for getText(Revision::FOR_THIS_USER)
959 * @deprecated since 1.17
962 public function revText() {
963 wfDeprecated( __METHOD__
, '1.17' );
964 return $this->getText( self
::FOR_THIS_USER
);
968 * Fetch revision text without regard for view restrictions
972 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
973 * or Revision::getSerializedData() as appropriate.
975 public function getRawText() {
976 ContentHandler
::deprecated( __METHOD__
, "1.21" );
977 return $this->getText( self
::RAW
);
981 * Fetch original serialized data without regard for view restrictions
986 public function getSerializedData() {
991 * Gets the content object for the revision (or null on failure).
993 * Note that for mutable Content objects, each call to this method will return a
997 * @return Content|null the Revision's content, or null on failure.
999 protected function getContentInternal() {
1000 if( is_null( $this->mContent
) ) {
1001 // Revision is immutable. Load on demand:
1002 if( is_null( $this->mText
) ) {
1003 $this->mText
= $this->loadText();
1006 if ( $this->mText
!== null && $this->mText
!== false ) {
1007 // Unserialize content
1008 $handler = $this->getContentHandler();
1009 $format = $this->getContentFormat();
1011 $this->mContent
= $handler->unserializeContent( $this->mText
, $format );
1013 $this->mContent
= false; // negative caching!
1017 // NOTE: copy() will return $this for immutable content objects
1018 return $this->mContent ?
$this->mContent
->copy() : null;
1022 * Returns the content model for this revision.
1024 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
1025 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1026 * is used as a last resort.
1028 * @return String the content model id associated with this revision, see the CONTENT_MODEL_XXX constants.
1030 public function getContentModel() {
1031 if ( !$this->mContentModel
) {
1032 $title = $this->getTitle();
1033 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
1035 assert( !empty( $this->mContentModel
) );
1038 return $this->mContentModel
;
1042 * Returns the content format for this revision.
1044 * If no content format was stored in the database, the default format for this
1045 * revision's content model is returned.
1047 * @return String the content format id associated with this revision, see the CONTENT_FORMAT_XXX constants.
1049 public function getContentFormat() {
1050 if ( !$this->mContentFormat
) {
1051 $handler = $this->getContentHandler();
1052 $this->mContentFormat
= $handler->getDefaultFormat();
1054 assert( !empty( $this->mContentFormat
) );
1057 return $this->mContentFormat
;
1061 * Returns the content handler appropriate for this revision's content model.
1063 * @throws MWException
1064 * @return ContentHandler
1066 public function getContentHandler() {
1067 if ( !$this->mContentHandler
) {
1068 $model = $this->getContentModel();
1069 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1071 $format = $this->getContentFormat();
1073 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1074 throw new MWException( "Oops, the content format $format is not supported for this content model, $model" );
1078 return $this->mContentHandler
;
1084 public function getTimestamp() {
1085 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1091 public function isCurrent() {
1092 return $this->mCurrent
;
1096 * Get previous revision for this title
1098 * @return Revision or null
1100 public function getPrevious() {
1101 if( $this->getTitle() ) {
1102 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1104 return self
::newFromTitle( $this->getTitle(), $prev );
1111 * Get next revision for this title
1113 * @return Revision or null
1115 public function getNext() {
1116 if( $this->getTitle() ) {
1117 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1119 return self
::newFromTitle( $this->getTitle(), $next );
1126 * Get previous revision Id for this page_id
1127 * This is used to populate rev_parent_id on save
1129 * @param $db DatabaseBase
1132 private function getPreviousRevisionId( $db ) {
1133 if( is_null( $this->mPage
) ) {
1136 # Use page_latest if ID is not given
1138 $prevId = $db->selectField( 'page', 'page_latest',
1139 array( 'page_id' => $this->mPage
),
1142 $prevId = $db->selectField( 'revision', 'rev_id',
1143 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1145 array( 'ORDER BY' => 'rev_id DESC' ) );
1147 return intval( $prevId );
1151 * Get revision text associated with an old or archive row
1152 * $row is usually an object from wfFetchRow(), both the flags and the text
1153 * field must be included
1155 * @param $row Object: the text data
1156 * @param $prefix String: table prefix (default 'old_')
1157 * @param $wiki String|false: the name of the wiki to load the revision text from
1158 * (same as the the wiki $row was loaded from) or false to indicate the local
1159 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1160 * identifier as understood by the LoadBalancer class.
1161 * @return String: text the text requested or false on failure
1163 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1164 wfProfileIn( __METHOD__
);
1167 $textField = $prefix . 'text';
1168 $flagsField = $prefix . 'flags';
1170 if( isset( $row->$flagsField ) ) {
1171 $flags = explode( ',', $row->$flagsField );
1176 if( isset( $row->$textField ) ) {
1177 $text = $row->$textField;
1179 wfProfileOut( __METHOD__
);
1183 # Use external methods for external objects, text in table is URL-only then
1184 if ( in_array( 'external', $flags ) ) {
1186 $parts = explode( '://', $url, 2 );
1187 if( count( $parts ) == 1 ||
$parts[1] == '' ) {
1188 wfProfileOut( __METHOD__
);
1191 $text = ExternalStore
::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1194 // If the text was fetched without an error, convert it
1195 if ( $text !== false ) {
1196 if( in_array( 'gzip', $flags ) ) {
1197 # Deal with optional compression of archived pages.
1198 # This can be done periodically via maintenance/compressOld.php, and
1199 # as pages are saved if $wgCompressRevisions is set.
1200 $text = gzinflate( $text );
1203 if( in_array( 'object', $flags ) ) {
1204 # Generic compressed storage
1205 $obj = unserialize( $text );
1206 if ( !is_object( $obj ) ) {
1208 wfProfileOut( __METHOD__
);
1211 $text = $obj->getText();
1214 global $wgLegacyEncoding;
1215 if( $text !== false && $wgLegacyEncoding
1216 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
1218 # Old revisions kept around in a legacy encoding?
1219 # Upconvert on demand.
1220 # ("utf8" checked for compatibility with some broken
1221 # conversion scripts 2008-12-30)
1223 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1226 wfProfileOut( __METHOD__
);
1231 * If $wgCompressRevisions is enabled, we will compress data.
1232 * The input string is modified in place.
1233 * Return value is the flags field: contains 'gzip' if the
1234 * data is compressed, and 'utf-8' if we're saving in UTF-8
1237 * @param $text Mixed: reference to a text
1240 public static function compressRevisionText( &$text ) {
1241 global $wgCompressRevisions;
1244 # Revisions not marked this way will be converted
1245 # on load if $wgLegacyCharset is set in the future.
1248 if( $wgCompressRevisions ) {
1249 if( function_exists( 'gzdeflate' ) ) {
1250 $text = gzdeflate( $text );
1253 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1256 return implode( ',', $flags );
1260 * Insert a new revision into the database, returning the new revision ID
1261 * number on success and dies horribly on failure.
1263 * @param $dbw DatabaseBase: (master connection)
1264 * @throws MWException
1267 public function insertOn( $dbw ) {
1268 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1270 wfProfileIn( __METHOD__
);
1272 $this->checkContentModel();
1274 $data = $this->mText
;
1275 $flags = self
::compressRevisionText( $data );
1277 # Write to external storage if required
1278 if( $wgDefaultExternalStore ) {
1279 // Store and get the URL
1280 $data = ExternalStore
::insertToDefault( $data );
1282 throw new MWException( "Unable to store text to external storage" );
1287 $flags .= 'external';
1290 # Record the text (or external storage URL) to the text table
1291 if( !isset( $this->mTextId
) ) {
1292 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1293 $dbw->insert( 'text',
1295 'old_id' => $old_id,
1296 'old_text' => $data,
1297 'old_flags' => $flags,
1300 $this->mTextId
= $dbw->insertId();
1303 if ( $this->mComment
=== null ) $this->mComment
= "";
1305 # Record the edit in revisions
1306 $rev_id = isset( $this->mId
)
1308 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1310 'rev_id' => $rev_id,
1311 'rev_page' => $this->mPage
,
1312 'rev_text_id' => $this->mTextId
,
1313 'rev_comment' => $this->mComment
,
1314 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1315 'rev_user' => $this->mUser
,
1316 'rev_user_text' => $this->mUserText
,
1317 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1318 'rev_deleted' => $this->mDeleted
,
1319 'rev_len' => $this->mSize
,
1320 'rev_parent_id' => is_null( $this->mParentId
)
1321 ?
$this->getPreviousRevisionId( $dbw )
1323 'rev_sha1' => is_null( $this->mSha1
)
1324 ? Revision
::base36Sha1( $this->mText
)
1328 if ( $wgContentHandlerUseDB ) {
1329 //NOTE: Store null for the default model and format, to save space.
1330 //XXX: Makes the DB sensitive to changed defaults. Make this behaviour optional? Only in miser mode?
1332 $model = $this->getContentModel();
1333 $format = $this->getContentFormat();
1335 $title = $this->getTitle();
1337 if ( $title === null ) {
1338 throw new MWException( "Insufficient information to determine the title of the revision's page!" );
1341 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1342 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1344 $row[ 'rev_content_model' ] = ( $model === $defaultModel ) ?
null : $model;
1345 $row[ 'rev_content_format' ] = ( $format === $defaultFormat ) ?
null : $format;
1348 $dbw->insert( 'revision', $row, __METHOD__
);
1350 $this->mId
= !is_null( $rev_id ) ?
$rev_id : $dbw->insertId();
1352 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1354 wfProfileOut( __METHOD__
);
1358 protected function checkContentModel() {
1359 global $wgContentHandlerUseDB;
1361 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1363 $model = $this->getContentModel();
1364 $format = $this->getContentFormat();
1365 $handler = $this->getContentHandler();
1367 if ( !$handler->isSupportedFormat( $format ) ) {
1368 $t = $title->getPrefixedDBkey();
1370 throw new MWException( "Can't use format $format with content model $model on $t" );
1373 if ( !$wgContentHandlerUseDB && $title ) {
1374 // if $wgContentHandlerUseDB is not set, all revisions must use the default content model and format.
1376 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1377 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1378 $defaultFormat = $defaultHandler->getDefaultFormat();
1380 if ( $this->getContentModel() != $defaultModel ) {
1381 $t = $title->getPrefixedDBkey();
1383 throw new MWException( "Can't save non-default content model with \$wgContentHandlerUseDB disabled: "
1384 . "model is $model , default for $t is $defaultModel" );
1387 if ( $this->getContentFormat() != $defaultFormat ) {
1388 $t = $title->getPrefixedDBkey();
1390 throw new MWException( "Can't use non-default content format with \$wgContentHandlerUseDB disabled: "
1391 . "format is $format, default for $t is $defaultFormat" );
1395 $content = $this->getContent( Revision
::RAW
);
1397 if ( !$content ||
!$content->isValid() ) {
1398 $t = $title->getPrefixedDBkey();
1400 throw new MWException( "Content of $t is not valid! Content model is $model" );
1405 * Get the base 36 SHA-1 value for a string of text
1406 * @param $text String
1409 public static function base36Sha1( $text ) {
1410 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1414 * Lazy-load the revision's text.
1415 * Currently hardcoded to the 'text' table storage engine.
1417 * @return String|bool the revision's text, or false on failure
1419 protected function loadText() {
1420 wfProfileIn( __METHOD__
);
1422 // Caching may be beneficial for massive use of external storage
1423 global $wgRevisionCacheExpiry, $wgMemc;
1424 $textId = $this->getTextId();
1425 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1426 if( $wgRevisionCacheExpiry ) {
1427 $text = $wgMemc->get( $key );
1428 if( is_string( $text ) ) {
1429 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1430 wfProfileOut( __METHOD__
);
1435 // If we kept data for lazy extraction, use it now...
1436 if ( isset( $this->mTextRow
) ) {
1437 $row = $this->mTextRow
;
1438 $this->mTextRow
= null;
1444 // Text data is immutable; check slaves first.
1445 $dbr = wfGetDB( DB_SLAVE
);
1446 $row = $dbr->selectRow( 'text',
1447 array( 'old_text', 'old_flags' ),
1448 array( 'old_id' => $this->getTextId() ),
1452 if( !$row && wfGetLB()->getServerCount() > 1 ) {
1453 // Possible slave lag!
1454 $dbw = wfGetDB( DB_MASTER
);
1455 $row = $dbw->selectRow( 'text',
1456 array( 'old_text', 'old_flags' ),
1457 array( 'old_id' => $this->getTextId() ),
1461 $text = self
::getRevisionText( $row );
1463 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1464 if( $wgRevisionCacheExpiry && $text !== false ) {
1465 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1468 wfProfileOut( __METHOD__
);
1474 * Create a new null-revision for insertion into a page's
1475 * history. This will not re-save the text, but simply refer
1476 * to the text from the previous version.
1478 * Such revisions can for instance identify page rename
1479 * operations and other such meta-modifications.
1481 * @param $dbw DatabaseBase
1482 * @param $pageId Integer: ID number of the page to read from
1483 * @param $summary String: revision's summary
1484 * @param $minor Boolean: whether the revision should be considered as minor
1485 * @return Revision|null on error
1487 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1488 global $wgContentHandlerUseDB;
1490 wfProfileIn( __METHOD__
);
1492 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1493 'rev_text_id', 'rev_len', 'rev_sha1' );
1495 if ( $wgContentHandlerUseDB ) {
1496 $fields[] = 'rev_content_model';
1497 $fields[] = 'rev_content_format';
1500 $current = $dbw->selectRow(
1501 array( 'page', 'revision' ),
1504 'page_id' => $pageId,
1505 'page_latest=rev_id',
1512 'comment' => $summary,
1513 'minor_edit' => $minor,
1514 'text_id' => $current->rev_text_id
,
1515 'parent_id' => $current->page_latest
,
1516 'len' => $current->rev_len
,
1517 'sha1' => $current->rev_sha1
1520 if ( $wgContentHandlerUseDB ) {
1521 $row[ 'content_model' ] = $current->rev_content_model
;
1522 $row[ 'content_format' ] = $current->rev_content_format
;
1525 $revision = new Revision( $row );
1526 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1531 wfProfileOut( __METHOD__
);
1536 * Determine if the current user is allowed to view a particular
1537 * field of this revision, if it's marked as deleted.
1539 * @param $field Integer:one of self::DELETED_TEXT,
1540 * self::DELETED_COMMENT,
1541 * self::DELETED_USER
1542 * @param $user User object to check, or null to use $wgUser
1545 public function userCan( $field, User
$user = null ) {
1546 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1550 * Determine if the current user is allowed to view a particular
1551 * field of this revision, if it's marked as deleted. This is used
1552 * by various classes to avoid duplication.
1554 * @param $bitfield Integer: current field
1555 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1556 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1557 * self::DELETED_USER = File::DELETED_USER
1558 * @param $user User object to check, or null to use $wgUser
1561 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
1562 if( $bitfield & $field ) { // aspect is deleted
1563 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1564 $permission = 'suppressrevision';
1565 } elseif ( $field & self
::DELETED_TEXT
) {
1566 $permission = 'deletedtext';
1568 $permission = 'deletedhistory';
1570 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1571 if ( $user === null ) {
1575 return $user->isAllowed( $permission );
1582 * Get rev_timestamp from rev_id, without loading the rest of the row
1584 * @param $title Title
1585 * @param $id Integer
1588 static function getTimestampFromId( $title, $id ) {
1589 $dbr = wfGetDB( DB_SLAVE
);
1590 // Casting fix for DB2
1594 $conds = array( 'rev_id' => $id );
1595 $conds['rev_page'] = $title->getArticleID();
1596 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1597 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1598 # Not in slave, try master
1599 $dbw = wfGetDB( DB_MASTER
);
1600 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1602 return wfTimestamp( TS_MW
, $timestamp );
1606 * Get count of revisions per page...not very efficient
1608 * @param $db DatabaseBase
1609 * @param $id Integer: page id
1612 static function countByPageId( $db, $id ) {
1613 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1614 array( 'rev_page' => $id ), __METHOD__
);
1616 return $row->revCount
;
1622 * Get count of revisions per page...not very efficient
1624 * @param $db DatabaseBase
1625 * @param $title Title
1628 static function countByTitle( $db, $title ) {
1629 $id = $title->getArticleID();
1631 return self
::countByPageId( $db, $id );
1637 * Check if no edits were made by other users since
1638 * the time a user started editing the page. Limit to
1639 * 50 revisions for the sake of performance.
1643 * @param DatabaseBase|int $db the Database to perform the check on. May be given as a Database object or
1644 * a database identifier usable with wfGetDB.
1645 * @param int $pageId the ID of the page in question
1646 * @param int $userId the ID of the user in question
1647 * @param string $since look at edits since this time
1649 * @return bool True if the given user was the only one to edit since the given timestamp
1651 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1652 if ( !$userId ) return false;
1654 if ( is_int( $db ) ) {
1655 $db = wfGetDB( $db );
1658 $res = $db->select( 'revision',
1661 'rev_page' => $pageId,
1662 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1665 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1666 foreach ( $res as $row ) {
1667 if ( $row->rev_user
!= $userId ) {