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