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