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