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 $flags Integer (optional)
91 * @return Revision or 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 $id Integer (optional)
108 * @param $flags Integer Bitfield (optional)
109 * @return Revision or 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;
120 // Use a join to get the latest revision
121 $conds[] = 'rev_id=page_latest';
123 return self
::newFromConds( $conds, (int)$flags );
127 * Load either the current, or a specified, revision
128 * that's attached to a given page ID.
129 * Returns null if no such revision can be found.
132 * Revision::READ_LATEST : Select the data from the master (since 1.20)
133 * Revision::READ_LOCKING : Select & lock the data from the master
135 * @param $revId Integer
136 * @param $pageId Integer (optional)
137 * @param $flags Integer Bitfield (optional)
138 * @return Revision or null
140 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
141 $conds = array( 'page_id' => $pageId );
143 $conds['rev_id'] = $revId;
145 // Use a join to get the latest revision
146 $conds[] = 'rev_id = page_latest';
148 return self
::newFromConds( $conds, (int)$flags );
152 * Make a fake revision object from an archive table row. This is queried
153 * for permissions or even inserted (as in Special:Undelete)
154 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
157 * @param $overrides array
159 * @throws MWException
162 public static function newFromArchiveRow( $row, $overrides = array() ) {
163 global $wgContentHandlerUseDB;
165 $attribs = $overrides +
array(
166 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
167 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
168 'comment' => $row->ar_comment
,
169 'user' => $row->ar_user
,
170 'user_text' => $row->ar_user_text
,
171 'timestamp' => $row->ar_timestamp
,
172 'minor_edit' => $row->ar_minor_edit
,
173 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
174 'deleted' => $row->ar_deleted
,
175 'len' => $row->ar_len
,
176 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
177 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
178 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
181 if ( !$wgContentHandlerUseDB ) {
182 unset( $attribs['content_model'] );
183 unset( $attribs['content_format'] );
186 if ( !isset( $attribs['title'] )
187 && isset( $row->ar_namespace
)
188 && isset( $row->ar_title
) ) {
190 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
193 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
194 // Pre-1.5 ar_text row
195 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
196 if ( $attribs['text'] === false ) {
197 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
200 return new self( $attribs );
209 public static function newFromRow( $row ) {
210 return new self( $row );
214 * Load a page revision from a given revision ID number.
215 * Returns null if no such revision can be found.
217 * @param $db DatabaseBase
219 * @return Revision or null
221 public static function loadFromId( $db, $id ) {
222 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
226 * Load either the current, or a specified, revision
227 * that's attached to a given page. If not attached
228 * to that page, will return null.
230 * @param $db DatabaseBase
231 * @param $pageid Integer
233 * @return Revision or null
235 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
236 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
238 $conds['rev_id'] = intval( $id );
240 $conds[] = 'rev_id=page_latest';
242 return self
::loadFromConds( $db, $conds );
246 * Load either the current, or a specified, revision
247 * that's attached to a given page. If not attached
248 * to that page, will return null.
250 * @param $db DatabaseBase
251 * @param $title Title
253 * @return Revision or null
255 public static function loadFromTitle( $db, $title, $id = 0 ) {
257 $matchId = intval( $id );
259 $matchId = 'page_latest';
261 return self
::loadFromConds( $db,
264 'page_namespace' => $title->getNamespace(),
265 'page_title' => $title->getDBkey()
271 * Load the revision for the given title with the given timestamp.
272 * WARNING: Timestamps may in some circumstances not be unique,
273 * so this isn't the best key to use.
275 * @param $db DatabaseBase
276 * @param $title Title
277 * @param $timestamp String
278 * @return Revision or null
280 public static function loadFromTimestamp( $db, $title, $timestamp ) {
281 return self
::loadFromConds( $db,
283 'rev_timestamp' => $db->timestamp( $timestamp ),
284 'page_namespace' => $title->getNamespace(),
285 'page_title' => $title->getDBkey()
291 * Given a set of conditions, fetch a revision.
293 * @param $conditions Array
294 * @param $flags integer (optional)
295 * @return Revision or null
297 private static function newFromConds( $conditions, $flags = 0 ) {
298 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
299 $rev = self
::loadFromConds( $db, $conditions, $flags );
300 if ( is_null( $rev ) && wfGetLB()->getServerCount() > 1 ) {
301 if ( !( $flags & self
::READ_LATEST
) ) {
302 $dbw = wfGetDB( DB_MASTER
);
303 $rev = self
::loadFromConds( $dbw, $conditions, $flags );
307 $rev->mQueryFlags
= $flags;
313 * Given a set of conditions, fetch a revision from
314 * the given database connection.
316 * @param $db DatabaseBase
317 * @param $conditions Array
318 * @param $flags integer (optional)
319 * @return Revision or null
321 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
322 $res = self
::fetchFromConds( $db, $conditions, $flags );
324 $row = $res->fetchObject();
326 $ret = new Revision( $row );
335 * Return a wrapper for a series of database rows to
336 * fetch all of a given page's revisions in turn.
337 * Each row can be fed to the constructor to get objects.
339 * @param $title Title
340 * @return ResultWrapper
342 public static function fetchRevision( $title ) {
343 return self
::fetchFromConds(
346 'rev_id=page_latest',
347 'page_namespace' => $title->getNamespace(),
348 'page_title' => $title->getDBkey()
354 * Given a set of conditions, return a ResultWrapper
355 * which will return matching database rows with the
356 * fields necessary to build Revision objects.
358 * @param $db DatabaseBase
359 * @param $conditions Array
360 * @param $flags integer (optional)
361 * @return ResultWrapper
363 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
364 $fields = array_merge(
365 self
::selectFields(),
366 self
::selectPageFields(),
367 self
::selectUserFields()
369 $options = array( 'LIMIT' => 1 );
370 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
371 $options[] = 'FOR UPDATE';
374 array( 'revision', 'page', 'user' ),
379 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
384 * Return the value of a select() JOIN conds array for the user table.
385 * This will get user table rows for logged-in users.
389 public static function userJoinCond() {
390 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
394 * Return the value of a select() page conds array for the page table.
395 * This will assure that the revision(s) are not orphaned from live pages.
399 public static function pageJoinCond() {
400 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
404 * Return the list of revision fields that should be selected to create
408 public static function selectFields() {
409 global $wgContentHandlerUseDB;
426 if ( $wgContentHandlerUseDB ) {
427 $fields[] = 'rev_content_format';
428 $fields[] = 'rev_content_model';
435 * Return the list of text fields that should be selected to read the
439 public static function selectTextFields() {
447 * Return the list of page fields that should be selected from page table
450 public static function selectPageFields() {
462 * Return the list of user fields that should be selected from user table
465 public static function selectUserFields() {
466 return array( 'user_name' );
470 * Do a batched query to get the parent revision lengths
471 * @param $db DatabaseBase
472 * @param $revIds Array
475 public static function getParentLengths( $db, array $revIds ) {
478 return $revLens; // empty
480 wfProfileIn( __METHOD__
);
481 $res = $db->select( 'revision',
482 array( 'rev_id', 'rev_len' ),
483 array( 'rev_id' => $revIds ),
485 foreach ( $res as $row ) {
486 $revLens[$row->rev_id
] = $row->rev_len
;
488 wfProfileOut( __METHOD__
);
495 * @param $row Mixed: either a database row or an array
496 * @throws MWException
499 function __construct( $row ) {
500 if ( is_object( $row ) ) {
501 $this->mId
= intval( $row->rev_id
);
502 $this->mPage
= intval( $row->rev_page
);
503 $this->mTextId
= intval( $row->rev_text_id
);
504 $this->mComment
= $row->rev_comment
;
505 $this->mUser
= intval( $row->rev_user
);
506 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
507 $this->mTimestamp
= $row->rev_timestamp
;
508 $this->mDeleted
= intval( $row->rev_deleted
);
510 if ( !isset( $row->rev_parent_id
) ) {
511 $this->mParentId
= null;
513 $this->mParentId
= intval( $row->rev_parent_id
);
516 if ( !isset( $row->rev_len
) ) {
519 $this->mSize
= intval( $row->rev_len
);
522 if ( !isset( $row->rev_sha1
) ) {
525 $this->mSha1
= $row->rev_sha1
;
528 if ( isset( $row->page_latest
) ) {
529 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
530 $this->mTitle
= Title
::newFromRow( $row );
532 $this->mCurrent
= false;
533 $this->mTitle
= null;
536 if ( !isset( $row->rev_content_model
) ||
is_null( $row->rev_content_model
) ) {
537 $this->mContentModel
= null; # determine on demand if needed
539 $this->mContentModel
= strval( $row->rev_content_model
);
542 if ( !isset( $row->rev_content_format
) ||
is_null( $row->rev_content_format
) ) {
543 $this->mContentFormat
= null; # determine on demand if needed
545 $this->mContentFormat
= strval( $row->rev_content_format
);
548 // Lazy extraction...
550 if ( isset( $row->old_text
) ) {
551 $this->mTextRow
= $row;
553 // 'text' table row entry will be lazy-loaded
554 $this->mTextRow
= null;
557 // Use user_name for users and rev_user_text for IPs...
558 $this->mUserText
= null; // lazy load if left null
559 if ( $this->mUser
== 0 ) {
560 $this->mUserText
= $row->rev_user_text
; // IP user
561 } elseif ( isset( $row->user_name
) ) {
562 $this->mUserText
= $row->user_name
; // logged-in user
564 $this->mOrigUserText
= $row->rev_user_text
;
565 } elseif ( is_array( $row ) ) {
566 // Build a new revision to be saved...
567 global $wgUser; // ugh
569 # if we have a content object, use it to set the model and type
570 if ( !empty( $row['content'] ) ) {
571 // @todo when is that set? test with external store setup! check out insertOn() [dk]
572 if ( !empty( $row['text_id'] ) ) {
573 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
574 "can't serialize content object" );
577 $row['content_model'] = $row['content']->getModel();
578 # note: mContentFormat is initializes later accordingly
579 # note: content is serialized later in this method!
580 # also set text to null?
583 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
584 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
585 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
586 $this->mUserText
= isset( $row['user_text'] ) ?
strval( $row['user_text'] ) : $wgUser->getName();
587 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
588 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
589 $this->mTimestamp
= isset( $row['timestamp'] ) ?
strval( $row['timestamp'] ) : wfTimestampNow();
590 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
591 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
592 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
593 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
595 $this->mContentModel
= isset( $row['content_model'] ) ?
strval( $row['content_model'] ) : null;
596 $this->mContentFormat
= isset( $row['content_format'] ) ?
strval( $row['content_format'] ) : null;
598 // Enforce spacing trimming on supplied text
599 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
600 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
601 $this->mTextRow
= null;
603 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
605 // if we have a Content object, override mText and mContentModel
606 if ( !empty( $row['content'] ) ) {
607 if ( !( $row['content'] instanceof Content
) ) {
608 throw new MWException( '`content` field must contain a Content object.' );
611 $handler = $this->getContentHandler();
612 $this->mContent
= $row['content'];
614 $this->mContentModel
= $this->mContent
->getModel();
615 $this->mContentHandler
= null;
617 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
618 } elseif ( !is_null( $this->mText
) ) {
619 $handler = $this->getContentHandler();
620 $this->mContent
= $handler->unserializeContent( $this->mText
);
623 // If we have a Title object, make sure it is consistent with mPage.
624 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
625 if ( $this->mPage
=== null ) {
626 // if the page ID wasn't known, set it now
627 $this->mPage
= $this->mTitle
->getArticleID();
628 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
629 // Got different page IDs. This may be legit (e.g. during undeletion),
630 // but it seems worth mentioning it in the log.
631 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
632 $this->mTitle
->getArticleID() . " provided by the Title object." );
636 $this->mCurrent
= false;
638 // If we still have no length, see it we have the text to figure it out
639 if ( !$this->mSize
) {
640 if ( !is_null( $this->mContent
) ) {
641 $this->mSize
= $this->mContent
->getSize();
643 #NOTE: this should never happen if we have either text or content object!
649 if ( $this->mSha1
=== null ) {
650 $this->mSha1
= is_null( $this->mText
) ?
null : self
::base36Sha1( $this->mText
);
654 $this->getContentModel();
655 $this->getContentFormat();
657 throw new MWException( 'Revision constructor passed invalid row format.' );
659 $this->mUnpatrolled
= null;
665 * @return Integer|null
667 public function getId() {
672 * Set the revision ID
677 public function setId( $id ) {
684 * @return Integer|null
686 public function getTextId() {
687 return $this->mTextId
;
691 * Get parent revision ID (the original previous page revision)
693 * @return Integer|null
695 public function getParentId() {
696 return $this->mParentId
;
700 * Returns the length of the text in this revision, or null if unknown.
702 * @return Integer|null
704 public function getSize() {
709 * Returns the base36 sha1 of the text in this revision, or null if unknown.
711 * @return String|null
713 public function getSha1() {
718 * Returns the title of the page associated with this entry or null.
720 * Will do a query, when title is not set and id is given.
724 public function getTitle() {
725 if ( isset( $this->mTitle
) ) {
726 return $this->mTitle
;
728 if ( !is_null( $this->mId
) ) { //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
729 $dbr = wfGetDB( DB_SLAVE
);
730 $row = $dbr->selectRow(
731 array( 'page', 'revision' ),
732 self
::selectPageFields(),
733 array( 'page_id=rev_page',
734 'rev_id' => $this->mId
),
737 $this->mTitle
= Title
::newFromRow( $row );
741 if ( !$this->mTitle
&& !is_null( $this->mPage
) && $this->mPage
> 0 ) {
742 $this->mTitle
= Title
::newFromID( $this->mPage
);
745 return $this->mTitle
;
749 * Set the title of the revision
751 * @param $title Title
753 public function setTitle( $title ) {
754 $this->mTitle
= $title;
760 * @return Integer|null
762 public function getPage() {
767 * Fetch revision's user id if it's available to the specified audience.
768 * If the specified audience does not have access to it, zero will be
771 * @param $audience Integer: one of:
772 * Revision::FOR_PUBLIC to be displayed to all users
773 * Revision::FOR_THIS_USER to be displayed to the given user
774 * Revision::RAW get the ID regardless of permissions
775 * @param $user User object to check for, only if FOR_THIS_USER is passed
776 * to the $audience parameter
779 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
780 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
782 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
790 * Fetch revision's user id without regard for the current user's permissions
794 public function getRawUser() {
799 * Fetch revision's username if it's available to the specified audience.
800 * If the specified audience does not have access to the username, an
801 * empty string will be returned.
803 * @param $audience Integer: one of:
804 * Revision::FOR_PUBLIC to be displayed to all users
805 * Revision::FOR_THIS_USER to be displayed to the given user
806 * Revision::RAW get the text regardless of permissions
807 * @param $user User object to check for, only if FOR_THIS_USER is passed
808 * to the $audience parameter
811 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
812 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
814 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
817 return $this->getRawUserText();
822 * Fetch revision's username without regard for view restrictions
826 public function getRawUserText() {
827 if ( $this->mUserText
=== null ) {
828 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
829 if ( $this->mUserText
=== false ) {
830 # This shouldn't happen, but it can if the wiki was recovered
831 # via importing revs and there is no user table entry yet.
832 $this->mUserText
= $this->mOrigUserText
;
835 return $this->mUserText
;
839 * Fetch revision comment if it's available to the specified audience.
840 * If the specified audience does not have access to the comment, an
841 * empty string will be returned.
843 * @param $audience Integer: one of:
844 * Revision::FOR_PUBLIC to be displayed to all users
845 * Revision::FOR_THIS_USER to be displayed to the given user
846 * Revision::RAW get the text regardless of permissions
847 * @param $user User object to check for, only if FOR_THIS_USER is passed
848 * to the $audience parameter
851 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
852 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
854 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
857 return $this->mComment
;
862 * Fetch revision comment without regard for the current user's permissions
866 public function getRawComment() {
867 return $this->mComment
;
873 public function isMinor() {
874 return (bool)$this->mMinorEdit
;
878 * @return integer rcid of the unpatrolled row, zero if there isn't one
880 public function isUnpatrolled() {
881 if ( $this->mUnpatrolled
!== null ) {
882 return $this->mUnpatrolled
;
884 $rc = $this->getRecentChange();
885 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
886 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
888 $this->mUnpatrolled
= 0;
890 return $this->mUnpatrolled
;
894 * Get the RC object belonging to the current revision, if there's one
897 * @return RecentChange|null
899 public function getRecentChange() {
900 $dbr = wfGetDB( DB_SLAVE
);
901 return RecentChange
::newFromConds(
903 'rc_user_text' => $this->getRawUserText(),
904 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
905 'rc_this_oldid' => $this->getId()
912 * @param int $field one of DELETED_* bitfield constants
916 public function isDeleted( $field ) {
917 return ( $this->mDeleted
& $field ) == $field;
921 * Get the deletion bitfield of the revision
925 public function getVisibility() {
926 return (int)$this->mDeleted
;
930 * Fetch revision text if it's available to the specified audience.
931 * If the specified audience does not have the ability to view this
932 * revision, an empty string will be returned.
934 * @param $audience Integer: one of:
935 * Revision::FOR_PUBLIC to be displayed to all users
936 * Revision::FOR_THIS_USER to be displayed to the given user
937 * Revision::RAW get the text regardless of permissions
938 * @param $user User object to check for, only if FOR_THIS_USER is passed
939 * to the $audience parameter
941 * @deprecated in 1.21, use getContent() instead
942 * @todo Replace usage in core
945 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
946 ContentHandler
::deprecated( __METHOD__
, '1.21' );
948 $content = $this->getContent( $audience, $user );
949 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
953 * Fetch revision content if it's available to the specified audience.
954 * If the specified audience does not have the ability to view this
955 * revision, null will be returned.
957 * @param $audience Integer: one of:
958 * Revision::FOR_PUBLIC to be displayed to all users
959 * Revision::FOR_THIS_USER to be displayed to $wgUser
960 * Revision::RAW get the text regardless of permissions
961 * @param $user User object to check for, only if FOR_THIS_USER is passed
962 * to the $audience parameter
964 * @return Content|null
966 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
967 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
969 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
972 return $this->getContentInternal();
977 * Alias for getText(Revision::FOR_THIS_USER)
979 * @deprecated since 1.17
982 public function revText() {
983 wfDeprecated( __METHOD__
, '1.17' );
984 return $this->getText( self
::FOR_THIS_USER
);
988 * Fetch revision text without regard for view restrictions
992 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
993 * or Revision::getSerializedData() as appropriate.
995 public function getRawText() {
996 ContentHandler
::deprecated( __METHOD__
, "1.21" );
997 return $this->getText( self
::RAW
);
1001 * Fetch original serialized data without regard for view restrictions
1006 public function getSerializedData() {
1007 if ( is_null( $this->mText
) ) {
1008 $this->mText
= $this->loadText();
1011 return $this->mText
;
1015 * Gets the content object for the revision (or null on failure).
1017 * Note that for mutable Content objects, each call to this method will return a
1021 * @return Content|null the Revision's content, or null on failure.
1023 protected function getContentInternal() {
1024 if ( is_null( $this->mContent
) ) {
1025 // Revision is immutable. Load on demand:
1026 if ( is_null( $this->mText
) ) {
1027 $this->mText
= $this->loadText();
1030 if ( $this->mText
!== null && $this->mText
!== false ) {
1031 // Unserialize content
1032 $handler = $this->getContentHandler();
1033 $format = $this->getContentFormat();
1035 $this->mContent
= $handler->unserializeContent( $this->mText
, $format );
1037 $this->mContent
= false; // negative caching!
1041 // NOTE: copy() will return $this for immutable content objects
1042 return $this->mContent ?
$this->mContent
->copy() : null;
1046 * Returns the content model for this revision.
1048 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
1049 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1050 * is used as a last resort.
1052 * @return String the content model id associated with this revision, see the CONTENT_MODEL_XXX constants.
1054 public function getContentModel() {
1055 if ( !$this->mContentModel
) {
1056 $title = $this->getTitle();
1057 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
1059 assert( !empty( $this->mContentModel
) );
1062 return $this->mContentModel
;
1066 * Returns the content format for this revision.
1068 * If no content format was stored in the database, the default format for this
1069 * revision's content model is returned.
1071 * @return String the content format id associated with this revision, see the CONTENT_FORMAT_XXX constants.
1073 public function getContentFormat() {
1074 if ( !$this->mContentFormat
) {
1075 $handler = $this->getContentHandler();
1076 $this->mContentFormat
= $handler->getDefaultFormat();
1078 assert( !empty( $this->mContentFormat
) );
1081 return $this->mContentFormat
;
1085 * Returns the content handler appropriate for this revision's content model.
1087 * @throws MWException
1088 * @return ContentHandler
1090 public function getContentHandler() {
1091 if ( !$this->mContentHandler
) {
1092 $model = $this->getContentModel();
1093 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1095 $format = $this->getContentFormat();
1097 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1098 throw new MWException( "Oops, the content format $format is not supported for this content model, $model" );
1102 return $this->mContentHandler
;
1108 public function getTimestamp() {
1109 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1115 public function isCurrent() {
1116 return $this->mCurrent
;
1120 * Get previous revision for this title
1122 * @return Revision|null
1124 public function getPrevious() {
1125 if ( $this->getTitle() ) {
1126 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1128 return self
::newFromTitle( $this->getTitle(), $prev );
1135 * Get next revision for this title
1137 * @return Revision or null
1139 public function getNext() {
1140 if ( $this->getTitle() ) {
1141 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1143 return self
::newFromTitle( $this->getTitle(), $next );
1150 * Get previous revision Id for this page_id
1151 * This is used to populate rev_parent_id on save
1153 * @param $db DatabaseBase
1156 private function getPreviousRevisionId( $db ) {
1157 if ( is_null( $this->mPage
) ) {
1160 # Use page_latest if ID is not given
1161 if ( !$this->mId
) {
1162 $prevId = $db->selectField( 'page', 'page_latest',
1163 array( 'page_id' => $this->mPage
),
1166 $prevId = $db->selectField( 'revision', 'rev_id',
1167 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1169 array( 'ORDER BY' => 'rev_id DESC' ) );
1171 return intval( $prevId );
1175 * Get revision text associated with an old or archive row
1176 * $row is usually an object from wfFetchRow(), both the flags and the text
1177 * field must be included
1179 * @param $row Object: the text data
1180 * @param string $prefix table prefix (default 'old_')
1181 * @param string|false $wiki the name of the wiki to load the revision text from
1182 * (same as the the wiki $row was loaded from) or false to indicate the local
1183 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1184 * identifier as understood by the LoadBalancer class.
1185 * @return String: text the text requested or false on failure
1187 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1188 wfProfileIn( __METHOD__
);
1191 $textField = $prefix . 'text';
1192 $flagsField = $prefix . 'flags';
1194 if ( isset( $row->$flagsField ) ) {
1195 $flags = explode( ',', $row->$flagsField );
1200 if ( isset( $row->$textField ) ) {
1201 $text = $row->$textField;
1203 wfProfileOut( __METHOD__
);
1207 # Use external methods for external objects, text in table is URL-only then
1208 if ( in_array( 'external', $flags ) ) {
1210 $parts = explode( '://', $url, 2 );
1211 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1212 wfProfileOut( __METHOD__
);
1215 $text = ExternalStore
::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1218 // If the text was fetched without an error, convert it
1219 if ( $text !== false ) {
1220 $text = self
::decompressRevisionText( $text, $flags );
1222 wfProfileOut( __METHOD__
);
1227 * If $wgCompressRevisions is enabled, we will compress data.
1228 * The input string is modified in place.
1229 * Return value is the flags field: contains 'gzip' if the
1230 * data is compressed, and 'utf-8' if we're saving in UTF-8
1233 * @param $text Mixed: reference to a text
1236 public static function compressRevisionText( &$text ) {
1237 global $wgCompressRevisions;
1240 # Revisions not marked this way will be converted
1241 # on load if $wgLegacyCharset is set in the future.
1244 if ( $wgCompressRevisions ) {
1245 if ( function_exists( 'gzdeflate' ) ) {
1246 $text = gzdeflate( $text );
1249 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1252 return implode( ',', $flags );
1256 * Re-converts revision text according to it's flags.
1258 * @param $text Mixed: reference to a text
1259 * @param $flags array: compression flags
1260 * @return String|bool decompressed text, or false on failure
1262 public static function decompressRevisionText( $text, $flags ) {
1263 if ( in_array( 'gzip', $flags ) ) {
1264 # Deal with optional compression of archived pages.
1265 # This can be done periodically via maintenance/compressOld.php, and
1266 # as pages are saved if $wgCompressRevisions is set.
1267 $text = gzinflate( $text );
1270 if ( in_array( 'object', $flags ) ) {
1271 # Generic compressed storage
1272 $obj = unserialize( $text );
1273 if ( !is_object( $obj ) ) {
1277 $text = $obj->getText();
1280 global $wgLegacyEncoding;
1281 if ( $text !== false && $wgLegacyEncoding
1282 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
1284 # Old revisions kept around in a legacy encoding?
1285 # Upconvert on demand.
1286 # ("utf8" checked for compatibility with some broken
1287 # conversion scripts 2008-12-30)
1289 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1296 * Insert a new revision into the database, returning the new revision ID
1297 * number on success and dies horribly on failure.
1299 * @param $dbw DatabaseBase: (master connection)
1300 * @throws MWException
1303 public function insertOn( $dbw ) {
1304 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1306 wfProfileIn( __METHOD__
);
1308 $this->checkContentModel();
1310 $data = $this->mText
;
1311 $flags = self
::compressRevisionText( $data );
1313 # Write to external storage if required
1314 if ( $wgDefaultExternalStore ) {
1315 // Store and get the URL
1316 $data = ExternalStore
::insertToDefault( $data );
1318 wfProfileOut( __METHOD__
);
1319 throw new MWException( "Unable to store text to external storage" );
1324 $flags .= 'external';
1327 # Record the text (or external storage URL) to the text table
1328 if ( !isset( $this->mTextId
) ) {
1329 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1330 $dbw->insert( 'text',
1332 'old_id' => $old_id,
1333 'old_text' => $data,
1334 'old_flags' => $flags,
1337 $this->mTextId
= $dbw->insertId();
1340 if ( $this->mComment
=== null ) {
1341 $this->mComment
= "";
1344 # Record the edit in revisions
1345 $rev_id = isset( $this->mId
)
1347 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1349 'rev_id' => $rev_id,
1350 'rev_page' => $this->mPage
,
1351 'rev_text_id' => $this->mTextId
,
1352 'rev_comment' => $this->mComment
,
1353 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1354 'rev_user' => $this->mUser
,
1355 'rev_user_text' => $this->mUserText
,
1356 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1357 'rev_deleted' => $this->mDeleted
,
1358 'rev_len' => $this->mSize
,
1359 'rev_parent_id' => is_null( $this->mParentId
)
1360 ?
$this->getPreviousRevisionId( $dbw )
1362 'rev_sha1' => is_null( $this->mSha1
)
1363 ? Revision
::base36Sha1( $this->mText
)
1367 if ( $wgContentHandlerUseDB ) {
1368 //NOTE: Store null for the default model and format, to save space.
1369 //XXX: Makes the DB sensitive to changed defaults. Make this behavior optional? Only in miser mode?
1371 $model = $this->getContentModel();
1372 $format = $this->getContentFormat();
1374 $title = $this->getTitle();
1376 if ( $title === null ) {
1377 wfProfileOut( __METHOD__
);
1378 throw new MWException( "Insufficient information to determine the title of the revision's page!" );
1381 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1382 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1384 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1385 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1388 $dbw->insert( 'revision', $row, __METHOD__
);
1390 $this->mId
= !is_null( $rev_id ) ?
$rev_id : $dbw->insertId();
1392 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1394 wfProfileOut( __METHOD__
);
1398 protected function checkContentModel() {
1399 global $wgContentHandlerUseDB;
1401 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1403 $model = $this->getContentModel();
1404 $format = $this->getContentFormat();
1405 $handler = $this->getContentHandler();
1407 if ( !$handler->isSupportedFormat( $format ) ) {
1408 $t = $title->getPrefixedDBkey();
1410 throw new MWException( "Can't use format $format with content model $model on $t" );
1413 if ( !$wgContentHandlerUseDB && $title ) {
1414 // if $wgContentHandlerUseDB is not set, all revisions must use the default content model and format.
1416 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1417 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1418 $defaultFormat = $defaultHandler->getDefaultFormat();
1420 if ( $this->getContentModel() != $defaultModel ) {
1421 $t = $title->getPrefixedDBkey();
1423 throw new MWException( "Can't save non-default content model with \$wgContentHandlerUseDB disabled: "
1424 . "model is $model , default for $t is $defaultModel" );
1427 if ( $this->getContentFormat() != $defaultFormat ) {
1428 $t = $title->getPrefixedDBkey();
1430 throw new MWException( "Can't use non-default content format with \$wgContentHandlerUseDB disabled: "
1431 . "format is $format, default for $t is $defaultFormat" );
1435 $content = $this->getContent( Revision
::RAW
);
1437 if ( !$content ||
!$content->isValid() ) {
1438 $t = $title->getPrefixedDBkey();
1440 throw new MWException( "Content of $t is not valid! Content model is $model" );
1445 * Get the base 36 SHA-1 value for a string of text
1446 * @param $text String
1449 public static function base36Sha1( $text ) {
1450 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1454 * Lazy-load the revision's text.
1455 * Currently hardcoded to the 'text' table storage engine.
1457 * @return String|bool the revision's text, or false on failure
1459 protected function loadText() {
1460 wfProfileIn( __METHOD__
);
1462 // Caching may be beneficial for massive use of external storage
1463 global $wgRevisionCacheExpiry, $wgMemc;
1464 $textId = $this->getTextId();
1465 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1466 if ( $wgRevisionCacheExpiry ) {
1467 $text = $wgMemc->get( $key );
1468 if ( is_string( $text ) ) {
1469 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1470 wfProfileOut( __METHOD__
);
1475 // If we kept data for lazy extraction, use it now...
1476 if ( isset( $this->mTextRow
) ) {
1477 $row = $this->mTextRow
;
1478 $this->mTextRow
= null;
1484 // Text data is immutable; check slaves first.
1485 $dbr = wfGetDB( DB_SLAVE
);
1486 $row = $dbr->selectRow( 'text',
1487 array( 'old_text', 'old_flags' ),
1488 array( 'old_id' => $textId ),
1492 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1493 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1494 $forUpdate = ( $this->mQueryFlags
& self
::READ_LOCKING
== self
::READ_LOCKING
);
1495 if ( !$row && ( $forUpdate ||
wfGetLB()->getServerCount() > 1 ) ) {
1496 $dbw = wfGetDB( DB_MASTER
);
1497 $row = $dbw->selectRow( 'text',
1498 array( 'old_text', 'old_flags' ),
1499 array( 'old_id' => $textId ),
1501 $forUpdate ?
array( 'FOR UPDATE' ) : array() );
1505 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1508 $text = self
::getRevisionText( $row );
1509 if ( $row && $text === false ) {
1510 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1513 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1514 if ( $wgRevisionCacheExpiry && $text !== false ) {
1515 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1518 wfProfileOut( __METHOD__
);
1524 * Create a new null-revision for insertion into a page's
1525 * history. This will not re-save the text, but simply refer
1526 * to the text from the previous version.
1528 * Such revisions can for instance identify page rename
1529 * operations and other such meta-modifications.
1531 * @param $dbw DatabaseBase
1532 * @param $pageId Integer: ID number of the page to read from
1533 * @param string $summary revision's summary
1534 * @param $minor Boolean: whether the revision should be considered as minor
1535 * @return Revision|null on error
1537 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1538 global $wgContentHandlerUseDB;
1540 wfProfileIn( __METHOD__
);
1542 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1543 'rev_text_id', 'rev_len', 'rev_sha1' );
1545 if ( $wgContentHandlerUseDB ) {
1546 $fields[] = 'rev_content_model';
1547 $fields[] = 'rev_content_format';
1550 $current = $dbw->selectRow(
1551 array( 'page', 'revision' ),
1554 'page_id' => $pageId,
1555 'page_latest=rev_id',
1562 'comment' => $summary,
1563 'minor_edit' => $minor,
1564 'text_id' => $current->rev_text_id
,
1565 'parent_id' => $current->page_latest
,
1566 'len' => $current->rev_len
,
1567 'sha1' => $current->rev_sha1
1570 if ( $wgContentHandlerUseDB ) {
1571 $row['content_model'] = $current->rev_content_model
;
1572 $row['content_format'] = $current->rev_content_format
;
1575 $revision = new Revision( $row );
1576 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1581 wfProfileOut( __METHOD__
);
1586 * Determine if the current user is allowed to view a particular
1587 * field of this revision, if it's marked as deleted.
1589 * @param $field Integer:one of self::DELETED_TEXT,
1590 * self::DELETED_COMMENT,
1591 * self::DELETED_USER
1592 * @param $user User object to check, or null to use $wgUser
1595 public function userCan( $field, User
$user = null ) {
1596 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1600 * Determine if the current user is allowed to view a particular
1601 * field of this revision, if it's marked as deleted. This is used
1602 * by various classes to avoid duplication.
1604 * @param $bitfield Integer: current field
1605 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1606 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1607 * self::DELETED_USER = File::DELETED_USER
1608 * @param $user User object to check, or null to use $wgUser
1611 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
1612 if ( $bitfield & $field ) { // aspect is deleted
1613 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1614 $permission = 'suppressrevision';
1615 } elseif ( $field & self
::DELETED_TEXT
) {
1616 $permission = 'deletedtext';
1618 $permission = 'deletedhistory';
1620 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1621 if ( $user === null ) {
1625 return $user->isAllowed( $permission );
1632 * Get rev_timestamp from rev_id, without loading the rest of the row
1634 * @param $title Title
1635 * @param $id Integer
1638 static function getTimestampFromId( $title, $id ) {
1639 $dbr = wfGetDB( DB_SLAVE
);
1640 // Casting fix for databases that can't take '' for rev_id
1644 $conds = array( 'rev_id' => $id );
1645 $conds['rev_page'] = $title->getArticleID();
1646 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1647 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1648 # Not in slave, try master
1649 $dbw = wfGetDB( DB_MASTER
);
1650 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1652 return wfTimestamp( TS_MW
, $timestamp );
1656 * Get count of revisions per page...not very efficient
1658 * @param $db DatabaseBase
1659 * @param $id Integer: page id
1662 static function countByPageId( $db, $id ) {
1663 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1664 array( 'rev_page' => $id ), __METHOD__
);
1666 return $row->revCount
;
1672 * Get count of revisions per page...not very efficient
1674 * @param $db DatabaseBase
1675 * @param $title Title
1678 static function countByTitle( $db, $title ) {
1679 $id = $title->getArticleID();
1681 return self
::countByPageId( $db, $id );
1687 * Check if no edits were made by other users since
1688 * the time a user started editing the page. Limit to
1689 * 50 revisions for the sake of performance.
1693 * @param DatabaseBase|int $db the Database to perform the check on. May be given as a Database object or
1694 * a database identifier usable with wfGetDB.
1695 * @param int $pageId the ID of the page in question
1696 * @param int $userId the ID of the user in question
1697 * @param string $since look at edits since this time
1699 * @return bool True if the given user was the only one to edit since the given timestamp
1701 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1706 if ( is_int( $db ) ) {
1707 $db = wfGetDB( $db );
1710 $res = $db->select( 'revision',
1713 'rev_page' => $pageId,
1714 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1717 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1718 foreach ( $res as $row ) {
1719 if ( $row->rev_user
!= $userId ) {