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