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