3 * Representation of a page version.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
26 class Revision
implements IDBAccessObject
{
34 protected $mOrigUserText;
36 protected $mMinorEdit;
37 protected $mTimestamp;
56 protected $mContentModel;
57 protected $mContentFormat;
60 * @var Content|null|bool
65 * @var null|ContentHandler
67 protected $mContentHandler;
72 protected $mQueryFlags = 0;
74 // Revision deletion constants
75 const DELETED_TEXT
= 1;
76 const DELETED_COMMENT
= 2;
77 const DELETED_USER
= 4;
78 const DELETED_RESTRICTED
= 8;
79 const SUPPRESSED_USER
= 12; // convenience
81 // Audience options for accessors
83 const FOR_THIS_USER
= 2;
87 * Load a page revision from a given revision ID number.
88 * Returns null if no such revision can be found.
91 * Revision::READ_LATEST : Select the data from the master
92 * Revision::READ_LOCKING : Select & lock the data from the master
95 * @param int $flags (optional)
96 * @return Revision|null
98 public static function newFromId( $id, $flags = 0 ) {
99 return self
::newFromConds( array( 'rev_id' => intval( $id ) ), $flags );
103 * Load either the current, or a specified, revision
104 * that's attached to a given title. If not attached
105 * to that title, will return null.
108 * Revision::READ_LATEST : Select the data from the master
109 * Revision::READ_LOCKING : Select & lock the data from the master
111 * @param Title $title
112 * @param int $id (optional)
113 * @param int $flags Bitfield (optional)
114 * @return Revision|null
116 public static function newFromTitle( $title, $id = 0, $flags = 0 ) {
118 'page_namespace' => $title->getNamespace(),
119 'page_title' => $title->getDBkey()
122 // Use the specified ID
123 $conds['rev_id'] = $id;
124 return self
::newFromConds( $conds, (int)$flags );
126 // Use a join to get the latest revision
127 $conds[] = 'rev_id=page_latest';
128 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
129 return self
::loadFromConds( $db, $conds, $flags );
134 * Load either the current, or a specified, revision
135 * that's attached to a given page ID.
136 * Returns null if no such revision can be found.
139 * Revision::READ_LATEST : Select the data from the master (since 1.20)
140 * Revision::READ_LOCKING : Select & lock the data from the master
143 * @param int $revId (optional)
144 * @param int $flags Bitfield (optional)
145 * @return Revision|null
147 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
148 $conds = array( 'page_id' => $pageId );
150 $conds['rev_id'] = $revId;
152 // Use a join to get the latest revision
153 $conds[] = 'rev_id = page_latest';
155 return self
::newFromConds( $conds, (int)$flags );
159 * Make a fake revision object from an archive table row. This is queried
160 * for permissions or even inserted (as in Special:Undelete)
161 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
164 * @param array $overrides
166 * @throws MWException
169 public static function newFromArchiveRow( $row, $overrides = array() ) {
170 global $wgContentHandlerUseDB;
172 $attribs = $overrides +
array(
173 'page' => isset( $row->ar_page_id
) ?
$row->ar_page_id
: null,
174 'id' => isset( $row->ar_rev_id
) ?
$row->ar_rev_id
: null,
175 'comment' => $row->ar_comment
,
176 'user' => $row->ar_user
,
177 'user_text' => $row->ar_user_text
,
178 'timestamp' => $row->ar_timestamp
,
179 'minor_edit' => $row->ar_minor_edit
,
180 'text_id' => isset( $row->ar_text_id
) ?
$row->ar_text_id
: null,
181 'deleted' => $row->ar_deleted
,
182 'len' => $row->ar_len
,
183 'sha1' => isset( $row->ar_sha1
) ?
$row->ar_sha1
: null,
184 'content_model' => isset( $row->ar_content_model
) ?
$row->ar_content_model
: null,
185 'content_format' => isset( $row->ar_content_format
) ?
$row->ar_content_format
: null,
188 if ( !$wgContentHandlerUseDB ) {
189 unset( $attribs['content_model'] );
190 unset( $attribs['content_format'] );
193 if ( !isset( $attribs['title'] )
194 && isset( $row->ar_namespace
)
195 && isset( $row->ar_title
) ) {
197 $attribs['title'] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
200 if ( isset( $row->ar_text
) && !$row->ar_text_id
) {
201 // Pre-1.5 ar_text row
202 $attribs['text'] = self
::getRevisionText( $row, 'ar_' );
203 if ( $attribs['text'] === false ) {
204 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
207 return new self( $attribs );
216 public static function newFromRow( $row ) {
217 return new self( $row );
221 * Load a page revision from a given revision ID number.
222 * Returns null if no such revision can be found.
224 * @param DatabaseBase $db
226 * @return Revision|null
228 public static function loadFromId( $db, $id ) {
229 return self
::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
233 * Load either the current, or a specified, revision
234 * that's attached to a given page. If not attached
235 * to that page, will return null.
237 * @param DatabaseBase $db
240 * @return Revision|null
242 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
243 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
245 $conds['rev_id'] = intval( $id );
247 $conds[] = 'rev_id=page_latest';
249 return self
::loadFromConds( $db, $conds );
253 * Load either the current, or a specified, revision
254 * that's attached to a given page. If not attached
255 * to that page, will return null.
257 * @param DatabaseBase $db
258 * @param Title $title
260 * @return Revision|null
262 public static function loadFromTitle( $db, $title, $id = 0 ) {
264 $matchId = intval( $id );
266 $matchId = 'page_latest';
268 return self
::loadFromConds( $db,
271 'page_namespace' => $title->getNamespace(),
272 'page_title' => $title->getDBkey()
278 * Load the revision for the given title with the given timestamp.
279 * WARNING: Timestamps may in some circumstances not be unique,
280 * so this isn't the best key to use.
282 * @param DatabaseBase $db
283 * @param Title $title
284 * @param string $timestamp
285 * @return Revision|null
287 public static function loadFromTimestamp( $db, $title, $timestamp ) {
288 return self
::loadFromConds( $db,
290 'rev_timestamp' => $db->timestamp( $timestamp ),
291 'page_namespace' => $title->getNamespace(),
292 'page_title' => $title->getDBkey()
298 * Given a set of conditions, fetch a revision.
300 * @param array $conditions
301 * @param int $flags (optional)
302 * @return Revision|null
304 private static function newFromConds( $conditions, $flags = 0 ) {
305 $db = wfGetDB( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_SLAVE
);
306 $rev = self
::loadFromConds( $db, $conditions, $flags );
307 if ( $rev === null && wfGetLB()->getServerCount() > 1 ) {
308 if ( !( $flags & self
::READ_LATEST
) ) {
309 $dbw = wfGetDB( DB_MASTER
);
310 $rev = self
::loadFromConds( $dbw, $conditions, $flags );
314 $rev->mQueryFlags
= $flags;
320 * Given a set of conditions, fetch a revision from
321 * the given database connection.
323 * @param DatabaseBase $db
324 * @param array $conditions
325 * @param int $flags (optional)
326 * @return Revision|null
328 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
329 $res = self
::fetchFromConds( $db, $conditions, $flags );
331 $row = $res->fetchObject();
333 $ret = new Revision( $row );
342 * Return a wrapper for a series of database rows to
343 * fetch all of a given page's revisions in turn.
344 * Each row can be fed to the constructor to get objects.
346 * @param Title $title
347 * @return ResultWrapper
349 public static function fetchRevision( $title ) {
350 return self
::fetchFromConds(
353 'rev_id=page_latest',
354 'page_namespace' => $title->getNamespace(),
355 'page_title' => $title->getDBkey()
361 * Given a set of conditions, return a ResultWrapper
362 * which will return matching database rows with the
363 * fields necessary to build Revision objects.
365 * @param DatabaseBase $db
366 * @param array $conditions
367 * @param int $flags (optional)
368 * @return ResultWrapper
370 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
371 $fields = array_merge(
372 self
::selectFields(),
373 self
::selectPageFields(),
374 self
::selectUserFields()
376 $options = array( 'LIMIT' => 1 );
377 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
378 $options[] = 'FOR UPDATE';
381 array( 'revision', 'page', 'user' ),
386 array( 'page' => self
::pageJoinCond(), 'user' => self
::userJoinCond() )
391 * Return the value of a select() JOIN conds array for the user table.
392 * This will get user table rows for logged-in users.
396 public static function userJoinCond() {
397 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
401 * Return the value of a select() page conds array for the page table.
402 * This will assure that the revision(s) are not orphaned from live pages.
406 public static function pageJoinCond() {
407 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
411 * Return the list of revision fields that should be selected to create
415 public static function selectFields() {
416 global $wgContentHandlerUseDB;
433 if ( $wgContentHandlerUseDB ) {
434 $fields[] = 'rev_content_format';
435 $fields[] = 'rev_content_model';
442 * Return the list of revision fields that should be selected to create
443 * a new revision from an archive row.
446 public static function selectArchiveFields() {
447 global $wgContentHandlerUseDB;
465 if ( $wgContentHandlerUseDB ) {
466 $fields[] = 'ar_content_format';
467 $fields[] = 'ar_content_model';
473 * Return the list of text fields that should be selected to read the
477 public static function selectTextFields() {
485 * Return the list of page fields that should be selected from page table
488 public static function selectPageFields() {
500 * Return the list of user fields that should be selected from user table
503 public static function selectUserFields() {
504 return array( 'user_name' );
508 * Do a batched query to get the parent revision lengths
509 * @param DatabaseBase $db
510 * @param array $revIds
513 public static function getParentLengths( $db, array $revIds ) {
516 return $revLens; // empty
518 $res = $db->select( 'revision',
519 array( 'rev_id', 'rev_len' ),
520 array( 'rev_id' => $revIds ),
522 foreach ( $res as $row ) {
523 $revLens[$row->rev_id
] = $row->rev_len
;
531 * @param object|array $row Either a database row or an array
532 * @throws MWException
535 function __construct( $row ) {
536 if ( is_object( $row ) ) {
537 $this->mId
= intval( $row->rev_id
);
538 $this->mPage
= intval( $row->rev_page
);
539 $this->mTextId
= intval( $row->rev_text_id
);
540 $this->mComment
= $row->rev_comment
;
541 $this->mUser
= intval( $row->rev_user
);
542 $this->mMinorEdit
= intval( $row->rev_minor_edit
);
543 $this->mTimestamp
= $row->rev_timestamp
;
544 $this->mDeleted
= intval( $row->rev_deleted
);
546 if ( !isset( $row->rev_parent_id
) ) {
547 $this->mParentId
= null;
549 $this->mParentId
= intval( $row->rev_parent_id
);
552 if ( !isset( $row->rev_len
) ) {
555 $this->mSize
= intval( $row->rev_len
);
558 if ( !isset( $row->rev_sha1
) ) {
561 $this->mSha1
= $row->rev_sha1
;
564 if ( isset( $row->page_latest
) ) {
565 $this->mCurrent
= ( $row->rev_id
== $row->page_latest
);
566 $this->mTitle
= Title
::newFromRow( $row );
568 $this->mCurrent
= false;
569 $this->mTitle
= null;
572 if ( !isset( $row->rev_content_model
) ) {
573 $this->mContentModel
= null; # determine on demand if needed
575 $this->mContentModel
= strval( $row->rev_content_model
);
578 if ( !isset( $row->rev_content_format
) ) {
579 $this->mContentFormat
= null; # determine on demand if needed
581 $this->mContentFormat
= strval( $row->rev_content_format
);
584 // Lazy extraction...
586 if ( isset( $row->old_text
) ) {
587 $this->mTextRow
= $row;
589 // 'text' table row entry will be lazy-loaded
590 $this->mTextRow
= null;
593 // Use user_name for users and rev_user_text for IPs...
594 $this->mUserText
= null; // lazy load if left null
595 if ( $this->mUser
== 0 ) {
596 $this->mUserText
= $row->rev_user_text
; // IP user
597 } elseif ( isset( $row->user_name
) ) {
598 $this->mUserText
= $row->user_name
; // logged-in user
600 $this->mOrigUserText
= $row->rev_user_text
;
601 } elseif ( is_array( $row ) ) {
602 // Build a new revision to be saved...
603 global $wgUser; // ugh
605 # if we have a content object, use it to set the model and type
606 if ( !empty( $row['content'] ) ) {
607 // @todo when is that set? test with external store setup! check out insertOn() [dk]
608 if ( !empty( $row['text_id'] ) ) {
609 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
610 "can't serialize content object" );
613 $row['content_model'] = $row['content']->getModel();
614 # note: mContentFormat is initializes later accordingly
615 # note: content is serialized later in this method!
616 # also set text to null?
619 $this->mId
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
620 $this->mPage
= isset( $row['page'] ) ?
intval( $row['page'] ) : null;
621 $this->mTextId
= isset( $row['text_id'] ) ?
intval( $row['text_id'] ) : null;
622 $this->mUserText
= isset( $row['user_text'] )
623 ?
strval( $row['user_text'] ) : $wgUser->getName();
624 $this->mUser
= isset( $row['user'] ) ?
intval( $row['user'] ) : $wgUser->getId();
625 $this->mMinorEdit
= isset( $row['minor_edit'] ) ?
intval( $row['minor_edit'] ) : 0;
626 $this->mTimestamp
= isset( $row['timestamp'] )
627 ?
strval( $row['timestamp'] ) : wfTimestampNow();
628 $this->mDeleted
= isset( $row['deleted'] ) ?
intval( $row['deleted'] ) : 0;
629 $this->mSize
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
630 $this->mParentId
= isset( $row['parent_id'] ) ?
intval( $row['parent_id'] ) : null;
631 $this->mSha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
633 $this->mContentModel
= isset( $row['content_model'] )
634 ?
strval( $row['content_model'] ) : null;
635 $this->mContentFormat
= isset( $row['content_format'] )
636 ?
strval( $row['content_format'] ) : null;
638 // Enforce spacing trimming on supplied text
639 $this->mComment
= isset( $row['comment'] ) ?
trim( strval( $row['comment'] ) ) : null;
640 $this->mText
= isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
641 $this->mTextRow
= null;
643 $this->mTitle
= isset( $row['title'] ) ?
$row['title'] : null;
645 // if we have a Content object, override mText and mContentModel
646 if ( !empty( $row['content'] ) ) {
647 if ( !( $row['content'] instanceof Content
) ) {
648 throw new MWException( '`content` field must contain a Content object.' );
651 $handler = $this->getContentHandler();
652 $this->mContent
= $row['content'];
654 $this->mContentModel
= $this->mContent
->getModel();
655 $this->mContentHandler
= null;
657 $this->mText
= $handler->serializeContent( $row['content'], $this->getContentFormat() );
658 } elseif ( $this->mText
!== null ) {
659 $handler = $this->getContentHandler();
660 $this->mContent
= $handler->unserializeContent( $this->mText
);
663 // If we have a Title object, make sure it is consistent with mPage.
664 if ( $this->mTitle
&& $this->mTitle
->exists() ) {
665 if ( $this->mPage
=== null ) {
666 // if the page ID wasn't known, set it now
667 $this->mPage
= $this->mTitle
->getArticleID();
668 } elseif ( $this->mTitle
->getArticleID() !== $this->mPage
) {
669 // Got different page IDs. This may be legit (e.g. during undeletion),
670 // but it seems worth mentioning it in the log.
671 wfDebug( "Page ID " . $this->mPage
. " mismatches the ID " .
672 $this->mTitle
->getArticleID() . " provided by the Title object." );
676 $this->mCurrent
= false;
678 // If we still have no length, see it we have the text to figure it out
679 if ( !$this->mSize
&& $this->mContent
!== null ) {
680 $this->mSize
= $this->mContent
->getSize();
684 if ( $this->mSha1
=== null ) {
685 $this->mSha1
= $this->mText
=== null ?
null : self
::base36Sha1( $this->mText
);
689 $this->getContentModel();
690 $this->getContentFormat();
692 throw new MWException( 'Revision constructor passed invalid row format.' );
694 $this->mUnpatrolled
= null;
702 public function getId() {
707 * Set the revision ID
712 public function setId( $id ) {
721 public function getTextId() {
722 return $this->mTextId
;
726 * Get parent revision ID (the original previous page revision)
730 public function getParentId() {
731 return $this->mParentId
;
735 * Returns the length of the text in this revision, or null if unknown.
739 public function getSize() {
744 * Returns the base36 sha1 of the text in this revision, or null if unknown.
746 * @return string|null
748 public function getSha1() {
753 * Returns the title of the page associated with this entry or null.
755 * Will do a query, when title is not set and id is given.
759 public function getTitle() {
760 if ( $this->mTitle
!== null ) {
761 return $this->mTitle
;
763 //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
764 if ( $this->mId
!== null ) {
765 $dbr = wfGetDB( DB_SLAVE
);
766 $row = $dbr->selectRow(
767 array( 'page', 'revision' ),
768 self
::selectPageFields(),
769 array( 'page_id=rev_page',
770 'rev_id' => $this->mId
),
773 $this->mTitle
= Title
::newFromRow( $row );
777 if ( !$this->mTitle
&& $this->mPage
!== null && $this->mPage
> 0 ) {
778 $this->mTitle
= Title
::newFromID( $this->mPage
);
781 return $this->mTitle
;
785 * Set the title of the revision
787 * @param Title $title
789 public function setTitle( $title ) {
790 $this->mTitle
= $title;
798 public function getPage() {
803 * Fetch revision's user id if it's available to the specified audience.
804 * If the specified audience does not have access to it, zero will be
807 * @param int $audience One of:
808 * Revision::FOR_PUBLIC to be displayed to all users
809 * Revision::FOR_THIS_USER to be displayed to the given user
810 * Revision::RAW get the ID regardless of permissions
811 * @param User $user User object to check for, only if FOR_THIS_USER is passed
812 * to the $audience parameter
815 public function getUser( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
816 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
818 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
826 * Fetch revision's user id without regard for the current user's permissions
830 public function getRawUser() {
835 * Fetch revision's username if it's available to the specified audience.
836 * If the specified audience does not have access to the username, an
837 * empty string will be returned.
839 * @param int $audience One of:
840 * Revision::FOR_PUBLIC to be displayed to all users
841 * Revision::FOR_THIS_USER to be displayed to the given user
842 * Revision::RAW get the text regardless of permissions
843 * @param User $user User object to check for, only if FOR_THIS_USER is passed
844 * to the $audience parameter
847 public function getUserText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
848 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
850 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $user ) ) {
853 return $this->getRawUserText();
858 * Fetch revision's username without regard for view restrictions
862 public function getRawUserText() {
863 if ( $this->mUserText
=== null ) {
864 $this->mUserText
= User
::whoIs( $this->mUser
); // load on demand
865 if ( $this->mUserText
=== false ) {
866 # This shouldn't happen, but it can if the wiki was recovered
867 # via importing revs and there is no user table entry yet.
868 $this->mUserText
= $this->mOrigUserText
;
871 return $this->mUserText
;
875 * Fetch revision comment if it's available to the specified audience.
876 * If the specified audience does not have access to the comment, an
877 * empty string will be returned.
879 * @param int $audience One of:
880 * Revision::FOR_PUBLIC to be displayed to all users
881 * Revision::FOR_THIS_USER to be displayed to the given user
882 * Revision::RAW get the text regardless of permissions
883 * @param User $user User object to check for, only if FOR_THIS_USER is passed
884 * to the $audience parameter
887 function getComment( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
888 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
890 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $user ) ) {
893 return $this->mComment
;
898 * Fetch revision comment without regard for the current user's permissions
902 public function getRawComment() {
903 return $this->mComment
;
909 public function isMinor() {
910 return (bool)$this->mMinorEdit
;
914 * @return int Rcid of the unpatrolled row, zero if there isn't one
916 public function isUnpatrolled() {
917 if ( $this->mUnpatrolled
!== null ) {
918 return $this->mUnpatrolled
;
920 $rc = $this->getRecentChange();
921 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
922 $this->mUnpatrolled
= $rc->getAttribute( 'rc_id' );
924 $this->mUnpatrolled
= 0;
926 return $this->mUnpatrolled
;
930 * Get the RC object belonging to the current revision, if there's one
933 * @return RecentChange|null
935 public function getRecentChange() {
936 $dbr = wfGetDB( DB_SLAVE
);
937 return RecentChange
::newFromConds(
939 'rc_user_text' => $this->getRawUserText(),
940 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
941 'rc_this_oldid' => $this->getId()
948 * @param int $field One of DELETED_* bitfield constants
952 public function isDeleted( $field ) {
953 return ( $this->mDeleted
& $field ) == $field;
957 * Get the deletion bitfield of the revision
961 public function getVisibility() {
962 return (int)$this->mDeleted
;
966 * Fetch revision text if it's available to the specified audience.
967 * If the specified audience does not have the ability to view this
968 * revision, an empty string will be returned.
970 * @param int $audience One of:
971 * Revision::FOR_PUBLIC to be displayed to all users
972 * Revision::FOR_THIS_USER to be displayed to the given user
973 * Revision::RAW get the text regardless of permissions
974 * @param User $user User object to check for, only if FOR_THIS_USER is passed
975 * to the $audience parameter
977 * @deprecated since 1.21, use getContent() instead
978 * @todo Replace usage in core
981 public function getText( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
982 ContentHandler
::deprecated( __METHOD__
, '1.21' );
984 $content = $this->getContent( $audience, $user );
985 return ContentHandler
::getContentText( $content ); # returns the raw content text, if applicable
989 * Fetch revision content if it's available to the specified audience.
990 * If the specified audience does not have the ability to view this
991 * revision, null will be returned.
993 * @param int $audience One of:
994 * Revision::FOR_PUBLIC to be displayed to all users
995 * Revision::FOR_THIS_USER to be displayed to $wgUser
996 * Revision::RAW get the text regardless of permissions
997 * @param User $user User object to check for, only if FOR_THIS_USER is passed
998 * to the $audience parameter
1000 * @return Content|null
1002 public function getContent( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1003 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_TEXT
) ) {
1005 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_TEXT
, $user ) ) {
1008 return $this->getContentInternal();
1013 * Fetch revision text without regard for view restrictions
1017 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
1018 * or Revision::getSerializedData() as appropriate.
1020 public function getRawText() {
1021 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1022 return $this->getText( self
::RAW
);
1026 * Fetch original serialized data without regard for view restrictions
1031 public function getSerializedData() {
1032 if ( $this->mText
=== null ) {
1033 $this->mText
= $this->loadText();
1036 return $this->mText
;
1040 * Gets the content object for the revision (or null on failure).
1042 * Note that for mutable Content objects, each call to this method will return a
1046 * @return Content|null The Revision's content, or null on failure.
1048 protected function getContentInternal() {
1049 if ( $this->mContent
=== null ) {
1050 // Revision is immutable. Load on demand:
1051 if ( $this->mText
=== null ) {
1052 $this->mText
= $this->loadText();
1055 if ( $this->mText
!== null && $this->mText
!== false ) {
1056 // Unserialize content
1057 $handler = $this->getContentHandler();
1058 $format = $this->getContentFormat();
1060 $this->mContent
= $handler->unserializeContent( $this->mText
, $format );
1064 // NOTE: copy() will return $this for immutable content objects
1065 return $this->mContent ?
$this->mContent
->copy() : null;
1069 * Returns the content model for this revision.
1071 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
1072 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1073 * is used as a last resort.
1075 * @return string The content model id associated with this revision,
1076 * see the CONTENT_MODEL_XXX constants.
1078 public function getContentModel() {
1079 if ( !$this->mContentModel
) {
1080 $title = $this->getTitle();
1081 $this->mContentModel
= ( $title ?
$title->getContentModel() : CONTENT_MODEL_WIKITEXT
);
1083 assert( !empty( $this->mContentModel
) );
1086 return $this->mContentModel
;
1090 * Returns the content format for this revision.
1092 * If no content format was stored in the database, the default format for this
1093 * revision's content model is returned.
1095 * @return string The content format id associated with this revision,
1096 * see the CONTENT_FORMAT_XXX constants.
1098 public function getContentFormat() {
1099 if ( !$this->mContentFormat
) {
1100 $handler = $this->getContentHandler();
1101 $this->mContentFormat
= $handler->getDefaultFormat();
1103 assert( !empty( $this->mContentFormat
) );
1106 return $this->mContentFormat
;
1110 * Returns the content handler appropriate for this revision's content model.
1112 * @throws MWException
1113 * @return ContentHandler
1115 public function getContentHandler() {
1116 if ( !$this->mContentHandler
) {
1117 $model = $this->getContentModel();
1118 $this->mContentHandler
= ContentHandler
::getForModelID( $model );
1120 $format = $this->getContentFormat();
1122 if ( !$this->mContentHandler
->isSupportedFormat( $format ) ) {
1123 throw new MWException( "Oops, the content format $format is not supported for "
1124 . "this content model, $model" );
1128 return $this->mContentHandler
;
1134 public function getTimestamp() {
1135 return wfTimestamp( TS_MW
, $this->mTimestamp
);
1141 public function isCurrent() {
1142 return $this->mCurrent
;
1146 * Get previous revision for this title
1148 * @return Revision|null
1150 public function getPrevious() {
1151 if ( $this->getTitle() ) {
1152 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1154 return self
::newFromTitle( $this->getTitle(), $prev );
1161 * Get next revision for this title
1163 * @return Revision|null
1165 public function getNext() {
1166 if ( $this->getTitle() ) {
1167 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1169 return self
::newFromTitle( $this->getTitle(), $next );
1176 * Get previous revision Id for this page_id
1177 * This is used to populate rev_parent_id on save
1179 * @param DatabaseBase $db
1182 private function getPreviousRevisionId( $db ) {
1183 if ( $this->mPage
=== null ) {
1186 # Use page_latest if ID is not given
1187 if ( !$this->mId
) {
1188 $prevId = $db->selectField( 'page', 'page_latest',
1189 array( 'page_id' => $this->mPage
),
1192 $prevId = $db->selectField( 'revision', 'rev_id',
1193 array( 'rev_page' => $this->mPage
, 'rev_id < ' . $this->mId
),
1195 array( 'ORDER BY' => 'rev_id DESC' ) );
1197 return intval( $prevId );
1201 * Get revision text associated with an old or archive row
1202 * $row is usually an object from wfFetchRow(), both the flags and the text
1203 * field must be included.
1205 * @param stdClass $row The text data
1206 * @param string $prefix Table prefix (default 'old_')
1207 * @param string|bool $wiki The name of the wiki to load the revision text from
1208 * (same as the the wiki $row was loaded from) or false to indicate the local
1209 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1210 * identifier as understood by the LoadBalancer class.
1211 * @return string Text the text requested or false on failure
1213 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1216 $textField = $prefix . 'text';
1217 $flagsField = $prefix . 'flags';
1219 if ( isset( $row->$flagsField ) ) {
1220 $flags = explode( ',', $row->$flagsField );
1225 if ( isset( $row->$textField ) ) {
1226 $text = $row->$textField;
1231 # Use external methods for external objects, text in table is URL-only then
1232 if ( in_array( 'external', $flags ) ) {
1234 $parts = explode( '://', $url, 2 );
1235 if ( count( $parts ) == 1 ||
$parts[1] == '' ) {
1238 $text = ExternalStore
::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1241 // If the text was fetched without an error, convert it
1242 if ( $text !== false ) {
1243 $text = self
::decompressRevisionText( $text, $flags );
1249 * If $wgCompressRevisions is enabled, we will compress data.
1250 * The input string is modified in place.
1251 * Return value is the flags field: contains 'gzip' if the
1252 * data is compressed, and 'utf-8' if we're saving in UTF-8
1255 * @param mixed $text Reference to a text
1258 public static function compressRevisionText( &$text ) {
1259 global $wgCompressRevisions;
1262 # Revisions not marked this way will be converted
1263 # on load if $wgLegacyCharset is set in the future.
1266 if ( $wgCompressRevisions ) {
1267 if ( function_exists( 'gzdeflate' ) ) {
1268 $text = gzdeflate( $text );
1271 wfDebug( __METHOD__
. " -- no zlib support, not compressing\n" );
1274 return implode( ',', $flags );
1278 * Re-converts revision text according to it's flags.
1280 * @param mixed $text Reference to a text
1281 * @param array $flags Compression flags
1282 * @return string|bool Decompressed text, or false on failure
1284 public static function decompressRevisionText( $text, $flags ) {
1285 if ( in_array( 'gzip', $flags ) ) {
1286 # Deal with optional compression of archived pages.
1287 # This can be done periodically via maintenance/compressOld.php, and
1288 # as pages are saved if $wgCompressRevisions is set.
1289 $text = gzinflate( $text );
1292 if ( in_array( 'object', $flags ) ) {
1293 # Generic compressed storage
1294 $obj = unserialize( $text );
1295 if ( !is_object( $obj ) ) {
1299 $text = $obj->getText();
1302 global $wgLegacyEncoding;
1303 if ( $text !== false && $wgLegacyEncoding
1304 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1306 # Old revisions kept around in a legacy encoding?
1307 # Upconvert on demand.
1308 # ("utf8" checked for compatibility with some broken
1309 # conversion scripts 2008-12-30)
1311 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1318 * Insert a new revision into the database, returning the new revision ID
1319 * number on success and dies horribly on failure.
1321 * @param DatabaseBase $dbw (master connection)
1322 * @throws MWException
1325 public function insertOn( $dbw ) {
1326 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1329 $this->checkContentModel();
1331 $data = $this->mText
;
1332 $flags = self
::compressRevisionText( $data );
1334 # Write to external storage if required
1335 if ( $wgDefaultExternalStore ) {
1336 // Store and get the URL
1337 $data = ExternalStore
::insertToDefault( $data );
1339 throw new MWException( "Unable to store text to external storage" );
1344 $flags .= 'external';
1347 # Record the text (or external storage URL) to the text table
1348 if ( $this->mTextId
=== null ) {
1349 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1350 $dbw->insert( 'text',
1352 'old_id' => $old_id,
1353 'old_text' => $data,
1354 'old_flags' => $flags,
1357 $this->mTextId
= $dbw->insertId();
1360 if ( $this->mComment
=== null ) {
1361 $this->mComment
= "";
1364 # Record the edit in revisions
1365 $rev_id = $this->mId
!== null
1367 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1369 'rev_id' => $rev_id,
1370 'rev_page' => $this->mPage
,
1371 'rev_text_id' => $this->mTextId
,
1372 'rev_comment' => $this->mComment
,
1373 'rev_minor_edit' => $this->mMinorEdit ?
1 : 0,
1374 'rev_user' => $this->mUser
,
1375 'rev_user_text' => $this->mUserText
,
1376 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp
),
1377 'rev_deleted' => $this->mDeleted
,
1378 'rev_len' => $this->mSize
,
1379 'rev_parent_id' => $this->mParentId
=== null
1380 ?
$this->getPreviousRevisionId( $dbw )
1382 'rev_sha1' => $this->mSha1
=== null
1383 ? Revision
::base36Sha1( $this->mText
)
1387 if ( $wgContentHandlerUseDB ) {
1388 //NOTE: Store null for the default model and format, to save space.
1389 //XXX: Makes the DB sensitive to changed defaults.
1390 // Make this behavior optional? Only in miser mode?
1392 $model = $this->getContentModel();
1393 $format = $this->getContentFormat();
1395 $title = $this->getTitle();
1397 if ( $title === null ) {
1398 throw new MWException( "Insufficient information to determine the title of the "
1399 . "revision's page!" );
1402 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1403 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
1405 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
1406 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
1409 $dbw->insert( 'revision', $row, __METHOD__
);
1411 $this->mId
= $rev_id !== null ?
$rev_id : $dbw->insertId();
1413 Hooks
::run( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1418 protected function checkContentModel() {
1419 global $wgContentHandlerUseDB;
1421 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1423 $model = $this->getContentModel();
1424 $format = $this->getContentFormat();
1425 $handler = $this->getContentHandler();
1427 if ( !$handler->isSupportedFormat( $format ) ) {
1428 $t = $title->getPrefixedDBkey();
1430 throw new MWException( "Can't use format $format with content model $model on $t" );
1433 if ( !$wgContentHandlerUseDB && $title ) {
1434 // if $wgContentHandlerUseDB is not set,
1435 // all revisions must use the default content model and format.
1437 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
1438 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
1439 $defaultFormat = $defaultHandler->getDefaultFormat();
1441 if ( $this->getContentModel() != $defaultModel ) {
1442 $t = $title->getPrefixedDBkey();
1444 throw new MWException( "Can't save non-default content model with "
1445 . "\$wgContentHandlerUseDB disabled: model is $model, "
1446 . "default for $t is $defaultModel" );
1449 if ( $this->getContentFormat() != $defaultFormat ) {
1450 $t = $title->getPrefixedDBkey();
1452 throw new MWException( "Can't use non-default content format with "
1453 . "\$wgContentHandlerUseDB disabled: format is $format, "
1454 . "default for $t is $defaultFormat" );
1458 $content = $this->getContent( Revision
::RAW
);
1460 if ( !$content ||
!$content->isValid() ) {
1461 $t = $title->getPrefixedDBkey();
1463 throw new MWException( "Content of $t is not valid! Content model is $model" );
1468 * Get the base 36 SHA-1 value for a string of text
1469 * @param string $text
1472 public static function base36Sha1( $text ) {
1473 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1477 * Lazy-load the revision's text.
1478 * Currently hardcoded to the 'text' table storage engine.
1480 * @return string|bool The revision's text, or false on failure
1482 protected function loadText() {
1484 // Caching may be beneficial for massive use of external storage
1485 global $wgRevisionCacheExpiry, $wgMemc;
1486 $textId = $this->getTextId();
1487 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1488 if ( $wgRevisionCacheExpiry ) {
1489 $text = $wgMemc->get( $key );
1490 if ( is_string( $text ) ) {
1491 wfDebug( __METHOD__
. ": got id $textId from cache\n" );
1496 // If we kept data for lazy extraction, use it now...
1497 if ( $this->mTextRow
!== null ) {
1498 $row = $this->mTextRow
;
1499 $this->mTextRow
= null;
1505 // Text data is immutable; check slaves first.
1506 $dbr = wfGetDB( DB_SLAVE
);
1507 $row = $dbr->selectRow( 'text',
1508 array( 'old_text', 'old_flags' ),
1509 array( 'old_id' => $textId ),
1513 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1514 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1515 $forUpdate = ( $this->mQueryFlags
& self
::READ_LOCKING
== self
::READ_LOCKING
);
1516 if ( !$row && ( $forUpdate ||
wfGetLB()->getServerCount() > 1 ) ) {
1517 $dbw = wfGetDB( DB_MASTER
);
1518 $row = $dbw->selectRow( 'text',
1519 array( 'old_text', 'old_flags' ),
1520 array( 'old_id' => $textId ),
1522 $forUpdate ?
array( 'FOR UPDATE' ) : array() );
1526 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1529 $text = self
::getRevisionText( $row );
1530 if ( $row && $text === false ) {
1531 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1534 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1535 if ( $wgRevisionCacheExpiry && $text !== false ) {
1536 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1544 * Create a new null-revision for insertion into a page's
1545 * history. This will not re-save the text, but simply refer
1546 * to the text from the previous version.
1548 * Such revisions can for instance identify page rename
1549 * operations and other such meta-modifications.
1551 * @param DatabaseBase $dbw
1552 * @param int $pageId ID number of the page to read from
1553 * @param string $summary Revision's summary
1554 * @param bool $minor Whether the revision should be considered as minor
1555 * @param User|null $user User object to use or null for $wgUser
1556 * @return Revision|null Revision or null on error
1558 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1559 global $wgContentHandlerUseDB;
1562 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1563 'rev_text_id', 'rev_len', 'rev_sha1' );
1565 if ( $wgContentHandlerUseDB ) {
1566 $fields[] = 'rev_content_model';
1567 $fields[] = 'rev_content_format';
1570 $current = $dbw->selectRow(
1571 array( 'page', 'revision' ),
1574 'page_id' => $pageId,
1575 'page_latest=rev_id',
1587 'user_text' => $user->getName(),
1588 'user' => $user->getId(),
1589 'comment' => $summary,
1590 'minor_edit' => $minor,
1591 'text_id' => $current->rev_text_id
,
1592 'parent_id' => $current->page_latest
,
1593 'len' => $current->rev_len
,
1594 'sha1' => $current->rev_sha1
1597 if ( $wgContentHandlerUseDB ) {
1598 $row['content_model'] = $current->rev_content_model
;
1599 $row['content_format'] = $current->rev_content_format
;
1602 $revision = new Revision( $row );
1603 $revision->setTitle( Title
::makeTitle( $current->page_namespace
, $current->page_title
) );
1612 * Determine if the current user is allowed to view a particular
1613 * field of this revision, if it's marked as deleted.
1615 * @param int $field One of self::DELETED_TEXT,
1616 * self::DELETED_COMMENT,
1617 * self::DELETED_USER
1618 * @param User|null $user User object to check, or null to use $wgUser
1621 public function userCan( $field, User
$user = null ) {
1622 return self
::userCanBitfield( $this->mDeleted
, $field, $user );
1626 * Determine if the current user is allowed to view a particular
1627 * field of this revision, if it's marked as deleted. This is used
1628 * by various classes to avoid duplication.
1630 * @param int $bitfield Current field
1631 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1632 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1633 * self::DELETED_USER = File::DELETED_USER
1634 * @param User|null $user User object to check, or null to use $wgUser
1635 * @param Title|null $title A Title object to check for per-page restrictions on,
1636 * instead of just plain userrights
1639 public static function userCanBitfield( $bitfield, $field, User
$user = null,
1642 if ( $bitfield & $field ) { // aspect is deleted
1643 if ( $user === null ) {
1647 if ( $bitfield & self
::DELETED_RESTRICTED
) {
1648 $permissions = array( 'suppressrevision', 'viewsuppressed' );
1649 } elseif ( $field & self
::DELETED_TEXT
) {
1650 $permissions = array( 'deletedtext' );
1652 $permissions = array( 'deletedhistory' );
1654 $permissionlist = implode( ', ', $permissions );
1655 if ( $title === null ) {
1656 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1657 return call_user_func_array( array( $user, 'isAllowedAny' ), $permissions );
1659 $text = $title->getPrefixedText();
1660 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1661 foreach ( $permissions as $perm ) {
1662 if ( $title->userCan( $perm, $user ) ) {
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.
1734 * @deprecated since 1.24
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 ) {