Reinstated r94289 et all - rev_sha1/ar_sha1 field for bug 21860
[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' => $row->ar_sha1
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' => array( 'INNER JOIN', 'page_id = rev_page' ),
298 'user' => array( 'LEFT JOIN', 'rev_user != 0 AND user_id = rev_user' ) )
299 );
300 }
301
302 /**
303 * Return the list of revision fields that should be selected to create
304 * a new revision.
305 */
306 public static function selectFields() {
307 return array(
308 'rev_id',
309 'rev_page',
310 'rev_text_id',
311 'rev_timestamp',
312 'rev_comment',
313 'rev_user_text',
314 'rev_user',
315 'rev_minor_edit',
316 'rev_deleted',
317 'rev_len',
318 'rev_parent_id',
319 'rev_sha1'
320 );
321 }
322
323 /**
324 * Return the list of text fields that should be selected to read the
325 * revision text
326 */
327 public static function selectTextFields() {
328 return array(
329 'old_text',
330 'old_flags'
331 );
332 }
333
334 /**
335 * Return the list of page fields that should be selected from page table
336 */
337 public static function selectPageFields() {
338 return array(
339 'page_namespace',
340 'page_title',
341 'page_latest'
342 );
343 }
344
345 /**
346 * Return the list of user fields that should be selected from user table
347 */
348 public static function selectUserFields() {
349 return array( 'user_name' );
350 }
351
352 /**
353 * Constructor
354 *
355 * @param $row Mixed: either a database row or an array
356 * @access private
357 */
358 function __construct( $row ) {
359 if( is_object( $row ) ) {
360 $this->mId = intval( $row->rev_id );
361 $this->mPage = intval( $row->rev_page );
362 $this->mTextId = intval( $row->rev_text_id );
363 $this->mComment = $row->rev_comment;
364 $this->mUser = intval( $row->rev_user );
365 $this->mMinorEdit = intval( $row->rev_minor_edit );
366 $this->mTimestamp = $row->rev_timestamp;
367 $this->mDeleted = intval( $row->rev_deleted );
368
369 if( !isset( $row->rev_parent_id ) ) {
370 $this->mParentId = is_null( $row->rev_parent_id ) ? null : 0;
371 } else {
372 $this->mParentId = intval( $row->rev_parent_id );
373 }
374
375 if( !isset( $row->rev_len ) || is_null( $row->rev_len ) ) {
376 $this->mSize = null;
377 } else {
378 $this->mSize = intval( $row->rev_len );
379 }
380
381 if ( !isset( $row->rev_sha1 ) ) {
382 $this->mSha1 = null;
383 } else {
384 $this->mSha1 = $row->rev_sha1;
385 }
386
387 if( isset( $row->page_latest ) ) {
388 $this->mCurrent = ( $row->rev_id == $row->page_latest );
389 $this->mTitle = Title::newFromRow( $row );
390 } else {
391 $this->mCurrent = false;
392 $this->mTitle = null;
393 }
394
395 // Lazy extraction...
396 $this->mText = null;
397 if( isset( $row->old_text ) ) {
398 $this->mTextRow = $row;
399 } else {
400 // 'text' table row entry will be lazy-loaded
401 $this->mTextRow = null;
402 }
403
404 // Use user_name for users and rev_user_text for IPs...
405 $this->mUserText = null; // lazy load if left null
406 if ( $this->mUser == 0 ) {
407 $this->mUserText = $row->rev_user_text; // IP user
408 } elseif ( isset( $row->user_name ) ) {
409 $this->mUserText = $row->user_name; // logged-in user
410 }
411 $this->mOrigUserText = $row->rev_user_text;
412 } elseif( is_array( $row ) ) {
413 // Build a new revision to be saved...
414 global $wgUser; // ugh
415
416 $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null;
417 $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null;
418 $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null;
419 $this->mUserText = isset( $row['user_text'] ) ? strval( $row['user_text'] ) : $wgUser->getName();
420 $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId();
421 $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0;
422 $this->mTimestamp = isset( $row['timestamp'] ) ? strval( $row['timestamp'] ) : wfTimestamp( TS_MW );
423 $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0;
424 $this->mSize = isset( $row['len'] ) ? intval( $row['len'] ) : null;
425 $this->mParentId = isset( $row['parent_id'] ) ? intval( $row['parent_id'] ) : null;
426 $this->mSha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
427
428 // Enforce spacing trimming on supplied text
429 $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null;
430 $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
431 $this->mTextRow = null;
432
433 $this->mTitle = null; # Load on demand if needed
434 $this->mCurrent = false;
435 # If we still have no length, see it we have the text to figure it out
436 if ( !$this->mSize ) {
437 $this->mSize = is_null( $this->mText ) ? null : strlen( $this->mText );
438 }
439 # Same for sha1
440 if ( $this->mSha1 === null ) {
441 $this->mSha1 = is_null( $this->mText ) ? null : self::base36Sha1( $this->mText );
442 }
443 } else {
444 throw new MWException( 'Revision constructor passed invalid row format.' );
445 }
446 $this->mUnpatrolled = null;
447 }
448
449 /**
450 * Get revision ID
451 *
452 * @return Integer
453 */
454 public function getId() {
455 return $this->mId;
456 }
457
458 /**
459 * Get text row ID
460 *
461 * @return Integer
462 */
463 public function getTextId() {
464 return $this->mTextId;
465 }
466
467 /**
468 * Get parent revision ID (the original previous page revision)
469 *
470 * @return Integer
471 */
472 public function getParentId() {
473 return $this->mParentId;
474 }
475
476 /**
477 * Returns the length of the text in this revision, or null if unknown.
478 *
479 * @return Integer
480 */
481 public function getSize() {
482 return $this->mSize;
483 }
484
485 /**
486 * Returns the base36 sha1 of the text in this revision, or null if unknown.
487 *
488 * @return String
489 */
490 public function getSha1() {
491 return $this->mSha1;
492 }
493
494 /**
495 * Returns the title of the page associated with this entry.
496 *
497 * @return Title
498 */
499 public function getTitle() {
500 if( isset( $this->mTitle ) ) {
501 return $this->mTitle;
502 }
503 $dbr = wfGetDB( DB_SLAVE );
504 $row = $dbr->selectRow(
505 array( 'page', 'revision' ),
506 array( 'page_namespace', 'page_title' ),
507 array( 'page_id=rev_page',
508 'rev_id' => $this->mId ),
509 'Revision::getTitle' );
510 if( $row ) {
511 $this->mTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
512 }
513 return $this->mTitle;
514 }
515
516 /**
517 * Set the title of the revision
518 *
519 * @param $title Title
520 */
521 public function setTitle( $title ) {
522 $this->mTitle = $title;
523 }
524
525 /**
526 * Get the page ID
527 *
528 * @return Integer
529 */
530 public function getPage() {
531 return $this->mPage;
532 }
533
534 /**
535 * Fetch revision's user id if it's available to the specified audience.
536 * If the specified audience does not have access to it, zero will be
537 * returned.
538 *
539 * @param $audience Integer: one of:
540 * Revision::FOR_PUBLIC to be displayed to all users
541 * Revision::FOR_THIS_USER to be displayed to $wgUser
542 * Revision::RAW get the ID regardless of permissions
543 * @param $user User object to check for, only if FOR_THIS_USER is passed
544 * to the $audience parameter
545 * @return Integer
546 */
547 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
548 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
549 return 0;
550 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
551 return 0;
552 } else {
553 return $this->mUser;
554 }
555 }
556
557 /**
558 * Fetch revision's user id without regard for the current user's permissions
559 *
560 * @return String
561 */
562 public function getRawUser() {
563 return $this->mUser;
564 }
565
566 /**
567 * Fetch revision's username if it's available to the specified audience.
568 * If the specified audience does not have access to the username, an
569 * empty string will be returned.
570 *
571 * @param $audience Integer: one of:
572 * Revision::FOR_PUBLIC to be displayed to all users
573 * Revision::FOR_THIS_USER to be displayed to $wgUser
574 * Revision::RAW get the text regardless of permissions
575 * @param $user User object to check for, only if FOR_THIS_USER is passed
576 * to the $audience parameter
577 * @return string
578 */
579 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
580 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
581 return '';
582 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
583 return '';
584 } else {
585 return $this->getRawUserText();
586 }
587 }
588
589 /**
590 * Fetch revision's username without regard for view restrictions
591 *
592 * @return String
593 */
594 public function getRawUserText() {
595 if ( $this->mUserText === null ) {
596 $this->mUserText = User::whoIs( $this->mUser ); // load on demand
597 if ( $this->mUserText === false ) {
598 # This shouldn't happen, but it can if the wiki was recovered
599 # via importing revs and there is no user table entry yet.
600 $this->mUserText = $this->mOrigUserText;
601 }
602 }
603 return $this->mUserText;
604 }
605
606 /**
607 * Fetch revision comment if it's available to the specified audience.
608 * If the specified audience does not have access to the comment, an
609 * empty string will be returned.
610 *
611 * @param $audience Integer: one of:
612 * Revision::FOR_PUBLIC to be displayed to all users
613 * Revision::FOR_THIS_USER to be displayed to $wgUser
614 * Revision::RAW get the text regardless of permissions
615 * @param $user User object to check for, only if FOR_THIS_USER is passed
616 * to the $audience parameter
617 * @return String
618 */
619 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
620 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
621 return '';
622 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $user ) ) {
623 return '';
624 } else {
625 return $this->mComment;
626 }
627 }
628
629 /**
630 * Fetch revision comment without regard for the current user's permissions
631 *
632 * @return String
633 */
634 public function getRawComment() {
635 return $this->mComment;
636 }
637
638 /**
639 * @return Boolean
640 */
641 public function isMinor() {
642 return (bool)$this->mMinorEdit;
643 }
644
645 /**
646 * @return Integer rcid of the unpatrolled row, zero if there isn't one
647 */
648 public function isUnpatrolled() {
649 if( $this->mUnpatrolled !== null ) {
650 return $this->mUnpatrolled;
651 }
652 $dbr = wfGetDB( DB_SLAVE );
653 $this->mUnpatrolled = $dbr->selectField( 'recentchanges',
654 'rc_id',
655 array( // Add redundant user,timestamp condition so we can use the existing index
656 'rc_user_text' => $this->getRawUserText(),
657 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
658 'rc_this_oldid' => $this->getId(),
659 'rc_patrolled' => 0
660 ),
661 __METHOD__
662 );
663 return (int)$this->mUnpatrolled;
664 }
665
666 /**
667 * @param $field int one of DELETED_* bitfield constants
668 *
669 * @return Boolean
670 */
671 public function isDeleted( $field ) {
672 return ( $this->mDeleted & $field ) == $field;
673 }
674
675 /**
676 * Get the deletion bitfield of the revision
677 *
678 * @return int
679 */
680 public function getVisibility() {
681 return (int)$this->mDeleted;
682 }
683
684 /**
685 * Fetch revision text if it's available to the specified audience.
686 * If the specified audience does not have the ability to view this
687 * revision, an empty string will be returned.
688 *
689 * @param $audience Integer: one of:
690 * Revision::FOR_PUBLIC to be displayed to all users
691 * Revision::FOR_THIS_USER to be displayed to $wgUser
692 * Revision::RAW get the text regardless of permissions
693 * @param $user User object to check for, only if FOR_THIS_USER is passed
694 * to the $audience parameter
695 * @return String
696 */
697 public function getText( $audience = self::FOR_PUBLIC, User $user = null ) {
698 if( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_TEXT ) ) {
699 return '';
700 } elseif( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_TEXT, $user ) ) {
701 return '';
702 } else {
703 return $this->getRawText();
704 }
705 }
706
707 /**
708 * Alias for getText(Revision::FOR_THIS_USER)
709 *
710 * @deprecated since 1.17
711 * @return String
712 */
713 public function revText() {
714 wfDeprecated( __METHOD__ );
715 return $this->getText( self::FOR_THIS_USER );
716 }
717
718 /**
719 * Fetch revision text without regard for view restrictions
720 *
721 * @return String
722 */
723 public function getRawText() {
724 if( is_null( $this->mText ) ) {
725 // Revision text is immutable. Load on demand:
726 $this->mText = $this->loadText();
727 }
728 return $this->mText;
729 }
730
731 /**
732 * @return String
733 */
734 public function getTimestamp() {
735 return wfTimestamp( TS_MW, $this->mTimestamp );
736 }
737
738 /**
739 * @return Boolean
740 */
741 public function isCurrent() {
742 return $this->mCurrent;
743 }
744
745 /**
746 * Get previous revision for this title
747 *
748 * @return Revision or null
749 */
750 public function getPrevious() {
751 if( $this->getTitle() ) {
752 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
753 if( $prev ) {
754 return Revision::newFromTitle( $this->getTitle(), $prev );
755 }
756 }
757 return null;
758 }
759
760 /**
761 * Get next revision for this title
762 *
763 * @return Revision or null
764 */
765 public function getNext() {
766 if( $this->getTitle() ) {
767 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
768 if ( $next ) {
769 return Revision::newFromTitle( $this->getTitle(), $next );
770 }
771 }
772 return null;
773 }
774
775 /**
776 * Get previous revision Id for this page_id
777 * This is used to populate rev_parent_id on save
778 *
779 * @param $db DatabaseBase
780 * @return Integer
781 */
782 private function getPreviousRevisionId( $db ) {
783 if( is_null( $this->mPage ) ) {
784 return 0;
785 }
786 # Use page_latest if ID is not given
787 if( !$this->mId ) {
788 $prevId = $db->selectField( 'page', 'page_latest',
789 array( 'page_id' => $this->mPage ),
790 __METHOD__ );
791 } else {
792 $prevId = $db->selectField( 'revision', 'rev_id',
793 array( 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ),
794 __METHOD__,
795 array( 'ORDER BY' => 'rev_id DESC' ) );
796 }
797 return intval( $prevId );
798 }
799
800 /**
801 * Get revision text associated with an old or archive row
802 * $row is usually an object from wfFetchRow(), both the flags and the text
803 * field must be included
804 *
805 * @param $row Object: the text data
806 * @param $prefix String: table prefix (default 'old_')
807 * @return String: text the text requested or false on failure
808 */
809 public static function getRevisionText( $row, $prefix = 'old_' ) {
810 wfProfileIn( __METHOD__ );
811
812 # Get data
813 $textField = $prefix . 'text';
814 $flagsField = $prefix . 'flags';
815
816 if( isset( $row->$flagsField ) ) {
817 $flags = explode( ',', $row->$flagsField );
818 } else {
819 $flags = array();
820 }
821
822 if( isset( $row->$textField ) ) {
823 $text = $row->$textField;
824 } else {
825 wfProfileOut( __METHOD__ );
826 return false;
827 }
828
829 # Use external methods for external objects, text in table is URL-only then
830 if ( in_array( 'external', $flags ) ) {
831 $url = $text;
832 $parts = explode( '://', $url, 2 );
833 if( count( $parts ) == 1 || $parts[1] == '' ) {
834 wfProfileOut( __METHOD__ );
835 return false;
836 }
837 $text = ExternalStore::fetchFromURL( $url );
838 }
839
840 // If the text was fetched without an error, convert it
841 if ( $text !== false ) {
842 if( in_array( 'gzip', $flags ) ) {
843 # Deal with optional compression of archived pages.
844 # This can be done periodically via maintenance/compressOld.php, and
845 # as pages are saved if $wgCompressRevisions is set.
846 $text = gzinflate( $text );
847 }
848
849 if( in_array( 'object', $flags ) ) {
850 # Generic compressed storage
851 $obj = unserialize( $text );
852 if ( !is_object( $obj ) ) {
853 // Invalid object
854 wfProfileOut( __METHOD__ );
855 return false;
856 }
857 $text = $obj->getText();
858 }
859
860 global $wgLegacyEncoding;
861 if( $text !== false && $wgLegacyEncoding
862 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
863 {
864 # Old revisions kept around in a legacy encoding?
865 # Upconvert on demand.
866 # ("utf8" checked for compatibility with some broken
867 # conversion scripts 2008-12-30)
868 global $wgContLang;
869 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
870 }
871 }
872 wfProfileOut( __METHOD__ );
873 return $text;
874 }
875
876 /**
877 * If $wgCompressRevisions is enabled, we will compress data.
878 * The input string is modified in place.
879 * Return value is the flags field: contains 'gzip' if the
880 * data is compressed, and 'utf-8' if we're saving in UTF-8
881 * mode.
882 *
883 * @param $text Mixed: reference to a text
884 * @return String
885 */
886 public static function compressRevisionText( &$text ) {
887 global $wgCompressRevisions;
888 $flags = array();
889
890 # Revisions not marked this way will be converted
891 # on load if $wgLegacyCharset is set in the future.
892 $flags[] = 'utf-8';
893
894 if( $wgCompressRevisions ) {
895 if( function_exists( 'gzdeflate' ) ) {
896 $text = gzdeflate( $text );
897 $flags[] = 'gzip';
898 } else {
899 wfDebug( "Revision::compressRevisionText() -- no zlib support, not compressing\n" );
900 }
901 }
902 return implode( ',', $flags );
903 }
904
905 /**
906 * Insert a new revision into the database, returning the new revision ID
907 * number on success and dies horribly on failure.
908 *
909 * @param $dbw DatabaseBase: (master connection)
910 * @return Integer
911 */
912 public function insertOn( $dbw ) {
913 global $wgDefaultExternalStore;
914
915 wfProfileIn( __METHOD__ );
916
917 $data = $this->mText;
918 $flags = Revision::compressRevisionText( $data );
919
920 # Write to external storage if required
921 if( $wgDefaultExternalStore ) {
922 // Store and get the URL
923 $data = ExternalStore::insertToDefault( $data );
924 if( !$data ) {
925 throw new MWException( "Unable to store text to external storage" );
926 }
927 if( $flags ) {
928 $flags .= ',';
929 }
930 $flags .= 'external';
931 }
932
933 # Record the text (or external storage URL) to the text table
934 if( !isset( $this->mTextId ) ) {
935 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
936 $dbw->insert( 'text',
937 array(
938 'old_id' => $old_id,
939 'old_text' => $data,
940 'old_flags' => $flags,
941 ), __METHOD__
942 );
943 $this->mTextId = $dbw->insertId();
944 }
945
946 if ( $this->mComment === null ) $this->mComment = "";
947
948 # Record the edit in revisions
949 $rev_id = isset( $this->mId )
950 ? $this->mId
951 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
952 $dbw->insert( 'revision',
953 array(
954 'rev_id' => $rev_id,
955 'rev_page' => $this->mPage,
956 'rev_text_id' => $this->mTextId,
957 'rev_comment' => $this->mComment,
958 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
959 'rev_user' => $this->mUser,
960 'rev_user_text' => $this->mUserText,
961 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
962 'rev_deleted' => $this->mDeleted,
963 'rev_len' => $this->mSize,
964 'rev_parent_id' => is_null( $this->mParentId )
965 ? $this->getPreviousRevisionId( $dbw )
966 : $this->mParentId,
967 'rev_sha1' => is_null( $this->mSha1 )
968 ? Revision::base36Sha1( $this->mText )
969 : $this->mSha1
970 ), __METHOD__
971 );
972
973 $this->mId = !is_null( $rev_id ) ? $rev_id : $dbw->insertId();
974
975 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
976
977 wfProfileOut( __METHOD__ );
978 return $this->mId;
979 }
980
981 /**
982 * Get the base 36 SHA-1 value for a string of text
983 * @param $text String
984 * @return String
985 */
986 public static function base36Sha1( $text ) {
987 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
988 }
989
990 /**
991 * Lazy-load the revision's text.
992 * Currently hardcoded to the 'text' table storage engine.
993 *
994 * @return String
995 */
996 protected function loadText() {
997 wfProfileIn( __METHOD__ );
998
999 // Caching may be beneficial for massive use of external storage
1000 global $wgRevisionCacheExpiry, $wgMemc;
1001 $textId = $this->getTextId();
1002 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1003 if( $wgRevisionCacheExpiry ) {
1004 $text = $wgMemc->get( $key );
1005 if( is_string( $text ) ) {
1006 wfDebug( __METHOD__ . ": got id $textId from cache\n" );
1007 wfProfileOut( __METHOD__ );
1008 return $text;
1009 }
1010 }
1011
1012 // If we kept data for lazy extraction, use it now...
1013 if ( isset( $this->mTextRow ) ) {
1014 $row = $this->mTextRow;
1015 $this->mTextRow = null;
1016 } else {
1017 $row = null;
1018 }
1019
1020 if( !$row ) {
1021 // Text data is immutable; check slaves first.
1022 $dbr = wfGetDB( DB_SLAVE );
1023 $row = $dbr->selectRow( 'text',
1024 array( 'old_text', 'old_flags' ),
1025 array( 'old_id' => $this->getTextId() ),
1026 __METHOD__ );
1027 }
1028
1029 if( !$row && wfGetLB()->getServerCount() > 1 ) {
1030 // Possible slave lag!
1031 $dbw = wfGetDB( DB_MASTER );
1032 $row = $dbw->selectRow( 'text',
1033 array( 'old_text', 'old_flags' ),
1034 array( 'old_id' => $this->getTextId() ),
1035 __METHOD__ );
1036 }
1037
1038 $text = self::getRevisionText( $row );
1039
1040 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1041 if( $wgRevisionCacheExpiry && $text !== false ) {
1042 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1043 }
1044
1045 wfProfileOut( __METHOD__ );
1046
1047 return $text;
1048 }
1049
1050 /**
1051 * Create a new null-revision for insertion into a page's
1052 * history. This will not re-save the text, but simply refer
1053 * to the text from the previous version.
1054 *
1055 * Such revisions can for instance identify page rename
1056 * operations and other such meta-modifications.
1057 *
1058 * @param $dbw DatabaseBase
1059 * @param $pageId Integer: ID number of the page to read from
1060 * @param $summary String: revision's summary
1061 * @param $minor Boolean: whether the revision should be considered as minor
1062 * @return Revision|null on error
1063 */
1064 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1065 wfProfileIn( __METHOD__ );
1066
1067 $current = $dbw->selectRow(
1068 array( 'page', 'revision' ),
1069 array( 'page_latest', 'rev_text_id', 'rev_len' ),
1070 array(
1071 'page_id' => $pageId,
1072 'page_latest=rev_id',
1073 ),
1074 __METHOD__ );
1075
1076 if( $current ) {
1077 $revision = new Revision( array(
1078 'page' => $pageId,
1079 'comment' => $summary,
1080 'minor_edit' => $minor,
1081 'text_id' => $current->rev_text_id,
1082 'parent_id' => $current->page_latest,
1083 'len' => $current->rev_len
1084 ) );
1085 } else {
1086 $revision = null;
1087 }
1088
1089 wfProfileOut( __METHOD__ );
1090 return $revision;
1091 }
1092
1093 /**
1094 * Determine if the current user is allowed to view a particular
1095 * field of this revision, if it's marked as deleted.
1096 *
1097 * @param $field Integer:one of self::DELETED_TEXT,
1098 * self::DELETED_COMMENT,
1099 * self::DELETED_USER
1100 * @param $user User object to check, or null to use $wgUser
1101 * @return Boolean
1102 */
1103 public function userCan( $field, User $user = null ) {
1104 return self::userCanBitfield( $this->mDeleted, $field, $user );
1105 }
1106
1107 /**
1108 * Determine if the current user is allowed to view a particular
1109 * field of this revision, if it's marked as deleted. This is used
1110 * by various classes to avoid duplication.
1111 *
1112 * @param $bitfield Integer: current field
1113 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1114 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1115 * self::DELETED_USER = File::DELETED_USER
1116 * @param $user User object to check, or null to use $wgUser
1117 * @return Boolean
1118 */
1119 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
1120 if( $bitfield & $field ) { // aspect is deleted
1121 if ( $bitfield & self::DELETED_RESTRICTED ) {
1122 $permission = 'suppressrevision';
1123 } elseif ( $field & self::DELETED_TEXT ) {
1124 $permission = 'deletedtext';
1125 } else {
1126 $permission = 'deletedhistory';
1127 }
1128 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1129 if ( $user === null ) {
1130 global $wgUser;
1131 $user = $wgUser;
1132 }
1133 return $user->isAllowed( $permission );
1134 } else {
1135 return true;
1136 }
1137 }
1138
1139 /**
1140 * Get rev_timestamp from rev_id, without loading the rest of the row
1141 *
1142 * @param $title Title
1143 * @param $id Integer
1144 * @return String
1145 */
1146 static function getTimestampFromId( $title, $id ) {
1147 $dbr = wfGetDB( DB_SLAVE );
1148 // Casting fix for DB2
1149 if ( $id == '' ) {
1150 $id = 0;
1151 }
1152 $conds = array( 'rev_id' => $id );
1153 $conds['rev_page'] = $title->getArticleId();
1154 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1155 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1156 # Not in slave, try master
1157 $dbw = wfGetDB( DB_MASTER );
1158 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1159 }
1160 return wfTimestamp( TS_MW, $timestamp );
1161 }
1162
1163 /**
1164 * Get count of revisions per page...not very efficient
1165 *
1166 * @param $db DatabaseBase
1167 * @param $id Integer: page id
1168 * @return Integer
1169 */
1170 static function countByPageId( $db, $id ) {
1171 $row = $db->selectRow( 'revision', 'COUNT(*) AS revCount',
1172 array( 'rev_page' => $id ), __METHOD__ );
1173 if( $row ) {
1174 return $row->revCount;
1175 }
1176 return 0;
1177 }
1178
1179 /**
1180 * Get count of revisions per page...not very efficient
1181 *
1182 * @param $db DatabaseBase
1183 * @param $title Title
1184 * @return Integer
1185 */
1186 static function countByTitle( $db, $title ) {
1187 $id = $title->getArticleId();
1188 if( $id ) {
1189 return Revision::countByPageId( $db, $id );
1190 }
1191 return 0;
1192 }
1193 }