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