Merge "Removed excess title validity check"
[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 revision fields that should be selected to create
438 * a new revision from an archive row.
439 * @return array
440 */
441 public static function selectArchiveFields() {
442 global $wgContentHandlerUseDB;
443 $fields = array(
444 'ar_id',
445 'ar_page_id',
446 'ar_rev_id',
447 'ar_text_id',
448 'ar_timestamp',
449 'ar_comment',
450 'ar_user_text',
451 'ar_user',
452 'ar_minor_edit',
453 'ar_deleted',
454 'ar_len',
455 'ar_parent_id',
456 'ar_sha1',
457 );
458
459 if ( $wgContentHandlerUseDB ) {
460 $fields[] = 'ar_content_format';
461 $fields[] = 'ar_content_model';
462 }
463 return $fields;
464 }
465
466 /**
467 * Return the list of text fields that should be selected to read the
468 * revision text
469 * @return array
470 */
471 public static function selectTextFields() {
472 return array(
473 'old_text',
474 'old_flags'
475 );
476 }
477
478 /**
479 * Return the list of page fields that should be selected from page table
480 * @return array
481 */
482 public static function selectPageFields() {
483 return array(
484 'page_namespace',
485 'page_title',
486 'page_id',
487 'page_latest',
488 'page_is_redirect',
489 'page_len',
490 );
491 }
492
493 /**
494 * Return the list of user fields that should be selected from user table
495 * @return array
496 */
497 public static function selectUserFields() {
498 return array( 'user_name' );
499 }
500
501 /**
502 * Do a batched query to get the parent revision lengths
503 * @param $db DatabaseBase
504 * @param $revIds Array
505 * @return array
506 */
507 public static function getParentLengths( $db, array $revIds ) {
508 $revLens = array();
509 if ( !$revIds ) {
510 return $revLens; // empty
511 }
512 wfProfileIn( __METHOD__ );
513 $res = $db->select( 'revision',
514 array( 'rev_id', 'rev_len' ),
515 array( 'rev_id' => $revIds ),
516 __METHOD__ );
517 foreach ( $res as $row ) {
518 $revLens[$row->rev_id] = $row->rev_len;
519 }
520 wfProfileOut( __METHOD__ );
521 return $revLens;
522 }
523
524 /**
525 * Constructor
526 *
527 * @param $row Mixed: either a database row or an array
528 * @throws MWException
529 * @access private
530 */
531 function __construct( $row ) {
532 if ( is_object( $row ) ) {
533 $this->mId = intval( $row->rev_id );
534 $this->mPage = intval( $row->rev_page );
535 $this->mTextId = intval( $row->rev_text_id );
536 $this->mComment = $row->rev_comment;
537 $this->mUser = intval( $row->rev_user );
538 $this->mMinorEdit = intval( $row->rev_minor_edit );
539 $this->mTimestamp = $row->rev_timestamp;
540 $this->mDeleted = intval( $row->rev_deleted );
541
542 if ( !isset( $row->rev_parent_id ) ) {
543 $this->mParentId = null;
544 } else {
545 $this->mParentId = intval( $row->rev_parent_id );
546 }
547
548 if ( !isset( $row->rev_len ) ) {
549 $this->mSize = null;
550 } else {
551 $this->mSize = intval( $row->rev_len );
552 }
553
554 if ( !isset( $row->rev_sha1 ) ) {
555 $this->mSha1 = null;
556 } else {
557 $this->mSha1 = $row->rev_sha1;
558 }
559
560 if ( isset( $row->page_latest ) ) {
561 $this->mCurrent = ( $row->rev_id == $row->page_latest );
562 $this->mTitle = Title::newFromRow( $row );
563 } else {
564 $this->mCurrent = false;
565 $this->mTitle = null;
566 }
567
568 if ( !isset( $row->rev_content_model ) || is_null( $row->rev_content_model ) ) {
569 $this->mContentModel = null; # determine on demand if needed
570 } else {
571 $this->mContentModel = strval( $row->rev_content_model );
572 }
573
574 if ( !isset( $row->rev_content_format ) || is_null( $row->rev_content_format ) ) {
575 $this->mContentFormat = null; # determine on demand if needed
576 } else {
577 $this->mContentFormat = strval( $row->rev_content_format );
578 }
579
580 // Lazy extraction...
581 $this->mText = null;
582 if ( isset( $row->old_text ) ) {
583 $this->mTextRow = $row;
584 } else {
585 // 'text' table row entry will be lazy-loaded
586 $this->mTextRow = null;
587 }
588
589 // Use user_name for users and rev_user_text for IPs...
590 $this->mUserText = null; // lazy load if left null
591 if ( $this->mUser == 0 ) {
592 $this->mUserText = $row->rev_user_text; // IP user
593 } elseif ( isset( $row->user_name ) ) {
594 $this->mUserText = $row->user_name; // logged-in user
595 }
596 $this->mOrigUserText = $row->rev_user_text;
597 } elseif ( is_array( $row ) ) {
598 // Build a new revision to be saved...
599 global $wgUser; // ugh
600
601 # if we have a content object, use it to set the model and type
602 if ( !empty( $row['content'] ) ) {
603 // @todo when is that set? test with external store setup! check out insertOn() [dk]
604 if ( !empty( $row['text_id'] ) ) {
605 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
606 "can't serialize content object" );
607 }
608
609 $row['content_model'] = $row['content']->getModel();
610 # note: mContentFormat is initializes later accordingly
611 # note: content is serialized later in this method!
612 # also set text to null?
613 }
614
615 $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null;
616 $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null;
617 $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null;
618 $this->mUserText = isset( $row['user_text'] )
619 ? strval( $row['user_text'] ) : $wgUser->getName();
620 $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId();
621 $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0;
622 $this->mTimestamp = isset( $row['timestamp'] )
623 ? strval( $row['timestamp'] ) : wfTimestampNow();
624 $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0;
625 $this->mSize = isset( $row['len'] ) ? intval( $row['len'] ) : null;
626 $this->mParentId = isset( $row['parent_id'] ) ? intval( $row['parent_id'] ) : null;
627 $this->mSha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
628
629 $this->mContentModel = isset( $row['content_model'] )
630 ? strval( $row['content_model'] ) : null;
631 $this->mContentFormat = isset( $row['content_format'] )
632 ? strval( $row['content_format'] ) : null;
633
634 // Enforce spacing trimming on supplied text
635 $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null;
636 $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
637 $this->mTextRow = null;
638
639 $this->mTitle = isset( $row['title'] ) ? $row['title'] : null;
640
641 // if we have a Content object, override mText and mContentModel
642 if ( !empty( $row['content'] ) ) {
643 if ( !( $row['content'] instanceof Content ) ) {
644 throw new MWException( '`content` field must contain a Content object.' );
645 }
646
647 $handler = $this->getContentHandler();
648 $this->mContent = $row['content'];
649
650 $this->mContentModel = $this->mContent->getModel();
651 $this->mContentHandler = null;
652
653 $this->mText = $handler->serializeContent( $row['content'], $this->getContentFormat() );
654 } elseif ( !is_null( $this->mText ) ) {
655 $handler = $this->getContentHandler();
656 $this->mContent = $handler->unserializeContent( $this->mText );
657 }
658
659 // If we have a Title object, make sure it is consistent with mPage.
660 if ( $this->mTitle && $this->mTitle->exists() ) {
661 if ( $this->mPage === null ) {
662 // if the page ID wasn't known, set it now
663 $this->mPage = $this->mTitle->getArticleID();
664 } elseif ( $this->mTitle->getArticleID() !== $this->mPage ) {
665 // Got different page IDs. This may be legit (e.g. during undeletion),
666 // but it seems worth mentioning it in the log.
667 wfDebug( "Page ID " . $this->mPage . " mismatches the ID " .
668 $this->mTitle->getArticleID() . " provided by the Title object." );
669 }
670 }
671
672 $this->mCurrent = false;
673
674 // If we still have no length, see it we have the text to figure it out
675 if ( !$this->mSize ) {
676 if ( !is_null( $this->mContent ) ) {
677 $this->mSize = $this->mContent->getSize();
678 } else {
679 #NOTE: this should never happen if we have either text or content object!
680 $this->mSize = null;
681 }
682 }
683
684 // Same for sha1
685 if ( $this->mSha1 === null ) {
686 $this->mSha1 = is_null( $this->mText ) ? null : self::base36Sha1( $this->mText );
687 }
688
689 // force lazy init
690 $this->getContentModel();
691 $this->getContentFormat();
692 } else {
693 throw new MWException( 'Revision constructor passed invalid row format.' );
694 }
695 $this->mUnpatrolled = null;
696 }
697
698 /**
699 * Get revision ID
700 *
701 * @return Integer|null
702 */
703 public function getId() {
704 return $this->mId;
705 }
706
707 /**
708 * Set the revision ID
709 *
710 * @since 1.19
711 * @param $id Integer
712 */
713 public function setId( $id ) {
714 $this->mId = $id;
715 }
716
717 /**
718 * Get text row ID
719 *
720 * @return Integer|null
721 */
722 public function getTextId() {
723 return $this->mTextId;
724 }
725
726 /**
727 * Get parent revision ID (the original previous page revision)
728 *
729 * @return Integer|null
730 */
731 public function getParentId() {
732 return $this->mParentId;
733 }
734
735 /**
736 * Returns the length of the text in this revision, or null if unknown.
737 *
738 * @return Integer|null
739 */
740 public function getSize() {
741 return $this->mSize;
742 }
743
744 /**
745 * Returns the base36 sha1 of the text in this revision, or null if unknown.
746 *
747 * @return String|null
748 */
749 public function getSha1() {
750 return $this->mSha1;
751 }
752
753 /**
754 * Returns the title of the page associated with this entry or null.
755 *
756 * Will do a query, when title is not set and id is given.
757 *
758 * @return Title|null
759 */
760 public function getTitle() {
761 if ( isset( $this->mTitle ) ) {
762 return $this->mTitle;
763 }
764 //rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
765 if ( !is_null( $this->mId ) ) {
766 $dbr = wfGetDB( DB_SLAVE );
767 $row = $dbr->selectRow(
768 array( 'page', 'revision' ),
769 self::selectPageFields(),
770 array( 'page_id=rev_page',
771 'rev_id' => $this->mId ),
772 __METHOD__ );
773 if ( $row ) {
774 $this->mTitle = Title::newFromRow( $row );
775 }
776 }
777
778 if ( !$this->mTitle && !is_null( $this->mPage ) && $this->mPage > 0 ) {
779 $this->mTitle = Title::newFromID( $this->mPage );
780 }
781
782 return $this->mTitle;
783 }
784
785 /**
786 * Set the title of the revision
787 *
788 * @param $title Title
789 */
790 public function setTitle( $title ) {
791 $this->mTitle = $title;
792 }
793
794 /**
795 * Get the page ID
796 *
797 * @return Integer|null
798 */
799 public function getPage() {
800 return $this->mPage;
801 }
802
803 /**
804 * Fetch revision's user id if it's available to the specified audience.
805 * If the specified audience does not have access to it, zero will be
806 * returned.
807 *
808 * @param $audience Integer: one of:
809 * Revision::FOR_PUBLIC to be displayed to all users
810 * Revision::FOR_THIS_USER to be displayed to the given user
811 * Revision::RAW get the ID regardless of permissions
812 * @param $user User object to check for, only if FOR_THIS_USER is passed
813 * to the $audience parameter
814 * @return Integer
815 */
816 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
817 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
818 return 0;
819 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
820 return 0;
821 } else {
822 return $this->mUser;
823 }
824 }
825
826 /**
827 * Fetch revision's user id without regard for the current user's permissions
828 *
829 * @return String
830 */
831 public function getRawUser() {
832 return $this->mUser;
833 }
834
835 /**
836 * Fetch revision's username if it's available to the specified audience.
837 * If the specified audience does not have access to the username, an
838 * empty string will be returned.
839 *
840 * @param $audience Integer: one of:
841 * Revision::FOR_PUBLIC to be displayed to all users
842 * Revision::FOR_THIS_USER to be displayed to the given user
843 * Revision::RAW get the text regardless of permissions
844 * @param $user User object to check for, only if FOR_THIS_USER is passed
845 * to the $audience parameter
846 * @return string
847 */
848 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
849 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
850 return '';
851 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
852 return '';
853 } else {
854 return $this->getRawUserText();
855 }
856 }
857
858 /**
859 * Fetch revision's username without regard for view restrictions
860 *
861 * @return String
862 */
863 public function getRawUserText() {
864 if ( $this->mUserText === null ) {
865 $this->mUserText = User::whoIs( $this->mUser ); // load on demand
866 if ( $this->mUserText === false ) {
867 # This shouldn't happen, but it can if the wiki was recovered
868 # via importing revs and there is no user table entry yet.
869 $this->mUserText = $this->mOrigUserText;
870 }
871 }
872 return $this->mUserText;
873 }
874
875 /**
876 * Fetch revision comment if it's available to the specified audience.
877 * If the specified audience does not have access to the comment, an
878 * empty string will be returned.
879 *
880 * @param $audience Integer: one of:
881 * Revision::FOR_PUBLIC to be displayed to all users
882 * Revision::FOR_THIS_USER to be displayed to the given user
883 * Revision::RAW get the text regardless of permissions
884 * @param $user User object to check for, only if FOR_THIS_USER is passed
885 * to the $audience parameter
886 * @return String
887 */
888 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
889 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
890 return '';
891 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $user ) ) {
892 return '';
893 } else {
894 return $this->mComment;
895 }
896 }
897
898 /**
899 * Fetch revision comment without regard for the current user's permissions
900 *
901 * @return String
902 */
903 public function getRawComment() {
904 return $this->mComment;
905 }
906
907 /**
908 * @return Boolean
909 */
910 public function isMinor() {
911 return (bool)$this->mMinorEdit;
912 }
913
914 /**
915 * @return integer rcid of the unpatrolled row, zero if there isn't one
916 */
917 public function isUnpatrolled() {
918 if ( $this->mUnpatrolled !== null ) {
919 return $this->mUnpatrolled;
920 }
921 $rc = $this->getRecentChange();
922 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
923 $this->mUnpatrolled = $rc->getAttribute( 'rc_id' );
924 } else {
925 $this->mUnpatrolled = 0;
926 }
927 return $this->mUnpatrolled;
928 }
929
930 /**
931 * Get the RC object belonging to the current revision, if there's one
932 *
933 * @since 1.22
934 * @return RecentChange|null
935 */
936 public function getRecentChange() {
937 $dbr = wfGetDB( DB_SLAVE );
938 return RecentChange::newFromConds(
939 array(
940 'rc_user_text' => $this->getRawUserText(),
941 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
942 'rc_this_oldid' => $this->getId()
943 ),
944 __METHOD__
945 );
946 }
947
948 /**
949 * @param int $field one of DELETED_* bitfield constants
950 *
951 * @return Boolean
952 */
953 public function isDeleted( $field ) {
954 return ( $this->mDeleted & $field ) == $field;
955 }
956
957 /**
958 * Get the deletion bitfield of the revision
959 *
960 * @return int
961 */
962 public function getVisibility() {
963 return (int)$this->mDeleted;
964 }
965
966 /**
967 * Fetch revision text if it's available to the specified audience.
968 * If the specified audience does not have the ability to view this
969 * revision, an empty string will be returned.
970 *
971 * @param $audience Integer: one of:
972 * Revision::FOR_PUBLIC to be displayed to all users
973 * Revision::FOR_THIS_USER to be displayed to the given user
974 * Revision::RAW get the text regardless of permissions
975 * @param $user User object to check for, only if FOR_THIS_USER is passed
976 * to the $audience parameter
977 *
978 * @deprecated in 1.21, use getContent() instead
979 * @todo Replace usage in core
980 * @return String
981 */
982 public function getText( $audience = self::FOR_PUBLIC, User $user = null ) {
983 ContentHandler::deprecated( __METHOD__, '1.21' );
984
985 $content = $this->getContent( $audience, $user );
986 return ContentHandler::getContentText( $content ); # returns the raw content text, if applicable
987 }
988
989 /**
990 * Fetch revision content if it's available to the specified audience.
991 * If the specified audience does not have the ability to view this
992 * revision, null will be returned.
993 *
994 * @param $audience Integer: one of:
995 * Revision::FOR_PUBLIC to be displayed to all users
996 * Revision::FOR_THIS_USER to be displayed to $wgUser
997 * Revision::RAW get the text regardless of permissions
998 * @param $user User object to check for, only if FOR_THIS_USER is passed
999 * to the $audience parameter
1000 * @since 1.21
1001 * @return Content|null
1002 */
1003 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
1004 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_TEXT ) ) {
1005 return null;
1006 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_TEXT, $user ) ) {
1007 return null;
1008 } else {
1009 return $this->getContentInternal();
1010 }
1011 }
1012
1013 /**
1014 * Alias for getText(Revision::FOR_THIS_USER)
1015 *
1016 * @deprecated since 1.17
1017 * @return String
1018 */
1019 public function revText() {
1020 wfDeprecated( __METHOD__, '1.17' );
1021 return $this->getText( self::FOR_THIS_USER );
1022 }
1023
1024 /**
1025 * Fetch revision text without regard for view restrictions
1026 *
1027 * @return String
1028 *
1029 * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW )
1030 * or Revision::getSerializedData() as appropriate.
1031 */
1032 public function getRawText() {
1033 ContentHandler::deprecated( __METHOD__, "1.21" );
1034 return $this->getText( self::RAW );
1035 }
1036
1037 /**
1038 * Fetch original serialized data without regard for view restrictions
1039 *
1040 * @since 1.21
1041 * @return String
1042 */
1043 public function getSerializedData() {
1044 if ( is_null( $this->mText ) ) {
1045 $this->mText = $this->loadText();
1046 }
1047
1048 return $this->mText;
1049 }
1050
1051 /**
1052 * Gets the content object for the revision (or null on failure).
1053 *
1054 * Note that for mutable Content objects, each call to this method will return a
1055 * fresh clone.
1056 *
1057 * @since 1.21
1058 * @return Content|null the Revision's content, or null on failure.
1059 */
1060 protected function getContentInternal() {
1061 if ( is_null( $this->mContent ) ) {
1062 // Revision is immutable. Load on demand:
1063 if ( is_null( $this->mText ) ) {
1064 $this->mText = $this->loadText();
1065 }
1066
1067 if ( $this->mText !== null && $this->mText !== false ) {
1068 // Unserialize content
1069 $handler = $this->getContentHandler();
1070 $format = $this->getContentFormat();
1071
1072 $this->mContent = $handler->unserializeContent( $this->mText, $format );
1073 } else {
1074 $this->mContent = false; // negative caching!
1075 }
1076 }
1077
1078 // NOTE: copy() will return $this for immutable content objects
1079 return $this->mContent ? $this->mContent->copy() : null;
1080 }
1081
1082 /**
1083 * Returns the content model for this revision.
1084 *
1085 * If no content model was stored in the database, $this->getTitle()->getContentModel() is
1086 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1087 * is used as a last resort.
1088 *
1089 * @return String the content model id associated with this revision,
1090 * see the CONTENT_MODEL_XXX constants.
1091 **/
1092 public function getContentModel() {
1093 if ( !$this->mContentModel ) {
1094 $title = $this->getTitle();
1095 $this->mContentModel = ( $title ? $title->getContentModel() : CONTENT_MODEL_WIKITEXT );
1096
1097 assert( !empty( $this->mContentModel ) );
1098 }
1099
1100 return $this->mContentModel;
1101 }
1102
1103 /**
1104 * Returns the content format for this revision.
1105 *
1106 * If no content format was stored in the database, the default format for this
1107 * revision's content model is returned.
1108 *
1109 * @return String the content format id associated with this revision,
1110 * see the CONTENT_FORMAT_XXX constants.
1111 **/
1112 public function getContentFormat() {
1113 if ( !$this->mContentFormat ) {
1114 $handler = $this->getContentHandler();
1115 $this->mContentFormat = $handler->getDefaultFormat();
1116
1117 assert( !empty( $this->mContentFormat ) );
1118 }
1119
1120 return $this->mContentFormat;
1121 }
1122
1123 /**
1124 * Returns the content handler appropriate for this revision's content model.
1125 *
1126 * @throws MWException
1127 * @return ContentHandler
1128 */
1129 public function getContentHandler() {
1130 if ( !$this->mContentHandler ) {
1131 $model = $this->getContentModel();
1132 $this->mContentHandler = ContentHandler::getForModelID( $model );
1133
1134 $format = $this->getContentFormat();
1135
1136 if ( !$this->mContentHandler->isSupportedFormat( $format ) ) {
1137 throw new MWException( "Oops, the content format $format is not supported for "
1138 . "this content model, $model" );
1139 }
1140 }
1141
1142 return $this->mContentHandler;
1143 }
1144
1145 /**
1146 * @return String
1147 */
1148 public function getTimestamp() {
1149 return wfTimestamp( TS_MW, $this->mTimestamp );
1150 }
1151
1152 /**
1153 * @return Boolean
1154 */
1155 public function isCurrent() {
1156 return $this->mCurrent;
1157 }
1158
1159 /**
1160 * Get previous revision for this title
1161 *
1162 * @return Revision|null
1163 */
1164 public function getPrevious() {
1165 if ( $this->getTitle() ) {
1166 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1167 if ( $prev ) {
1168 return self::newFromTitle( $this->getTitle(), $prev );
1169 }
1170 }
1171 return null;
1172 }
1173
1174 /**
1175 * Get next revision for this title
1176 *
1177 * @return Revision or null
1178 */
1179 public function getNext() {
1180 if ( $this->getTitle() ) {
1181 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1182 if ( $next ) {
1183 return self::newFromTitle( $this->getTitle(), $next );
1184 }
1185 }
1186 return null;
1187 }
1188
1189 /**
1190 * Get previous revision Id for this page_id
1191 * This is used to populate rev_parent_id on save
1192 *
1193 * @param $db DatabaseBase
1194 * @return Integer
1195 */
1196 private function getPreviousRevisionId( $db ) {
1197 if ( is_null( $this->mPage ) ) {
1198 return 0;
1199 }
1200 # Use page_latest if ID is not given
1201 if ( !$this->mId ) {
1202 $prevId = $db->selectField( 'page', 'page_latest',
1203 array( 'page_id' => $this->mPage ),
1204 __METHOD__ );
1205 } else {
1206 $prevId = $db->selectField( 'revision', 'rev_id',
1207 array( 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ),
1208 __METHOD__,
1209 array( 'ORDER BY' => 'rev_id DESC' ) );
1210 }
1211 return intval( $prevId );
1212 }
1213
1214 /**
1215 * Get revision text associated with an old or archive row
1216 * $row is usually an object from wfFetchRow(), both the flags and the text
1217 * field must be included
1218 *
1219 * @param $row Object: the text data
1220 * @param string $prefix table prefix (default 'old_')
1221 * @param string|false $wiki the name of the wiki to load the revision text from
1222 * (same as the the wiki $row was loaded from) or false to indicate the local
1223 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1224 * identifier as understood by the LoadBalancer class.
1225 * @return String: text the text requested or false on failure
1226 */
1227 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1228 wfProfileIn( __METHOD__ );
1229
1230 # Get data
1231 $textField = $prefix . 'text';
1232 $flagsField = $prefix . 'flags';
1233
1234 if ( isset( $row->$flagsField ) ) {
1235 $flags = explode( ',', $row->$flagsField );
1236 } else {
1237 $flags = array();
1238 }
1239
1240 if ( isset( $row->$textField ) ) {
1241 $text = $row->$textField;
1242 } else {
1243 wfProfileOut( __METHOD__ );
1244 return false;
1245 }
1246
1247 # Use external methods for external objects, text in table is URL-only then
1248 if ( in_array( 'external', $flags ) ) {
1249 $url = $text;
1250 $parts = explode( '://', $url, 2 );
1251 if ( count( $parts ) == 1 || $parts[1] == '' ) {
1252 wfProfileOut( __METHOD__ );
1253 return false;
1254 }
1255 $text = ExternalStore::fetchFromURL( $url, array( 'wiki' => $wiki ) );
1256 }
1257
1258 // If the text was fetched without an error, convert it
1259 if ( $text !== false ) {
1260 $text = self::decompressRevisionText( $text, $flags );
1261 }
1262 wfProfileOut( __METHOD__ );
1263 return $text;
1264 }
1265
1266 /**
1267 * If $wgCompressRevisions is enabled, we will compress data.
1268 * The input string is modified in place.
1269 * Return value is the flags field: contains 'gzip' if the
1270 * data is compressed, and 'utf-8' if we're saving in UTF-8
1271 * mode.
1272 *
1273 * @param $text Mixed: reference to a text
1274 * @return String
1275 */
1276 public static function compressRevisionText( &$text ) {
1277 global $wgCompressRevisions;
1278 $flags = array();
1279
1280 # Revisions not marked this way will be converted
1281 # on load if $wgLegacyCharset is set in the future.
1282 $flags[] = 'utf-8';
1283
1284 if ( $wgCompressRevisions ) {
1285 if ( function_exists( 'gzdeflate' ) ) {
1286 $text = gzdeflate( $text );
1287 $flags[] = 'gzip';
1288 } else {
1289 wfDebug( __METHOD__ . " -- no zlib support, not compressing\n" );
1290 }
1291 }
1292 return implode( ',', $flags );
1293 }
1294
1295 /**
1296 * Re-converts revision text according to it's flags.
1297 *
1298 * @param $text Mixed: reference to a text
1299 * @param $flags array: compression flags
1300 * @return String|bool decompressed text, or false on failure
1301 */
1302 public static function decompressRevisionText( $text, $flags ) {
1303 if ( in_array( 'gzip', $flags ) ) {
1304 # Deal with optional compression of archived pages.
1305 # This can be done periodically via maintenance/compressOld.php, and
1306 # as pages are saved if $wgCompressRevisions is set.
1307 $text = gzinflate( $text );
1308 }
1309
1310 if ( in_array( 'object', $flags ) ) {
1311 # Generic compressed storage
1312 $obj = unserialize( $text );
1313 if ( !is_object( $obj ) ) {
1314 // Invalid object
1315 return false;
1316 }
1317 $text = $obj->getText();
1318 }
1319
1320 global $wgLegacyEncoding;
1321 if ( $text !== false && $wgLegacyEncoding
1322 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1323 ) {
1324 # Old revisions kept around in a legacy encoding?
1325 # Upconvert on demand.
1326 # ("utf8" checked for compatibility with some broken
1327 # conversion scripts 2008-12-30)
1328 global $wgContLang;
1329 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1330 }
1331
1332 return $text;
1333 }
1334
1335 /**
1336 * Insert a new revision into the database, returning the new revision ID
1337 * number on success and dies horribly on failure.
1338 *
1339 * @param $dbw DatabaseBase: (master connection)
1340 * @throws MWException
1341 * @return Integer
1342 */
1343 public function insertOn( $dbw ) {
1344 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1345
1346 wfProfileIn( __METHOD__ );
1347
1348 $this->checkContentModel();
1349
1350 $data = $this->mText;
1351 $flags = self::compressRevisionText( $data );
1352
1353 # Write to external storage if required
1354 if ( $wgDefaultExternalStore ) {
1355 // Store and get the URL
1356 $data = ExternalStore::insertToDefault( $data );
1357 if ( !$data ) {
1358 wfProfileOut( __METHOD__ );
1359 throw new MWException( "Unable to store text to external storage" );
1360 }
1361 if ( $flags ) {
1362 $flags .= ',';
1363 }
1364 $flags .= 'external';
1365 }
1366
1367 # Record the text (or external storage URL) to the text table
1368 if ( !isset( $this->mTextId ) ) {
1369 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1370 $dbw->insert( 'text',
1371 array(
1372 'old_id' => $old_id,
1373 'old_text' => $data,
1374 'old_flags' => $flags,
1375 ), __METHOD__
1376 );
1377 $this->mTextId = $dbw->insertId();
1378 }
1379
1380 if ( $this->mComment === null ) {
1381 $this->mComment = "";
1382 }
1383
1384 # Record the edit in revisions
1385 $rev_id = isset( $this->mId )
1386 ? $this->mId
1387 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1388 $row = array(
1389 'rev_id' => $rev_id,
1390 'rev_page' => $this->mPage,
1391 'rev_text_id' => $this->mTextId,
1392 'rev_comment' => $this->mComment,
1393 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
1394 'rev_user' => $this->mUser,
1395 'rev_user_text' => $this->mUserText,
1396 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
1397 'rev_deleted' => $this->mDeleted,
1398 'rev_len' => $this->mSize,
1399 'rev_parent_id' => is_null( $this->mParentId )
1400 ? $this->getPreviousRevisionId( $dbw )
1401 : $this->mParentId,
1402 'rev_sha1' => is_null( $this->mSha1 )
1403 ? Revision::base36Sha1( $this->mText )
1404 : $this->mSha1,
1405 );
1406
1407 if ( $wgContentHandlerUseDB ) {
1408 //NOTE: Store null for the default model and format, to save space.
1409 //XXX: Makes the DB sensitive to changed defaults.
1410 // Make this behavior optional? Only in miser mode?
1411
1412 $model = $this->getContentModel();
1413 $format = $this->getContentFormat();
1414
1415 $title = $this->getTitle();
1416
1417 if ( $title === null ) {
1418 wfProfileOut( __METHOD__ );
1419 throw new MWException( "Insufficient information to determine the title of the "
1420 . "revision's page!" );
1421 }
1422
1423 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1424 $defaultFormat = ContentHandler::getForModelID( $defaultModel )->getDefaultFormat();
1425
1426 $row['rev_content_model'] = ( $model === $defaultModel ) ? null : $model;
1427 $row['rev_content_format'] = ( $format === $defaultFormat ) ? null : $format;
1428 }
1429
1430 $dbw->insert( 'revision', $row, __METHOD__ );
1431
1432 $this->mId = !is_null( $rev_id ) ? $rev_id : $dbw->insertId();
1433
1434 wfRunHooks( 'RevisionInsertComplete', array( &$this, $data, $flags ) );
1435
1436 wfProfileOut( __METHOD__ );
1437 return $this->mId;
1438 }
1439
1440 protected function checkContentModel() {
1441 global $wgContentHandlerUseDB;
1442
1443 $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted.
1444
1445 $model = $this->getContentModel();
1446 $format = $this->getContentFormat();
1447 $handler = $this->getContentHandler();
1448
1449 if ( !$handler->isSupportedFormat( $format ) ) {
1450 $t = $title->getPrefixedDBkey();
1451
1452 throw new MWException( "Can't use format $format with content model $model on $t" );
1453 }
1454
1455 if ( !$wgContentHandlerUseDB && $title ) {
1456 // if $wgContentHandlerUseDB is not set,
1457 // all revisions must use the default content model and format.
1458
1459 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1460 $defaultHandler = ContentHandler::getForModelID( $defaultModel );
1461 $defaultFormat = $defaultHandler->getDefaultFormat();
1462
1463 if ( $this->getContentModel() != $defaultModel ) {
1464 $t = $title->getPrefixedDBkey();
1465
1466 throw new MWException( "Can't save non-default content model with "
1467 . "\$wgContentHandlerUseDB disabled: model is $model, "
1468 . "default for $t is $defaultModel" );
1469 }
1470
1471 if ( $this->getContentFormat() != $defaultFormat ) {
1472 $t = $title->getPrefixedDBkey();
1473
1474 throw new MWException( "Can't use non-default content format with "
1475 . "\$wgContentHandlerUseDB disabled: format is $format, "
1476 . "default for $t is $defaultFormat" );
1477 }
1478 }
1479
1480 $content = $this->getContent( Revision::RAW );
1481
1482 if ( !$content || !$content->isValid() ) {
1483 $t = $title->getPrefixedDBkey();
1484
1485 throw new MWException( "Content of $t is not valid! Content model is $model" );
1486 }
1487 }
1488
1489 /**
1490 * Get the base 36 SHA-1 value for a string of text
1491 * @param $text String
1492 * @return String
1493 */
1494 public static function base36Sha1( $text ) {
1495 return wfBaseConvert( sha1( $text ), 16, 36, 31 );
1496 }
1497
1498 /**
1499 * Lazy-load the revision's text.
1500 * Currently hardcoded to the 'text' table storage engine.
1501 *
1502 * @return String|bool the revision's text, or false on failure
1503 */
1504 protected function loadText() {
1505 wfProfileIn( __METHOD__ );
1506
1507 // Caching may be beneficial for massive use of external storage
1508 global $wgRevisionCacheExpiry, $wgMemc;
1509 $textId = $this->getTextId();
1510 $key = wfMemcKey( 'revisiontext', 'textid', $textId );
1511 if ( $wgRevisionCacheExpiry ) {
1512 $text = $wgMemc->get( $key );
1513 if ( is_string( $text ) ) {
1514 wfDebug( __METHOD__ . ": got id $textId from cache\n" );
1515 wfProfileOut( __METHOD__ );
1516 return $text;
1517 }
1518 }
1519
1520 // If we kept data for lazy extraction, use it now...
1521 if ( isset( $this->mTextRow ) ) {
1522 $row = $this->mTextRow;
1523 $this->mTextRow = null;
1524 } else {
1525 $row = null;
1526 }
1527
1528 if ( !$row ) {
1529 // Text data is immutable; check slaves first.
1530 $dbr = wfGetDB( DB_SLAVE );
1531 $row = $dbr->selectRow( 'text',
1532 array( 'old_text', 'old_flags' ),
1533 array( 'old_id' => $textId ),
1534 __METHOD__ );
1535 }
1536
1537 // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was
1538 // used to fetch this revision to avoid missing the row due to REPEATABLE-READ.
1539 $forUpdate = ( $this->mQueryFlags & self::READ_LOCKING == self::READ_LOCKING );
1540 if ( !$row && ( $forUpdate || wfGetLB()->getServerCount() > 1 ) ) {
1541 $dbw = wfGetDB( DB_MASTER );
1542 $row = $dbw->selectRow( 'text',
1543 array( 'old_text', 'old_flags' ),
1544 array( 'old_id' => $textId ),
1545 __METHOD__,
1546 $forUpdate ? array( 'FOR UPDATE' ) : array() );
1547 }
1548
1549 if ( !$row ) {
1550 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1551 }
1552
1553 $text = self::getRevisionText( $row );
1554 if ( $row && $text === false ) {
1555 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1556 }
1557
1558 # No negative caching -- negative hits on text rows may be due to corrupted slave servers
1559 if ( $wgRevisionCacheExpiry && $text !== false ) {
1560 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
1561 }
1562
1563 wfProfileOut( __METHOD__ );
1564
1565 return $text;
1566 }
1567
1568 /**
1569 * Create a new null-revision for insertion into a page's
1570 * history. This will not re-save the text, but simply refer
1571 * to the text from the previous version.
1572 *
1573 * Such revisions can for instance identify page rename
1574 * operations and other such meta-modifications.
1575 *
1576 * @param $dbw DatabaseBase
1577 * @param $pageId Integer: ID number of the page to read from
1578 * @param string $summary revision's summary
1579 * @param $minor Boolean: whether the revision should be considered as minor
1580 * @return Revision|null on error
1581 */
1582 public static function newNullRevision( $dbw, $pageId, $summary, $minor ) {
1583 global $wgContentHandlerUseDB;
1584
1585 wfProfileIn( __METHOD__ );
1586
1587 $fields = array( 'page_latest', 'page_namespace', 'page_title',
1588 'rev_text_id', 'rev_len', 'rev_sha1' );
1589
1590 if ( $wgContentHandlerUseDB ) {
1591 $fields[] = 'rev_content_model';
1592 $fields[] = 'rev_content_format';
1593 }
1594
1595 $current = $dbw->selectRow(
1596 array( 'page', 'revision' ),
1597 $fields,
1598 array(
1599 'page_id' => $pageId,
1600 'page_latest=rev_id',
1601 ),
1602 __METHOD__ );
1603
1604 if ( $current ) {
1605 $row = array(
1606 'page' => $pageId,
1607 'comment' => $summary,
1608 'minor_edit' => $minor,
1609 'text_id' => $current->rev_text_id,
1610 'parent_id' => $current->page_latest,
1611 'len' => $current->rev_len,
1612 'sha1' => $current->rev_sha1
1613 );
1614
1615 if ( $wgContentHandlerUseDB ) {
1616 $row['content_model'] = $current->rev_content_model;
1617 $row['content_format'] = $current->rev_content_format;
1618 }
1619
1620 $revision = new Revision( $row );
1621 $revision->setTitle( Title::makeTitle( $current->page_namespace, $current->page_title ) );
1622 } else {
1623 $revision = null;
1624 }
1625
1626 wfProfileOut( __METHOD__ );
1627 return $revision;
1628 }
1629
1630 /**
1631 * Determine if the current user is allowed to view a particular
1632 * field of this revision, if it's marked as deleted.
1633 *
1634 * @param $field Integer:one of self::DELETED_TEXT,
1635 * self::DELETED_COMMENT,
1636 * self::DELETED_USER
1637 * @param $user User object to check, or null to use $wgUser
1638 * @return Boolean
1639 */
1640 public function userCan( $field, User $user = null ) {
1641 return self::userCanBitfield( $this->mDeleted, $field, $user );
1642 }
1643
1644 /**
1645 * Determine if the current user is allowed to view a particular
1646 * field of this revision, if it's marked as deleted. This is used
1647 * by various classes to avoid duplication.
1648 *
1649 * @param $bitfield Integer: current field
1650 * @param $field Integer: one of self::DELETED_TEXT = File::DELETED_FILE,
1651 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1652 * self::DELETED_USER = File::DELETED_USER
1653 * @param $user User object to check, or null to use $wgUser
1654 * @return Boolean
1655 */
1656 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
1657 if ( $bitfield & $field ) { // aspect is deleted
1658 if ( $bitfield & self::DELETED_RESTRICTED ) {
1659 $permission = 'suppressrevision';
1660 } elseif ( $field & self::DELETED_TEXT ) {
1661 $permission = 'deletedtext';
1662 } else {
1663 $permission = 'deletedhistory';
1664 }
1665 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
1666 if ( $user === null ) {
1667 global $wgUser;
1668 $user = $wgUser;
1669 }
1670 return $user->isAllowed( $permission );
1671 } else {
1672 return true;
1673 }
1674 }
1675
1676 /**
1677 * Get rev_timestamp from rev_id, without loading the rest of the row
1678 *
1679 * @param $title Title
1680 * @param $id Integer
1681 * @return String
1682 */
1683 static function getTimestampFromId( $title, $id ) {
1684 $dbr = wfGetDB( DB_SLAVE );
1685 // Casting fix for databases that can't take '' for rev_id
1686 if ( $id == '' ) {
1687 $id = 0;
1688 }
1689 $conds = array( 'rev_id' => $id );
1690 $conds['rev_page'] = $title->getArticleID();
1691 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1692 if ( $timestamp === false && wfGetLB()->getServerCount() > 1 ) {
1693 # Not in slave, try master
1694 $dbw = wfGetDB( DB_MASTER );
1695 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1696 }
1697 return wfTimestamp( TS_MW, $timestamp );
1698 }
1699
1700 /**
1701 * Get count of revisions per page...not very efficient
1702 *
1703 * @param $db DatabaseBase
1704 * @param $id Integer: page id
1705 * @return Integer
1706 */
1707 static function countByPageId( $db, $id ) {
1708 $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ),
1709 array( 'rev_page' => $id ), __METHOD__ );
1710 if ( $row ) {
1711 return $row->revCount;
1712 }
1713 return 0;
1714 }
1715
1716 /**
1717 * Get count of revisions per page...not very efficient
1718 *
1719 * @param $db DatabaseBase
1720 * @param $title Title
1721 * @return Integer
1722 */
1723 static function countByTitle( $db, $title ) {
1724 $id = $title->getArticleID();
1725 if ( $id ) {
1726 return self::countByPageId( $db, $id );
1727 }
1728 return 0;
1729 }
1730
1731 /**
1732 * Check if no edits were made by other users since
1733 * the time a user started editing the page. Limit to
1734 * 50 revisions for the sake of performance.
1735 *
1736 * @since 1.20
1737 *
1738 * @param DatabaseBase|int $db the Database to perform the check on. May be given as a
1739 * Database object or a database identifier usable with wfGetDB.
1740 * @param int $pageId the ID of the page in question
1741 * @param int $userId the ID of the user in question
1742 * @param string $since look at edits since this time
1743 *
1744 * @return bool True if the given user was the only one to edit since the given timestamp
1745 */
1746 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1747 if ( !$userId ) {
1748 return false;
1749 }
1750
1751 if ( is_int( $db ) ) {
1752 $db = wfGetDB( $db );
1753 }
1754
1755 $res = $db->select( 'revision',
1756 'rev_user',
1757 array(
1758 'rev_page' => $pageId,
1759 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1760 ),
1761 __METHOD__,
1762 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1763 foreach ( $res as $row ) {
1764 if ( $row->rev_user != $userId ) {
1765 return false;
1766 }
1767 }
1768 return true;
1769 }
1770 }