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