merged master
[lhc/web/wiklou.git] / includes / Revision.php
1 <?php
2 /**
3 * Representation of a page version.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * @todo document
25 */
26 class Revision {
27 protected $mId;
28 protected $mPage;
29 protected $mUserText;
30 protected $mOrigUserText;
31 protected $mUser;
32 protected $mMinorEdit;
33 protected $mTimestamp;
34 protected $mDeleted;
35 protected $mSize;
36 protected $mSha1;
37 protected $mParentId;
38 protected $mComment;
39 protected $mText;
40 protected $mTextRow;
41 protected $mTitle;
42 protected $mCurrent;
43 protected $mContentModel;
44 protected $mContentFormat;
45 protected $mContent;
46 protected $mContentHandler;
47
48 const DELETED_TEXT = 1;
49 const DELETED_COMMENT = 2;
50 const DELETED_USER = 4;
51 const DELETED_RESTRICTED = 8;
52 // Convenience field
53 const SUPPRESSED_USER = 12;
54 // Audience options for Revision::getText()
55 const FOR_PUBLIC = 1;
56 const FOR_THIS_USER = 2;
57 const RAW = 3;
58
59 /**
60 * Load a page revision from a given revision ID number.
61 * Returns null if no such revision can be found.
62 *
63 * @param $id Integer
64 * @return Revision or null
65 */
66 public static function newFromId( $id ) {
67 return Revision::newFromConds( array( 'rev_id' => intval( $id ) ) );
68 }
69
70 /**
71 * Load either the current, or a specified, revision
72 * that's attached to a given title. If not attached
73 * to that title, will return null.
74 *
75 * @param $title Title
76 * @param $id Integer (optional)
77 * @return Revision or null
78 */
79 public static function newFromTitle( $title, $id = 0 ) {
80 $conds = array(
81 'page_namespace' => $title->getNamespace(),
82 'page_title' => $title->getDBkey()
83 );
84 if ( $id ) {
85 // Use the specified ID
86 $conds['rev_id'] = $id;
87 } elseif ( wfGetLB()->getServerCount() > 1 ) {
88 // Get the latest revision ID from the master
89 $dbw = wfGetDB( DB_MASTER );
90 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
91 if ( $latest === false ) {
92 return null; // page does not exist
93 }
94 $conds['rev_id'] = $latest;
95 } else {
96 // Use a join to get the latest revision
97 $conds[] = 'rev_id=page_latest';
98 }
99 return Revision::newFromConds( $conds );
100 }
101
102 /**
103 * Load either the current, or a specified, revision
104 * that's attached to a given page ID.
105 * Returns null if no such revision can be found.
106 *
107 * @param $revId Integer
108 * @param $pageId Integer (optional)
109 * @return Revision or null
110 */
111 public static function newFromPageId( $pageId, $revId = 0 ) {
112 $conds = array( 'page_id' => $pageId );
113 if ( $revId ) {
114 $conds['rev_id'] = $revId;
115 } elseif ( wfGetLB()->getServerCount() > 1 ) {
116 // Get the latest revision ID from the master
117 $dbw = wfGetDB( DB_MASTER );
118 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
119 if ( $latest === false ) {
120 return null; // page does not exist
121 }
122 $conds['rev_id'] = $latest;
123 } else {
124 $conds[] = 'rev_id = page_latest';
125 }
126 return Revision::newFromConds( $conds );
127 }
128
129 /**
130 * Make a fake revision object from an archive table row. This is queried
131 * for permissions or even inserted (as in Special:Undelete)
132 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
133 *
134 * @param $row
135 * @param $overrides array
136 *
137 * @return Revision
138 */
139 public static function newFromArchiveRow( $row, $overrides = array() ) {
140 global $wgContentHandlerUseDB;
141
142 $attribs = $overrides + array(
143 'page' => isset( $row->ar_page_id ) ? $row->ar_page_id : null,
144 'id' => isset( $row->ar_rev_id ) ? $row->ar_rev_id : null,
145 'comment' => $row->ar_comment,
146 'user' => $row->ar_user,
147 'user_text' => $row->ar_user_text,
148 'timestamp' => $row->ar_timestamp,
149 'minor_edit' => $row->ar_minor_edit,
150 'text_id' => isset( $row->ar_text_id ) ? $row->ar_text_id : null,
151 'deleted' => $row->ar_deleted,
152 'len' => $row->ar_len,
153 'sha1' => isset( $row->ar_sha1 ) ? $row->ar_sha1 : null,
154 'content_model' => isset( $row->ar_content_model ) ? $row->ar_content_model : null,
155 'content_format' => isset( $row->ar_content_format ) ? $row->ar_content_format : null,
156 );
157
158 if ( !$wgContentHandlerUseDB ) {
159 unset( $attribs['content_model'] );
160 unset( $attribs['content_format'] );
161 }
162
163 if ( isset( $row->ar_text ) && !$row->ar_text_id ) {
164 // Pre-1.5 ar_text row
165 $attribs['text'] = self::getRevisionText( $row, 'ar_' );
166 if ( $attribs['text'] === false ) {
167 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
168 }
169 }
170 return new self( $attribs );
171 }
172
173 /**
174 * @since 1.19
175 *
176 * @param $row
177 * @return Revision
178 */
179 public static function newFromRow( $row ) {
180 return new self( $row );
181 }
182
183 /**
184 * Load a page revision from a given revision ID number.
185 * Returns null if no such revision can be found.
186 *
187 * @param $db DatabaseBase
188 * @param $id Integer
189 * @return Revision or null
190 */
191 public static function loadFromId( $db, $id ) {
192 return Revision::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) );
193 }
194
195 /**
196 * Load either the current, or a specified, revision
197 * that's attached to a given page. If not attached
198 * to that page, will return null.
199 *
200 * @param $db DatabaseBase
201 * @param $pageid Integer
202 * @param $id Integer
203 * @return Revision or null
204 */
205 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
206 $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) );
207 if( $id ) {
208 $conds['rev_id'] = intval( $id );
209 } else {
210 $conds[] = 'rev_id=page_latest';
211 }
212 return Revision::loadFromConds( $db, $conds );
213 }
214
215 /**
216 * Load either the current, or a specified, revision
217 * that's attached to a given page. If not attached
218 * to that page, will return null.
219 *
220 * @param $db DatabaseBase
221 * @param $title Title
222 * @param $id Integer
223 * @return Revision or null
224 */
225 public static function loadFromTitle( $db, $title, $id = 0 ) {
226 if( $id ) {
227 $matchId = intval( $id );
228 } else {
229 $matchId = 'page_latest';
230 }
231 return Revision::loadFromConds( $db,
232 array( "rev_id=$matchId",
233 'page_namespace' => $title->getNamespace(),
234 'page_title' => $title->getDBkey() )
235 );
236 }
237
238 /**
239 * Load the revision for the given title with the given timestamp.
240 * WARNING: Timestamps may in some circumstances not be unique,
241 * so this isn't the best key to use.
242 *
243 * @param $db DatabaseBase
244 * @param $title Title
245 * @param $timestamp String
246 * @return Revision or null
247 */
248 public static function loadFromTimestamp( $db, $title, $timestamp ) {
249 return Revision::loadFromConds( $db,
250 array( 'rev_timestamp' => $db->timestamp( $timestamp ),
251 'page_namespace' => $title->getNamespace(),
252 'page_title' => $title->getDBkey() )
253 );
254 }
255
256 /**
257 * Given a set of conditions, fetch a revision.
258 *
259 * @param $conditions Array
260 * @return Revision or null
261 */
262 public static function newFromConds( $conditions ) {
263 $db = wfGetDB( DB_SLAVE );
264 $rev = Revision::loadFromConds( $db, $conditions );
265 if( is_null( $rev ) && wfGetLB()->getServerCount() > 1 ) {
266 $dbw = wfGetDB( DB_MASTER );
267 $rev = Revision::loadFromConds( $dbw, $conditions );
268 }
269 return $rev;
270 }
271
272 /**
273 * Given a set of conditions, fetch a revision from
274 * the given database connection.
275 *
276 * @param $db DatabaseBase
277 * @param $conditions Array
278 * @return Revision or null
279 */
280 private static function loadFromConds( $db, $conditions ) {
281 $res = Revision::fetchFromConds( $db, $conditions );
282 if( $res ) {
283 $row = $res->fetchObject();
284 if( $row ) {
285 $ret = new Revision( $row );
286 return $ret;
287 }
288 }
289 $ret = null;
290 return $ret;
291 }
292
293 /**
294 * Return a wrapper for a series of database rows to
295 * fetch all of a given page's revisions in turn.
296 * Each row can be fed to the constructor to get objects.
297 *
298 * @param $title Title
299 * @return ResultWrapper
300 */
301 public static function fetchRevision( $title ) {
302 return Revision::fetchFromConds(
303 wfGetDB( DB_SLAVE ),
304 array( 'rev_id=page_latest',
305 'page_namespace' => $title->getNamespace(),
306 'page_title' => $title->getDBkey() )
307 );
308 }
309
310 /**
311 * Given a set of conditions, return a ResultWrapper
312 * which will return matching database rows with the
313 * fields necessary to build Revision objects.
314 *
315 * @param $db DatabaseBase
316 * @param $conditions Array
317 * @return ResultWrapper
318 */
319 private static function fetchFromConds( $db, $conditions ) {
320 $fields = array_merge(
321 self::selectFields(),
322 self::selectPageFields(),
323 self::selectUserFields()
324 );
325 return $db->select(
326 array( 'revision', 'page', 'user' ),
327 $fields,
328 $conditions,
329 __METHOD__,
330 array( 'LIMIT' => 1 ),
331 array( 'page' => self::pageJoinCond(), 'user' => self::userJoinCond() )
332 );
333 }
334
335 /**
336 * Return the value of a select() JOIN conds array for the user table.
337 * This will get user table rows for logged-in users.
338 * @since 1.19
339 * @return Array
340 */
341 public static function userJoinCond() {
342 return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) );
343 }
344
345 /**
346 * Return the value of a select() page conds array for the paeg table.
347 * This will assure that the revision(s) are not orphaned from live pages.
348 * @since 1.19
349 * @return Array
350 */
351 public static function pageJoinCond() {
352 return array( 'INNER JOIN', array( 'page_id = rev_page' ) );
353 }
354
355 /**
356 * Return the list of revision fields that should be selected to create
357 * a new revision.
358 * @return array
359 */
360 public static function selectFields() {
361 global $wgContentHandlerUseDB;
362
363 $fields = array(
364 'rev_id',
365 'rev_page',
366 'rev_text_id',
367 'rev_timestamp',
368 'rev_comment',
369 'rev_user_text',
370 'rev_user',
371 'rev_minor_edit',
372 'rev_deleted',
373 'rev_len',
374 'rev_parent_id',
375 'rev_sha1',
376 );
377
378 if ( $wgContentHandlerUseDB ) {
379 $fields[] = 'rev_content_format';
380 $fields[] = 'rev_content_model';
381 }
382
383 return $fields;
384 }
385
386 /**
387 * Return the list of text fields that should be selected to read the
388 * revision text
389 * @return array
390 */
391 public static function selectTextFields() {
392 return array(
393 'old_text',
394 'old_flags'
395 );
396 }
397
398 /**
399 * Return the list of page fields that should be selected from page table
400 * @return array
401 */
402 public static function selectPageFields() {
403 return array(
404 'page_namespace',
405 'page_title',
406 'page_id',
407 'page_latest',
408 'page_is_redirect',
409 'page_len',
410 );
411 }
412
413 /**
414 * Return the list of user fields that should be selected from user table
415 * @return array
416 */
417 public static function selectUserFields() {
418 return array( 'user_name' );
419 }
420
421 /**
422 * Constructor
423 *
424 * @param $row Mixed: either a database row or an array
425 * @access private
426 */
427 function __construct( $row ) {
428 if( is_object( $row ) ) {
429 $this->mId = intval( $row->rev_id );
430 $this->mPage = intval( $row->rev_page );
431 $this->mTextId = intval( $row->rev_text_id );
432 $this->mComment = $row->rev_comment;
433 $this->mUser = intval( $row->rev_user );
434 $this->mMinorEdit = intval( $row->rev_minor_edit );
435 $this->mTimestamp = $row->rev_timestamp;
436 $this->mDeleted = intval( $row->rev_deleted );
437
438 if( !isset( $row->rev_parent_id ) ) {
439 $this->mParentId = is_null( $row->rev_parent_id ) ? null : 0;
440 } else {
441 $this->mParentId = intval( $row->rev_parent_id );
442 }
443
444 if( !isset( $row->rev_len ) || is_null( $row->rev_len ) ) {
445 $this->mSize = null;
446 } else {
447 $this->mSize = intval( $row->rev_len );
448 }
449
450 if ( !isset( $row->rev_sha1 ) ) {
451 $this->mSha1 = null;
452 } else {
453 $this->mSha1 = $row->rev_sha1;
454 }
455
456 if( isset( $row->page_latest ) ) {
457 $this->mCurrent = ( $row->rev_id == $row->page_latest );
458 $this->mTitle = Title::newFromRow( $row );
459 } else {
460 $this->mCurrent = false;
461 $this->mTitle = null;
462 }
463
464 if( !isset( $row->rev_content_model ) || is_null( $row->rev_content_model ) ) {
465 $this->mContentModel = null; # determine on demand if needed
466 } else {
467 $this->mContentModel = intval( $row->rev_content_model );
468 }
469
470 if( !isset( $row->rev_content_format ) || is_null( $row->rev_content_format ) ) {
471 $this->mContentFormat = null; # determine on demand if needed
472 } else {
473 $this->mContentFormat = intval( $row->rev_content_format );
474 }
475
476 // Lazy extraction...
477 $this->mText = null;
478 if( isset( $row->old_text ) ) {
479 $this->mTextRow = $row;
480 } else {
481 // 'text' table row entry will be lazy-loaded
482 $this->mTextRow = null;
483 }
484
485 // Use user_name for users and rev_user_text for IPs...
486 $this->mUserText = null; // lazy load if left null
487 if ( $this->mUser == 0 ) {
488 $this->mUserText = $row->rev_user_text; // IP user
489 } elseif ( isset( $row->user_name ) ) {
490 $this->mUserText = $row->user_name; // logged-in user
491 }
492 $this->mOrigUserText = $row->rev_user_text;
493 } elseif( is_array( $row ) ) {
494 // Build a new revision to be saved...
495 global $wgUser; // ugh
496
497
498 # if we have a content object, use it to set the model and type
499 if ( !empty( $row['content'] ) ) {
500 if ( !empty( $row['text_id'] ) ) { #FIXME: when is that set? test with external store setup! check out insertOn()
501 throw new MWException( "Text already stored in external store (id {$row['text_id']}), can't serialize content object" );
502 }
503
504 $row['content_model'] = $row['content']->getModel();
505 # note: mContentFormat is initializes later accordingly
506 # note: content is serialized later in this method!
507 # also set text to null?
508 }
509
510 $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null;
511 $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null;
512 $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null;
513 $this->mUserText = isset( $row['user_text'] ) ? strval( $row['user_text'] ) : $wgUser->getName();
514 $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId();
515 $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0;
516 $this->mTimestamp = isset( $row['timestamp'] ) ? strval( $row['timestamp'] ) : wfTimestampNow();
517 $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0;
518 $this->mSize = isset( $row['len'] ) ? intval( $row['len'] ) : null;
519 $this->mParentId = isset( $row['parent_id'] ) ? intval( $row['parent_id'] ) : null;
520 $this->mSha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
521
522 $this->mContentModel = isset( $row['content_model'] ) ? intval( $row['content_model'] ) : null;
523 $this->mContentFormat = isset( $row['content_format'] ) ? intval( $row['content_format'] ) : null;
524
525 // Enforce spacing trimming on supplied text
526 $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null;
527 $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
528 $this->mTextRow = null;
529
530 # if we have a content object, override mText and mContentModel
531 if ( !empty( $row['content'] ) ) {
532 $handler = $this->getContentHandler();
533 $this->mContent = $row['content'];
534
535 $this->mContentModel = $this->mContent->getModel();
536 $this->mContentHandler = null;
537
538 $this->mText = $handler->serializeContent( $row['content'], $this->getContentFormat() );
539 } elseif ( !is_null( $this->mText ) ) {
540 $handler = $this->getContentHandler();
541 $this->mContent = $handler->unserializeContent( $this->mText );
542 }
543
544 $this->mTitle = null; # Load on demand if needed
545 $this->mCurrent = false; #XXX: really? we are about to create a revision. it will usually then be the current one.
546
547 # If we still have no length, see it we have the text to figure it out
548 if ( !$this->mSize ) {
549 if ( !is_null( $this->mContent ) ) {
550 $this->mSize = $this->mContent->getSize();
551 } else {
552 #XXX: my be inconsistent with the notion of "size" use for the present content model
553 #NOTE: should never happen if we have either text or content object!
554 $this->mSize = is_null( $this->mText ) ? null : strlen( $this->mText );
555 }
556 }
557
558 # Same for sha1
559 if ( $this->mSha1 === null ) {
560 $this->mSha1 = is_null( $this->mText ) ? null : self::base36Sha1( $this->mText );
561 }
562
563 $this->getContentModel(); # force lazy init
564 $this->getContentFormat(); # force lazy init
565 } else {
566 throw new MWException( 'Revision constructor passed invalid row format.' );
567 }
568 $this->mUnpatrolled = null;
569
570 // @TODO: add support for ar_content_format, ar_content_model, rev_content_format, rev_content_model to API
571 // @TODO: get rid of $mText
572 }
573
574 /**
575 * Get revision ID
576 *
577 * @return Integer|null
578 */
579 public function getId() {
580 return $this->mId;
581 }
582
583 /**
584 * Set the revision ID
585 *
586 * @since 1.19
587 * @param $id Integer
588 */
589 public function setId( $id ) {
590 $this->mId = $id;
591 }
592
593 /**
594 * Get text row ID
595 *
596 * @return Integer|null
597 */
598 public function getTextId() {
599 return $this->mTextId;
600 }
601
602 /**
603 * Get parent revision ID (the original previous page revision)
604 *
605 * @return Integer|null
606 */
607 public function getParentId() {
608 return $this->mParentId;
609 }
610
611 /**
612 * Returns the length of the text in this revision, or null if unknown.
613 *
614 * @return Integer|null
615 */
616 public function getSize() {
617 return $this->mSize;
618 }
619
620 /**
621 * Returns the base36 sha1 of the text in this revision, or null if unknown.
622 *
623 * @return String|null
624 */
625 public function getSha1() {
626 return $this->mSha1;
627 }
628
629 /**
630 * Returns the title of the page associated with this entry or null.
631 *
632 * Will do a query, when title is not set and id is given.
633 *
634 * @return Title|null
635 */
636 public function getTitle() {
637 if( isset( $this->mTitle ) ) {
638 return $this->mTitle;
639 }
640 if( !is_null( $this->mId ) ) { //rev_id is defined as NOT NULL
641 $dbr = wfGetDB( DB_SLAVE );
642 $row = $dbr->selectRow(
643 array( 'page', 'revision' ),
644 self::selectPageFields(),
645 array( 'page_id=rev_page',
646 'rev_id' => $this->mId ),
647 __METHOD__ );
648 if ( $row ) {
649 $this->mTitle = Title::newFromRow( $row );
650 }
651 }
652 return $this->mTitle;
653 }
654
655 /**
656 * Set the title of the revision
657 *
658 * @param $title Title
659 */
660 public function setTitle( $title ) {
661 $this->mTitle = $title;
662 }
663
664 /**
665 * Get the page ID
666 *
667 * @return Integer|null
668 */
669 public function getPage() {
670 return $this->mPage;
671 }
672
673 /**
674 * Fetch revision's user id if it's available to the specified audience.
675 * If the specified audience does not have access to it, zero will be
676 * returned.
677 *
678 * @param $audience Integer: one of:
679 * Revision::FOR_PUBLIC to be displayed to all users
680 * Revision::FOR_THIS_USER to be displayed to the given user
681 * Revision::RAW get the ID regardless of permissions
682 * @param $user User object to check for, only if FOR_THIS_USER is passed
683 * to the $audience parameter
684 * @return Integer
685 */
686 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
687 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
688 return 0;
689 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
690 return 0;
691 } else {
692 return $this->mUser;
693 }
694 }
695
696 /**
697 * Fetch revision's user id without regard for the current user's permissions
698 *
699 * @return String
700 */
701 public function getRawUser() {
702 return $this->mUser;
703 }
704
705 /**
706 * Fetch revision's username if it's available to the specified audience.
707 * If the specified audience does not have access to the username, an
708 * empty string will be returned.
709 *
710 * @param $audience Integer: one of:
711 * Revision::FOR_PUBLIC to be displayed to all users
712 * Revision::FOR_THIS_USER to be displayed to the given user
713 * Revision::RAW get the text regardless of permissions
714 * @param $user User object to check for, only if FOR_THIS_USER is passed
715 * to the $audience parameter
716 * @return string
717 */
718 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
719 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
720 return '';
721 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
722 return '';
723 } else {
724 return $this->getRawUserText();
725 }
726 }
727
728 /**
729 * Fetch revision's username without regard for view restrictions
730 *
731 * @return String
732 */
733 public function getRawUserText() {
734 if ( $this->mUserText === null ) {
735 $this->mUserText = User::whoIs( $this->mUser ); // load on demand
736 if ( $this->mUserText === false ) {
737 # This shouldn't happen, but it can if the wiki was recovered
738 # via importing revs and there is no user table entry yet.
739 $this->mUserText = $this->mOrigUserText;
740 }
741 }
742 return $this->mUserText;
743 }
744
745 /**
746 * Fetch revision comment if it's available to the specified audience.
747 * If the specified audience does not have access to the comment, an
748 * empty string will be returned.
749 *
750 * @param $audience Integer: one of:
751 * Revision::FOR_PUBLIC to be displayed to all users
752 * Revision::FOR_THIS_USER to be displayed to the given user
753 * Revision::RAW get the text regardless of permissions
754 * @param $user User object to check for, only if FOR_THIS_USER is passed
755 * to the $audience parameter
756 * @return String
757 */
758 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
759 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
760 return '';
761 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $user ) ) {
762 return '';
763 } else {
764 return $this->mComment;
765 }
766 }
767
768 /**
769 * Fetch revision comment without regard for the current user's permissions
770 *
771 * @return String
772 */
773 public function getRawComment() {
774 return $this->mComment;
775 }
776
777 /**
778 * @return Boolean
779 */
780 public function isMinor() {
781 return (bool)$this->mMinorEdit;
782 }
783
784 /**
785 * @return Integer rcid of the unpatrolled row, zero if there isn't one
786 */
787 public function isUnpatrolled() {
788 if( $this->mUnpatrolled !== null ) {
789 return $this->mUnpatrolled;
790 }
791 $dbr = wfGetDB( DB_SLAVE );
792 $this->mUnpatrolled = $dbr->selectField( 'recentchanges',
793 'rc_id',
794 array( // Add redundant user,timestamp condition so we can use the existing index
795 'rc_user_text' => $this->getRawUserText(),
796 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
797 'rc_this_oldid' => $this->getId(),
798 'rc_patrolled' => 0
799 ),
800 __METHOD__
801 );
802 return (int)$this->mUnpatrolled;
803 }
804
805 /**
806 * @param $field int one of DELETED_* bitfield constants
807 *
808 * @return Boolean
809 */
810 public function isDeleted( $field ) {
811 return ( $this->mDeleted & $field ) == $field;
812 }
813
814 /**
815 * Get the deletion bitfield of the revision
816 *
817 * @return int
818 */
819 public function getVisibility() {
820 return (int)$this->mDeleted;
821 }
822
823 /**
824 * Fetch revision text if it's available to the specified audience.
825 * If the specified audience does not have the ability to view this
826 * revision, an empty string will be returned.
827 *
828 * @param $audience Integer: one of:
829 * Revision::FOR_PUBLIC to be displayed to all users
830 * Revision::FOR_THIS_USER to be displayed to the given user
831 * Revision::RAW get the text regardless of permissions
832 * @param $user User object to check for, only if FOR_THIS_USER is passed
833 * to the $audience parameter
834 * @return String
835 * @deprecated in 1.WD, use getContent() instead
836 */
837 public function getText( $audience = self::FOR_PUBLIC, User $user = null ) { #FIXME: deprecated, replace usage! #FIXME: used a LOT!
838 wfDeprecated( __METHOD__, '1.WD' );
839
840 $content = $this->getContent();
841 return ContentHandler::getContentText( $content ); # returns the raw content text, if applicable
842 }
843
844 /**
845 * Fetch revision content if it's available to the specified audience.
846 * If the specified audience does not have the ability to view this
847 * revision, null will be returned.
848 *
849 * @param $audience Integer: one of:
850 * Revision::FOR_PUBLIC to be displayed to all users
851 * Revision::FOR_THIS_USER to be displayed to $wgUser
852 * Revision::RAW get the text regardless of permissions
853 * @param $user User object to check for, only if FOR_THIS_USER is passed
854 * to the $audience parameter
855 * @return Content
856 *
857 * @since 1.WD
858 */
859 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
860 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_TEXT ) ) {
861 return null;
862 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_TEXT, $user ) ) {
863 return null;
864 } else {
865 return $this->getContentInternal();
866 }
867 }
868
869 /**
870 * Alias for getText(Revision::FOR_THIS_USER)
871 *
872 * @deprecated since 1.17
873 * @return String
874 */
875 public function revText() {
876 wfDeprecated( __METHOD__, '1.17' );
877 return $this->getText( self::FOR_THIS_USER );
878 }
879
880 /**
881 * Fetch revision text without regard for view restrictions
882 *
883 * @return String
884 */
885 public function getRawText() { #FIXME: deprecated, replace usage!
886 return $this->getText( self::RAW );
887 }
888
889 protected function getContentInternal() {
890 if( is_null( $this->mContent ) ) {
891 // Revision is immutable. Load on demand:
892
893 $handler = $this->getContentHandler();
894 $format = $this->getContentFormat();
895 $title = $this->getTitle();
896
897 if( is_null( $this->mText ) ) {
898 // Load text on demand:
899 $this->mText = $this->loadText();
900 }
901
902 $this->mContent = is_null( $this->mText ) ? null : $handler->unserializeContent( $this->mText, $format );
903 }
904
905 return $this->mContent;
906 }
907
908 /**
909 * Returns the content model for this revision.
910 *
911 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
912 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
913 * is used as a last resort.
914 *
915 * @return int the content model id associated with this revision, see the CONTENT_MODEL_XXX constants.
916 **/
917 public function getContentModel() {
918 if ( !$this->mContentModel ) {
919 $title = $this->getTitle();
920 $this->mContentModel = ( $title ? $title->getContentModel() : CONTENT_MODEL_WIKITEXT );
921
922 assert( !empty( $this->mContentModel ) );
923 }
924
925 return $this->mContentModel;
926 }
927
928 /**
929 * Returns the content format for this revision.
930 *
931 * If no content format was stored in the database, the default format for this
932 * revision's content model is returned.
933 *
934 * @return int the content format id associated with this revision, see the CONTENT_FORMAT_XXX constants.
935 **/
936 public function getContentFormat() {
937 if ( !$this->mContentFormat ) {
938 $handler = $this->getContentHandler();
939 $this->mContentFormat = $handler->getDefaultFormat();
940
941 assert( !empty( $this->mContentFormat ) );
942 }
943
944 return $this->mContentFormat;
945 }
946
947 /**
948 * Returns the content handler appropriate for this revision's content model.
949 *
950 * @return ContentHandler
951 */
952 public function getContentHandler() {
953 if ( !$this->mContentHandler ) {
954 $model = $this->getContentModel();
955 $this->mContentHandler = ContentHandler::getForModelID( $model );
956
957 assert( $this->mContentHandler->isSupportedFormat( $this->getContentFormat() ) );
958 }
959
960 return $this->mContentHandler;
961 }
962
963 /**
964 * @return String
965 */
966 public function getTimestamp() {
967 return wfTimestamp( TS_MW, $this->mTimestamp );
968 }
969
970 /**
971 * @return Boolean
972 */
973 public function isCurrent() {
974 return $this->mCurrent;
975 }
976
977 /**
978 * Get previous revision for this title
979 *
980 * @return Revision or null
981 */
982 public function getPrevious() {
983 if( $this->getTitle() ) {
984 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
985 if( $prev ) {
986 return Revision::newFromTitle( $this->getTitle(), $prev );
987 }
988 }
989 return null;
990 }
991
992 /**
993 * Get next revision for this title
994 *
995 * @return Revision or null
996 */
997 public function getNext() {
998 if( $this->getTitle() ) {
999 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1000 if ( $next ) {
1001 return Revision::newFromTitle( $this->getTitle(), $next );
1002 }
1003 }
1004 return null;
1005 }
1006
1007 /**
1008 * Get previous revision Id for this page_id
1009 * This is used to populate rev_parent_id on save
1010 *
1011 * @param $db DatabaseBase
1012 * @return Integer
1013 */
1014 private function getPreviousRevisionId( $db ) {
1015 if( is_null( $this->mPage ) ) {
1016 return 0;
1017 }
1018 # Use page_latest if ID is not given
1019 if( !$this->mId ) {
1020 $prevId = $db->selectField( 'page', 'page_latest',
1021 array( 'page_id' => $this->mPage ),
1022 __METHOD__ );
1023 } else {
1024 $prevId = $db->selectField( 'revision', 'rev_id',
1025 array( 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ),
1026 __METHOD__,
1027 array( 'ORDER BY' => 'rev_id DESC' ) );
1028 }
1029 return intval( $prevId );
1030 }
1031
1032 /**
1033 * Get revision text associated with an old or archive row
1034 * $row is usually an object from wfFetchRow(), both the flags and the text
1035 * field must be included
1036 *
1037 * @param $row Object: the text data
1038 * @param $prefix String: table prefix (default 'old_')
1039 * @return String: text the text requested or false on failure
1040 */
1041 public static function getRevisionText( $row, $prefix = 'old_' ) {
1042 wfProfileIn( __METHOD__ );
1043
1044 # Get data
1045 $textField = $prefix . 'text';
1046 $flagsField = $prefix . 'flags';
1047
1048 if( isset( $row->$flagsField ) ) {
1049 $flags = explode( ',', $row->$flagsField );
1050 } else {
1051 $flags = array();
1052 }
1053
1054 if( isset( $row->$textField ) ) {
1055 $text = $row->$textField;
1056 } else {
1057 wfProfileOut( __METHOD__ );
1058 return false;
1059 }
1060
1061 # Use external methods for external objects, text in table is URL-only then
1062 if ( in_array( 'external', $flags ) ) {
1063 $url = $text;
1064 $parts = explode( '://', $url, 2 );
1065 if( count( $parts ) == 1 || $parts[1] == '' ) {
1066 wfProfileOut( __METHOD__ );
1067 return false;
1068 }
1069 $text = ExternalStore::fetchFromURL( $url );
1070 }
1071
1072 // If the text was fetched without an error, convert it
1073 if ( $text !== false ) {
1074 if( in_array( 'gzip', $flags ) ) {
1075 # Deal with optional compression of archived pages.
1076 # This can be done periodically via maintenance/compressOld.php, and
1077 # as pages are saved if $wgCompressRevisions is set.
1078 $text = gzinflate( $text );
1079 }
1080
1081 if( in_array( 'object', $flags ) ) {
1082 # Generic compressed storage
1083 $obj = unserialize( $text );
1084 if ( !is_object( $obj ) ) {
1085 // Invalid object
1086 wfProfileOut( __METHOD__ );
1087 return false;
1088 }
1089 $text = $obj->getText();
1090 }
1091
1092 global $wgLegacyEncoding;
1093 if( $text !== false && $wgLegacyEncoding
1094 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
1095 {
1096 # Old revisions kept around in a legacy encoding?
1097 # Upconvert on demand.
1098 # ("utf8" checked for compatibility with some broken
1099 # conversion scripts 2008-12-30)
1100 global $wgContLang;
1101 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1102 }
1103 }
1104 wfProfileOut( __METHOD__ );
1105 return $text;
1106 }
1107
1108 /**
1109 * If $wgCompressRevisions is enabled, we will compress data.
1110 * The input string is modified in place.
1111 * Return value is the flags field: contains 'gzip' if the
1112 * data is compressed, and 'utf-8' if we're saving in UTF-8
1113 * mode.
1114 *
1115 * @param $text Mixed: reference to a text
1116 * @return String
1117 */
1118 public static function compressRevisionText( &$text ) {
1119 global $wgCompressRevisions;
1120 $flags = array();
1121
1122 # Revisions not marked this way will be converted
1123 # on load if $wgLegacyCharset is set in the future.
1124 $flags[] = 'utf-8';
1125
1126 if( $wgCompressRevisions ) {
1127 if( function_exists( 'gzdeflate' ) ) {
1128 $text = gzdeflate( $text );
1129 $flags[] = 'gzip';
1130 } else {
1131 wfDebug( "Revision::compressRevisionText() -- no zlib support, not compressing\n" );
1132 }
1133 }
1134 return implode( ',', $flags );
1135 }
1136
1137 /**
1138 * Insert a new revision into the database, returning the new revision ID
1139 * number on success and dies horribly on failure.
1140 *
1141 * @param $dbw DatabaseBase: (master connection)
1142 * @return Integer
1143 */
1144 public function insertOn( $dbw ) {
1145 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1146
1147 wfProfileIn( __METHOD__ );
1148
1149 $data = $this->mText;
1150 $flags = Revision::compressRevisionText( $data );
1151
1152 # Write to external storage if required
1153 if( $wgDefaultExternalStore ) {
1154 // Store and get the URL
1155 $data = ExternalStore::insertToDefault( $data );
1156 if( !$data ) {
1157 throw new MWException( "Unable to store text to external storage" );
1158 }
1159 if( $flags ) {
1160 $flags .= ',';
1161 }
1162 $flags .= 'external';
1163 }
1164
1165 # Record the text (or external storage URL) to the text table
1166 if( !isset( $this->mTextId ) ) {
1167 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1168 $dbw->insert( 'text',
1169 array(
1170 'old_id' => $old_id,
1171 'old_text' => $data,
1172 'old_flags' => $flags,
1173 ), __METHOD__
1174 );
1175 $this->mTextId = $dbw->insertId();
1176 }
1177
1178 if ( $this->mComment === null ) $this->mComment = "";
1179
1180 # Record the edit in revisions
1181 $rev_id = isset( $this->mId )
1182 ? $this->mId
1183 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1184
1185 $row = array(
1186 'rev_id' => $rev_id,
1187 'rev_page' => $this->mPage,
1188 'rev_text_id' => $this->mTextId,
1189 'rev_comment' => $this->mComment,
1190 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
1191 'rev_user' => $this->mUser,
1192 'rev_user_text' => $this->mUserText,
1193 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
1194 'rev_deleted' => $this->mDeleted,
1195 'rev_len' => $this->mSize,
1196 'rev_parent_id' => is_null( $this->mParentId )
1197 ? $this->getPreviousRevisionId( $dbw )
1198 : $this->mParentId,
1199 'rev_sha1' => is_null( $this->mSha1 )
1200 ? Revision::base36Sha1( $this->mText )
1201 : $this->mSha1,
1202 );
1203
1204 if ( $wgContentHandlerUseDB ) {
1205 $row[ 'rev_content_model' ] = $this->getContentModel();
1206 $row[ 'rev_content_format' ] = $this->getContentFormat();
1207 }
1208
1209 $dbw->insert( 'revision', $row, __METHOD__ );
1210
1211 $this->mId = !is_null( $rev_id ) ? $rev_id : $dbw->insertId();
1212
1213 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1214
1215 wfProfileOut( __METHOD__ );
1216 return $this->mId;
1217 }
1218
1219 /**
1220 * Get the base 36 SHA-1 value for a string of text
1221 * @param $text String
1222 * @return String
1223 */
1224 public static function base36Sha1( $text ) {
1225 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1226 }
1227
1228 /**
1229 * Lazy-load the revision's text.
1230 * Currently hardcoded to the 'text' table storage engine.
1231 *
1232 * @return String
1233 */
1234 protected function loadText() {
1235 wfProfileIn( __METHOD__ );
1236
1237 // Caching may be beneficial for massive use of external storage
1238 global $wgRevisionCacheExpiry, $wgMemc;
1239 $textId = $this->getTextId();
1240 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1241 if( $wgRevisionCacheExpiry ) {
1242 $text = $wgMemc->get( $key );
1243 if( is_string( $text ) ) {
1244 wfDebug( __METHOD__ . ": got id $textId from cache\n" );
1245 wfProfileOut( __METHOD__ );
1246 return $text;
1247 }
1248 }
1249
1250 // If we kept data for lazy extraction, use it now...
1251 if ( isset( $this->mTextRow ) ) {
1252 $row = $this->mTextRow;
1253 $this->mTextRow = null;
1254 } else {
1255 $row = null;
1256 }
1257
1258 if( !$row ) {
1259 // Text data is immutable; check slaves first.
1260 $dbr = wfGetDB( DB_SLAVE );
1261 $row = $dbr->selectRow( 'text',
1262 array( 'old_text', 'old_flags' ),
1263 array( 'old_id' => $this->getTextId() ),
1264 __METHOD__ );
1265 }
1266
1267 if( !$row && wfGetLB()->getServerCount() > 1 ) {
1268 // Possible slave lag!
1269 $dbw = wfGetDB( DB_MASTER );
1270 $row = $dbw->selectRow( 'text',
1271 array( 'old_text', 'old_flags' ),
1272 array( 'old_id' => $this->getTextId() ),
1273 __METHOD__ );
1274 }
1275
1276 $text = self::getRevisionText( $row );
1277
1278 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1279 if( $wgRevisionCacheExpiry && $text !== false ) {
1280 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1281 }
1282
1283 wfProfileOut( __METHOD__ );
1284
1285 return $text;
1286 }
1287
1288 /**
1289 * Create a new null-revision for insertion into a page's
1290 * history. This will not re-save the text, but simply refer
1291 * to the text from the previous version.
1292 *
1293 * Such revisions can for instance identify page rename
1294 * operations and other such meta-modifications.
1295 *
1296 * @param $dbw DatabaseBase
1297 * @param $pageId Integer: ID number of the page to read from
1298 * @param $summary String: revision's summary
1299 * @param $minor Boolean: whether the revision should be considered as minor
1300 * @return Revision|null on error
1301 */
1302 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1303 global $wgContentHandlerUseDB;
1304
1305 wfProfileIn( __METHOD__ );
1306
1307 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1308 'rev_text_id', 'rev_len', 'rev_sha1' );
1309
1310 if ( $wgContentHandlerUseDB ) {
1311 $fields[] = 'rev_content_model';
1312 $fields[] = 'rev_content_format';
1313 }
1314
1315 $current = $dbw->selectRow(
1316 array( 'page', 'revision' ),
1317 $fields,
1318 array(
1319 'page_id' => $pageId,
1320 'page_latest=rev_id',
1321 ),
1322 __METHOD__ );
1323
1324 if( $current ) {
1325 $row = array(
1326 'page' => $pageId,
1327 'comment' => $summary,
1328 'minor_edit' => $minor,
1329 'text_id' => $current->rev_text_id,
1330 'parent_id' => $current->page_latest,
1331 'len' => $current->rev_len,
1332 'sha1' => $current->rev_sha1
1333 );
1334
1335 if ( $wgContentHandlerUseDB ) {
1336 $row[ 'content_model' ] = $current->rev_content_model;
1337 $row[ 'content_format' ] = $current->rev_content_format;
1338 }
1339
1340 $revision = new Revision( $row );
1341 $revision->setTitle( Title::makeTitle( $current->page_namespace, $current->page_title ) );
1342 } else {
1343 $revision = null;
1344 }
1345
1346 wfProfileOut( __METHOD__ );
1347 return $revision;
1348 }
1349
1350 /**
1351 * Determine if the current user is allowed to view a particular
1352 * field of this revision, if it's marked as deleted.
1353 *
1354 * @param $field Integer:one of self::DELETED_TEXT,
1355 * self::DELETED_COMMENT,
1356 * self::DELETED_USER
1357 * @param $user User object to check, or null to use $wgUser
1358 * @return Boolean
1359 */
1360 public function userCan( $field, User $user = null ) {
1361 return self::userCanBitfield( $this->mDeleted, $field, $user );
1362 }
1363
1364 /**
1365 * Determine if the current user is allowed to view a particular
1366 * field of this revision, if it's marked as deleted. This is used
1367 * by various classes to avoid duplication.
1368 *
1369 * @param $bitfield Integer: current field
1370 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1371 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1372 * self::DELETED_USER = File::DELETED_USER
1373 * @param $user User object to check, or null to use $wgUser
1374 * @return Boolean
1375 */
1376 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
1377 if( $bitfield & $field ) { // aspect is deleted
1378 if ( $bitfield & self::DELETED_RESTRICTED ) {
1379 $permission = 'suppressrevision';
1380 } elseif ( $field & self::DELETED_TEXT ) {
1381 $permission = 'deletedtext';
1382 } else {
1383 $permission = 'deletedhistory';
1384 }
1385 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1386 if ( $user === null ) {
1387 global $wgUser;
1388 $user = $wgUser;
1389 }
1390 return $user->isAllowed( $permission );
1391 } else {
1392 return true;
1393 }
1394 }
1395
1396 /**
1397 * Get rev_timestamp from rev_id, without loading the rest of the row
1398 *
1399 * @param $title Title
1400 * @param $id Integer
1401 * @return String
1402 */
1403 static function getTimestampFromId( $title, $id ) {
1404 $dbr = wfGetDB( DB_SLAVE );
1405 // Casting fix for DB2
1406 if ( $id == '' ) {
1407 $id = 0;
1408 }
1409 $conds = array( 'rev_id' => $id );
1410 $conds['rev_page'] = $title->getArticleID();
1411 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1412 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1413 # Not in slave, try master
1414 $dbw = wfGetDB( DB_MASTER );
1415 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1416 }
1417 return wfTimestamp( TS_MW, $timestamp );
1418 }
1419
1420 /**
1421 * Get count of revisions per page...not very efficient
1422 *
1423 * @param $db DatabaseBase
1424 * @param $id Integer: page id
1425 * @return Integer
1426 */
1427 static function countByPageId( $db, $id ) {
1428 $row = $db->selectRow( 'revision', 'COUNT(*) AS revCount',
1429 array( 'rev_page' => $id ), __METHOD__ );
1430 if( $row ) {
1431 return $row->revCount;
1432 }
1433 return 0;
1434 }
1435
1436 /**
1437 * Get count of revisions per page...not very efficient
1438 *
1439 * @param $db DatabaseBase
1440 * @param $title Title
1441 * @return Integer
1442 */
1443 static function countByTitle( $db, $title ) {
1444 $id = $title->getArticleID();
1445 if( $id ) {
1446 return Revision::countByPageId( $db, $id );
1447 }
1448 return 0;
1449 }
1450 }