Merge "Revert "[search] Remove more dead code""
[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 *
1244 * Both the flags and the text field must be included. Including the old_id
1245 * field will activate cache usage as long as the $wiki parameter is not set.
1246 *
1247 * @param stdClass $row The text data
1248 * @param string $prefix Table prefix (default 'old_')
1249 * @param string|bool $wiki The name of the wiki to load the revision text from
1250 * (same as the the wiki $row was loaded from) or false to indicate the local
1251 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1252 * identifier as understood by the LoadBalancer class.
1253 * @return string|false Text the text requested or false on failure
1254 */
1255 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1256 $textField = $prefix . 'text';
1257 $flagsField = $prefix . 'flags';
1258
1259 if ( isset( $row->$flagsField ) ) {
1260 $flags = explode( ',', $row->$flagsField );
1261 } else {
1262 $flags = [];
1263 }
1264
1265 if ( isset( $row->$textField ) ) {
1266 $text = $row->$textField;
1267 } else {
1268 return false;
1269 }
1270
1271 // Use external methods for external objects, text in table is URL-only then
1272 if ( in_array( 'external', $flags ) ) {
1273 $url = $text;
1274 $parts = explode( '://', $url, 2 );
1275 if ( count( $parts ) == 1 || $parts[1] == '' ) {
1276 return false;
1277 }
1278
1279 if ( isset( $row->old_id ) && $wiki === false ) {
1280 // Make use of the wiki-local revision text cache
1281 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1282 $text = $cache->getWithSetCallback(
1283 $cache->makeKey( 'revisiontext', 'textid', $row->old_id ),
1284 self::getCacheTTL( $cache ),
1285 function () use ( $url, $wiki ) {
1286 // No negative caching per Revision::loadText()
1287 return ExternalStore::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1288 },
1289 [ 'pcGroup' => self::TEXT_CACHE_GROUP, 'pcTTL' => $cache::TTL_PROC_LONG ]
1290 );
1291 } else {
1292 $text = ExternalStore::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1293 }
1294 }
1295
1296 // If the text was fetched without an error, convert it
1297 if ( $text !== false ) {
1298 $text = self::decompressRevisionText( $text, $flags );
1299 }
1300
1301 return $text;
1302 }
1303
1304 /**
1305 * If $wgCompressRevisions is enabled, we will compress data.
1306 * The input string is modified in place.
1307 * Return value is the flags field: contains 'gzip' if the
1308 * data is compressed, and 'utf-8' if we're saving in UTF-8
1309 * mode.
1310 *
1311 * @param mixed $text Reference to a text
1312 * @return string
1313 */
1314 public static function compressRevisionText( &$text ) {
1315 global $wgCompressRevisions;
1316 $flags = [];
1317
1318 # Revisions not marked this way will be converted
1319 # on load if $wgLegacyCharset is set in the future.
1320 $flags[] = 'utf-8';
1321
1322 if ( $wgCompressRevisions ) {
1323 if ( function_exists( 'gzdeflate' ) ) {
1324 $deflated = gzdeflate( $text );
1325
1326 if ( $deflated === false ) {
1327 wfLogWarning( __METHOD__ . ': gzdeflate() failed' );
1328 } else {
1329 $text = $deflated;
1330 $flags[] = 'gzip';
1331 }
1332 } else {
1333 wfDebug( __METHOD__ . " -- no zlib support, not compressing\n" );
1334 }
1335 }
1336 return implode( ',', $flags );
1337 }
1338
1339 /**
1340 * Re-converts revision text according to it's flags.
1341 *
1342 * @param mixed $text Reference to a text
1343 * @param array $flags Compression flags
1344 * @return string|bool Decompressed text, or false on failure
1345 */
1346 public static function decompressRevisionText( $text, $flags ) {
1347 if ( in_array( 'gzip', $flags ) ) {
1348 # Deal with optional compression of archived pages.
1349 # This can be done periodically via maintenance/compressOld.php, and
1350 # as pages are saved if $wgCompressRevisions is set.
1351 $text = gzinflate( $text );
1352
1353 if ( $text === false ) {
1354 wfLogWarning( __METHOD__ . ': gzinflate() failed' );
1355 return false;
1356 }
1357 }
1358
1359 if ( in_array( 'object', $flags ) ) {
1360 # Generic compressed storage
1361 $obj = unserialize( $text );
1362 if ( !is_object( $obj ) ) {
1363 // Invalid object
1364 return false;
1365 }
1366 $text = $obj->getText();
1367 }
1368
1369 global $wgLegacyEncoding;
1370 if ( $text !== false && $wgLegacyEncoding
1371 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1372 ) {
1373 # Old revisions kept around in a legacy encoding?
1374 # Upconvert on demand.
1375 # ("utf8" checked for compatibility with some broken
1376 # conversion scripts 2008-12-30)
1377 global $wgContLang;
1378 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1379 }
1380
1381 return $text;
1382 }
1383
1384 /**
1385 * Insert a new revision into the database, returning the new revision ID
1386 * number on success and dies horribly on failure.
1387 *
1388 * @param IDatabase $dbw (master connection)
1389 * @throws MWException
1390 * @return int
1391 */
1392 public function insertOn( $dbw ) {
1393 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1394
1395 // We're inserting a new revision, so we have to use master anyway.
1396 // If it's a null revision, it may have references to rows that
1397 // are not in the replica yet (the text row).
1398 $this->mQueryFlags |= self::READ_LATEST;
1399
1400 // Not allowed to have rev_page equal to 0, false, etc.
1401 if ( !$this->mPage ) {
1402 $title = $this->getTitle();
1403 if ( $title instanceof Title ) {
1404 $titleText = ' for page ' . $title->getPrefixedText();
1405 } else {
1406 $titleText = '';
1407 }
1408 throw new MWException( "Cannot insert revision$titleText: page ID must be nonzero" );
1409 }
1410
1411 $this->checkContentModel();
1412
1413 $data = $this->mText;
1414 $flags = self::compressRevisionText( $data );
1415
1416 # Write to external storage if required
1417 if ( $wgDefaultExternalStore ) {
1418 // Store and get the URL
1419 $data = ExternalStore::insertToDefault( $data );
1420 if ( !$data ) {
1421 throw new MWException( "Unable to store text to external storage" );
1422 }
1423 if ( $flags ) {
1424 $flags .= ',';
1425 }
1426 $flags .= 'external';
1427 }
1428
1429 # Record the text (or external storage URL) to the text table
1430 if ( $this->mTextId === null ) {
1431 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1432 $dbw->insert( 'text',
1433 [
1434 'old_id' => $old_id,
1435 'old_text' => $data,
1436 'old_flags' => $flags,
1437 ], __METHOD__
1438 );
1439 $this->mTextId = $dbw->insertId();
1440 }
1441
1442 if ( $this->mComment === null ) {
1443 $this->mComment = "";
1444 }
1445
1446 # Record the edit in revisions
1447 $rev_id = $this->mId !== null
1448 ? $this->mId
1449 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1450 $row = [
1451 'rev_id' => $rev_id,
1452 'rev_page' => $this->mPage,
1453 'rev_text_id' => $this->mTextId,
1454 'rev_comment' => $this->mComment,
1455 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
1456 'rev_user' => $this->mUser,
1457 'rev_user_text' => $this->mUserText,
1458 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
1459 'rev_deleted' => $this->mDeleted,
1460 'rev_len' => $this->mSize,
1461 'rev_parent_id' => $this->mParentId === null
1462 ? $this->getPreviousRevisionId( $dbw )
1463 : $this->mParentId,
1464 'rev_sha1' => $this->mSha1 === null
1465 ? Revision::base36Sha1( $this->mText )
1466 : $this->mSha1,
1467 ];
1468
1469 if ( $wgContentHandlerUseDB ) {
1470 // NOTE: Store null for the default model and format, to save space.
1471 // XXX: Makes the DB sensitive to changed defaults.
1472 // Make this behavior optional? Only in miser mode?
1473
1474 $model = $this->getContentModel();
1475 $format = $this->getContentFormat();
1476
1477 $title = $this->getTitle();
1478
1479 if ( $title === null ) {
1480 throw new MWException( "Insufficient information to determine the title of the "
1481 . "revision's page!" );
1482 }
1483
1484 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1485 $defaultFormat = ContentHandler::getForModelID( $defaultModel )->getDefaultFormat();
1486
1487 $row['rev_content_model'] = ( $model === $defaultModel ) ? null : $model;
1488 $row['rev_content_format'] = ( $format === $defaultFormat ) ? null : $format;
1489 }
1490
1491 $dbw->insert( 'revision', $row, __METHOD__ );
1492
1493 $this->mId = $rev_id !== null ? $rev_id : $dbw->insertId();
1494
1495 // Assertion to try to catch T92046
1496 if ( (int)$this->mId === 0 ) {
1497 throw new UnexpectedValueException(
1498 'After insert, Revision mId is ' . var_export( $this->mId, 1 ) . ': ' .
1499 var_export( $row, 1 )
1500 );
1501 }
1502
1503 // Avoid PHP 7.1 warning of passing $this by reference
1504 $revision = $this;
1505 Hooks::run( 'RevisionInsertComplete', [ &$revision, $data, $flags ] );
1506
1507 return $this->mId;
1508 }
1509
1510 protected function checkContentModel() {
1511 global $wgContentHandlerUseDB;
1512
1513 // Note: may return null for revisions that have not yet been inserted
1514 $title = $this->getTitle();
1515
1516 $model = $this->getContentModel();
1517 $format = $this->getContentFormat();
1518 $handler = $this->getContentHandler();
1519
1520 if ( !$handler->isSupportedFormat( $format ) ) {
1521 $t = $title->getPrefixedDBkey();
1522
1523 throw new MWException( "Can't use format $format with content model $model on $t" );
1524 }
1525
1526 if ( !$wgContentHandlerUseDB && $title ) {
1527 // if $wgContentHandlerUseDB is not set,
1528 // all revisions must use the default content model and format.
1529
1530 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1531 $defaultHandler = ContentHandler::getForModelID( $defaultModel );
1532 $defaultFormat = $defaultHandler->getDefaultFormat();
1533
1534 if ( $this->getContentModel() != $defaultModel ) {
1535 $t = $title->getPrefixedDBkey();
1536
1537 throw new MWException( "Can't save non-default content model with "
1538 . "\$wgContentHandlerUseDB disabled: model is $model, "
1539 . "default for $t is $defaultModel" );
1540 }
1541
1542 if ( $this->getContentFormat() != $defaultFormat ) {
1543 $t = $title->getPrefixedDBkey();
1544
1545 throw new MWException( "Can't use non-default content format with "
1546 . "\$wgContentHandlerUseDB disabled: format is $format, "
1547 . "default for $t is $defaultFormat" );
1548 }
1549 }
1550
1551 $content = $this->getContent( Revision::RAW );
1552 $prefixedDBkey = $title->getPrefixedDBkey();
1553 $revId = $this->mId;
1554
1555 if ( !$content ) {
1556 throw new MWException(
1557 "Content of revision $revId ($prefixedDBkey) could not be loaded for validation!"
1558 );
1559 }
1560 if ( !$content->isValid() ) {
1561 throw new MWException(
1562 "Content of revision $revId ($prefixedDBkey) is not valid! Content model is $model"
1563 );
1564 }
1565 }
1566
1567 /**
1568 * Get the base 36 SHA-1 value for a string of text
1569 * @param string $text
1570 * @return string
1571 */
1572 public static function base36Sha1( $text ) {
1573 return Wikimedia\base_convert( sha1( $text ), 16, 36, 31 );
1574 }
1575
1576 /**
1577 * Get the text cache TTL
1578 *
1579 * @param WANObjectCache $cache
1580 * @return integer
1581 */
1582 private static function getCacheTTL( WANObjectCache $cache ) {
1583 global $wgRevisionCacheExpiry;
1584
1585 if ( $cache->getQoS( $cache::ATTR_EMULATION ) <= $cache::QOS_EMULATION_SQL ) {
1586 // Do not cache RDBMs blobs in...the RDBMs store
1587 $ttl = $cache::TTL_UNCACHEABLE;
1588 } else {
1589 $ttl = $wgRevisionCacheExpiry ?: $cache::TTL_UNCACHEABLE;
1590 }
1591
1592 return $ttl;
1593 }
1594
1595 /**
1596 * Lazy-load the revision's text.
1597 * Currently hardcoded to the 'text' table storage engine.
1598 *
1599 * @return string|bool The revision's text, or false on failure
1600 */
1601 private function loadText() {
1602 $cache = ObjectCache::getMainWANInstance();
1603
1604 // No negative caching; negative hits on text rows may be due to corrupted replica DBs
1605 return $cache->getWithSetCallback(
1606 $cache->makeKey( 'revisiontext', 'textid', $this->getTextId() ),
1607 self::getCacheTTL( $cache ),
1608 function () {
1609 return $this->fetchText();
1610 },
1611 [ 'pcGroup' => self::TEXT_CACHE_GROUP, 'pcTTL' => $cache::TTL_PROC_LONG ]
1612 );
1613 }
1614
1615 private function fetchText() {
1616 $textId = $this->getTextId();
1617
1618 // If we kept data for lazy extraction, use it now...
1619 if ( $this->mTextRow !== null ) {
1620 $row = $this->mTextRow;
1621 $this->mTextRow = null;
1622 } else {
1623 $row = null;
1624 }
1625
1626 // Callers doing updates will pass in READ_LATEST as usual. Since the text/blob tables
1627 // do not normally get rows changed around, set READ_LATEST_IMMUTABLE in those cases.
1628 $flags = $this->mQueryFlags;
1629 $flags |= DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST )
1630 ? self::READ_LATEST_IMMUTABLE
1631 : 0;
1632
1633 list( $index, $options, $fallbackIndex, $fallbackOptions ) =
1634 DBAccessObjectUtils::getDBOptions( $flags );
1635
1636 if ( !$row ) {
1637 // Text data is immutable; check replica DBs first.
1638 $row = wfGetDB( $index )->selectRow(
1639 'text',
1640 [ 'old_text', 'old_flags' ],
1641 [ 'old_id' => $textId ],
1642 __METHOD__,
1643 $options
1644 );
1645 }
1646
1647 // Fallback to DB_MASTER in some cases if the row was not found
1648 if ( !$row && $fallbackIndex !== null ) {
1649 // Use FOR UPDATE if it was used to fetch this revision. This avoids missing the row
1650 // due to REPEATABLE-READ. Also fallback to the master if READ_LATEST is provided.
1651 $row = wfGetDB( $fallbackIndex )->selectRow(
1652 'text',
1653 [ 'old_text', 'old_flags' ],
1654 [ 'old_id' => $textId ],
1655 __METHOD__,
1656 $fallbackOptions
1657 );
1658 }
1659
1660 if ( !$row ) {
1661 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1662 }
1663
1664 $text = self::getRevisionText( $row );
1665 if ( $row && $text === false ) {
1666 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1667 }
1668
1669 return is_string( $text ) ? $text : false;
1670 }
1671
1672 /**
1673 * Create a new null-revision for insertion into a page's
1674 * history. This will not re-save the text, but simply refer
1675 * to the text from the previous version.
1676 *
1677 * Such revisions can for instance identify page rename
1678 * operations and other such meta-modifications.
1679 *
1680 * @param IDatabase $dbw
1681 * @param int $pageId ID number of the page to read from
1682 * @param string $summary Revision's summary
1683 * @param bool $minor Whether the revision should be considered as minor
1684 * @param User|null $user User object to use or null for $wgUser
1685 * @return Revision|null Revision or null on error
1686 */
1687 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1688 global $wgContentHandlerUseDB, $wgContLang;
1689
1690 $fields = [ 'page_latest', 'page_namespace', 'page_title',
1691 'rev_text_id', 'rev_len', 'rev_sha1' ];
1692
1693 if ( $wgContentHandlerUseDB ) {
1694 $fields[] = 'rev_content_model';
1695 $fields[] = 'rev_content_format';
1696 }
1697
1698 $current = $dbw->selectRow(
1699 [ 'page', 'revision' ],
1700 $fields,
1701 [
1702 'page_id' => $pageId,
1703 'page_latest=rev_id',
1704 ],
1705 __METHOD__,
1706 [ 'FOR UPDATE' ] // T51581
1707 );
1708
1709 if ( $current ) {
1710 if ( !$user ) {
1711 global $wgUser;
1712 $user = $wgUser;
1713 }
1714
1715 // Truncate for whole multibyte characters
1716 $summary = $wgContLang->truncate( $summary, 255 );
1717
1718 $row = [
1719 'page' => $pageId,
1720 'user_text' => $user->getName(),
1721 'user' => $user->getId(),
1722 'comment' => $summary,
1723 'minor_edit' => $minor,
1724 'text_id' => $current->rev_text_id,
1725 'parent_id' => $current->page_latest,
1726 'len' => $current->rev_len,
1727 'sha1' => $current->rev_sha1
1728 ];
1729
1730 if ( $wgContentHandlerUseDB ) {
1731 $row['content_model'] = $current->rev_content_model;
1732 $row['content_format'] = $current->rev_content_format;
1733 }
1734
1735 $row['title'] = Title::makeTitle( $current->page_namespace, $current->page_title );
1736
1737 $revision = new Revision( $row );
1738 } else {
1739 $revision = null;
1740 }
1741
1742 return $revision;
1743 }
1744
1745 /**
1746 * Determine if the current user is allowed to view a particular
1747 * field of this revision, if it's marked as deleted.
1748 *
1749 * @param int $field One of self::DELETED_TEXT,
1750 * self::DELETED_COMMENT,
1751 * self::DELETED_USER
1752 * @param User|null $user User object to check, or null to use $wgUser
1753 * @return bool
1754 */
1755 public function userCan( $field, User $user = null ) {
1756 return self::userCanBitfield( $this->getVisibility(), $field, $user );
1757 }
1758
1759 /**
1760 * Determine if the current user is allowed to view a particular
1761 * field of this revision, if it's marked as deleted. This is used
1762 * by various classes to avoid duplication.
1763 *
1764 * @param int $bitfield Current field
1765 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1766 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1767 * self::DELETED_USER = File::DELETED_USER
1768 * @param User|null $user User object to check, or null to use $wgUser
1769 * @param Title|null $title A Title object to check for per-page restrictions on,
1770 * instead of just plain userrights
1771 * @return bool
1772 */
1773 public static function userCanBitfield( $bitfield, $field, User $user = null,
1774 Title $title = null
1775 ) {
1776 if ( $bitfield & $field ) { // aspect is deleted
1777 if ( $user === null ) {
1778 global $wgUser;
1779 $user = $wgUser;
1780 }
1781 if ( $bitfield & self::DELETED_RESTRICTED ) {
1782 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
1783 } elseif ( $field & self::DELETED_TEXT ) {
1784 $permissions = [ 'deletedtext' ];
1785 } else {
1786 $permissions = [ 'deletedhistory' ];
1787 }
1788 $permissionlist = implode( ', ', $permissions );
1789 if ( $title === null ) {
1790 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1791 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
1792 } else {
1793 $text = $title->getPrefixedText();
1794 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1795 foreach ( $permissions as $perm ) {
1796 if ( $title->userCan( $perm, $user ) ) {
1797 return true;
1798 }
1799 }
1800 return false;
1801 }
1802 } else {
1803 return true;
1804 }
1805 }
1806
1807 /**
1808 * Get rev_timestamp from rev_id, without loading the rest of the row
1809 *
1810 * @param Title $title
1811 * @param int $id
1812 * @param int $flags
1813 * @return string|bool False if not found
1814 */
1815 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1816 $db = ( $flags & self::READ_LATEST )
1817 ? wfGetDB( DB_MASTER )
1818 : wfGetDB( DB_REPLICA );
1819 // Casting fix for databases that can't take '' for rev_id
1820 if ( $id == '' ) {
1821 $id = 0;
1822 }
1823 $conds = [ 'rev_id' => $id ];
1824 $conds['rev_page'] = $title->getArticleID();
1825 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1826
1827 return ( $timestamp !== false ) ? wfTimestamp( TS_MW, $timestamp ) : false;
1828 }
1829
1830 /**
1831 * Get count of revisions per page...not very efficient
1832 *
1833 * @param IDatabase $db
1834 * @param int $id Page id
1835 * @return int
1836 */
1837 static function countByPageId( $db, $id ) {
1838 $row = $db->selectRow( 'revision', [ 'revCount' => 'COUNT(*)' ],
1839 [ 'rev_page' => $id ], __METHOD__ );
1840 if ( $row ) {
1841 return $row->revCount;
1842 }
1843 return 0;
1844 }
1845
1846 /**
1847 * Get count of revisions per page...not very efficient
1848 *
1849 * @param IDatabase $db
1850 * @param Title $title
1851 * @return int
1852 */
1853 static function countByTitle( $db, $title ) {
1854 $id = $title->getArticleID();
1855 if ( $id ) {
1856 return self::countByPageId( $db, $id );
1857 }
1858 return 0;
1859 }
1860
1861 /**
1862 * Check if no edits were made by other users since
1863 * the time a user started editing the page. Limit to
1864 * 50 revisions for the sake of performance.
1865 *
1866 * @since 1.20
1867 * @deprecated since 1.24
1868 *
1869 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1870 * Database object or a database identifier usable with wfGetDB.
1871 * @param int $pageId The ID of the page in question
1872 * @param int $userId The ID of the user in question
1873 * @param string $since Look at edits since this time
1874 *
1875 * @return bool True if the given user was the only one to edit since the given timestamp
1876 */
1877 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1878 if ( !$userId ) {
1879 return false;
1880 }
1881
1882 if ( is_int( $db ) ) {
1883 $db = wfGetDB( $db );
1884 }
1885
1886 $res = $db->select( 'revision',
1887 'rev_user',
1888 [
1889 'rev_page' => $pageId,
1890 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1891 ],
1892 __METHOD__,
1893 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ] );
1894 foreach ( $res as $row ) {
1895 if ( $row->rev_user != $userId ) {
1896 return false;
1897 }
1898 }
1899 return true;
1900 }
1901
1902 /**
1903 * Load a revision based on a known page ID and current revision ID from the DB
1904 *
1905 * This method allows for the use of caching, though accessing anything that normally
1906 * requires permission checks (aside from the text) will trigger a small DB lookup.
1907 * The title will also be lazy loaded, though setTitle() can be used to preload it.
1908 *
1909 * @param IDatabase $db
1910 * @param int $pageId Page ID
1911 * @param int $revId Known current revision of this page
1912 * @return Revision|bool Returns false if missing
1913 * @since 1.28
1914 */
1915 public static function newKnownCurrent( IDatabase $db, $pageId, $revId ) {
1916 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1917 return $cache->getWithSetCallback(
1918 // Page/rev IDs passed in from DB to reflect history merges
1919 $cache->makeGlobalKey( 'revision', $db->getWikiID(), $pageId, $revId ),
1920 $cache::TTL_WEEK,
1921 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1922 $setOpts += Database::getCacheSetOptions( $db );
1923
1924 $rev = Revision::loadFromPageId( $db, $pageId, $revId );
1925 // Reflect revision deletion and user renames
1926 if ( $rev ) {
1927 $rev->mTitle = null; // mutable; lazy-load
1928 $rev->mRefreshMutableFields = true;
1929 }
1930
1931 return $rev ?: false; // don't cache negatives
1932 }
1933 );
1934 }
1935
1936 /**
1937 * For cached revisions, make sure the user name and rev_deleted is up-to-date
1938 */
1939 private function loadMutableFields() {
1940 if ( !$this->mRefreshMutableFields ) {
1941 return; // not needed
1942 }
1943
1944 $this->mRefreshMutableFields = false;
1945 $dbr = wfGetLB( $this->mWiki )->getConnectionRef( DB_REPLICA, [], $this->mWiki );
1946 $row = $dbr->selectRow(
1947 [ 'revision', 'user' ],
1948 [ 'rev_deleted', 'user_name' ],
1949 [ 'rev_id' => $this->mId, 'user_id = rev_user' ],
1950 __METHOD__
1951 );
1952 if ( $row ) { // update values
1953 $this->mDeleted = (int)$row->rev_deleted;
1954 $this->mUserText = $row->user_name;
1955 }
1956 }
1957 }