3 * Representation of a page version.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
26 class Revision
implements IDBAccessObject
{
34 protected $mOrigUserText;
36 protected $mMinorEdit;
37 protected $mTimestamp;
56 protected $mContentModel;
57 protected $mContentFormat;
60 * @var Content|null|bool
65 * @var null|ContentHandler
67 protected $mContentHandler;
72 protected $mQueryFlags = 0;
74 // Revision deletion constants
75 const DELETED_TEXT
= 1;
76 const DELETED_COMMENT
= 2;
77 const DELETED_USER
= 4;
78 const DELETED_RESTRICTED
= 8;
79 const SUPPRESSED_USER
= 12; // convenience
81 // Audience options for accessors
83 const FOR_THIS_USER
= 2;
87 * Load a page revision from a given revision ID number.
88 * Returns null if no such revision can be found.
91 * Revision::READ_LATEST : Select the data from the master
92 * Revision::READ_LOCKING : Select & lock the data from the master
95 * @param int $flags (optional)
96 * @return Revision|null
98 public static function newFromId( $id, $flags = 0 ) {
99 return self
::newFromConds( array( 'rev_id' => intval( $id ) ), $flags );
103 * Load either the current, or a specified, revision
104 * that's attached to a given title. If not attached
105 * to that title, will return null.
108 * Revision::READ_LATEST : Select the data from the master
109 * Revision::READ_LOCKING : Select & lock the data from the master
111 * @param Title $title
112 * @param int $id (optional)
113 * @param int $flags Bitfield (optional)
114 * @return Revision|null
116 public static function newFromTitle( $title, $id = 0, $flags = 0 ) {
118 'page_namespace' => $title->getNamespace(),
119 'page_title' => $title->getDBkey()
122 // Use the specified ID
123 $conds['rev_id'] = $id;
124 // This uses slave->master fallback with READ_NORMAL. Assuming revdelete,
125 // moves, and merges are rare, callers can use this to reduce master queries.
126 return self
::newFromConds( $conds, $flags );
128 // Use a join to get the latest revision
129 $conds[] = 'rev_id=page_latest';
130 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
131 return self
::loadFromConds( $db, $conds, $flags );
136 * Load either the current, or a specified, revision
137 * that's attached to a given page ID.
138 * Returns null if no such revision can be found.
141 * Revision::READ_LATEST : Select the data from the master (since 1.20)
142 * Revision::READ_LOCKING : Select & lock the data from the master
145 * @param int $revId (optional)
146 * @param int $flags Bitfield (optional)
147 * @return Revision|null
149 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
150 $conds = array( 'page_id' => $pageId );
152 $conds['rev_id'] = $revId;
153 // This uses slave->master fallback with READ_NORMAL. Assuming revdelete
154 // and merges are rare, callers can use this to reduce master queries.
155 return self
::newFromConds( $conds, $flags );
157 // Use a join to get the latest revision
158 $conds[] = 'rev_id = page_latest';
159 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
160 return self
::loadFromConds( $db, $conds, $flags );
165 * Make a fake revision object from an archive table row. This is queried
166 * for permissions or even inserted (as in Special:Undelete)
167 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
170 * @param array $overrides
172 * @throws MWException
175 public static function newFromArchiveRow( $row, $overrides = array() ) {
176 global $wgContentHandlerUseDB;
178 $attribs = $overrides +
array(
179 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
180 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
181 'comment' => $row->ar_comment
,
182 'user' => $row->ar_user
,
183 'user_text' => $row->ar_user_text
,
184 'timestamp' => $row->ar_timestamp
,
185 'minor_edit' => $row->ar_minor_edit
,
186 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
187 'deleted' => $row->ar_deleted
,
188 'len' => $row->ar_len
,
189 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
190 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
191 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
194 if ( !$wgContentHandlerUseDB ) {
195 unset( $attribs['content_model'] );
196 unset( $attribs['content_format'] );
199 if ( !isset( $attribs['title'] )
200 && isset( $row->ar_namespace
)
201 && isset( $row->ar_title
) ) {
203 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
206 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
207 // Pre-1.5 ar_text row
208 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
209 if ( $attribs['text'] === false ) {
210 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
213 return new self( $attribs );
222 public static function newFromRow( $row ) {
223 return new self( $row );
227 * Load a page revision from a given revision ID number.
228 * Returns null if no such revision can be found.
230 * @param DatabaseBase $db
232 * @return Revision|null
234 public static function loadFromId( $db, $id ) {
235 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
239 * Load either the current, or a specified, revision
240 * that's attached to a given page. If not attached
241 * to that page, will return null.
243 * @param DatabaseBase $db
246 * @return Revision|null
248 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
249 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
251 $conds['rev_id'] = intval( $id );
253 $conds[] = 'rev_id=page_latest';
255 return self
::loadFromConds( $db, $conds );
259 * Load either the current, or a specified, revision
260 * that's attached to a given page. If not attached
261 * to that page, will return null.
263 * @param DatabaseBase $db
264 * @param Title $title
266 * @return Revision|null
268 public static function loadFromTitle( $db, $title, $id = 0 ) {
270 $matchId = intval( $id );
272 $matchId = 'page_latest';
274 return self
::loadFromConds( $db,
277 'page_namespace' => $title->getNamespace(),
278 'page_title' => $title->getDBkey()
284 * Load the revision for the given title with the given timestamp.
285 * WARNING: Timestamps may in some circumstances not be unique,
286 * so this isn't the best key to use.
288 * @param DatabaseBase $db
289 * @param Title $title
290 * @param string $timestamp
291 * @return Revision|null
293 public static function loadFromTimestamp( $db, $title, $timestamp ) {
294 return self
::loadFromConds( $db,
296 'rev_timestamp' => $db->timestamp( $timestamp ),
297 'page_namespace' => $title->getNamespace(),
298 'page_title' => $title->getDBkey()
304 * Given a set of conditions, fetch a revision.
306 * @param array $conditions
307 * @param int $flags (optional)
308 * @return Revision|null
310 private static function newFromConds( $conditions, $flags = 0 ) {
311 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
312 $rev = self
::loadFromConds( $db, $conditions, $flags );
313 if ( $rev === null && wfGetLB()->getServerCount() > 1 ) {
314 if ( !( $flags & self
::READ_LATEST
) ) {
315 $dbw = wfGetDB( DB_MASTER
);
316 $rev = self
::loadFromConds( $dbw, $conditions, $flags );
320 $rev->mQueryFlags
= $flags;
326 * Given a set of conditions, fetch a revision from
327 * the given database connection.
329 * @param DatabaseBase $db
330 * @param array $conditions
331 * @param int $flags (optional)
332 * @return Revision|null
334 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
335 $res = self
::fetchFromConds( $db, $conditions, $flags );
337 $row = $res->fetchObject();
339 $ret = new Revision( $row );
348 * Return a wrapper for a series of database rows to
349 * fetch all of a given page's revisions in turn.
350 * Each row can be fed to the constructor to get objects.
352 * @param Title $title
353 * @return ResultWrapper
355 public static function fetchRevision( $title ) {
356 return self
::fetchFromConds(
359 'rev_id=page_latest',
360 'page_namespace' => $title->getNamespace(),
361 'page_title' => $title->getDBkey()
367 * Given a set of conditions, return a ResultWrapper
368 * which will return matching database rows with the
369 * fields necessary to build Revision objects.
371 * @param DatabaseBase $db
372 * @param array $conditions
373 * @param int $flags (optional)
374 * @return ResultWrapper
376 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
377 $fields = array_merge(
378 self
::selectFields(),
379 self
::selectPageFields(),
380 self
::selectUserFields()
382 $options = array( 'LIMIT' => 1 );
383 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
384 $options[] = 'FOR UPDATE';
387 array( 'revision', 'page', 'user' ),
392 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
397 * Return the value of a select() JOIN conds array for the user table.
398 * This will get user table rows for logged-in users.
402 public static function userJoinCond() {
403 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
407 * Return the value of a select() page conds array for the page table.
408 * This will assure that the revision(s) are not orphaned from live pages.
412 public static function pageJoinCond() {
413 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
417 * Return the list of revision fields that should be selected to create
421 public static function selectFields() {
422 global $wgContentHandlerUseDB;
439 if ( $wgContentHandlerUseDB ) {
440 $fields[] = 'rev_content_format';
441 $fields[] = 'rev_content_model';
448 * Return the list of revision fields that should be selected to create
449 * a new revision from an archive row.
452 public static function selectArchiveFields() {
453 global $wgContentHandlerUseDB;
471 if ( $wgContentHandlerUseDB ) {
472 $fields[] = 'ar_content_format';
473 $fields[] = 'ar_content_model';
479 * Return the list of text fields that should be selected to read the
483 public static function selectTextFields() {
491 * Return the list of page fields that should be selected from page table
494 public static function selectPageFields() {
506 * Return the list of user fields that should be selected from user table
509 public static function selectUserFields() {
510 return array( 'user_name' );
514 * Do a batched query to get the parent revision lengths
515 * @param DatabaseBase $db
516 * @param array $revIds
519 public static function getParentLengths( $db, array $revIds ) {
522 return $revLens; // empty
524 $res = $db->select( 'revision',
525 array( 'rev_id', 'rev_len' ),
526 array( 'rev_id' => $revIds ),
528 foreach ( $res as $row ) {
529 $revLens[$row->rev_id
] = $row->rev_len
;
537 * @param object|array $row Either a database row or an array
538 * @throws MWException
541 function __construct( $row ) {
542 if ( is_object( $row ) ) {
543 $this->mId
= intval( $row->rev_id
);
544 $this->mPage
= intval( $row->rev_page
);
545 $this->mTextId
= intval( $row->rev_text_id
);
546 $this->mComment
= $row->rev_comment
;
547 $this->mUser
= intval( $row->rev_user
);
548 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
549 $this->mTimestamp
= $row->rev_timestamp
;
550 $this->mDeleted
= intval( $row->rev_deleted
);
552 if ( !isset( $row->rev_parent_id
) ) {
553 $this->mParentId
= null;
555 $this->mParentId
= intval( $row->rev_parent_id
);
558 if ( !isset( $row->rev_len
) ) {
561 $this->mSize
= intval( $row->rev_len
);
564 if ( !isset( $row->rev_sha1
) ) {
567 $this->mSha1
= $row->rev_sha1
;
570 if ( isset( $row->page_latest
) ) {
571 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
572 $this->mTitle
= Title
::newFromRow( $row );
574 $this->mCurrent
= false;
575 $this->mTitle
= null;
578 if ( !isset( $row->rev_content_model
) ) {
579 $this->mContentModel
= null; # determine on demand if needed
581 $this->mContentModel
= strval( $row->rev_content_model
);
584 if ( !isset( $row->rev_content_format
) ) {
585 $this->mContentFormat
= null; # determine on demand if needed
587 $this->mContentFormat
= strval( $row->rev_content_format
);
590 // Lazy extraction...
592 if ( isset( $row->old_text
) ) {
593 $this->mTextRow
= $row;
595 // 'text' table row entry will be lazy-loaded
596 $this->mTextRow
= null;
599 // Use user_name for users and rev_user_text for IPs...
600 $this->mUserText
= null; // lazy load if left null
601 if ( $this->mUser
== 0 ) {
602 $this->mUserText
= $row->rev_user_text
; // IP user
603 } elseif ( isset( $row->user_name
) ) {
604 $this->mUserText
= $row->user_name
; // logged-in user
606 $this->mOrigUserText
= $row->rev_user_text
;
607 } elseif ( is_array( $row ) ) {
608 // Build a new revision to be saved...
609 global $wgUser; // ugh
611 # if we have a content object, use it to set the model and type
612 if ( !empty( $row['content'] ) ) {
613 // @todo when is that set? test with external store setup! check out insertOn() [dk]
614 if ( !empty( $row['text_id'] ) ) {
615 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
616 "can't serialize content object" );
619 $row['content_model'] = $row['content']->getModel();
620 # note: mContentFormat is initializes later accordingly
621 # note: content is serialized later in this method!
622 # also set text to null?
625 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
626 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
627 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
628 $this->mUserText
= isset( $row['user_text'] )
629 ?
strval( $row['user_text'] ) : $wgUser->getName();
630 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
631 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
632 $this->mTimestamp
= isset( $row['timestamp'] )
633 ?
strval( $row['timestamp'] ) : wfTimestampNow();
634 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
635 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
636 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
637 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
639 $this->mContentModel
= isset( $row['content_model'] )
640 ?
strval( $row['content_model'] ) : null;
641 $this->mContentFormat
= isset( $row['content_format'] )
642 ?
strval( $row['content_format'] ) : null;
644 // Enforce spacing trimming on supplied text
645 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
646 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
647 $this->mTextRow
= null;
649 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
651 // if we have a Content object, override mText and mContentModel
652 if ( !empty( $row['content'] ) ) {
653 if ( !( $row['content'] instanceof Content
) ) {
654 throw new MWException( '`content` field must contain a Content object.' );
657 $handler = $this->getContentHandler();
658 $this->mContent
= $row['content'];
660 $this->mContentModel
= $this->mContent
->getModel();
661 $this->mContentHandler
= null;
663 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
664 } elseif ( $this->mText
!== null ) {
665 $handler = $this->getContentHandler();
666 $this->mContent
= $handler->unserializeContent( $this->mText
);
669 // If we have a Title object, make sure it is consistent with mPage.
670 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
671 if ( $this->mPage
=== null ) {
672 // if the page ID wasn't known, set it now
673 $this->mPage
= $this->mTitle
->getArticleID();
674 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
675 // Got different page IDs. This may be legit (e.g. during undeletion),
676 // but it seems worth mentioning it in the log.
677 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
678 $this->mTitle
->getArticleID() . " provided by the Title object." );
682 $this->mCurrent
= false;
684 // If we still have no length, see it we have the text to figure it out
685 if ( !$this->mSize
&& $this->mContent
!== null ) {
686 $this->mSize
= $this->mContent
->getSize();
690 if ( $this->mSha1
=== null ) {
691 $this->mSha1
= $this->mText
=== null ?
null : self
::base36Sha1( $this->mText
);
695 $this->getContentModel();
696 $this->getContentFormat();
698 throw new MWException( 'Revision constructor passed invalid row format.' );
700 $this->mUnpatrolled
= null;
708 public function getId() {
713 * Set the revision ID
718 public function setId( $id ) {
727 public function getTextId() {
728 return $this->mTextId
;
732 * Get parent revision ID (the original previous page revision)
736 public function getParentId() {
737 return $this->mParentId
;
741 * Returns the length of the text in this revision, or null if unknown.
745 public function getSize() {
750 * Returns the base36 sha1 of the text in this revision, or null if unknown.
752 * @return string|null
754 public function getSha1() {
759 * Returns the title of the page associated with this entry or null.
761 * Will do a query, when title is not set and id is given.
765 public function getTitle() {
766 if ( $this->mTitle
!== null ) {
767 return $this->mTitle
;
769 //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
770 if ( $this->mId
!== null ) {
771 $dbr = wfGetDB( DB_SLAVE
);
772 $row = $dbr->selectRow(
773 array( 'page', 'revision' ),
774 self
::selectPageFields(),
775 array( 'page_id=rev_page',
776 'rev_id' => $this->mId
),
779 $this->mTitle
= Title
::newFromRow( $row );
783 if ( !$this->mTitle
&& $this->mPage
!== null && $this->mPage
> 0 ) {
784 $this->mTitle
= Title
::newFromID( $this->mPage
);
787 return $this->mTitle
;
791 * Set the title of the revision
793 * @param Title $title
795 public function setTitle( $title ) {
796 $this->mTitle
= $title;
804 public function getPage() {
809 * Fetch revision's user id if it's available to the specified audience.
810 * If the specified audience does not have access to it, zero will be
813 * @param int $audience One of:
814 * Revision::FOR_PUBLIC to be displayed to all users
815 * Revision::FOR_THIS_USER to be displayed to the given user
816 * Revision::RAW get the ID regardless of permissions
817 * @param User $user User object to check for, only if FOR_THIS_USER is passed
818 * to the $audience parameter
821 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
822 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
824 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
832 * Fetch revision's user id without regard for the current user's permissions
835 * @deprecated since 1.25, use getUser( Revision::RAW )
837 public function getRawUser() {
838 wfDeprecated( __METHOD__
, '1.25' );
839 return $this->getUser( self
::RAW
);
843 * Fetch revision's username if it's available to the specified audience.
844 * If the specified audience does not have access to the username, an
845 * empty string will be returned.
847 * @param int $audience One of:
848 * Revision::FOR_PUBLIC to be displayed to all users
849 * Revision::FOR_THIS_USER to be displayed to the given user
850 * Revision::RAW get the text regardless of permissions
851 * @param User $user User object to check for, only if FOR_THIS_USER is passed
852 * to the $audience parameter
855 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
856 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
858 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
861 if ( $this->mUserText
=== null ) {
862 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
863 if ( $this->mUserText
=== false ) {
864 # This shouldn't happen, but it can if the wiki was recovered
865 # via importing revs and there is no user table entry yet.
866 $this->mUserText
= $this->mOrigUserText
;
869 return $this->mUserText
;
874 * Fetch revision's username without regard for view restrictions
877 * @deprecated since 1.25, use getUserText( Revision::RAW )
879 public function getRawUserText() {
880 wfDeprecated( __METHOD__
, '1.25' );
881 return $this->getUserText( self
::RAW
);
885 * Fetch revision comment if it's available to the specified audience.
886 * If the specified audience does not have access to the comment, an
887 * empty string will be returned.
889 * @param int $audience One of:
890 * Revision::FOR_PUBLIC to be displayed to all users
891 * Revision::FOR_THIS_USER to be displayed to the given user
892 * Revision::RAW get the text regardless of permissions
893 * @param User $user User object to check for, only if FOR_THIS_USER is passed
894 * to the $audience parameter
897 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
898 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
900 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
903 return $this->mComment
;
908 * Fetch revision comment without regard for the current user's permissions
911 * @deprecated since 1.25, use getComment( Revision::RAW )
913 public function getRawComment() {
914 wfDeprecated( __METHOD__
, '1.25' );
915 return $this->getComment( self
::RAW
);
921 public function isMinor() {
922 return (bool)$this->mMinorEdit
;
926 * @return int Rcid of the unpatrolled row, zero if there isn't one
928 public function isUnpatrolled() {
929 if ( $this->mUnpatrolled
!== null ) {
930 return $this->mUnpatrolled
;
932 $rc = $this->getRecentChange();
933 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
934 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
936 $this->mUnpatrolled
= 0;
938 return $this->mUnpatrolled
;
942 * Get the RC object belonging to the current revision, if there's one
945 * @return RecentChange|null
947 public function getRecentChange() {
948 $dbr = wfGetDB( DB_SLAVE
);
949 return RecentChange
::newFromConds(
951 'rc_user_text' => $this->getUserText( Revision
::RAW
),
952 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
953 'rc_this_oldid' => $this->getId()
960 * @param int $field One of DELETED_* bitfield constants
964 public function isDeleted( $field ) {
965 return ( $this->mDeleted
& $field ) == $field;
969 * Get the deletion bitfield of the revision
973 public function getVisibility() {
974 return (int)$this->mDeleted
;
978 * Fetch revision text if it's available to the specified audience.
979 * If the specified audience does not have the ability to view this
980 * revision, an empty string will be returned.
982 * @param int $audience One of:
983 * Revision::FOR_PUBLIC to be displayed to all users
984 * Revision::FOR_THIS_USER to be displayed to the given user
985 * Revision::RAW get the text regardless of permissions
986 * @param User $user User object to check for, only if FOR_THIS_USER is passed
987 * to the $audience parameter
989 * @deprecated since 1.21, use getContent() instead
990 * @todo Replace usage in core
993 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
994 ContentHandler
::deprecated( __METHOD__
, '1.21' );
996 $content = $this->getContent( $audience, $user );
997 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
1001 * Fetch revision content if it's available to the specified audience.
1002 * If the specified audience does not have the ability to view this
1003 * revision, null will be returned.
1005 * @param int $audience One of:
1006 * Revision::FOR_PUBLIC to be displayed to all users
1007 * Revision::FOR_THIS_USER to be displayed to $wgUser
1008 * Revision::RAW get the text regardless of permissions
1009 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1010 * to the $audience parameter
1012 * @return Content|null
1014 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1015 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1017 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1020 return $this->getContentInternal();
1025 * Fetch revision text without regard for view restrictions
1029 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
1030 * or Revision::getSerializedData() as appropriate.
1032 public function getRawText() {
1033 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1034 return $this->getText( self
::RAW
);
1038 * Fetch original serialized data without regard for view restrictions
1043 public function getSerializedData() {
1044 if ( $this->mText
=== null ) {
1045 $this->mText
= $this->loadText();
1048 return $this->mText
;
1052 * Gets the content object for the revision (or null on failure).
1054 * Note that for mutable Content objects, each call to this method will return a
1058 * @return Content|null The Revision's content, or null on failure.
1060 protected function getContentInternal() {
1061 if ( $this->mContent
=== null ) {
1062 // Revision is immutable. Load on demand:
1063 if ( $this->mText
=== null ) {
1064 $this->mText
= $this->loadText();
1067 if ( $this->mText
!== null && $this->mText
!== false ) {
1068 // Unserialize content
1069 $handler = $this->getContentHandler();
1070 $format = $this->getContentFormat();
1072 $this->mContent
= $handler->unserializeContent( $this->mText
, $format );
1076 // NOTE: copy() will return $this for immutable content objects
1077 return $this->mContent ?
$this->mContent
->copy() : null;
1081 * Returns the content model for this revision.
1083 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
1084 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1085 * is used as a last resort.
1087 * @return string The content model id associated with this revision,
1088 * see the CONTENT_MODEL_XXX constants.
1090 public function getContentModel() {
1091 if ( !$this->mContentModel
) {
1092 $title = $this->getTitle();
1093 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
1095 assert( !empty( $this->mContentModel
) );
1098 return $this->mContentModel
;
1102 * Returns the content format for this revision.
1104 * If no content format was stored in the database, the default format for this
1105 * revision's content model is returned.
1107 * @return string The content format id associated with this revision,
1108 * see the CONTENT_FORMAT_XXX constants.
1110 public function getContentFormat() {
1111 if ( !$this->mContentFormat
) {
1112 $handler = $this->getContentHandler();
1113 $this->mContentFormat
= $handler->getDefaultFormat();
1115 assert( !empty( $this->mContentFormat
) );
1118 return $this->mContentFormat
;
1122 * Returns the content handler appropriate for this revision's content model.
1124 * @throws MWException
1125 * @return ContentHandler
1127 public function getContentHandler() {
1128 if ( !$this->mContentHandler
) {
1129 $model = $this->getContentModel();
1130 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1132 $format = $this->getContentFormat();
1134 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1135 throw new MWException( "Oops, the content format $format is not supported for "
1136 . "this content model, $model" );
1140 return $this->mContentHandler
;
1146 public function getTimestamp() {
1147 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1153 public function isCurrent() {
1154 return $this->mCurrent
;
1158 * Get previous revision for this title
1160 * @return Revision|null
1162 public function getPrevious() {
1163 if ( $this->getTitle() ) {
1164 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1166 return self
::newFromTitle( $this->getTitle(), $prev );
1173 * Get next revision for this title
1175 * @return Revision|null
1177 public function getNext() {
1178 if ( $this->getTitle() ) {
1179 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1181 return self
::newFromTitle( $this->getTitle(), $next );
1188 * Get previous revision Id for this page_id
1189 * This is used to populate rev_parent_id on save
1191 * @param DatabaseBase $db
1194 private function getPreviousRevisionId( $db ) {
1195 if ( $this->mPage
=== null ) {
1198 # Use page_latest if ID is not given
1199 if ( !$this->mId
) {
1200 $prevId = $db->selectField( 'page', 'page_latest',
1201 array( 'page_id' => $this->mPage
),
1204 $prevId = $db->selectField( 'revision', 'rev_id',
1205 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1207 array( 'ORDER BY' => 'rev_id DESC' ) );
1209 return intval( $prevId );
1213 * Get revision text associated with an old or archive row
1214 * $row is usually an object from wfFetchRow(), both the flags and the text
1215 * field must be included.
1217 * @param stdClass $row The text data
1218 * @param string $prefix Table prefix (default 'old_')
1219 * @param string|bool $wiki The name of the wiki to load the revision text from
1220 * (same as the the wiki $row was loaded from) or false to indicate the local
1221 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1222 * identifier as understood by the LoadBalancer class.
1223 * @return string Text the text requested or false on failure
1225 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1228 $textField = $prefix . 'text';
1229 $flagsField = $prefix . 'flags';
1231 if ( isset( $row->$flagsField ) ) {
1232 $flags = explode( ',', $row->$flagsField );
1237 if ( isset( $row->$textField ) ) {
1238 $text = $row->$textField;
1243 # Use external methods for external objects, text in table is URL-only then
1244 if ( in_array( 'external', $flags ) ) {
1246 $parts = explode( '://', $url, 2 );
1247 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1250 $text = ExternalStore
::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1253 // If the text was fetched without an error, convert it
1254 if ( $text !== false ) {
1255 $text = self
::decompressRevisionText( $text, $flags );
1261 * If $wgCompressRevisions is enabled, we will compress data.
1262 * The input string is modified in place.
1263 * Return value is the flags field: contains 'gzip' if the
1264 * data is compressed, and 'utf-8' if we're saving in UTF-8
1267 * @param mixed $text Reference to a text
1270 public static function compressRevisionText( &$text ) {
1271 global $wgCompressRevisions;
1274 # Revisions not marked this way will be converted
1275 # on load if $wgLegacyCharset is set in the future.
1278 if ( $wgCompressRevisions ) {
1279 if ( function_exists( 'gzdeflate' ) ) {
1280 $text = gzdeflate( $text );
1283 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1286 return implode( ',', $flags );
1290 * Re-converts revision text according to it's flags.
1292 * @param mixed $text Reference to a text
1293 * @param array $flags Compression flags
1294 * @return string|bool Decompressed text, or false on failure
1296 public static function decompressRevisionText( $text, $flags ) {
1297 if ( in_array( 'gzip', $flags ) ) {
1298 # Deal with optional compression of archived pages.
1299 # This can be done periodically via maintenance/compressOld.php, and
1300 # as pages are saved if $wgCompressRevisions is set.
1301 $text = gzinflate( $text );
1304 if ( in_array( 'object', $flags ) ) {
1305 # Generic compressed storage
1306 $obj = unserialize( $text );
1307 if ( !is_object( $obj ) ) {
1311 $text = $obj->getText();
1314 global $wgLegacyEncoding;
1315 if ( $text !== false && $wgLegacyEncoding
1316 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1318 # Old revisions kept around in a legacy encoding?
1319 # Upconvert on demand.
1320 # ("utf8" checked for compatibility with some broken
1321 # conversion scripts 2008-12-30)
1323 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1330 * Insert a new revision into the database, returning the new revision ID
1331 * number on success and dies horribly on failure.
1333 * @param DatabaseBase $dbw (master connection)
1334 * @throws MWException
1337 public function insertOn( $dbw ) {
1338 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1340 $this->checkContentModel();
1342 $data = $this->mText
;
1343 $flags = self
::compressRevisionText( $data );
1345 # Write to external storage if required
1346 if ( $wgDefaultExternalStore ) {
1347 // Store and get the URL
1348 $data = ExternalStore
::insertToDefault( $data );
1350 throw new MWException( "Unable to store text to external storage" );
1355 $flags .= 'external';
1358 # Record the text (or external storage URL) to the text table
1359 if ( $this->mTextId
=== null ) {
1360 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1361 $dbw->insert( 'text',
1363 'old_id' => $old_id,
1364 'old_text' => $data,
1365 'old_flags' => $flags,
1368 $this->mTextId
= $dbw->insertId();
1371 if ( $this->mComment
=== null ) {
1372 $this->mComment
= "";
1375 # Record the edit in revisions
1376 $rev_id = $this->mId
!== null
1378 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1380 'rev_id' => $rev_id,
1381 'rev_page' => $this->mPage
,
1382 'rev_text_id' => $this->mTextId
,
1383 'rev_comment' => $this->mComment
,
1384 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1385 'rev_user' => $this->mUser
,
1386 'rev_user_text' => $this->mUserText
,
1387 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1388 'rev_deleted' => $this->mDeleted
,
1389 'rev_len' => $this->mSize
,
1390 'rev_parent_id' => $this->mParentId
=== null
1391 ?
$this->getPreviousRevisionId( $dbw )
1393 'rev_sha1' => $this->mSha1
=== null
1394 ? Revision
::base36Sha1( $this->mText
)
1398 if ( $wgContentHandlerUseDB ) {
1399 //NOTE: Store null for the default model and format, to save space.
1400 //XXX: Makes the DB sensitive to changed defaults.
1401 // Make this behavior optional? Only in miser mode?
1403 $model = $this->getContentModel();
1404 $format = $this->getContentFormat();
1406 $title = $this->getTitle();
1408 if ( $title === null ) {
1409 throw new MWException( "Insufficient information to determine the title of the "
1410 . "revision's page!" );
1413 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1414 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1416 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1417 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1420 $dbw->insert( 'revision', $row, __METHOD__
);
1422 $this->mId
= $rev_id !== null ?
$rev_id : $dbw->insertId();
1424 Hooks
::run( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1429 protected function checkContentModel() {
1430 global $wgContentHandlerUseDB;
1432 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1434 $model = $this->getContentModel();
1435 $format = $this->getContentFormat();
1436 $handler = $this->getContentHandler();
1438 if ( !$handler->isSupportedFormat( $format ) ) {
1439 $t = $title->getPrefixedDBkey();
1441 throw new MWException( "Can't use format $format with content model $model on $t" );
1444 if ( !$wgContentHandlerUseDB && $title ) {
1445 // if $wgContentHandlerUseDB is not set,
1446 // all revisions must use the default content model and format.
1448 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1449 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1450 $defaultFormat = $defaultHandler->getDefaultFormat();
1452 if ( $this->getContentModel() != $defaultModel ) {
1453 $t = $title->getPrefixedDBkey();
1455 throw new MWException( "Can't save non-default content model with "
1456 . "\$wgContentHandlerUseDB disabled: model is $model, "
1457 . "default for $t is $defaultModel" );
1460 if ( $this->getContentFormat() != $defaultFormat ) {
1461 $t = $title->getPrefixedDBkey();
1463 throw new MWException( "Can't use non-default content format with "
1464 . "\$wgContentHandlerUseDB disabled: format is $format, "
1465 . "default for $t is $defaultFormat" );
1469 $content = $this->getContent( Revision
::RAW
);
1471 if ( !$content ||
!$content->isValid() ) {
1472 $t = $title->getPrefixedDBkey();
1474 throw new MWException( "Content of $t is not valid! Content model is $model" );
1479 * Get the base 36 SHA-1 value for a string of text
1480 * @param string $text
1483 public static function base36Sha1( $text ) {
1484 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1488 * Lazy-load the revision's text.
1489 * Currently hardcoded to the 'text' table storage engine.
1491 * @return string|bool The revision's text, or false on failure
1493 protected function loadText() {
1495 // Caching may be beneficial for massive use of external storage
1496 global $wgRevisionCacheExpiry, $wgMemc;
1497 $textId = $this->getTextId();
1498 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1499 if ( $wgRevisionCacheExpiry ) {
1500 $text = $wgMemc->get( $key );
1501 if ( is_string( $text ) ) {
1502 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1507 // If we kept data for lazy extraction, use it now...
1508 if ( $this->mTextRow
!== null ) {
1509 $row = $this->mTextRow
;
1510 $this->mTextRow
= null;
1516 // Text data is immutable; check slaves first.
1517 $dbr = wfGetDB( DB_SLAVE
);
1518 $row = $dbr->selectRow( 'text',
1519 array( 'old_text', 'old_flags' ),
1520 array( 'old_id' => $textId ),
1524 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1525 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1526 $forUpdate = ( $this->mQueryFlags
& self
::READ_LOCKING
== self
::READ_LOCKING
);
1527 if ( !$row && ( $forUpdate ||
wfGetLB()->getServerCount() > 1 ) ) {
1528 $dbw = wfGetDB( DB_MASTER
);
1529 $row = $dbw->selectRow( 'text',
1530 array( 'old_text', 'old_flags' ),
1531 array( 'old_id' => $textId ),
1533 $forUpdate ?
array( 'FOR UPDATE' ) : array() );
1537 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1540 $text = self
::getRevisionText( $row );
1541 if ( $row && $text === false ) {
1542 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1545 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1546 if ( $wgRevisionCacheExpiry && $text !== false ) {
1547 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1554 * Create a new null-revision for insertion into a page's
1555 * history. This will not re-save the text, but simply refer
1556 * to the text from the previous version.
1558 * Such revisions can for instance identify page rename
1559 * operations and other such meta-modifications.
1561 * @param DatabaseBase $dbw
1562 * @param int $pageId ID number of the page to read from
1563 * @param string $summary Revision's summary
1564 * @param bool $minor Whether the revision should be considered as minor
1565 * @param User|null $user User object to use or null for $wgUser
1566 * @return Revision|null Revision or null on error
1568 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1569 global $wgContentHandlerUseDB;
1571 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1572 'rev_text_id', 'rev_len', 'rev_sha1' );
1574 if ( $wgContentHandlerUseDB ) {
1575 $fields[] = 'rev_content_model';
1576 $fields[] = 'rev_content_format';
1579 $current = $dbw->selectRow(
1580 array( 'page', 'revision' ),
1583 'page_id' => $pageId,
1584 'page_latest=rev_id',
1596 'user_text' => $user->getName(),
1597 'user' => $user->getId(),
1598 'comment' => $summary,
1599 'minor_edit' => $minor,
1600 'text_id' => $current->rev_text_id
,
1601 'parent_id' => $current->page_latest
,
1602 'len' => $current->rev_len
,
1603 'sha1' => $current->rev_sha1
1606 if ( $wgContentHandlerUseDB ) {
1607 $row['content_model'] = $current->rev_content_model
;
1608 $row['content_format'] = $current->rev_content_format
;
1611 $revision = new Revision( $row );
1612 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1621 * Determine if the current user is allowed to view a particular
1622 * field of this revision, if it's marked as deleted.
1624 * @param int $field One of self::DELETED_TEXT,
1625 * self::DELETED_COMMENT,
1626 * self::DELETED_USER
1627 * @param User|null $user User object to check, or null to use $wgUser
1630 public function userCan( $field, User
$user = null ) {
1631 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1635 * Determine if the current user is allowed to view a particular
1636 * field of this revision, if it's marked as deleted. This is used
1637 * by various classes to avoid duplication.
1639 * @param int $bitfield Current field
1640 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1641 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1642 * self::DELETED_USER = File::DELETED_USER
1643 * @param User|null $user User object to check, or null to use $wgUser
1644 * @param Title|null $title A Title object to check for per-page restrictions on,
1645 * instead of just plain userrights
1648 public static function userCanBitfield( $bitfield, $field, User
$user = null,
1651 if ( $bitfield & $field ) { // aspect is deleted
1652 if ( $user === null ) {
1656 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1657 $permissions = array( 'suppressrevision', 'viewsuppressed' );
1658 } elseif ( $field & self
::DELETED_TEXT
) {
1659 $permissions = array( 'deletedtext' );
1661 $permissions = array( 'deletedhistory' );
1663 $permissionlist = implode( ', ', $permissions );
1664 if ( $title === null ) {
1665 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1666 return call_user_func_array( array( $user, 'isAllowedAny' ), $permissions );
1668 $text = $title->getPrefixedText();
1669 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1670 foreach ( $permissions as $perm ) {
1671 if ( $title->userCan( $perm, $user ) ) {
1683 * Get rev_timestamp from rev_id, without loading the rest of the row
1685 * @param Title $title
1689 static function getTimestampFromId( $title, $id ) {
1690 $dbr = wfGetDB( DB_SLAVE
);
1691 // Casting fix for databases that can't take '' for rev_id
1695 $conds = array( 'rev_id' => $id );
1696 $conds['rev_page'] = $title->getArticleID();
1697 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1698 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1699 # Not in slave, try master
1700 $dbw = wfGetDB( DB_MASTER
);
1701 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1703 return wfTimestamp( TS_MW
, $timestamp );
1707 * Get count of revisions per page...not very efficient
1709 * @param DatabaseBase $db
1710 * @param int $id Page id
1713 static function countByPageId( $db, $id ) {
1714 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1715 array( 'rev_page' => $id ), __METHOD__
);
1717 return $row->revCount
;
1723 * Get count of revisions per page...not very efficient
1725 * @param DatabaseBase $db
1726 * @param Title $title
1729 static function countByTitle( $db, $title ) {
1730 $id = $title->getArticleID();
1732 return self
::countByPageId( $db, $id );
1738 * Check if no edits were made by other users since
1739 * the time a user started editing the page. Limit to
1740 * 50 revisions for the sake of performance.
1743 * @deprecated since 1.24
1745 * @param DatabaseBase|int $db The Database to perform the check on. May be given as a
1746 * Database object or a database identifier usable with wfGetDB.
1747 * @param int $pageId The ID of the page in question
1748 * @param int $userId The ID of the user in question
1749 * @param string $since Look at edits since this time
1751 * @return bool True if the given user was the only one to edit since the given timestamp
1753 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1758 if ( is_int( $db ) ) {
1759 $db = wfGetDB( $db );
1762 $res = $db->select( 'revision',
1765 'rev_page' => $pageId,
1766 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1769 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1770 foreach ( $res as $row ) {
1771 if ( $row->rev_user
!= $userId ) {