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