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