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