Merge branch 'Wikidata' of ssh://review/mediawiki/core into Wikidata
[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 $mContentModel;
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->mContentModel = null; # determine on demand if needed
444 } else {
445 $this->mContentModel = intval( $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 = intval( $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']->getModel();
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->mContentModel = isset( $row['content_model'] ) ? intval( $row['content_model'] ) : null;
501 $this->mContentFormat = isset( $row['content_format'] ) ? intval( $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 mContentModel
509 if ( !empty( $row['content'] ) ) {
510 $handler = $this->getContentHandler();
511 $this->mContent = $row['content'];
512
513 $this->mContentModel = $this->mContent->getModel();
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->getContentModel(); # 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 /**
883 * Returns the content model for this revision.
884 *
885 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
886 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
887 * is used as a last resort.
888 *
889 * @return int the content model id associated with this revision, see the CONTENT_MODEL_XXX constants.
890 **/
891 public function getContentModel() {
892 if ( !$this->mContentModel ) {
893 $title = $this->getTitle();
894 $this->mContentModel = ( $title ? $title->getContentModel() : CONTENT_MODEL_WIKITEXT );
895
896 assert( !empty( $this->mContentModel ) );
897 }
898
899 return $this->mContentModel;
900 }
901
902 /**
903 * Returns the content format for this revision.
904 *
905 * If no content format was stored in the database, the default format for this
906 * revision's content model is returned.
907 *
908 * @return int the content format id associated with this revision, see the CONTENT_FORMAT_XXX constants.
909 **/
910 public function getContentFormat() {
911 if ( !$this->mContentFormat ) {
912 $handler = $this->getContentHandler();
913 $this->mContentFormat = $handler->getDefaultFormat();
914
915 assert( !empty( $this->mContentFormat ) );
916 }
917
918 return $this->mContentFormat;
919 }
920
921 /**
922 * Returns the content handler appropriate for this revision's content model.
923 *
924 * @return ContentHandler
925 */
926 public function getContentHandler() {
927 if ( !$this->mContentHandler ) {
928 $model = $this->getContentModel();
929 $this->mContentHandler = ContentHandler::getForModelID( $model );
930
931 assert( $this->mContentHandler->isSupportedFormat( $this->getContentFormat() ) );
932 }
933
934 return $this->mContentHandler;
935 }
936
937 /**
938 * @return String
939 */
940 public function getTimestamp() {
941 return wfTimestamp( TS_MW, $this->mTimestamp );
942 }
943
944 /**
945 * @return Boolean
946 */
947 public function isCurrent() {
948 return $this->mCurrent;
949 }
950
951 /**
952 * Get previous revision for this title
953 *
954 * @return Revision or null
955 */
956 public function getPrevious() {
957 if( $this->getTitle() ) {
958 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
959 if( $prev ) {
960 return Revision::newFromTitle( $this->getTitle(), $prev );
961 }
962 }
963 return null;
964 }
965
966 /**
967 * Get next revision for this title
968 *
969 * @return Revision or null
970 */
971 public function getNext() {
972 if( $this->getTitle() ) {
973 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
974 if ( $next ) {
975 return Revision::newFromTitle( $this->getTitle(), $next );
976 }
977 }
978 return null;
979 }
980
981 /**
982 * Get previous revision Id for this page_id
983 * This is used to populate rev_parent_id on save
984 *
985 * @param $db DatabaseBase
986 * @return Integer
987 */
988 private function getPreviousRevisionId( $db ) {
989 if( is_null( $this->mPage ) ) {
990 return 0;
991 }
992 # Use page_latest if ID is not given
993 if( !$this->mId ) {
994 $prevId = $db->selectField( 'page', 'page_latest',
995 array( 'page_id' => $this->mPage ),
996 __METHOD__ );
997 } else {
998 $prevId = $db->selectField( 'revision', 'rev_id',
999 array( 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ),
1000 __METHOD__,
1001 array( 'ORDER BY' => 'rev_id DESC' ) );
1002 }
1003 return intval( $prevId );
1004 }
1005
1006 /**
1007 * Get revision text associated with an old or archive row
1008 * $row is usually an object from wfFetchRow(), both the flags and the text
1009 * field must be included
1010 *
1011 * @param $row Object: the text data
1012 * @param $prefix String: table prefix (default 'old_')
1013 * @return String: text the text requested or false on failure
1014 */
1015 public static function getRevisionText( $row, $prefix = 'old_' ) {
1016 wfProfileIn( __METHOD__ );
1017
1018 # Get data
1019 $textField = $prefix . 'text';
1020 $flagsField = $prefix . 'flags';
1021
1022 if( isset( $row->$flagsField ) ) {
1023 $flags = explode( ',', $row->$flagsField );
1024 } else {
1025 $flags = array();
1026 }
1027
1028 if( isset( $row->$textField ) ) {
1029 $text = $row->$textField;
1030 } else {
1031 wfProfileOut( __METHOD__ );
1032 return false;
1033 }
1034
1035 # Use external methods for external objects, text in table is URL-only then
1036 if ( in_array( 'external', $flags ) ) {
1037 $url = $text;
1038 $parts = explode( '://', $url, 2 );
1039 if( count( $parts ) == 1 || $parts[1] == '' ) {
1040 wfProfileOut( __METHOD__ );
1041 return false;
1042 }
1043 $text = ExternalStore::fetchFromURL( $url );
1044 }
1045
1046 // If the text was fetched without an error, convert it
1047 if ( $text !== false ) {
1048 if( in_array( 'gzip', $flags ) ) {
1049 # Deal with optional compression of archived pages.
1050 # This can be done periodically via maintenance/compressOld.php, and
1051 # as pages are saved if $wgCompressRevisions is set.
1052 $text = gzinflate( $text );
1053 }
1054
1055 if( in_array( 'object', $flags ) ) {
1056 # Generic compressed storage
1057 $obj = unserialize( $text );
1058 if ( !is_object( $obj ) ) {
1059 // Invalid object
1060 wfProfileOut( __METHOD__ );
1061 return false;
1062 }
1063 $text = $obj->getText();
1064 }
1065
1066 global $wgLegacyEncoding;
1067 if( $text !== false && $wgLegacyEncoding
1068 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) )
1069 {
1070 # Old revisions kept around in a legacy encoding?
1071 # Upconvert on demand.
1072 # ("utf8" checked for compatibility with some broken
1073 # conversion scripts 2008-12-30)
1074 global $wgContLang;
1075 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1076 }
1077 }
1078 wfProfileOut( __METHOD__ );
1079 return $text;
1080 }
1081
1082 /**
1083 * If $wgCompressRevisions is enabled, we will compress data.
1084 * The input string is modified in place.
1085 * Return value is the flags field: contains 'gzip' if the
1086 * data is compressed, and 'utf-8' if we're saving in UTF-8
1087 * mode.
1088 *
1089 * @param $text Mixed: reference to a text
1090 * @return String
1091 */
1092 public static function compressRevisionText( &$text ) {
1093 global $wgCompressRevisions;
1094 $flags = array();
1095
1096 # Revisions not marked this way will be converted
1097 # on load if $wgLegacyCharset is set in the future.
1098 $flags[] = 'utf-8';
1099
1100 if( $wgCompressRevisions ) {
1101 if( function_exists( 'gzdeflate' ) ) {
1102 $text = gzdeflate( $text );
1103 $flags[] = 'gzip';
1104 } else {
1105 wfDebug( "Revision::compressRevisionText() -- no zlib support, not compressing\n" );
1106 }
1107 }
1108 return implode( ',', $flags );
1109 }
1110
1111 /**
1112 * Insert a new revision into the database, returning the new revision ID
1113 * number on success and dies horribly on failure.
1114 *
1115 * @param $dbw DatabaseBase: (master connection)
1116 * @return Integer
1117 */
1118 public function insertOn( $dbw ) {
1119 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1120
1121 wfProfileIn( __METHOD__ );
1122
1123 $data = $this->mText;
1124 $flags = Revision::compressRevisionText( $data );
1125
1126 # Write to external storage if required
1127 if( $wgDefaultExternalStore ) {
1128 // Store and get the URL
1129 $data = ExternalStore::insertToDefault( $data );
1130 if( !$data ) {
1131 throw new MWException( "Unable to store text to external storage" );
1132 }
1133 if( $flags ) {
1134 $flags .= ',';
1135 }
1136 $flags .= 'external';
1137 }
1138
1139 # Record the text (or external storage URL) to the text table
1140 if( !isset( $this->mTextId ) ) {
1141 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1142 $dbw->insert( 'text',
1143 array(
1144 'old_id' => $old_id,
1145 'old_text' => $data,
1146 'old_flags' => $flags,
1147 ), __METHOD__
1148 );
1149 $this->mTextId = $dbw->insertId();
1150 }
1151
1152 if ( $this->mComment === null ) $this->mComment = "";
1153
1154 # Record the edit in revisions
1155 $rev_id = isset( $this->mId )
1156 ? $this->mId
1157 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1158
1159 $row = array(
1160 'rev_id' => $rev_id,
1161 'rev_page' => $this->mPage,
1162 'rev_text_id' => $this->mTextId,
1163 'rev_comment' => $this->mComment,
1164 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
1165 'rev_user' => $this->mUser,
1166 'rev_user_text' => $this->mUserText,
1167 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
1168 'rev_deleted' => $this->mDeleted,
1169 'rev_len' => $this->mSize,
1170 'rev_parent_id' => is_null( $this->mParentId )
1171 ? $this->getPreviousRevisionId( $dbw )
1172 : $this->mParentId,
1173 'rev_sha1' => is_null( $this->mSha1 )
1174 ? Revision::base36Sha1( $this->mText )
1175 : $this->mSha1,
1176 );
1177
1178 if ( $wgContentHandlerUseDB ) {
1179 $row[ 'rev_content_model' ] = $this->getContentModel();
1180 $row[ 'rev_content_format' ] = $this->getContentFormat();
1181 }
1182
1183 $dbw->insert( 'revision', $row, __METHOD__ );
1184
1185 $this->mId = !is_null( $rev_id ) ? $rev_id : $dbw->insertId();
1186
1187 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1188
1189 wfProfileOut( __METHOD__ );
1190 return $this->mId;
1191 }
1192
1193 /**
1194 * Get the base 36 SHA-1 value for a string of text
1195 * @param $text String
1196 * @return String
1197 */
1198 public static function base36Sha1( $text ) {
1199 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1200 }
1201
1202 /**
1203 * Lazy-load the revision's text.
1204 * Currently hardcoded to the 'text' table storage engine.
1205 *
1206 * @return String
1207 */
1208 protected function loadText() {
1209 wfProfileIn( __METHOD__ );
1210
1211 // Caching may be beneficial for massive use of external storage
1212 global $wgRevisionCacheExpiry, $wgMemc;
1213 $textId = $this->getTextId();
1214 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1215 if( $wgRevisionCacheExpiry ) {
1216 $text = $wgMemc->get( $key );
1217 if( is_string( $text ) ) {
1218 wfDebug( __METHOD__ . ": got id $textId from cache\n" );
1219 wfProfileOut( __METHOD__ );
1220 return $text;
1221 }
1222 }
1223
1224 // If we kept data for lazy extraction, use it now...
1225 if ( isset( $this->mTextRow ) ) {
1226 $row = $this->mTextRow;
1227 $this->mTextRow = null;
1228 } else {
1229 $row = null;
1230 }
1231
1232 if( !$row ) {
1233 // Text data is immutable; check slaves first.
1234 $dbr = wfGetDB( DB_SLAVE );
1235 $row = $dbr->selectRow( 'text',
1236 array( 'old_text', 'old_flags' ),
1237 array( 'old_id' => $this->getTextId() ),
1238 __METHOD__ );
1239 }
1240
1241 if( !$row && wfGetLB()->getServerCount() > 1 ) {
1242 // Possible slave lag!
1243 $dbw = wfGetDB( DB_MASTER );
1244 $row = $dbw->selectRow( 'text',
1245 array( 'old_text', 'old_flags' ),
1246 array( 'old_id' => $this->getTextId() ),
1247 __METHOD__ );
1248 }
1249
1250 $text = self::getRevisionText( $row );
1251
1252 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1253 if( $wgRevisionCacheExpiry && $text !== false ) {
1254 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1255 }
1256
1257 wfProfileOut( __METHOD__ );
1258
1259 return $text;
1260 }
1261
1262 /**
1263 * Create a new null-revision for insertion into a page's
1264 * history. This will not re-save the text, but simply refer
1265 * to the text from the previous version.
1266 *
1267 * Such revisions can for instance identify page rename
1268 * operations and other such meta-modifications.
1269 *
1270 * @param $dbw DatabaseBase
1271 * @param $pageId Integer: ID number of the page to read from
1272 * @param $summary String: revision's summary
1273 * @param $minor Boolean: whether the revision should be considered as minor
1274 * @return Revision|null on error
1275 */
1276 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1277 global $wgContentHandlerUseDB;
1278
1279 wfProfileIn( __METHOD__ );
1280
1281 $fields = array( 'page_latest', 'rev_text_id', 'rev_len', 'rev_sha1' );
1282
1283 if ( $wgContentHandlerUseDB ) {
1284 $fields[] = 'rev_content_model';
1285 $fields[] = 'rev_content_format';
1286 }
1287
1288 $current = $dbw->selectRow(
1289 array( 'page', 'revision' ),
1290 $fields,
1291 array(
1292 'page_id' => $pageId,
1293 'page_latest=rev_id',
1294 ),
1295 __METHOD__ );
1296
1297 if( $current ) {
1298 $row = array(
1299 'page' => $pageId,
1300 'comment' => $summary,
1301 'minor_edit' => $minor,
1302 'text_id' => $current->rev_text_id,
1303 'parent_id' => $current->page_latest,
1304 'len' => $current->rev_len,
1305 'sha1' => $current->rev_sha1,
1306 );
1307
1308 if ( $wgContentHandlerUseDB ) {
1309 $row[ 'content_model' ] = $current->rev_content_model;
1310 $row[ 'content_format' ] = $current->rev_content_format;
1311 }
1312
1313 $revision = new Revision( $row );
1314 } else {
1315 $revision = null;
1316 }
1317
1318 wfProfileOut( __METHOD__ );
1319 return $revision;
1320 }
1321
1322 /**
1323 * Determine if the current user is allowed to view a particular
1324 * field of this revision, if it's marked as deleted.
1325 *
1326 * @param $field Integer:one of self::DELETED_TEXT,
1327 * self::DELETED_COMMENT,
1328 * self::DELETED_USER
1329 * @param $user User object to check, or null to use $wgUser
1330 * @return Boolean
1331 */
1332 public function userCan( $field, User $user = null ) {
1333 return self::userCanBitfield( $this->mDeleted, $field, $user );
1334 }
1335
1336 /**
1337 * Determine if the current user is allowed to view a particular
1338 * field of this revision, if it's marked as deleted. This is used
1339 * by various classes to avoid duplication.
1340 *
1341 * @param $bitfield Integer: current field
1342 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1343 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1344 * self::DELETED_USER = File::DELETED_USER
1345 * @param $user User object to check, or null to use $wgUser
1346 * @return Boolean
1347 */
1348 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
1349 if( $bitfield & $field ) { // aspect is deleted
1350 if ( $bitfield & self::DELETED_RESTRICTED ) {
1351 $permission = 'suppressrevision';
1352 } elseif ( $field & self::DELETED_TEXT ) {
1353 $permission = 'deletedtext';
1354 } else {
1355 $permission = 'deletedhistory';
1356 }
1357 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1358 if ( $user === null ) {
1359 global $wgUser;
1360 $user = $wgUser;
1361 }
1362 return $user->isAllowed( $permission );
1363 } else {
1364 return true;
1365 }
1366 }
1367
1368 /**
1369 * Get rev_timestamp from rev_id, without loading the rest of the row
1370 *
1371 * @param $title Title
1372 * @param $id Integer
1373 * @return String
1374 */
1375 static function getTimestampFromId( $title, $id ) {
1376 $dbr = wfGetDB( DB_SLAVE );
1377 // Casting fix for DB2
1378 if ( $id == '' ) {
1379 $id = 0;
1380 }
1381 $conds = array( 'rev_id' => $id );
1382 $conds['rev_page'] = $title->getArticleID();
1383 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1384 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1385 # Not in slave, try master
1386 $dbw = wfGetDB( DB_MASTER );
1387 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1388 }
1389 return wfTimestamp( TS_MW, $timestamp );
1390 }
1391
1392 /**
1393 * Get count of revisions per page...not very efficient
1394 *
1395 * @param $db DatabaseBase
1396 * @param $id Integer: page id
1397 * @return Integer
1398 */
1399 static function countByPageId( $db, $id ) {
1400 $row = $db->selectRow( 'revision', 'COUNT(*) AS revCount',
1401 array( 'rev_page' => $id ), __METHOD__ );
1402 if( $row ) {
1403 return $row->revCount;
1404 }
1405 return 0;
1406 }
1407
1408 /**
1409 * Get count of revisions per page...not very efficient
1410 *
1411 * @param $db DatabaseBase
1412 * @param $title Title
1413 * @return Integer
1414 */
1415 static function countByTitle( $db, $title ) {
1416 $id = $title->getArticleID();
1417 if( $id ) {
1418 return Revision::countByPageId( $db, $id );
1419 }
1420 return 0;
1421 }
1422 }