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