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;
67 protected $mQueryFlags = 0;
69 // Revision deletion constants
70 const DELETED_TEXT
= 1;
71 const DELETED_COMMENT
= 2;
72 const DELETED_USER
= 4;
73 const DELETED_RESTRICTED
= 8;
74 const SUPPRESSED_USER
= 12; // convenience
76 // Audience options for accessors
78 const FOR_THIS_USER
= 2;
82 * Load a page revision from a given revision ID number.
83 * Returns null if no such revision can be found.
86 * Revision::READ_LATEST : Select the data from the master
87 * Revision::READ_LOCKING : Select & lock the data from the master
90 * @param int $flags (optional)
91 * @return Revision|null
93 public static function newFromId( $id, $flags = 0 ) {
94 return self
::newFromConds( array( 'rev_id' => intval( $id ) ), $flags );
98 * Load either the current, or a specified, revision
99 * that's attached to a given title. If not attached
100 * to that title, will return null.
103 * Revision::READ_LATEST : Select the data from the master
104 * Revision::READ_LOCKING : Select & lock the data from the master
106 * @param Title $title
107 * @param int $id (optional)
108 * @param int $flags Bitfield (optional)
109 * @return Revision|null
111 public static function newFromTitle( $title, $id = 0, $flags = 0 ) {
113 'page_namespace' => $title->getNamespace(),
114 'page_title' => $title->getDBkey()
117 // Use the specified ID
118 $conds['rev_id'] = $id;
119 return self
::newFromConds( $conds, (int)$flags );
121 // Use a join to get the latest revision
122 $conds[] = 'rev_id=page_latest';
123 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
124 return self
::loadFromConds( $db, $conds, $flags );
129 * Load either the current, or a specified, revision
130 * that's attached to a given page ID.
131 * Returns null if no such revision can be found.
134 * Revision::READ_LATEST : Select the data from the master (since 1.20)
135 * Revision::READ_LOCKING : Select & lock the data from the master
138 * @param int $revId (optional)
139 * @param int $flags Bitfield (optional)
140 * @return Revision|null
142 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
143 $conds = array( 'page_id' => $pageId );
145 $conds['rev_id'] = $revId;
147 // Use a join to get the latest revision
148 $conds[] = 'rev_id = page_latest';
150 return self
::newFromConds( $conds, (int)$flags );
154 * Make a fake revision object from an archive table row. This is queried
155 * for permissions or even inserted (as in Special:Undelete)
156 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
159 * @param array $overrides
161 * @throws MWException
164 public static function newFromArchiveRow( $row, $overrides = array() ) {
165 global $wgContentHandlerUseDB;
167 $attribs = $overrides +
array(
168 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
169 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
170 'comment' => $row->ar_comment
,
171 'user' => $row->ar_user
,
172 'user_text' => $row->ar_user_text
,
173 'timestamp' => $row->ar_timestamp
,
174 'minor_edit' => $row->ar_minor_edit
,
175 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
176 'deleted' => $row->ar_deleted
,
177 'len' => $row->ar_len
,
178 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
179 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
180 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
183 if ( !$wgContentHandlerUseDB ) {
184 unset( $attribs['content_model'] );
185 unset( $attribs['content_format'] );
188 if ( !isset( $attribs['title'] )
189 && isset( $row->ar_namespace
)
190 && isset( $row->ar_title
) ) {
192 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
195 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
196 // Pre-1.5 ar_text row
197 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
198 if ( $attribs['text'] === false ) {
199 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
202 return new self( $attribs );
211 public static function newFromRow( $row ) {
212 return new self( $row );
216 * Load a page revision from a given revision ID number.
217 * Returns null if no such revision can be found.
219 * @param DatabaseBase $db
221 * @return Revision|null
223 public static function loadFromId( $db, $id ) {
224 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
228 * Load either the current, or a specified, revision
229 * that's attached to a given page. If not attached
230 * to that page, will return null.
232 * @param DatabaseBase $db
235 * @return Revision|null
237 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
238 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
240 $conds['rev_id'] = intval( $id );
242 $conds[] = 'rev_id=page_latest';
244 return self
::loadFromConds( $db, $conds );
248 * Load either the current, or a specified, revision
249 * that's attached to a given page. If not attached
250 * to that page, will return null.
252 * @param DatabaseBase $db
253 * @param Title $title
255 * @return Revision|null
257 public static function loadFromTitle( $db, $title, $id = 0 ) {
259 $matchId = intval( $id );
261 $matchId = 'page_latest';
263 return self
::loadFromConds( $db,
266 'page_namespace' => $title->getNamespace(),
267 'page_title' => $title->getDBkey()
273 * Load the revision for the given title with the given timestamp.
274 * WARNING: Timestamps may in some circumstances not be unique,
275 * so this isn't the best key to use.
277 * @param DatabaseBase $db
278 * @param Title $title
279 * @param string $timestamp
280 * @return Revision|null
282 public static function loadFromTimestamp( $db, $title, $timestamp ) {
283 return self
::loadFromConds( $db,
285 'rev_timestamp' => $db->timestamp( $timestamp ),
286 'page_namespace' => $title->getNamespace(),
287 'page_title' => $title->getDBkey()
293 * Given a set of conditions, fetch a revision.
295 * @param array $conditions
296 * @param int $flags (optional)
297 * @return Revision|null
299 private static function newFromConds( $conditions, $flags = 0 ) {
300 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
301 $rev = self
::loadFromConds( $db, $conditions, $flags );
302 if ( is_null( $rev ) && wfGetLB()->getServerCount() > 1 ) {
303 if ( !( $flags & self
::READ_LATEST
) ) {
304 $dbw = wfGetDB( DB_MASTER
);
305 $rev = self
::loadFromConds( $dbw, $conditions, $flags );
309 $rev->mQueryFlags
= $flags;
315 * Given a set of conditions, fetch a revision from
316 * the given database connection.
318 * @param DatabaseBase $db
319 * @param array $conditions
320 * @param int $flags (optional)
321 * @return Revision|null
323 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
324 $res = self
::fetchFromConds( $db, $conditions, $flags );
326 $row = $res->fetchObject();
328 $ret = new Revision( $row );
337 * Return a wrapper for a series of database rows to
338 * fetch all of a given page's revisions in turn.
339 * Each row can be fed to the constructor to get objects.
341 * @param Title $title
342 * @return ResultWrapper
344 public static function fetchRevision( $title ) {
345 return self
::fetchFromConds(
348 'rev_id=page_latest',
349 'page_namespace' => $title->getNamespace(),
350 'page_title' => $title->getDBkey()
356 * Given a set of conditions, return a ResultWrapper
357 * which will return matching database rows with the
358 * fields necessary to build Revision objects.
360 * @param DatabaseBase $db
361 * @param array $conditions
362 * @param int $flags (optional)
363 * @return ResultWrapper
365 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
366 $fields = array_merge(
367 self
::selectFields(),
368 self
::selectPageFields(),
369 self
::selectUserFields()
371 $options = array( 'LIMIT' => 1 );
372 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
373 $options[] = 'FOR UPDATE';
376 array( 'revision', 'page', 'user' ),
381 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
386 * Return the value of a select() JOIN conds array for the user table.
387 * This will get user table rows for logged-in users.
391 public static function userJoinCond() {
392 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
396 * Return the value of a select() page conds array for the page table.
397 * This will assure that the revision(s) are not orphaned from live pages.
401 public static function pageJoinCond() {
402 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
406 * Return the list of revision fields that should be selected to create
410 public static function selectFields() {
411 global $wgContentHandlerUseDB;
428 if ( $wgContentHandlerUseDB ) {
429 $fields[] = 'rev_content_format';
430 $fields[] = 'rev_content_model';
437 * Return the list of revision fields that should be selected to create
438 * a new revision from an archive row.
441 public static function selectArchiveFields() {
442 global $wgContentHandlerUseDB;
459 if ( $wgContentHandlerUseDB ) {
460 $fields[] = 'ar_content_format';
461 $fields[] = 'ar_content_model';
467 * Return the list of text fields that should be selected to read the
471 public static function selectTextFields() {
479 * Return the list of page fields that should be selected from page table
482 public static function selectPageFields() {
494 * Return the list of user fields that should be selected from user table
497 public static function selectUserFields() {
498 return array( 'user_name' );
502 * Do a batched query to get the parent revision lengths
503 * @param DatabaseBase $db
504 * @param array $revIds
507 public static function getParentLengths( $db, array $revIds ) {
510 return $revLens; // empty
512 wfProfileIn( __METHOD__
);
513 $res = $db->select( 'revision',
514 array( 'rev_id', 'rev_len' ),
515 array( 'rev_id' => $revIds ),
517 foreach ( $res as $row ) {
518 $revLens[$row->rev_id
] = $row->rev_len
;
520 wfProfileOut( __METHOD__
);
527 * @param object $row Either a database row or an array
528 * @throws MWException
531 function __construct( $row ) {
532 if ( is_object( $row ) ) {
533 $this->mId
= intval( $row->rev_id
);
534 $this->mPage
= intval( $row->rev_page
);
535 $this->mTextId
= intval( $row->rev_text_id
);
536 $this->mComment
= $row->rev_comment
;
537 $this->mUser
= intval( $row->rev_user
);
538 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
539 $this->mTimestamp
= $row->rev_timestamp
;
540 $this->mDeleted
= intval( $row->rev_deleted
);
542 if ( !isset( $row->rev_parent_id
) ) {
543 $this->mParentId
= null;
545 $this->mParentId
= intval( $row->rev_parent_id
);
548 if ( !isset( $row->rev_len
) ) {
551 $this->mSize
= intval( $row->rev_len
);
554 if ( !isset( $row->rev_sha1
) ) {
557 $this->mSha1
= $row->rev_sha1
;
560 if ( isset( $row->page_latest
) ) {
561 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
562 $this->mTitle
= Title
::newFromRow( $row );
564 $this->mCurrent
= false;
565 $this->mTitle
= null;
568 if ( !isset( $row->rev_content_model
) ||
is_null( $row->rev_content_model
) ) {
569 $this->mContentModel
= null; # determine on demand if needed
571 $this->mContentModel
= strval( $row->rev_content_model
);
574 if ( !isset( $row->rev_content_format
) ||
is_null( $row->rev_content_format
) ) {
575 $this->mContentFormat
= null; # determine on demand if needed
577 $this->mContentFormat
= strval( $row->rev_content_format
);
580 // Lazy extraction...
582 if ( isset( $row->old_text
) ) {
583 $this->mTextRow
= $row;
585 // 'text' table row entry will be lazy-loaded
586 $this->mTextRow
= null;
589 // Use user_name for users and rev_user_text for IPs...
590 $this->mUserText
= null; // lazy load if left null
591 if ( $this->mUser
== 0 ) {
592 $this->mUserText
= $row->rev_user_text
; // IP user
593 } elseif ( isset( $row->user_name
) ) {
594 $this->mUserText
= $row->user_name
; // logged-in user
596 $this->mOrigUserText
= $row->rev_user_text
;
597 } elseif ( is_array( $row ) ) {
598 // Build a new revision to be saved...
599 global $wgUser; // ugh
601 # if we have a content object, use it to set the model and type
602 if ( !empty( $row['content'] ) ) {
603 // @todo when is that set? test with external store setup! check out insertOn() [dk]
604 if ( !empty( $row['text_id'] ) ) {
605 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
606 "can't serialize content object" );
609 $row['content_model'] = $row['content']->getModel();
610 # note: mContentFormat is initializes later accordingly
611 # note: content is serialized later in this method!
612 # also set text to null?
615 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
616 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
617 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
618 $this->mUserText
= isset( $row['user_text'] )
619 ?
strval( $row['user_text'] ) : $wgUser->getName();
620 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
621 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
622 $this->mTimestamp
= isset( $row['timestamp'] )
623 ?
strval( $row['timestamp'] ) : wfTimestampNow();
624 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
625 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
626 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
627 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
629 $this->mContentModel
= isset( $row['content_model'] )
630 ?
strval( $row['content_model'] ) : null;
631 $this->mContentFormat
= isset( $row['content_format'] )
632 ?
strval( $row['content_format'] ) : null;
634 // Enforce spacing trimming on supplied text
635 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
636 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
637 $this->mTextRow
= null;
639 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
641 // if we have a Content object, override mText and mContentModel
642 if ( !empty( $row['content'] ) ) {
643 if ( !( $row['content'] instanceof Content
) ) {
644 throw new MWException( '`content` field must contain a Content object.' );
647 $handler = $this->getContentHandler();
648 $this->mContent
= $row['content'];
650 $this->mContentModel
= $this->mContent
->getModel();
651 $this->mContentHandler
= null;
653 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
654 } elseif ( !is_null( $this->mText
) ) {
655 $handler = $this->getContentHandler();
656 $this->mContent
= $handler->unserializeContent( $this->mText
);
659 // If we have a Title object, make sure it is consistent with mPage.
660 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
661 if ( $this->mPage
=== null ) {
662 // if the page ID wasn't known, set it now
663 $this->mPage
= $this->mTitle
->getArticleID();
664 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
665 // Got different page IDs. This may be legit (e.g. during undeletion),
666 // but it seems worth mentioning it in the log.
667 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
668 $this->mTitle
->getArticleID() . " provided by the Title object." );
672 $this->mCurrent
= false;
674 // If we still have no length, see it we have the text to figure it out
675 if ( !$this->mSize
) {
676 if ( !is_null( $this->mContent
) ) {
677 $this->mSize
= $this->mContent
->getSize();
679 #NOTE: this should never happen if we have either text or content object!
685 if ( $this->mSha1
=== null ) {
686 $this->mSha1
= is_null( $this->mText
) ?
null : self
::base36Sha1( $this->mText
);
690 $this->getContentModel();
691 $this->getContentFormat();
693 throw new MWException( 'Revision constructor passed invalid row format.' );
695 $this->mUnpatrolled
= null;
703 public function getId() {
708 * Set the revision ID
713 public function setId( $id ) {
722 public function getTextId() {
723 return $this->mTextId
;
727 * Get parent revision ID (the original previous page revision)
731 public function getParentId() {
732 return $this->mParentId
;
736 * Returns the length of the text in this revision, or null if unknown.
740 public function getSize() {
745 * Returns the base36 sha1 of the text in this revision, or null if unknown.
747 * @return string|null
749 public function getSha1() {
754 * Returns the title of the page associated with this entry or null.
756 * Will do a query, when title is not set and id is given.
760 public function getTitle() {
761 if ( isset( $this->mTitle
) ) {
762 return $this->mTitle
;
764 //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
765 if ( !is_null( $this->mId
) ) {
766 $dbr = wfGetDB( DB_SLAVE
);
767 $row = $dbr->selectRow(
768 array( 'page', 'revision' ),
769 self
::selectPageFields(),
770 array( 'page_id=rev_page',
771 'rev_id' => $this->mId
),
774 $this->mTitle
= Title
::newFromRow( $row );
778 if ( !$this->mTitle
&& !is_null( $this->mPage
) && $this->mPage
> 0 ) {
779 $this->mTitle
= Title
::newFromID( $this->mPage
);
782 return $this->mTitle
;
786 * Set the title of the revision
788 * @param Title $title
790 public function setTitle( $title ) {
791 $this->mTitle
= $title;
799 public function getPage() {
804 * Fetch revision's user id if it's available to the specified audience.
805 * If the specified audience does not have access to it, zero will be
808 * @param int $audience One of:
809 * Revision::FOR_PUBLIC to be displayed to all users
810 * Revision::FOR_THIS_USER to be displayed to the given user
811 * Revision::RAW get the ID regardless of permissions
812 * @param User $user User object to check for, only if FOR_THIS_USER is passed
813 * to the $audience parameter
816 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
817 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
819 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
827 * Fetch revision's user id without regard for the current user's permissions
831 public function getRawUser() {
836 * Fetch revision's username if it's available to the specified audience.
837 * If the specified audience does not have access to the username, an
838 * empty string will be returned.
840 * @param int $audience One of:
841 * Revision::FOR_PUBLIC to be displayed to all users
842 * Revision::FOR_THIS_USER to be displayed to the given user
843 * Revision::RAW get the text regardless of permissions
844 * @param User $user User object to check for, only if FOR_THIS_USER is passed
845 * to the $audience parameter
848 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
849 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
851 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
854 return $this->getRawUserText();
859 * Fetch revision's username without regard for view restrictions
863 public function getRawUserText() {
864 if ( $this->mUserText
=== null ) {
865 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
866 if ( $this->mUserText
=== false ) {
867 # This shouldn't happen, but it can if the wiki was recovered
868 # via importing revs and there is no user table entry yet.
869 $this->mUserText
= $this->mOrigUserText
;
872 return $this->mUserText
;
876 * Fetch revision comment if it's available to the specified audience.
877 * If the specified audience does not have access to the comment, an
878 * empty string will be returned.
880 * @param int $audience One of:
881 * Revision::FOR_PUBLIC to be displayed to all users
882 * Revision::FOR_THIS_USER to be displayed to the given user
883 * Revision::RAW get the text regardless of permissions
884 * @param User $user User object to check for, only if FOR_THIS_USER is passed
885 * to the $audience parameter
888 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
889 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
891 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
894 return $this->mComment
;
899 * Fetch revision comment without regard for the current user's permissions
903 public function getRawComment() {
904 return $this->mComment
;
910 public function isMinor() {
911 return (bool)$this->mMinorEdit
;
915 * @return int Rcid of the unpatrolled row, zero if there isn't one
917 public function isUnpatrolled() {
918 if ( $this->mUnpatrolled
!== null ) {
919 return $this->mUnpatrolled
;
921 $rc = $this->getRecentChange();
922 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
923 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
925 $this->mUnpatrolled
= 0;
927 return $this->mUnpatrolled
;
931 * Get the RC object belonging to the current revision, if there's one
934 * @return RecentChange|null
936 public function getRecentChange() {
937 $dbr = wfGetDB( DB_SLAVE
);
938 return RecentChange
::newFromConds(
940 'rc_user_text' => $this->getRawUserText(),
941 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
942 'rc_this_oldid' => $this->getId()
949 * @param int $field one of DELETED_* bitfield constants
953 public function isDeleted( $field ) {
954 return ( $this->mDeleted
& $field ) == $field;
958 * Get the deletion bitfield of the revision
962 public function getVisibility() {
963 return (int)$this->mDeleted
;
967 * Fetch revision text if it's available to the specified audience.
968 * If the specified audience does not have the ability to view this
969 * revision, an empty string will be returned.
971 * @param int $audience One of:
972 * Revision::FOR_PUBLIC to be displayed to all users
973 * Revision::FOR_THIS_USER to be displayed to the given user
974 * Revision::RAW get the text regardless of permissions
975 * @param User $user User object to check for, only if FOR_THIS_USER is passed
976 * to the $audience parameter
978 * @deprecated since 1.21, use getContent() instead
979 * @todo Replace usage in core
982 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
983 ContentHandler
::deprecated( __METHOD__
, '1.21' );
985 $content = $this->getContent( $audience, $user );
986 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
990 * Fetch revision content if it's available to the specified audience.
991 * If the specified audience does not have the ability to view this
992 * revision, null will be returned.
994 * @param int $audience One of:
995 * Revision::FOR_PUBLIC to be displayed to all users
996 * Revision::FOR_THIS_USER to be displayed to $wgUser
997 * Revision::RAW get the text regardless of permissions
998 * @param User $user User object to check for, only if FOR_THIS_USER is passed
999 * to the $audience parameter
1001 * @return Content|null
1003 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1004 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1006 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1009 return $this->getContentInternal();
1014 * Fetch revision text without regard for view restrictions
1018 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
1019 * or Revision::getSerializedData() as appropriate.
1021 public function getRawText() {
1022 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1023 return $this->getText( self
::RAW
);
1027 * Fetch original serialized data without regard for view restrictions
1032 public function getSerializedData() {
1033 if ( is_null( $this->mText
) ) {
1034 $this->mText
= $this->loadText();
1037 return $this->mText
;
1041 * Gets the content object for the revision (or null on failure).
1043 * Note that for mutable Content objects, each call to this method will return a
1047 * @return Content|null The Revision's content, or null on failure.
1049 protected function getContentInternal() {
1050 if ( is_null( $this->mContent
) ) {
1051 // Revision is immutable. Load on demand:
1052 if ( is_null( $this->mText
) ) {
1053 $this->mText
= $this->loadText();
1056 if ( $this->mText
!== null && $this->mText
!== false ) {
1057 // Unserialize content
1058 $handler = $this->getContentHandler();
1059 $format = $this->getContentFormat();
1061 $this->mContent
= $handler->unserializeContent( $this->mText
, $format );
1063 $this->mContent
= false; // negative caching!
1067 // NOTE: copy() will return $this for immutable content objects
1068 return $this->mContent ?
$this->mContent
->copy() : null;
1072 * Returns the content model for this revision.
1074 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
1075 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1076 * is used as a last resort.
1078 * @return string The content model id associated with this revision,
1079 * see the CONTENT_MODEL_XXX constants.
1081 public function getContentModel() {
1082 if ( !$this->mContentModel
) {
1083 $title = $this->getTitle();
1084 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
1086 assert( !empty( $this->mContentModel
) );
1089 return $this->mContentModel
;
1093 * Returns the content format for this revision.
1095 * If no content format was stored in the database, the default format for this
1096 * revision's content model is returned.
1098 * @return string The content format id associated with this revision,
1099 * see the CONTENT_FORMAT_XXX constants.
1101 public function getContentFormat() {
1102 if ( !$this->mContentFormat
) {
1103 $handler = $this->getContentHandler();
1104 $this->mContentFormat
= $handler->getDefaultFormat();
1106 assert( !empty( $this->mContentFormat
) );
1109 return $this->mContentFormat
;
1113 * Returns the content handler appropriate for this revision's content model.
1115 * @throws MWException
1116 * @return ContentHandler
1118 public function getContentHandler() {
1119 if ( !$this->mContentHandler
) {
1120 $model = $this->getContentModel();
1121 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1123 $format = $this->getContentFormat();
1125 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1126 throw new MWException( "Oops, the content format $format is not supported for "
1127 . "this content model, $model" );
1131 return $this->mContentHandler
;
1137 public function getTimestamp() {
1138 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1144 public function isCurrent() {
1145 return $this->mCurrent
;
1149 * Get previous revision for this title
1151 * @return Revision|null
1153 public function getPrevious() {
1154 if ( $this->getTitle() ) {
1155 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1157 return self
::newFromTitle( $this->getTitle(), $prev );
1164 * Get next revision for this title
1166 * @return Revision|null
1168 public function getNext() {
1169 if ( $this->getTitle() ) {
1170 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1172 return self
::newFromTitle( $this->getTitle(), $next );
1179 * Get previous revision Id for this page_id
1180 * This is used to populate rev_parent_id on save
1182 * @param DatabaseBase $db
1185 private function getPreviousRevisionId( $db ) {
1186 if ( is_null( $this->mPage
) ) {
1189 # Use page_latest if ID is not given
1190 if ( !$this->mId
) {
1191 $prevId = $db->selectField( 'page', 'page_latest',
1192 array( 'page_id' => $this->mPage
),
1195 $prevId = $db->selectField( 'revision', 'rev_id',
1196 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1198 array( 'ORDER BY' => 'rev_id DESC' ) );
1200 return intval( $prevId );
1204 * Get revision text associated with an old or archive row
1205 * $row is usually an object from wfFetchRow(), both the flags and the text
1206 * field must be included.
1208 * @param stdClass $row The text data
1209 * @param string $prefix Table prefix (default 'old_')
1210 * @param string|bool $wiki The name of the wiki to load the revision text from
1211 * (same as the the wiki $row was loaded from) or false to indicate the local
1212 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1213 * identifier as understood by the LoadBalancer class.
1214 * @return string Text the text requested or false on failure
1216 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1217 wfProfileIn( __METHOD__
);
1220 $textField = $prefix . 'text';
1221 $flagsField = $prefix . 'flags';
1223 if ( isset( $row->$flagsField ) ) {
1224 $flags = explode( ',', $row->$flagsField );
1229 if ( isset( $row->$textField ) ) {
1230 $text = $row->$textField;
1232 wfProfileOut( __METHOD__
);
1236 # Use external methods for external objects, text in table is URL-only then
1237 if ( in_array( 'external', $flags ) ) {
1239 $parts = explode( '://', $url, 2 );
1240 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1241 wfProfileOut( __METHOD__
);
1244 $text = ExternalStore
::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1247 // If the text was fetched without an error, convert it
1248 if ( $text !== false ) {
1249 $text = self
::decompressRevisionText( $text, $flags );
1251 wfProfileOut( __METHOD__
);
1256 * If $wgCompressRevisions is enabled, we will compress data.
1257 * The input string is modified in place.
1258 * Return value is the flags field: contains 'gzip' if the
1259 * data is compressed, and 'utf-8' if we're saving in UTF-8
1262 * @param mixed $text Reference to a text
1265 public static function compressRevisionText( &$text ) {
1266 global $wgCompressRevisions;
1269 # Revisions not marked this way will be converted
1270 # on load if $wgLegacyCharset is set in the future.
1273 if ( $wgCompressRevisions ) {
1274 if ( function_exists( 'gzdeflate' ) ) {
1275 $text = gzdeflate( $text );
1278 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1281 return implode( ',', $flags );
1285 * Re-converts revision text according to it's flags.
1287 * @param mixed $text Reference to a text
1288 * @param array $flags Compression flags
1289 * @return string|bool Decompressed text, or false on failure
1291 public static function decompressRevisionText( $text, $flags ) {
1292 if ( in_array( 'gzip', $flags ) ) {
1293 # Deal with optional compression of archived pages.
1294 # This can be done periodically via maintenance/compressOld.php, and
1295 # as pages are saved if $wgCompressRevisions is set.
1296 $text = gzinflate( $text );
1299 if ( in_array( 'object', $flags ) ) {
1300 # Generic compressed storage
1301 $obj = unserialize( $text );
1302 if ( !is_object( $obj ) ) {
1306 $text = $obj->getText();
1309 global $wgLegacyEncoding;
1310 if ( $text !== false && $wgLegacyEncoding
1311 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1313 # Old revisions kept around in a legacy encoding?
1314 # Upconvert on demand.
1315 # ("utf8" checked for compatibility with some broken
1316 # conversion scripts 2008-12-30)
1318 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1325 * Insert a new revision into the database, returning the new revision ID
1326 * number on success and dies horribly on failure.
1328 * @param DatabaseBase $dbw (master connection)
1329 * @throws MWException
1332 public function insertOn( $dbw ) {
1333 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1335 wfProfileIn( __METHOD__
);
1337 $this->checkContentModel();
1339 $data = $this->mText
;
1340 $flags = self
::compressRevisionText( $data );
1342 # Write to external storage if required
1343 if ( $wgDefaultExternalStore ) {
1344 // Store and get the URL
1345 $data = ExternalStore
::insertToDefault( $data );
1347 wfProfileOut( __METHOD__
);
1348 throw new MWException( "Unable to store text to external storage" );
1353 $flags .= 'external';
1356 # Record the text (or external storage URL) to the text table
1357 if ( !isset( $this->mTextId
) ) {
1358 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1359 $dbw->insert( 'text',
1361 'old_id' => $old_id,
1362 'old_text' => $data,
1363 'old_flags' => $flags,
1366 $this->mTextId
= $dbw->insertId();
1369 if ( $this->mComment
=== null ) {
1370 $this->mComment
= "";
1373 # Record the edit in revisions
1374 $rev_id = isset( $this->mId
)
1376 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1378 'rev_id' => $rev_id,
1379 'rev_page' => $this->mPage
,
1380 'rev_text_id' => $this->mTextId
,
1381 'rev_comment' => $this->mComment
,
1382 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1383 'rev_user' => $this->mUser
,
1384 'rev_user_text' => $this->mUserText
,
1385 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1386 'rev_deleted' => $this->mDeleted
,
1387 'rev_len' => $this->mSize
,
1388 'rev_parent_id' => is_null( $this->mParentId
)
1389 ?
$this->getPreviousRevisionId( $dbw )
1391 'rev_sha1' => is_null( $this->mSha1
)
1392 ? Revision
::base36Sha1( $this->mText
)
1396 if ( $wgContentHandlerUseDB ) {
1397 //NOTE: Store null for the default model and format, to save space.
1398 //XXX: Makes the DB sensitive to changed defaults.
1399 // Make this behavior optional? Only in miser mode?
1401 $model = $this->getContentModel();
1402 $format = $this->getContentFormat();
1404 $title = $this->getTitle();
1406 if ( $title === null ) {
1407 wfProfileOut( __METHOD__
);
1408 throw new MWException( "Insufficient information to determine the title of the "
1409 . "revision's page!" );
1412 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1413 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1415 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1416 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1419 $dbw->insert( 'revision', $row, __METHOD__
);
1421 $this->mId
= !is_null( $rev_id ) ?
$rev_id : $dbw->insertId();
1423 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1425 wfProfileOut( __METHOD__
);
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() {
1494 wfProfileIn( __METHOD__
);
1496 // Caching may be beneficial for massive use of external storage
1497 global $wgRevisionCacheExpiry, $wgMemc;
1498 $textId = $this->getTextId();
1499 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1500 if ( $wgRevisionCacheExpiry ) {
1501 $text = $wgMemc->get( $key );
1502 if ( is_string( $text ) ) {
1503 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1504 wfProfileOut( __METHOD__
);
1509 // If we kept data for lazy extraction, use it now...
1510 if ( isset( $this->mTextRow
) ) {
1511 $row = $this->mTextRow
;
1512 $this->mTextRow
= null;
1518 // Text data is immutable; check slaves first.
1519 $dbr = wfGetDB( DB_SLAVE
);
1520 $row = $dbr->selectRow( 'text',
1521 array( 'old_text', 'old_flags' ),
1522 array( 'old_id' => $textId ),
1526 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1527 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1528 $forUpdate = ( $this->mQueryFlags
& self
::READ_LOCKING
== self
::READ_LOCKING
);
1529 if ( !$row && ( $forUpdate ||
wfGetLB()->getServerCount() > 1 ) ) {
1530 $dbw = wfGetDB( DB_MASTER
);
1531 $row = $dbw->selectRow( 'text',
1532 array( 'old_text', 'old_flags' ),
1533 array( 'old_id' => $textId ),
1535 $forUpdate ?
array( 'FOR UPDATE' ) : array() );
1539 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1542 $text = self
::getRevisionText( $row );
1543 if ( $row && $text === false ) {
1544 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1547 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1548 if ( $wgRevisionCacheExpiry && $text !== false ) {
1549 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1552 wfProfileOut( __METHOD__
);
1558 * Create a new null-revision for insertion into a page's
1559 * history. This will not re-save the text, but simply refer
1560 * to the text from the previous version.
1562 * Such revisions can for instance identify page rename
1563 * operations and other such meta-modifications.
1565 * @param DatabaseBase $dbw
1566 * @param int $pageId: ID number of the page to read from
1567 * @param string $summary Revision's summary
1568 * @param bool $minor Whether the revision should be considered as minor
1569 * @param User|null $user User object to use or null for $wgUser
1570 * @return Revision|null Revision or null on error
1572 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1573 global $wgContentHandlerUseDB;
1575 wfProfileIn( __METHOD__
);
1577 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1578 'rev_text_id', 'rev_len', 'rev_sha1' );
1580 if ( $wgContentHandlerUseDB ) {
1581 $fields[] = 'rev_content_model';
1582 $fields[] = 'rev_content_format';
1585 $current = $dbw->selectRow(
1586 array( 'page', 'revision' ),
1589 'page_id' => $pageId,
1590 'page_latest=rev_id',
1602 'user_text' => $user->getName(),
1603 'user' => $user->getId(),
1604 'comment' => $summary,
1605 'minor_edit' => $minor,
1606 'text_id' => $current->rev_text_id
,
1607 'parent_id' => $current->page_latest
,
1608 'len' => $current->rev_len
,
1609 'sha1' => $current->rev_sha1
1612 if ( $wgContentHandlerUseDB ) {
1613 $row['content_model'] = $current->rev_content_model
;
1614 $row['content_format'] = $current->rev_content_format
;
1617 $revision = new Revision( $row );
1618 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1623 wfProfileOut( __METHOD__
);
1628 * Determine if the current user is allowed to view a particular
1629 * field of this revision, if it's marked as deleted.
1631 * @param int $field One of self::DELETED_TEXT,
1632 * self::DELETED_COMMENT,
1633 * self::DELETED_USER
1634 * @param User|null $user User object to check, or null to use $wgUser
1637 public function userCan( $field, User
$user = null ) {
1638 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1642 * Determine if the current user is allowed to view a particular
1643 * field of this revision, if it's marked as deleted. This is used
1644 * by various classes to avoid duplication.
1646 * @param int $bitfield Current field
1647 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1648 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1649 * self::DELETED_USER = File::DELETED_USER
1650 * @param User|null $user User object to check, or null to use $wgUser
1653 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
1654 if ( $bitfield & $field ) { // aspect is deleted
1655 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1656 $permission = 'suppressrevision';
1657 } elseif ( $field & self
::DELETED_TEXT
) {
1658 $permission = 'deletedtext';
1660 $permission = 'deletedhistory';
1662 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1663 if ( $user === null ) {
1667 return $user->isAllowed( $permission );
1674 * Get rev_timestamp from rev_id, without loading the rest of the row
1676 * @param Title $title
1680 static function getTimestampFromId( $title, $id ) {
1681 $dbr = wfGetDB( DB_SLAVE
);
1682 // Casting fix for databases that can't take '' for rev_id
1686 $conds = array( 'rev_id' => $id );
1687 $conds['rev_page'] = $title->getArticleID();
1688 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1689 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1690 # Not in slave, try master
1691 $dbw = wfGetDB( DB_MASTER
);
1692 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1694 return wfTimestamp( TS_MW
, $timestamp );
1698 * Get count of revisions per page...not very efficient
1700 * @param DatabaseBase $db
1701 * @param int $id Page id
1704 static function countByPageId( $db, $id ) {
1705 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1706 array( 'rev_page' => $id ), __METHOD__
);
1708 return $row->revCount
;
1714 * Get count of revisions per page...not very efficient
1716 * @param DatabaseBase $db
1717 * @param Title $title
1720 static function countByTitle( $db, $title ) {
1721 $id = $title->getArticleID();
1723 return self
::countByPageId( $db, $id );
1729 * Check if no edits were made by other users since
1730 * the time a user started editing the page. Limit to
1731 * 50 revisions for the sake of performance.
1735 * @param DatabaseBase|int $db The Database to perform the check on. May be given as a
1736 * Database object or a database identifier usable with wfGetDB.
1737 * @param int $pageId The ID of the page in question
1738 * @param int $userId The ID of the user in question
1739 * @param string $since Look at edits since this time
1741 * @return bool True if the given user was the only one to edit since the given timestamp
1743 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1748 if ( is_int( $db ) ) {
1749 $db = wfGetDB( $db );
1752 $res = $db->select( 'revision',
1755 'rev_page' => $pageId,
1756 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1759 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1760 foreach ( $res as $row ) {
1761 if ( $row->rev_user
!= $userId ) {