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