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 );
409 }
410
411 /**
412 * Return the list of user fields that should be selected from user table
413 * @return array
414 */
415 public static function selectUserFields() {
416 return array( 'user_name' );
417 }
418
419 /**
420 * Constructor
421 *
422 * @param $row Mixed: either a database row or an array
423 * @access private
424 */
425 function __construct( $row ) {
426 if( is_object( $row ) ) {
427 $this->mId = intval( $row->rev_id );
428 $this->mPage = intval( $row->rev_page );
429 $this->mTextId = intval( $row->rev_text_id );
430 $this->mComment = $row->rev_comment;
431 $this->mUser = intval( $row->rev_user );
432 $this->mMinorEdit = intval( $row->rev_minor_edit );
433 $this->mTimestamp = $row->rev_timestamp;
434 $this->mDeleted = intval( $row->rev_deleted );
435
436 if( !isset( $row->rev_parent_id ) ) {
437 $this->mParentId = is_null( $row->rev_parent_id ) ? null : 0;
438 } else {
439 $this->mParentId = intval( $row->rev_parent_id );
440 }
441
442 if( !isset( $row->rev_len ) || is_null( $row->rev_len ) ) {
443 $this->mSize = null;
444 } else {
445 $this->mSize = intval( $row->rev_len );
446 }
447
448 if ( !isset( $row->rev_sha1 ) ) {
449 $this->mSha1 = null;
450 } else {
451 $this->mSha1 = $row->rev_sha1;
452 }
453
454 if( isset( $row->page_latest ) ) {
455 $this->mCurrent = ( $row->rev_id == $row->page_latest );
456 $this->mTitle = Title::newFromRow( $row );
457 } else {
458 $this->mCurrent = false;
459 $this->mTitle = null;
460 }
461
462 if( !isset( $row->rev_content_model ) || is_null( $row->rev_content_model ) ) {
463 $this->mContentModel = null; # determine on demand if needed
464 } else {
465 $this->mContentModel = intval( $row->rev_content_model );
466 }
467
468 if( !isset( $row->rev_content_format ) || is_null( $row->rev_content_format ) ) {
469 $this->mContentFormat = null; # determine on demand if needed
470 } else {
471 $this->mContentFormat = intval( $row->rev_content_format );
472 }
473
474 // Lazy extraction...
475 $this->mText = null;
476 if( isset( $row->old_text ) ) {
477 $this->mTextRow = $row;
478 } else {
479 // 'text' table row entry will be lazy-loaded
480 $this->mTextRow = null;
481 }
482
483 // Use user_name for users and rev_user_text for IPs...
484 $this->mUserText = null; // lazy load if left null
485 if ( $this->mUser == 0 ) {
486 $this->mUserText = $row->rev_user_text; // IP user
487 } elseif ( isset( $row->user_name ) ) {
488 $this->mUserText = $row->user_name; // logged-in user
489 }
490 $this->mOrigUserText = $row->rev_user_text;
491 } elseif( is_array( $row ) ) {
492 // Build a new revision to be saved...
493 global $wgUser; // ugh
494
495
496 # if we have a content object, use it to set the model and type
497 if ( !empty( $row['content'] ) ) {
498 if ( !empty( $row['text_id'] ) ) { #FIXME: when is that set? test with external store setup! check out insertOn()
499 throw new MWException( "Text already stored in external store (id {$row['text_id']}), can't serialize content object" );
500 }
501
502 $row['content_model'] = $row['content']->getModel();
503 # note: mContentFormat is initializes later accordingly
504 # note: content is serialized later in this method!
505 # also set text to null?
506 }
507
508 $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null;
509 $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null;
510 $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null;
511 $this->mUserText = isset( $row['user_text'] ) ? strval( $row['user_text'] ) : $wgUser->getName();
512 $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId();
513 $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0;
514 $this->mTimestamp = isset( $row['timestamp'] ) ? strval( $row['timestamp'] ) : wfTimestampNow();
515 $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0;
516 $this->mSize = isset( $row['len'] ) ? intval( $row['len'] ) : null;
517 $this->mParentId = isset( $row['parent_id'] ) ? intval( $row['parent_id'] ) : null;
518 $this->mSha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
519
520 $this->mContentModel = isset( $row['content_model'] ) ? intval( $row['content_model'] ) : null;
521 $this->mContentFormat = isset( $row['content_format'] ) ? intval( $row['content_format'] ) : null;
522
523 // Enforce spacing trimming on supplied text
524 $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null;
525 $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
526 $this->mTextRow = null;
527
528 # if we have a content object, override mText and mContentModel
529 if ( !empty( $row['content'] ) ) {
530 $handler = $this->getContentHandler();
531 $this->mContent = $row['content'];
532
533 $this->mContentModel = $this->mContent->getModel();
534 $this->mContentHandler = null;
535
536 $this->mText = $handler->serializeContent( $row['content'], $this->getContentFormat() );
537 } elseif ( !is_null( $this->mText ) ) {
538 $handler = $this->getContentHandler();
539 $this->mContent = $handler->unserializeContent( $this->mText );
540 }
541
542 $this->mTitle = null; # Load on demand if needed
543 $this->mCurrent = false; #XXX: really? we are about to create a revision. it will usually then be the current one.
544
545 # If we still have no length, see it we have the text to figure it out
546 if ( !$this->mSize ) {
547 if ( !is_null( $this->mContent ) ) {
548 $this->mSize = $this->mContent->getSize();
549 } else {
550 #XXX: my be inconsistent with the notion of "size" use for the present content model
551 #NOTE: should never happen if we have either text or content object!
552 $this->mSize = is_null( $this->mText ) ? null : strlen( $this->mText );
553 }
554 }
555
556 # Same for sha1
557 if ( $this->mSha1 === null ) {
558 $this->mSha1 = is_null( $this->mText ) ? null : self::base36Sha1( $this->mText );
559 }
560
561 $this->getContentModel(); # force lazy init
562 $this->getContentFormat(); # force lazy init
563 } else {
564 throw new MWException( 'Revision constructor passed invalid row format.' );
565 }
566 $this->mUnpatrolled = null;
567
568 // @TODO: add support for ar_content_format, ar_content_model, rev_content_format, rev_content_model to API
569 // @TODO: get rid of $mText
570 }
571
572 /**
573 * Get revision ID
574 *
575 * @return Integer
576 */
577 public function getId() {
578 return $this->mId;
579 }
580
581 /**
582 * Set the revision ID
583 *
584 * @since 1.19
585 * @param $id Integer
586 */
587 public function setId( $id ) {
588 $this->mId = $id;
589 }
590
591 /**
592 * Get text row ID
593 *
594 * @return Integer
595 */
596 public function getTextId() {
597 return $this->mTextId;
598 }
599
600 /**
601 * Get parent revision ID (the original previous page revision)
602 *
603 * @return Integer|null
604 */
605 public function getParentId() {
606 return $this->mParentId;
607 }
608
609 /**
610 * Returns the length of the text in this revision, or null if unknown.
611 *
612 * @return Integer
613 */
614 public function getSize() {
615 return $this->mSize;
616 }
617
618 /**
619 * Returns the base36 sha1 of the text in this revision, or null if unknown.
620 *
621 * @return String
622 */
623 public function getSha1() {
624 return $this->mSha1;
625 }
626
627 /**
628 * Returns the title of the page associated with this entry.
629 *
630 * @return Title
631 */
632 public function getTitle() {
633 if( isset( $this->mTitle ) ) {
634 return $this->mTitle;
635 }
636 $dbr = wfGetDB( DB_SLAVE );
637 $row = $dbr->selectRow(
638 array( 'page', 'revision' ),
639 self::selectPageFields(),
640 array( 'page_id=rev_page',
641 'rev_id' => $this->mId ),
642 __METHOD__ );
643 if ( $row ) {
644 $this->mTitle = Title::newFromRow( $row );
645 }
646 return $this->mTitle;
647 }
648
649 /**
650 * Set the title of the revision
651 *
652 * @param $title Title
653 */
654 public function setTitle( $title ) {
655 $this->mTitle = $title;
656 }
657
658 /**
659 * Get the page ID
660 *
661 * @return Integer
662 */
663 public function getPage() {
664 return $this->mPage;
665 }
666
667 /**
668 * Fetch revision's user id if it's available to the specified audience.
669 * If the specified audience does not have access to it, zero will be
670 * returned.
671 *
672 * @param $audience Integer: one of:
673 * Revision::FOR_PUBLIC to be displayed to all users
674 * Revision::FOR_THIS_USER to be displayed to $wgUser
675 * Revision::RAW get the ID regardless of permissions
676 * @param $user User object to check for, only if FOR_THIS_USER is passed
677 * to the $audience parameter
678 * @return Integer
679 */
680 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
681 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
682 return 0;
683 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
684 return 0;
685 } else {
686 return $this->mUser;
687 }
688 }
689
690 /**
691 * Fetch revision's user id without regard for the current user's permissions
692 *
693 * @return String
694 */
695 public function getRawUser() {
696 return $this->mUser;
697 }
698
699 /**
700 * Fetch revision's username if it's available to the specified audience.
701 * If the specified audience does not have access to the username, an
702 * empty string will be returned.
703 *
704 * @param $audience Integer: one of:
705 * Revision::FOR_PUBLIC to be displayed to all users
706 * Revision::FOR_THIS_USER to be displayed to $wgUser
707 * Revision::RAW get the text regardless of permissions
708 * @param $user User object to check for, only if FOR_THIS_USER is passed
709 * to the $audience parameter
710 * @return string
711 */
712 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
713 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
714 return '';
715 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
716 return '';
717 } else {
718 return $this->getRawUserText();
719 }
720 }
721
722 /**
723 * Fetch revision's username without regard for view restrictions
724 *
725 * @return String
726 */
727 public function getRawUserText() {
728 if ( $this->mUserText === null ) {
729 $this->mUserText = User::whoIs( $this->mUser ); // load on demand
730 if ( $this->mUserText === false ) {
731 # This shouldn't happen, but it can if the wiki was recovered
732 # via importing revs and there is no user table entry yet.
733 $this->mUserText = $this->mOrigUserText;
734 }
735 }
736 return $this->mUserText;
737 }
738
739 /**
740 * Fetch revision comment if it's available to the specified audience.
741 * If the specified audience does not have access to the comment, an
742 * empty string will be returned.
743 *
744 * @param $audience Integer: one of:
745 * Revision::FOR_PUBLIC to be displayed to all users
746 * Revision::FOR_THIS_USER to be displayed to $wgUser
747 * Revision::RAW get the text regardless of permissions
748 * @param $user User object to check for, only if FOR_THIS_USER is passed
749 * to the $audience parameter
750 * @return String
751 */
752 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
753 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
754 return '';
755 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $user ) ) {
756 return '';
757 } else {
758 return $this->mComment;
759 }
760 }
761
762 /**
763 * Fetch revision comment without regard for the current user's permissions
764 *
765 * @return String
766 */
767 public function getRawComment() {
768 return $this->mComment;
769 }
770
771 /**
772 * @return Boolean
773 */
774 public function isMinor() {
775 return (bool)$this->mMinorEdit;
776 }
777
778 /**
779 * @return Integer rcid of the unpatrolled row, zero if there isn't one
780 */
781 public function isUnpatrolled() {
782 if( $this->mUnpatrolled !== null ) {
783 return $this->mUnpatrolled;
784 }
785 $dbr = wfGetDB( DB_SLAVE );
786 $this->mUnpatrolled = $dbr->selectField( 'recentchanges',
787 'rc_id',
788 array( // Add redundant user,timestamp condition so we can use the existing index
789 'rc_user_text' => $this->getRawUserText(),
790 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
791 'rc_this_oldid' => $this->getId(),
792 'rc_patrolled' => 0
793 ),
794 __METHOD__
795 );
796 return (int)$this->mUnpatrolled;
797 }
798
799 /**
800 * @param $field int one of DELETED_* bitfield constants
801 *
802 * @return Boolean
803 */
804 public function isDeleted( $field ) {
805 return ( $this->mDeleted & $field ) == $field;
806 }
807
808 /**
809 * Get the deletion bitfield of the revision
810 *
811 * @return int
812 */
813 public function getVisibility() {
814 return (int)$this->mDeleted;
815 }
816
817 /**
818 * Fetch revision text if it's available to the specified audience.
819 * If the specified audience does not have the ability to view this
820 * revision, an empty string will be returned.
821 *
822 * @param $audience Integer: one of:
823 * Revision::FOR_PUBLIC to be displayed to all users
824 * Revision::FOR_THIS_USER to be displayed to $wgUser
825 * Revision::RAW get the text regardless of permissions
826 * @param $user User object to check for, only if FOR_THIS_USER is passed
827 * to the $audience parameter
828 * @return String
829 * @deprecated in 1.WD, use getContent() instead
830 */
831 public function getText( $audience = self::FOR_PUBLIC, User $user = null ) { #FIXME: deprecated, replace usage! #FIXME: used a LOT!
832 wfDeprecated( __METHOD__, '1.WD' );
833
834 $content = $this->getContent();
835 return ContentHandler::getContentText( $content ); # returns the raw content text, if applicable
836 }
837
838 /**
839 * Fetch revision content if it's available to the specified audience.
840 * If the specified audience does not have the ability to view this
841 * revision, null will be returned.
842 *
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 $wgUser
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
849 * @return Content
850 *
851 * @since 1.WD
852 */
853 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
854 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_TEXT ) ) {
855 return null;
856 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_TEXT, $user ) ) {
857 return null;
858 } else {
859 return $this->getContentInternal();
860 }
861 }
862
863 /**
864 * Alias for getText(Revision::FOR_THIS_USER)
865 *
866 * @deprecated since 1.17
867 * @return String
868 */
869 public function revText() {
870 wfDeprecated( __METHOD__, '1.17' );
871 return $this->getText( self::FOR_THIS_USER );
872 }
873
874 /**
875 * Fetch revision text without regard for view restrictions
876 *
877 * @return String
878 */
879 public function getRawText() { #FIXME: deprecated, replace usage!
880 return $this->getText( self::RAW );
881 }
882
883 protected function getContentInternal() {
884 if( is_null( $this->mContent ) ) {
885 // Revision is immutable. Load on demand:
886
887 $handler = $this->getContentHandler();
888 $format = $this->getContentFormat();
889 $title = $this->getTitle();
890
891 if( is_null( $this->mText ) ) {
892 // Load text on demand:
893 $this->mText = $this->loadText();
894 }
895
896 $this->mContent = is_null( $this->mText ) ? null : $handler->unserializeContent( $this->mText, $format );
897 }
898
899 return $this->mContent;
900 }
901
902 /**
903 * Returns the content model for this revision.
904 *
905 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
906 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
907 * is used as a last resort.
908 *
909 * @return int the content model id associated with this revision, see the CONTENT_MODEL_XXX constants.
910 **/
911 public function getContentModel() {
912 if ( !$this->mContentModel ) {
913 $title = $this->getTitle();
914 $this->mContentModel = ( $title ? $title->getContentModel() : CONTENT_MODEL_WIKITEXT );
915
916 assert( !empty( $this->mContentModel ) );
917 }
918
919 return $this->mContentModel;
920 }
921
922 /**
923 * Returns the content format for this revision.
924 *
925 * If no content format was stored in the database, the default format for this
926 * revision's content model is returned.
927 *
928 * @return int the content format id associated with this revision, see the CONTENT_FORMAT_XXX constants.
929 **/
930 public function getContentFormat() {
931 if ( !$this->mContentFormat ) {
932 $handler = $this->getContentHandler();
933 $this->mContentFormat = $handler->getDefaultFormat();
934
935 assert( !empty( $this->mContentFormat ) );
936 }
937
938 return $this->mContentFormat;
939 }
940
941 /**
942 * Returns the content handler appropriate for this revision's content model.
943 *
944 * @return ContentHandler
945 */
946 public function getContentHandler() {
947 if ( !$this->mContentHandler ) {
948 $model = $this->getContentModel();
949 $this->mContentHandler = ContentHandler::getForModelID( $model );
950
951 assert( $this->mContentHandler->isSupportedFormat( $this->getContentFormat() ) );
952 }
953
954 return $this->mContentHandler;
955 }
956
957 /**
958 * @return String
959 */
960 public function getTimestamp() {
961 return wfTimestamp( TS_MW, $this->mTimestamp );
962 }
963
964 /**
965 * @return Boolean
966 */
967 public function isCurrent() {
968 return $this->mCurrent;
969 }
970
971 /**
972 * Get previous revision for this title
973 *
974 * @return Revision or null
975 */
976 public function getPrevious() {
977 if( $this->getTitle() ) {
978 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
979 if( $prev ) {
980 return Revision::newFromTitle( $this->getTitle(), $prev );
981 }
982 }
983 return null;
984 }
985
986 /**
987 * Get next revision for this title
988 *
989 * @return Revision or null
990 */
991 public function getNext() {
992 if( $this->getTitle() ) {
993 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
994 if ( $next ) {
995 return Revision::newFromTitle( $this->getTitle(), $next );
996 }
997 }
998 return null;
999 }
1000
1001 /**
1002 * Get previous revision Id for this page_id
1003 * This is used to populate rev_parent_id on save
1004 *
1005 * @param $db DatabaseBase
1006 * @return Integer
1007 */
1008 private function getPreviousRevisionId( $db ) {
1009 if( is_null( $this->mPage ) ) {
1010 return 0;
1011 }
1012 # Use page_latest if ID is not given
1013 if( !$this->mId ) {
1014 $prevId = $db->selectField( 'page', 'page_latest',
1015 array( 'page_id' => $this->mPage ),
1016 __METHOD__ );
1017 } else {
1018 $prevId = $db->selectField( 'revision', 'rev_id',
1019 array( 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ),
1020 __METHOD__,
1021 array( 'ORDER BY' => 'rev_id DESC' ) );
1022 }
1023 return intval( $prevId );
1024 }
1025
1026 /**
1027 * Get revision text associated with an old or archive row
1028 * $row is usually an object from wfFetchRow(), both the flags and the text
1029 * field must be included
1030 *
1031 * @param $row Object: the text data
1032 * @param $prefix String: table prefix (default 'old_')
1033 * @return String: text the text requested or false on failure
1034 */
1035 public static function getRevisionText( $row, $prefix = 'old_' ) {
1036 wfProfileIn( __METHOD__ );
1037
1038 # Get data
1039 $textField = $prefix . 'text';
1040 $flagsField = $prefix . 'flags';
1041
1042 if( isset( $row->$flagsField ) ) {
1043 $flags = explode( ',', $row->$flagsField );
1044 } else {
1045 $flags = array();
1046 }
1047
1048 if( isset( $row->$textField ) ) {
1049 $text = $row->$textField;
1050 } else {
1051 wfProfileOut( __METHOD__ );
1052 return false;
1053 }
1054
1055 # Use external methods for external objects, text in table is URL-only then
1056 if ( in_array( 'external', $flags ) ) {
1057 $url = $text;
1058 $parts = explode( '://', $url, 2 );
1059 if( count( $parts ) == 1 || $parts[1] == '' ) {
1060 wfProfileOut( __METHOD__ );
1061 return false;
1062 }
1063 $text = ExternalStore::fetchFromURL( $url );
1064 }
1065
1066 // If the text was fetched without an error, convert it
1067 if ( $text !== false ) {
1068 if( in_array( 'gzip', $flags ) ) {
1069 # Deal with optional compression of archived pages.
1070 # This can be done periodically via maintenance/compressOld.php, and
1071 # as pages are saved if $wgCompressRevisions is set.
1072 $text = gzinflate( $text );
1073 }
1074
1075 if( in_array( 'object', $flags ) ) {
1076 # Generic compressed storage
1077 $obj = unserialize( $text );
1078 if ( !is_object( $obj ) ) {
1079 // Invalid object
1080 wfProfileOut( __METHOD__ );
1081 return false;
1082 }
1083 $text = $obj->getText();
1084 }
1085
1086 global $wgLegacyEncoding;
1087 if( $text !== false && $wgLegacyEncoding
1088 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
1089 {
1090 # Old revisions kept around in a legacy encoding?
1091 # Upconvert on demand.
1092 # ("utf8" checked for compatibility with some broken
1093 # conversion scripts 2008-12-30)
1094 global $wgContLang;
1095 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1096 }
1097 }
1098 wfProfileOut( __METHOD__ );
1099 return $text;
1100 }
1101
1102 /**
1103 * If $wgCompressRevisions is enabled, we will compress data.
1104 * The input string is modified in place.
1105 * Return value is the flags field: contains 'gzip' if the
1106 * data is compressed, and 'utf-8' if we're saving in UTF-8
1107 * mode.
1108 *
1109 * @param $text Mixed: reference to a text
1110 * @return String
1111 */
1112 public static function compressRevisionText( &$text ) {
1113 global $wgCompressRevisions;
1114 $flags = array();
1115
1116 # Revisions not marked this way will be converted
1117 # on load if $wgLegacyCharset is set in the future.
1118 $flags[] = 'utf-8';
1119
1120 if( $wgCompressRevisions ) {
1121 if( function_exists( 'gzdeflate' ) ) {
1122 $text = gzdeflate( $text );
1123 $flags[] = 'gzip';
1124 } else {
1125 wfDebug( "Revision::compressRevisionText() -- no zlib support, not compressing\n" );
1126 }
1127 }
1128 return implode( ',', $flags );
1129 }
1130
1131 /**
1132 * Insert a new revision into the database, returning the new revision ID
1133 * number on success and dies horribly on failure.
1134 *
1135 * @param $dbw DatabaseBase: (master connection)
1136 * @return Integer
1137 */
1138 public function insertOn( $dbw ) {
1139 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1140
1141 wfProfileIn( __METHOD__ );
1142
1143 $data = $this->mText;
1144 $flags = Revision::compressRevisionText( $data );
1145
1146 # Write to external storage if required
1147 if( $wgDefaultExternalStore ) {
1148 // Store and get the URL
1149 $data = ExternalStore::insertToDefault( $data );
1150 if( !$data ) {
1151 throw new MWException( "Unable to store text to external storage" );
1152 }
1153 if( $flags ) {
1154 $flags .= ',';
1155 }
1156 $flags .= 'external';
1157 }
1158
1159 # Record the text (or external storage URL) to the text table
1160 if( !isset( $this->mTextId ) ) {
1161 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1162 $dbw->insert( 'text',
1163 array(
1164 'old_id' => $old_id,
1165 'old_text' => $data,
1166 'old_flags' => $flags,
1167 ), __METHOD__
1168 );
1169 $this->mTextId = $dbw->insertId();
1170 }
1171
1172 if ( $this->mComment === null ) $this->mComment = "";
1173
1174 # Record the edit in revisions
1175 $rev_id = isset( $this->mId )
1176 ? $this->mId
1177 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1178
1179 $row = array(
1180 'rev_id' => $rev_id,
1181 'rev_page' => $this->mPage,
1182 'rev_text_id' => $this->mTextId,
1183 'rev_comment' => $this->mComment,
1184 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
1185 'rev_user' => $this->mUser,
1186 'rev_user_text' => $this->mUserText,
1187 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
1188 'rev_deleted' => $this->mDeleted,
1189 'rev_len' => $this->mSize,
1190 'rev_parent_id' => is_null( $this->mParentId )
1191 ? $this->getPreviousRevisionId( $dbw )
1192 : $this->mParentId,
1193 'rev_sha1' => is_null( $this->mSha1 )
1194 ? Revision::base36Sha1( $this->mText )
1195 : $this->mSha1,
1196 );
1197
1198 if ( $wgContentHandlerUseDB ) {
1199 $row[ 'rev_content_model' ] = $this->getContentModel();
1200 $row[ 'rev_content_format' ] = $this->getContentFormat();
1201 }
1202
1203 $dbw->insert( 'revision', $row, __METHOD__ );
1204
1205 $this->mId = !is_null( $rev_id ) ? $rev_id : $dbw->insertId();
1206
1207 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1208
1209 wfProfileOut( __METHOD__ );
1210 return $this->mId;
1211 }
1212
1213 /**
1214 * Get the base 36 SHA-1 value for a string of text
1215 * @param $text String
1216 * @return String
1217 */
1218 public static function base36Sha1( $text ) {
1219 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1220 }
1221
1222 /**
1223 * Lazy-load the revision's text.
1224 * Currently hardcoded to the 'text' table storage engine.
1225 *
1226 * @return String
1227 */
1228 protected function loadText() {
1229 wfProfileIn( __METHOD__ );
1230
1231 // Caching may be beneficial for massive use of external storage
1232 global $wgRevisionCacheExpiry, $wgMemc;
1233 $textId = $this->getTextId();
1234 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1235 if( $wgRevisionCacheExpiry ) {
1236 $text = $wgMemc->get( $key );
1237 if( is_string( $text ) ) {
1238 wfDebug( __METHOD__ . ": got id $textId from cache\n" );
1239 wfProfileOut( __METHOD__ );
1240 return $text;
1241 }
1242 }
1243
1244 // If we kept data for lazy extraction, use it now...
1245 if ( isset( $this->mTextRow ) ) {
1246 $row = $this->mTextRow;
1247 $this->mTextRow = null;
1248 } else {
1249 $row = null;
1250 }
1251
1252 if( !$row ) {
1253 // Text data is immutable; check slaves first.
1254 $dbr = wfGetDB( DB_SLAVE );
1255 $row = $dbr->selectRow( 'text',
1256 array( 'old_text', 'old_flags' ),
1257 array( 'old_id' => $this->getTextId() ),
1258 __METHOD__ );
1259 }
1260
1261 if( !$row && wfGetLB()->getServerCount() > 1 ) {
1262 // Possible slave lag!
1263 $dbw = wfGetDB( DB_MASTER );
1264 $row = $dbw->selectRow( 'text',
1265 array( 'old_text', 'old_flags' ),
1266 array( 'old_id' => $this->getTextId() ),
1267 __METHOD__ );
1268 }
1269
1270 $text = self::getRevisionText( $row );
1271
1272 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1273 if( $wgRevisionCacheExpiry && $text !== false ) {
1274 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1275 }
1276
1277 wfProfileOut( __METHOD__ );
1278
1279 return $text;
1280 }
1281
1282 /**
1283 * Create a new null-revision for insertion into a page's
1284 * history. This will not re-save the text, but simply refer
1285 * to the text from the previous version.
1286 *
1287 * Such revisions can for instance identify page rename
1288 * operations and other such meta-modifications.
1289 *
1290 * @param $dbw DatabaseBase
1291 * @param $pageId Integer: ID number of the page to read from
1292 * @param $summary String: revision's summary
1293 * @param $minor Boolean: whether the revision should be considered as minor
1294 * @return Revision|null on error
1295 */
1296 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1297 global $wgContentHandlerUseDB;
1298
1299 wfProfileIn( __METHOD__ );
1300
1301 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1302 'rev_text_id', 'rev_len', 'rev_sha1' );
1303
1304 if ( $wgContentHandlerUseDB ) {
1305 $fields[] = 'rev_content_model';
1306 $fields[] = 'rev_content_format';
1307 }
1308
1309 $current = $dbw->selectRow(
1310 array( 'page', 'revision' ),
1311 $fields,
1312 array(
1313 'page_id' => $pageId,
1314 'page_latest=rev_id',
1315 ),
1316 __METHOD__ );
1317
1318 if( $current ) {
1319 $row = array(
1320 'page' => $pageId,
1321 'comment' => $summary,
1322 'minor_edit' => $minor,
1323 'text_id' => $current->rev_text_id,
1324 'parent_id' => $current->page_latest,
1325 'len' => $current->rev_len,
1326 'sha1' => $current->rev_sha1
1327 );
1328
1329 if ( $wgContentHandlerUseDB ) {
1330 $row[ 'content_model' ] = $current->rev_content_model;
1331 $row[ 'content_format' ] = $current->rev_content_format;
1332 }
1333
1334 $revision = new Revision( $row );
1335 $revision->setTitle( Title::makeTitle( $current->page_namespace, $current->page_title ) );
1336 } else {
1337 $revision = null;
1338 }
1339
1340 wfProfileOut( __METHOD__ );
1341 return $revision;
1342 }
1343
1344 /**
1345 * Determine if the current user is allowed to view a particular
1346 * field of this revision, if it's marked as deleted.
1347 *
1348 * @param $field Integer:one of self::DELETED_TEXT,
1349 * self::DELETED_COMMENT,
1350 * self::DELETED_USER
1351 * @param $user User object to check, or null to use $wgUser
1352 * @return Boolean
1353 */
1354 public function userCan( $field, User $user = null ) {
1355 return self::userCanBitfield( $this->mDeleted, $field, $user );
1356 }
1357
1358 /**
1359 * Determine if the current user is allowed to view a particular
1360 * field of this revision, if it's marked as deleted. This is used
1361 * by various classes to avoid duplication.
1362 *
1363 * @param $bitfield Integer: current field
1364 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1365 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1366 * self::DELETED_USER = File::DELETED_USER
1367 * @param $user User object to check, or null to use $wgUser
1368 * @return Boolean
1369 */
1370 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
1371 if( $bitfield & $field ) { // aspect is deleted
1372 if ( $bitfield & self::DELETED_RESTRICTED ) {
1373 $permission = 'suppressrevision';
1374 } elseif ( $field & self::DELETED_TEXT ) {
1375 $permission = 'deletedtext';
1376 } else {
1377 $permission = 'deletedhistory';
1378 }
1379 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1380 if ( $user === null ) {
1381 global $wgUser;
1382 $user = $wgUser;
1383 }
1384 return $user->isAllowed( $permission );
1385 } else {
1386 return true;
1387 }
1388 }
1389
1390 /**
1391 * Get rev_timestamp from rev_id, without loading the rest of the row
1392 *
1393 * @param $title Title
1394 * @param $id Integer
1395 * @return String
1396 */
1397 static function getTimestampFromId( $title, $id ) {
1398 $dbr = wfGetDB( DB_SLAVE );
1399 // Casting fix for DB2
1400 if ( $id == '' ) {
1401 $id = 0;
1402 }
1403 $conds = array( 'rev_id' => $id );
1404 $conds['rev_page'] = $title->getArticleID();
1405 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1406 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1407 # Not in slave, try master
1408 $dbw = wfGetDB( DB_MASTER );
1409 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1410 }
1411 return wfTimestamp( TS_MW, $timestamp );
1412 }
1413
1414 /**
1415 * Get count of revisions per page...not very efficient
1416 *
1417 * @param $db DatabaseBase
1418 * @param $id Integer: page id
1419 * @return Integer
1420 */
1421 static function countByPageId( $db, $id ) {
1422 $row = $db->selectRow( 'revision', 'COUNT(*) AS revCount',
1423 array( 'rev_page' => $id ), __METHOD__ );
1424 if( $row ) {
1425 return $row->revCount;
1426 }
1427 return 0;
1428 }
1429
1430 /**
1431 * Get count of revisions per page...not very efficient
1432 *
1433 * @param $db DatabaseBase
1434 * @param $title Title
1435 * @return Integer
1436 */
1437 static function countByTitle( $db, $title ) {
1438 $id = $title->getArticleID();
1439 if( $id ) {
1440 return Revision::countByPageId( $db, $id );
1441 }
1442 return 0;
1443 }
1444 }