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;
460 if ( $wgContentHandlerUseDB ) {
461 $fields[] = 'ar_content_format';
462 $fields[] = 'ar_content_model';
468 * Return the list of text fields that should be selected to read the
472 public static function selectTextFields() {
480 * Return the list of page fields that should be selected from page table
483 public static function selectPageFields() {
495 * Return the list of user fields that should be selected from user table
498 public static function selectUserFields() {
499 return array( 'user_name' );
503 * Do a batched query to get the parent revision lengths
504 * @param DatabaseBase $db
505 * @param array $revIds
508 public static function getParentLengths( $db, array $revIds ) {
511 return $revLens; // empty
513 wfProfileIn( __METHOD__
);
514 $res = $db->select( 'revision',
515 array( 'rev_id', 'rev_len' ),
516 array( 'rev_id' => $revIds ),
518 foreach ( $res as $row ) {
519 $revLens[$row->rev_id
] = $row->rev_len
;
521 wfProfileOut( __METHOD__
);
528 * @param object|array $row Either a database row or an array
529 * @throws MWException
532 function __construct( $row ) {
533 if ( is_object( $row ) ) {
534 $this->mId
= intval( $row->rev_id
);
535 $this->mPage
= intval( $row->rev_page
);
536 $this->mTextId
= intval( $row->rev_text_id
);
537 $this->mComment
= $row->rev_comment
;
538 $this->mUser
= intval( $row->rev_user
);
539 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
540 $this->mTimestamp
= $row->rev_timestamp
;
541 $this->mDeleted
= intval( $row->rev_deleted
);
543 if ( !isset( $row->rev_parent_id
) ) {
544 $this->mParentId
= null;
546 $this->mParentId
= intval( $row->rev_parent_id
);
549 if ( !isset( $row->rev_len
) ) {
552 $this->mSize
= intval( $row->rev_len
);
555 if ( !isset( $row->rev_sha1
) ) {
558 $this->mSha1
= $row->rev_sha1
;
561 if ( isset( $row->page_latest
) ) {
562 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
563 $this->mTitle
= Title
::newFromRow( $row );
565 $this->mCurrent
= false;
566 $this->mTitle
= null;
569 if ( !isset( $row->rev_content_model
) ||
is_null( $row->rev_content_model
) ) {
570 $this->mContentModel
= null; # determine on demand if needed
572 $this->mContentModel
= strval( $row->rev_content_model
);
575 if ( !isset( $row->rev_content_format
) ||
is_null( $row->rev_content_format
) ) {
576 $this->mContentFormat
= null; # determine on demand if needed
578 $this->mContentFormat
= strval( $row->rev_content_format
);
581 // Lazy extraction...
583 if ( isset( $row->old_text
) ) {
584 $this->mTextRow
= $row;
586 // 'text' table row entry will be lazy-loaded
587 $this->mTextRow
= null;
590 // Use user_name for users and rev_user_text for IPs...
591 $this->mUserText
= null; // lazy load if left null
592 if ( $this->mUser
== 0 ) {
593 $this->mUserText
= $row->rev_user_text
; // IP user
594 } elseif ( isset( $row->user_name
) ) {
595 $this->mUserText
= $row->user_name
; // logged-in user
597 $this->mOrigUserText
= $row->rev_user_text
;
598 } elseif ( is_array( $row ) ) {
599 // Build a new revision to be saved...
600 global $wgUser; // ugh
602 # if we have a content object, use it to set the model and type
603 if ( !empty( $row['content'] ) ) {
604 // @todo when is that set? test with external store setup! check out insertOn() [dk]
605 if ( !empty( $row['text_id'] ) ) {
606 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
607 "can't serialize content object" );
610 $row['content_model'] = $row['content']->getModel();
611 # note: mContentFormat is initializes later accordingly
612 # note: content is serialized later in this method!
613 # also set text to null?
616 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
617 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
618 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
619 $this->mUserText
= isset( $row['user_text'] )
620 ?
strval( $row['user_text'] ) : $wgUser->getName();
621 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
622 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
623 $this->mTimestamp
= isset( $row['timestamp'] )
624 ?
strval( $row['timestamp'] ) : wfTimestampNow();
625 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
626 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
627 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
628 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
630 $this->mContentModel
= isset( $row['content_model'] )
631 ?
strval( $row['content_model'] ) : null;
632 $this->mContentFormat
= isset( $row['content_format'] )
633 ?
strval( $row['content_format'] ) : null;
635 // Enforce spacing trimming on supplied text
636 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
637 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
638 $this->mTextRow
= null;
640 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
642 // if we have a Content object, override mText and mContentModel
643 if ( !empty( $row['content'] ) ) {
644 if ( !( $row['content'] instanceof Content
) ) {
645 throw new MWException( '`content` field must contain a Content object.' );
648 $handler = $this->getContentHandler();
649 $this->mContent
= $row['content'];
651 $this->mContentModel
= $this->mContent
->getModel();
652 $this->mContentHandler
= null;
654 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
655 } elseif ( !is_null( $this->mText
) ) {
656 $handler = $this->getContentHandler();
657 $this->mContent
= $handler->unserializeContent( $this->mText
);
660 // If we have a Title object, make sure it is consistent with mPage.
661 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
662 if ( $this->mPage
=== null ) {
663 // if the page ID wasn't known, set it now
664 $this->mPage
= $this->mTitle
->getArticleID();
665 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
666 // Got different page IDs. This may be legit (e.g. during undeletion),
667 // but it seems worth mentioning it in the log.
668 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
669 $this->mTitle
->getArticleID() . " provided by the Title object." );
673 $this->mCurrent
= false;
675 // If we still have no length, see it we have the text to figure it out
676 if ( !$this->mSize
) {
677 if ( !is_null( $this->mContent
) ) {
678 $this->mSize
= $this->mContent
->getSize();
680 #NOTE: this should never happen if we have either text or content object!
686 if ( $this->mSha1
=== null ) {
687 $this->mSha1
= is_null( $this->mText
) ?
null : self
::base36Sha1( $this->mText
);
691 $this->getContentModel();
692 $this->getContentFormat();
694 throw new MWException( 'Revision constructor passed invalid row format.' );
696 $this->mUnpatrolled
= null;
704 public function getId() {
709 * Set the revision ID
714 public function setId( $id ) {
723 public function getTextId() {
724 return $this->mTextId
;
728 * Get parent revision ID (the original previous page revision)
732 public function getParentId() {
733 return $this->mParentId
;
737 * Returns the length of the text in this revision, or null if unknown.
741 public function getSize() {
746 * Returns the base36 sha1 of the text in this revision, or null if unknown.
748 * @return string|null
750 public function getSha1() {
755 * Returns the title of the page associated with this entry or null.
757 * Will do a query, when title is not set and id is given.
761 public function getTitle() {
762 if ( isset( $this->mTitle
) ) {
763 return $this->mTitle
;
765 //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
766 if ( !is_null( $this->mId
) ) {
767 $dbr = wfGetDB( DB_SLAVE
);
768 $row = $dbr->selectRow(
769 array( 'page', 'revision' ),
770 self
::selectPageFields(),
771 array( 'page_id=rev_page',
772 'rev_id' => $this->mId
),
775 $this->mTitle
= Title
::newFromRow( $row );
779 if ( !$this->mTitle
&& !is_null( $this->mPage
) && $this->mPage
> 0 ) {
780 $this->mTitle
= Title
::newFromID( $this->mPage
);
783 return $this->mTitle
;
787 * Set the title of the revision
789 * @param Title $title
791 public function setTitle( $title ) {
792 $this->mTitle
= $title;
800 public function getPage() {
805 * Fetch revision's user id if it's available to the specified audience.
806 * If the specified audience does not have access to it, zero will be
809 * @param int $audience One of:
810 * Revision::FOR_PUBLIC to be displayed to all users
811 * Revision::FOR_THIS_USER to be displayed to the given user
812 * Revision::RAW get the ID regardless of permissions
813 * @param User $user User object to check for, only if FOR_THIS_USER is passed
814 * to the $audience parameter
817 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
818 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
820 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
828 * Fetch revision's user id without regard for the current user's permissions
832 public function getRawUser() {
837 * Fetch revision's username if it's available to the specified audience.
838 * If the specified audience does not have access to the username, an
839 * empty string will be returned.
841 * @param int $audience One of:
842 * Revision::FOR_PUBLIC to be displayed to all users
843 * Revision::FOR_THIS_USER to be displayed to the given user
844 * Revision::RAW get the text regardless of permissions
845 * @param User $user User object to check for, only if FOR_THIS_USER is passed
846 * to the $audience parameter
849 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
850 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
852 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
855 return $this->getRawUserText();
860 * Fetch revision's username without regard for view restrictions
864 public function getRawUserText() {
865 if ( $this->mUserText
=== null ) {
866 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
867 if ( $this->mUserText
=== false ) {
868 # This shouldn't happen, but it can if the wiki was recovered
869 # via importing revs and there is no user table entry yet.
870 $this->mUserText
= $this->mOrigUserText
;
873 return $this->mUserText
;
877 * Fetch revision comment if it's available to the specified audience.
878 * If the specified audience does not have access to the comment, an
879 * empty string will be returned.
881 * @param int $audience One of:
882 * Revision::FOR_PUBLIC to be displayed to all users
883 * Revision::FOR_THIS_USER to be displayed to the given user
884 * Revision::RAW get the text regardless of permissions
885 * @param User $user User object to check for, only if FOR_THIS_USER is passed
886 * to the $audience parameter
889 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
890 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
892 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
895 return $this->mComment
;
900 * Fetch revision comment without regard for the current user's permissions
904 public function getRawComment() {
905 return $this->mComment
;
911 public function isMinor() {
912 return (bool)$this->mMinorEdit
;
916 * @return int Rcid of the unpatrolled row, zero if there isn't one
918 public function isUnpatrolled() {
919 if ( $this->mUnpatrolled
!== null ) {
920 return $this->mUnpatrolled
;
922 $rc = $this->getRecentChange();
923 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
924 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
926 $this->mUnpatrolled
= 0;
928 return $this->mUnpatrolled
;
932 * Get the RC object belonging to the current revision, if there's one
935 * @return RecentChange|null
937 public function getRecentChange() {
938 $dbr = wfGetDB( DB_SLAVE
);
939 return RecentChange
::newFromConds(
941 'rc_user_text' => $this->getRawUserText(),
942 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
943 'rc_this_oldid' => $this->getId()
950 * @param int $field one of DELETED_* bitfield constants
954 public function isDeleted( $field ) {
955 return ( $this->mDeleted
& $field ) == $field;
959 * Get the deletion bitfield of the revision
963 public function getVisibility() {
964 return (int)$this->mDeleted
;
968 * Fetch revision text if it's available to the specified audience.
969 * If the specified audience does not have the ability to view this
970 * revision, an empty string will be returned.
972 * @param int $audience One of:
973 * Revision::FOR_PUBLIC to be displayed to all users
974 * Revision::FOR_THIS_USER to be displayed to the given user
975 * Revision::RAW get the text regardless of permissions
976 * @param User $user User object to check for, only if FOR_THIS_USER is passed
977 * to the $audience parameter
979 * @deprecated since 1.21, use getContent() instead
980 * @todo Replace usage in core
983 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
984 ContentHandler
::deprecated( __METHOD__
, '1.21' );
986 $content = $this->getContent( $audience, $user );
987 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
991 * Fetch revision content if it's available to the specified audience.
992 * If the specified audience does not have the ability to view this
993 * revision, null will be returned.
995 * @param int $audience One of:
996 * Revision::FOR_PUBLIC to be displayed to all users
997 * Revision::FOR_THIS_USER to be displayed to $wgUser
998 * Revision::RAW get the text regardless of permissions
999 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1000 * to the $audience parameter
1002 * @return Content|null
1004 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1005 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1007 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1010 return $this->getContentInternal();
1015 * Fetch revision text without regard for view restrictions
1019 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
1020 * or Revision::getSerializedData() as appropriate.
1022 public function getRawText() {
1023 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1024 return $this->getText( self
::RAW
);
1028 * Fetch original serialized data without regard for view restrictions
1033 public function getSerializedData() {
1034 if ( is_null( $this->mText
) ) {
1035 $this->mText
= $this->loadText();
1038 return $this->mText
;
1042 * Gets the content object for the revision (or null on failure).
1044 * Note that for mutable Content objects, each call to this method will return a
1048 * @return Content|null The Revision's content, or null on failure.
1050 protected function getContentInternal() {
1051 if ( is_null( $this->mContent
) ) {
1052 // Revision is immutable. Load on demand:
1053 if ( is_null( $this->mText
) ) {
1054 $this->mText
= $this->loadText();
1057 if ( $this->mText
!== null && $this->mText
!== false ) {
1058 // Unserialize content
1059 $handler = $this->getContentHandler();
1060 $format = $this->getContentFormat();
1062 $this->mContent
= $handler->unserializeContent( $this->mText
, $format );
1064 $this->mContent
= false; // negative caching!
1068 // NOTE: copy() will return $this for immutable content objects
1069 return $this->mContent ?
$this->mContent
->copy() : null;
1073 * Returns the content model for this revision.
1075 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
1076 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1077 * is used as a last resort.
1079 * @return string The content model id associated with this revision,
1080 * see the CONTENT_MODEL_XXX constants.
1082 public function getContentModel() {
1083 if ( !$this->mContentModel
) {
1084 $title = $this->getTitle();
1085 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
1087 assert( !empty( $this->mContentModel
) );
1090 return $this->mContentModel
;
1094 * Returns the content format for this revision.
1096 * If no content format was stored in the database, the default format for this
1097 * revision's content model is returned.
1099 * @return string The content format id associated with this revision,
1100 * see the CONTENT_FORMAT_XXX constants.
1102 public function getContentFormat() {
1103 if ( !$this->mContentFormat
) {
1104 $handler = $this->getContentHandler();
1105 $this->mContentFormat
= $handler->getDefaultFormat();
1107 assert( !empty( $this->mContentFormat
) );
1110 return $this->mContentFormat
;
1114 * Returns the content handler appropriate for this revision's content model.
1116 * @throws MWException
1117 * @return ContentHandler
1119 public function getContentHandler() {
1120 if ( !$this->mContentHandler
) {
1121 $model = $this->getContentModel();
1122 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1124 $format = $this->getContentFormat();
1126 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1127 throw new MWException( "Oops, the content format $format is not supported for "
1128 . "this content model, $model" );
1132 return $this->mContentHandler
;
1138 public function getTimestamp() {
1139 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1145 public function isCurrent() {
1146 return $this->mCurrent
;
1150 * Get previous revision for this title
1152 * @return Revision|null
1154 public function getPrevious() {
1155 if ( $this->getTitle() ) {
1156 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1158 return self
::newFromTitle( $this->getTitle(), $prev );
1165 * Get next revision for this title
1167 * @return Revision|null
1169 public function getNext() {
1170 if ( $this->getTitle() ) {
1171 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1173 return self
::newFromTitle( $this->getTitle(), $next );
1180 * Get previous revision Id for this page_id
1181 * This is used to populate rev_parent_id on save
1183 * @param DatabaseBase $db
1186 private function getPreviousRevisionId( $db ) {
1187 if ( is_null( $this->mPage
) ) {
1190 # Use page_latest if ID is not given
1191 if ( !$this->mId
) {
1192 $prevId = $db->selectField( 'page', 'page_latest',
1193 array( 'page_id' => $this->mPage
),
1196 $prevId = $db->selectField( 'revision', 'rev_id',
1197 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1199 array( 'ORDER BY' => 'rev_id DESC' ) );
1201 return intval( $prevId );
1205 * Get revision text associated with an old or archive row
1206 * $row is usually an object from wfFetchRow(), both the flags and the text
1207 * field must be included.
1209 * @param stdClass $row The text data
1210 * @param string $prefix Table prefix (default 'old_')
1211 * @param string|bool $wiki The name of the wiki to load the revision text from
1212 * (same as the the wiki $row was loaded from) or false to indicate the local
1213 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1214 * identifier as understood by the LoadBalancer class.
1215 * @return string Text the text requested or false on failure
1217 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1218 wfProfileIn( __METHOD__
);
1221 $textField = $prefix . 'text';
1222 $flagsField = $prefix . 'flags';
1224 if ( isset( $row->$flagsField ) ) {
1225 $flags = explode( ',', $row->$flagsField );
1230 if ( isset( $row->$textField ) ) {
1231 $text = $row->$textField;
1233 wfProfileOut( __METHOD__
);
1237 # Use external methods for external objects, text in table is URL-only then
1238 if ( in_array( 'external', $flags ) ) {
1240 $parts = explode( '://', $url, 2 );
1241 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1242 wfProfileOut( __METHOD__
);
1245 $text = ExternalStore
::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1248 // If the text was fetched without an error, convert it
1249 if ( $text !== false ) {
1250 $text = self
::decompressRevisionText( $text, $flags );
1252 wfProfileOut( __METHOD__
);
1257 * If $wgCompressRevisions is enabled, we will compress data.
1258 * The input string is modified in place.
1259 * Return value is the flags field: contains 'gzip' if the
1260 * data is compressed, and 'utf-8' if we're saving in UTF-8
1263 * @param mixed $text Reference to a text
1266 public static function compressRevisionText( &$text ) {
1267 global $wgCompressRevisions;
1270 # Revisions not marked this way will be converted
1271 # on load if $wgLegacyCharset is set in the future.
1274 if ( $wgCompressRevisions ) {
1275 if ( function_exists( 'gzdeflate' ) ) {
1276 $text = gzdeflate( $text );
1279 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1282 return implode( ',', $flags );
1286 * Re-converts revision text according to it's flags.
1288 * @param mixed $text Reference to a text
1289 * @param array $flags Compression flags
1290 * @return string|bool Decompressed text, or false on failure
1292 public static function decompressRevisionText( $text, $flags ) {
1293 if ( in_array( 'gzip', $flags ) ) {
1294 # Deal with optional compression of archived pages.
1295 # This can be done periodically via maintenance/compressOld.php, and
1296 # as pages are saved if $wgCompressRevisions is set.
1297 $text = gzinflate( $text );
1300 if ( in_array( 'object', $flags ) ) {
1301 # Generic compressed storage
1302 $obj = unserialize( $text );
1303 if ( !is_object( $obj ) ) {
1307 $text = $obj->getText();
1310 global $wgLegacyEncoding;
1311 if ( $text !== false && $wgLegacyEncoding
1312 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1314 # Old revisions kept around in a legacy encoding?
1315 # Upconvert on demand.
1316 # ("utf8" checked for compatibility with some broken
1317 # conversion scripts 2008-12-30)
1319 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1326 * Insert a new revision into the database, returning the new revision ID
1327 * number on success and dies horribly on failure.
1329 * @param DatabaseBase $dbw (master connection)
1330 * @throws MWException
1333 public function insertOn( $dbw ) {
1334 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1336 wfProfileIn( __METHOD__
);
1338 $this->checkContentModel();
1340 $data = $this->mText
;
1341 $flags = self
::compressRevisionText( $data );
1343 # Write to external storage if required
1344 if ( $wgDefaultExternalStore ) {
1345 // Store and get the URL
1346 $data = ExternalStore
::insertToDefault( $data );
1348 wfProfileOut( __METHOD__
);
1349 throw new MWException( "Unable to store text to external storage" );
1354 $flags .= 'external';
1357 # Record the text (or external storage URL) to the text table
1358 if ( !isset( $this->mTextId
) ) {
1359 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1360 $dbw->insert( 'text',
1362 'old_id' => $old_id,
1363 'old_text' => $data,
1364 'old_flags' => $flags,
1367 $this->mTextId
= $dbw->insertId();
1370 if ( $this->mComment
=== null ) {
1371 $this->mComment
= "";
1374 # Record the edit in revisions
1375 $rev_id = isset( $this->mId
)
1377 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1379 'rev_id' => $rev_id,
1380 'rev_page' => $this->mPage
,
1381 'rev_text_id' => $this->mTextId
,
1382 'rev_comment' => $this->mComment
,
1383 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1384 'rev_user' => $this->mUser
,
1385 'rev_user_text' => $this->mUserText
,
1386 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1387 'rev_deleted' => $this->mDeleted
,
1388 'rev_len' => $this->mSize
,
1389 'rev_parent_id' => is_null( $this->mParentId
)
1390 ?
$this->getPreviousRevisionId( $dbw )
1392 'rev_sha1' => is_null( $this->mSha1
)
1393 ? Revision
::base36Sha1( $this->mText
)
1397 if ( $wgContentHandlerUseDB ) {
1398 //NOTE: Store null for the default model and format, to save space.
1399 //XXX: Makes the DB sensitive to changed defaults.
1400 // Make this behavior optional? Only in miser mode?
1402 $model = $this->getContentModel();
1403 $format = $this->getContentFormat();
1405 $title = $this->getTitle();
1407 if ( $title === null ) {
1408 wfProfileOut( __METHOD__
);
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
= !is_null( $rev_id ) ?
$rev_id : $dbw->insertId();
1424 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1426 wfProfileOut( __METHOD__
);
1430 protected function checkContentModel() {
1431 global $wgContentHandlerUseDB;
1433 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1435 $model = $this->getContentModel();
1436 $format = $this->getContentFormat();
1437 $handler = $this->getContentHandler();
1439 if ( !$handler->isSupportedFormat( $format ) ) {
1440 $t = $title->getPrefixedDBkey();
1442 throw new MWException( "Can't use format $format with content model $model on $t" );
1445 if ( !$wgContentHandlerUseDB && $title ) {
1446 // if $wgContentHandlerUseDB is not set,
1447 // all revisions must use the default content model and format.
1449 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1450 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1451 $defaultFormat = $defaultHandler->getDefaultFormat();
1453 if ( $this->getContentModel() != $defaultModel ) {
1454 $t = $title->getPrefixedDBkey();
1456 throw new MWException( "Can't save non-default content model with "
1457 . "\$wgContentHandlerUseDB disabled: model is $model, "
1458 . "default for $t is $defaultModel" );
1461 if ( $this->getContentFormat() != $defaultFormat ) {
1462 $t = $title->getPrefixedDBkey();
1464 throw new MWException( "Can't use non-default content format with "
1465 . "\$wgContentHandlerUseDB disabled: format is $format, "
1466 . "default for $t is $defaultFormat" );
1470 $content = $this->getContent( Revision
::RAW
);
1472 if ( !$content ||
!$content->isValid() ) {
1473 $t = $title->getPrefixedDBkey();
1475 throw new MWException( "Content of $t is not valid! Content model is $model" );
1480 * Get the base 36 SHA-1 value for a string of text
1481 * @param string $text
1484 public static function base36Sha1( $text ) {
1485 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1489 * Lazy-load the revision's text.
1490 * Currently hardcoded to the 'text' table storage engine.
1492 * @return string|bool The revision's text, or false on failure
1494 protected function loadText() {
1495 wfProfileIn( __METHOD__
);
1497 // Caching may be beneficial for massive use of external storage
1498 global $wgRevisionCacheExpiry, $wgMemc;
1499 $textId = $this->getTextId();
1500 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1501 if ( $wgRevisionCacheExpiry ) {
1502 $text = $wgMemc->get( $key );
1503 if ( is_string( $text ) ) {
1504 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1505 wfProfileOut( __METHOD__
);
1510 // If we kept data for lazy extraction, use it now...
1511 if ( isset( $this->mTextRow
) ) {
1512 $row = $this->mTextRow
;
1513 $this->mTextRow
= null;
1519 // Text data is immutable; check slaves first.
1520 $dbr = wfGetDB( DB_SLAVE
);
1521 $row = $dbr->selectRow( 'text',
1522 array( 'old_text', 'old_flags' ),
1523 array( 'old_id' => $textId ),
1527 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1528 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1529 $forUpdate = ( $this->mQueryFlags
& self
::READ_LOCKING
== self
::READ_LOCKING
);
1530 if ( !$row && ( $forUpdate ||
wfGetLB()->getServerCount() > 1 ) ) {
1531 $dbw = wfGetDB( DB_MASTER
);
1532 $row = $dbw->selectRow( 'text',
1533 array( 'old_text', 'old_flags' ),
1534 array( 'old_id' => $textId ),
1536 $forUpdate ?
array( 'FOR UPDATE' ) : array() );
1540 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1543 $text = self
::getRevisionText( $row );
1544 if ( $row && $text === false ) {
1545 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1548 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1549 if ( $wgRevisionCacheExpiry && $text !== false ) {
1550 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1553 wfProfileOut( __METHOD__
);
1559 * Create a new null-revision for insertion into a page's
1560 * history. This will not re-save the text, but simply refer
1561 * to the text from the previous version.
1563 * Such revisions can for instance identify page rename
1564 * operations and other such meta-modifications.
1566 * @param DatabaseBase $dbw
1567 * @param int $pageId: ID number of the page to read from
1568 * @param string $summary Revision's summary
1569 * @param bool $minor Whether the revision should be considered as minor
1570 * @param User|null $user User object to use or null for $wgUser
1571 * @return Revision|null Revision or null on error
1573 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1574 global $wgContentHandlerUseDB;
1576 wfProfileIn( __METHOD__
);
1578 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1579 'rev_text_id', 'rev_len', 'rev_sha1' );
1581 if ( $wgContentHandlerUseDB ) {
1582 $fields[] = 'rev_content_model';
1583 $fields[] = 'rev_content_format';
1586 $current = $dbw->selectRow(
1587 array( 'page', 'revision' ),
1590 'page_id' => $pageId,
1591 'page_latest=rev_id',
1603 'user_text' => $user->getName(),
1604 'user' => $user->getId(),
1605 'comment' => $summary,
1606 'minor_edit' => $minor,
1607 'text_id' => $current->rev_text_id
,
1608 'parent_id' => $current->page_latest
,
1609 'len' => $current->rev_len
,
1610 'sha1' => $current->rev_sha1
1613 if ( $wgContentHandlerUseDB ) {
1614 $row['content_model'] = $current->rev_content_model
;
1615 $row['content_format'] = $current->rev_content_format
;
1618 $revision = new Revision( $row );
1619 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1624 wfProfileOut( __METHOD__
);
1629 * Determine if the current user is allowed to view a particular
1630 * field of this revision, if it's marked as deleted.
1632 * @param int $field One of self::DELETED_TEXT,
1633 * self::DELETED_COMMENT,
1634 * self::DELETED_USER
1635 * @param User|null $user User object to check, or null to use $wgUser
1638 public function userCan( $field, User
$user = null ) {
1639 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1643 * Determine if the current user is allowed to view a particular
1644 * field of this revision, if it's marked as deleted. This is used
1645 * by various classes to avoid duplication.
1647 * @param int $bitfield Current field
1648 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1649 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1650 * self::DELETED_USER = File::DELETED_USER
1651 * @param User|null $user User object to check, or null to use $wgUser
1654 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
1655 if ( $bitfield & $field ) { // aspect is deleted
1656 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1657 $permission = 'suppressrevision';
1658 } elseif ( $field & self
::DELETED_TEXT
) {
1659 $permission = 'deletedtext';
1661 $permission = 'deletedhistory';
1663 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1664 if ( $user === null ) {
1668 return $user->isAllowed( $permission );
1675 * Get rev_timestamp from rev_id, without loading the rest of the row
1677 * @param Title $title
1681 static function getTimestampFromId( $title, $id ) {
1682 $dbr = wfGetDB( DB_SLAVE
);
1683 // Casting fix for databases that can't take '' for rev_id
1687 $conds = array( 'rev_id' => $id );
1688 $conds['rev_page'] = $title->getArticleID();
1689 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1690 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1691 # Not in slave, try master
1692 $dbw = wfGetDB( DB_MASTER
);
1693 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1695 return wfTimestamp( TS_MW
, $timestamp );
1699 * Get count of revisions per page...not very efficient
1701 * @param DatabaseBase $db
1702 * @param int $id Page id
1705 static function countByPageId( $db, $id ) {
1706 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1707 array( 'rev_page' => $id ), __METHOD__
);
1709 return $row->revCount
;
1715 * Get count of revisions per page...not very efficient
1717 * @param DatabaseBase $db
1718 * @param Title $title
1721 static function countByTitle( $db, $title ) {
1722 $id = $title->getArticleID();
1724 return self
::countByPageId( $db, $id );
1730 * Check if no edits were made by other users since
1731 * the time a user started editing the page. Limit to
1732 * 50 revisions for the sake of performance.
1736 * @param DatabaseBase|int $db The Database to perform the check on. May be given as a
1737 * Database object or a database identifier usable with wfGetDB.
1738 * @param int $pageId The ID of the page in question
1739 * @param int $userId The ID of the user in question
1740 * @param string $since Look at edits since this time
1742 * @return bool True if the given user was the only one to edit since the given timestamp
1744 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1749 if ( is_int( $db ) ) {
1750 $db = wfGetDB( $db );
1753 $res = $db->select( 'revision',
1756 'rev_page' => $pageId,
1757 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1760 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1761 foreach ( $res as $row ) {
1762 if ( $row->rev_user
!= $userId ) {