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