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