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