Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / includes / Revision.php
blobd9e42ffd8b0efa2b3650ad68b316f148bf322eec
1 <?php
2 /**
3 * Representation of a page version.
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.
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.
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
20 * @file
22 use MediaWiki\Linker\LinkTarget;
23 use MediaWiki\MediaWikiServices;
25 /**
26 * @todo document
28 class Revision implements IDBAccessObject {
29 /** @var int|null */
30 protected $mId;
31 /** @var int|null */
32 protected $mPage;
33 /** @var string */
34 protected $mUserText;
35 /** @var string */
36 protected $mOrigUserText;
37 /** @var int */
38 protected $mUser;
39 /** @var bool */
40 protected $mMinorEdit;
41 /** @var string */
42 protected $mTimestamp;
43 /** @var int */
44 protected $mDeleted;
45 /** @var int */
46 protected $mSize;
47 /** @var string */
48 protected $mSha1;
49 /** @var int */
50 protected $mParentId;
51 /** @var string */
52 protected $mComment;
53 /** @var string */
54 protected $mText;
55 /** @var int */
56 protected $mTextId;
57 /** @var int */
58 protected $mUnpatrolled;
60 /** @var stdClass|null */
61 protected $mTextRow;
63 /** @var null|Title */
64 protected $mTitle;
65 /** @var bool */
66 protected $mCurrent;
67 /** @var string */
68 protected $mContentModel;
69 /** @var string */
70 protected $mContentFormat;
72 /** @var Content|null|bool */
73 protected $mContent;
74 /** @var null|ContentHandler */
75 protected $mContentHandler;
77 /** @var int */
78 protected $mQueryFlags = 0;
79 /** @var bool Used for cached values to reload user text and rev_deleted */
80 protected $mRefreshMutableFields = false;
81 /** @var string Wiki ID; false means the current wiki */
82 protected $mWiki = false;
84 // Revision deletion constants
85 const DELETED_TEXT = 1;
86 const DELETED_COMMENT = 2;
87 const DELETED_USER = 4;
88 const DELETED_RESTRICTED = 8;
89 const SUPPRESSED_USER = 12; // convenience
90 const SUPPRESSED_ALL = 15; // convenience
92 // Audience options for accessors
93 const FOR_PUBLIC = 1;
94 const FOR_THIS_USER = 2;
95 const RAW = 3;
97 const TEXT_CACHE_GROUP = 'revisiontext:10'; // process cache name and max key count
99 /**
100 * Load a page revision from a given revision ID number.
101 * Returns null if no such revision can be found.
103 * $flags include:
104 * Revision::READ_LATEST : Select the data from the master
105 * Revision::READ_LOCKING : Select & lock the data from the master
107 * @param int $id
108 * @param int $flags (optional)
109 * @return Revision|null
111 public static function newFromId( $id, $flags = 0 ) {
112 return self::newFromConds( [ 'rev_id' => intval( $id ) ], $flags );
116 * Load either the current, or a specified, revision
117 * that's attached to a given link target. If not attached
118 * to that link target, will return null.
120 * $flags include:
121 * Revision::READ_LATEST : Select the data from the master
122 * Revision::READ_LOCKING : Select & lock the data from the master
124 * @param LinkTarget $linkTarget
125 * @param int $id (optional)
126 * @param int $flags Bitfield (optional)
127 * @return Revision|null
129 public static function newFromTitle( LinkTarget $linkTarget, $id = 0, $flags = 0 ) {
130 $conds = [
131 'page_namespace' => $linkTarget->getNamespace(),
132 'page_title' => $linkTarget->getDBkey()
134 if ( $id ) {
135 // Use the specified ID
136 $conds['rev_id'] = $id;
137 return self::newFromConds( $conds, $flags );
138 } else {
139 // Use a join to get the latest revision
140 $conds[] = 'rev_id=page_latest';
141 $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
142 return self::loadFromConds( $db, $conds, $flags );
147 * Load either the current, or a specified, revision
148 * that's attached to a given page ID.
149 * Returns null if no such revision can be found.
151 * $flags include:
152 * Revision::READ_LATEST : Select the data from the master (since 1.20)
153 * Revision::READ_LOCKING : Select & lock the data from the master
155 * @param int $pageId
156 * @param int $revId (optional)
157 * @param int $flags Bitfield (optional)
158 * @return Revision|null
160 public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) {
161 $conds = [ 'page_id' => $pageId ];
162 if ( $revId ) {
163 $conds['rev_id'] = $revId;
164 return self::newFromConds( $conds, $flags );
165 } else {
166 // Use a join to get the latest revision
167 $conds[] = 'rev_id = page_latest';
168 $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
169 return self::loadFromConds( $db, $conds, $flags );
174 * Make a fake revision object from an archive table row. This is queried
175 * for permissions or even inserted (as in Special:Undelete)
176 * @todo FIXME: Should be a subclass for RevisionDelete. [TS]
178 * @param object $row
179 * @param array $overrides
181 * @throws MWException
182 * @return Revision
184 public static function newFromArchiveRow( $row, $overrides = [] ) {
185 global $wgContentHandlerUseDB;
187 $attribs = $overrides + [
188 'page' => isset( $row->ar_page_id ) ? $row->ar_page_id : null,
189 'id' => isset( $row->ar_rev_id ) ? $row->ar_rev_id : null,
190 'comment' => $row->ar_comment,
191 'user' => $row->ar_user,
192 'user_text' => $row->ar_user_text,
193 'timestamp' => $row->ar_timestamp,
194 'minor_edit' => $row->ar_minor_edit,
195 'text_id' => isset( $row->ar_text_id ) ? $row->ar_text_id : null,
196 'deleted' => $row->ar_deleted,
197 'len' => $row->ar_len,
198 'sha1' => isset( $row->ar_sha1 ) ? $row->ar_sha1 : null,
199 'content_model' => isset( $row->ar_content_model ) ? $row->ar_content_model : null,
200 'content_format' => isset( $row->ar_content_format ) ? $row->ar_content_format : null,
203 if ( !$wgContentHandlerUseDB ) {
204 unset( $attribs['content_model'] );
205 unset( $attribs['content_format'] );
208 if ( !isset( $attribs['title'] )
209 && isset( $row->ar_namespace )
210 && isset( $row->ar_title )
212 $attribs['title'] = Title::makeTitle( $row->ar_namespace, $row->ar_title );
215 if ( isset( $row->ar_text ) && !$row->ar_text_id ) {
216 // Pre-1.5 ar_text row
217 $attribs['text'] = self::getRevisionText( $row, 'ar_' );
218 if ( $attribs['text'] === false ) {
219 throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' );
222 return new self( $attribs );
226 * @since 1.19
228 * @param object $row
229 * @return Revision
231 public static function newFromRow( $row ) {
232 return new self( $row );
236 * Load a page revision from a given revision ID number.
237 * Returns null if no such revision can be found.
239 * @param IDatabase $db
240 * @param int $id
241 * @return Revision|null
243 public static function loadFromId( $db, $id ) {
244 return self::loadFromConds( $db, [ 'rev_id' => intval( $id ) ] );
248 * Load either the current, or a specified, revision
249 * that's attached to a given page. If not attached
250 * to that page, will return null.
252 * @param IDatabase $db
253 * @param int $pageid
254 * @param int $id
255 * @return Revision|null
257 public static function loadFromPageId( $db, $pageid, $id = 0 ) {
258 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
259 if ( $id ) {
260 $conds['rev_id'] = intval( $id );
261 } else {
262 $conds[] = 'rev_id=page_latest';
264 return self::loadFromConds( $db, $conds );
268 * Load either the current, or a specified, revision
269 * that's attached to a given page. If not attached
270 * to that page, will return null.
272 * @param IDatabase $db
273 * @param Title $title
274 * @param int $id
275 * @return Revision|null
277 public static function loadFromTitle( $db, $title, $id = 0 ) {
278 if ( $id ) {
279 $matchId = intval( $id );
280 } else {
281 $matchId = 'page_latest';
283 return self::loadFromConds( $db,
285 "rev_id=$matchId",
286 'page_namespace' => $title->getNamespace(),
287 'page_title' => $title->getDBkey()
293 * Load the revision for the given title with the given timestamp.
294 * WARNING: Timestamps may in some circumstances not be unique,
295 * so this isn't the best key to use.
297 * @param IDatabase $db
298 * @param Title $title
299 * @param string $timestamp
300 * @return Revision|null
302 public static function loadFromTimestamp( $db, $title, $timestamp ) {
303 return self::loadFromConds( $db,
305 'rev_timestamp' => $db->timestamp( $timestamp ),
306 'page_namespace' => $title->getNamespace(),
307 'page_title' => $title->getDBkey()
313 * Given a set of conditions, fetch a revision
315 * This method is used then a revision ID is qualified and
316 * will incorporate some basic replica DB/master fallback logic
318 * @param array $conditions
319 * @param int $flags (optional)
320 * @return Revision|null
322 private static function newFromConds( $conditions, $flags = 0 ) {
323 $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_REPLICA );
325 $rev = self::loadFromConds( $db, $conditions, $flags );
326 // Make sure new pending/committed revision are visibile later on
327 // within web requests to certain avoid bugs like T93866 and T94407.
328 if ( !$rev
329 && !( $flags & self::READ_LATEST )
330 && wfGetLB()->getServerCount() > 1
331 && wfGetLB()->hasOrMadeRecentMasterChanges()
333 $flags = self::READ_LATEST;
334 $db = wfGetDB( DB_MASTER );
335 $rev = self::loadFromConds( $db, $conditions, $flags );
338 if ( $rev ) {
339 $rev->mQueryFlags = $flags;
342 return $rev;
346 * Given a set of conditions, fetch a revision from
347 * the given database connection.
349 * @param IDatabase $db
350 * @param array $conditions
351 * @param int $flags (optional)
352 * @return Revision|null
354 private static function loadFromConds( $db, $conditions, $flags = 0 ) {
355 $row = self::fetchFromConds( $db, $conditions, $flags );
356 if ( $row ) {
357 $rev = new Revision( $row );
358 $rev->mWiki = $db->getWikiID();
360 return $rev;
363 return null;
367 * Return a wrapper for a series of database rows to
368 * fetch all of a given page's revisions in turn.
369 * Each row can be fed to the constructor to get objects.
371 * @param LinkTarget $title
372 * @return ResultWrapper
373 * @deprecated Since 1.28
375 public static function fetchRevision( LinkTarget $title ) {
376 $row = self::fetchFromConds(
377 wfGetDB( DB_REPLICA ),
379 'rev_id=page_latest',
380 'page_namespace' => $title->getNamespace(),
381 'page_title' => $title->getDBkey()
385 return new FakeResultWrapper( $row ? [ $row ] : [] );
389 * Given a set of conditions, return a ResultWrapper
390 * which will return matching database rows with the
391 * fields necessary to build Revision objects.
393 * @param IDatabase $db
394 * @param array $conditions
395 * @param int $flags (optional)
396 * @return stdClass
398 private static function fetchFromConds( $db, $conditions, $flags = 0 ) {
399 $fields = array_merge(
400 self::selectFields(),
401 self::selectPageFields(),
402 self::selectUserFields()
404 $options = [];
405 if ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING ) {
406 $options[] = 'FOR UPDATE';
408 return $db->selectRow(
409 [ 'revision', 'page', 'user' ],
410 $fields,
411 $conditions,
412 __METHOD__,
413 $options,
414 [ 'page' => self::pageJoinCond(), 'user' => self::userJoinCond() ]
419 * Return the value of a select() JOIN conds array for the user table.
420 * This will get user table rows for logged-in users.
421 * @since 1.19
422 * @return array
424 public static function userJoinCond() {
425 return [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
429 * Return the value of a select() page conds array for the page table.
430 * This will assure that the revision(s) are not orphaned from live pages.
431 * @since 1.19
432 * @return array
434 public static function pageJoinCond() {
435 return [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
439 * Return the list of revision fields that should be selected to create
440 * a new revision.
441 * @return array
443 public static function selectFields() {
444 global $wgContentHandlerUseDB;
446 $fields = [
447 'rev_id',
448 'rev_page',
449 'rev_text_id',
450 'rev_timestamp',
451 'rev_comment',
452 'rev_user_text',
453 'rev_user',
454 'rev_minor_edit',
455 'rev_deleted',
456 'rev_len',
457 'rev_parent_id',
458 'rev_sha1',
461 if ( $wgContentHandlerUseDB ) {
462 $fields[] = 'rev_content_format';
463 $fields[] = 'rev_content_model';
466 return $fields;
470 * Return the list of revision fields that should be selected to create
471 * a new revision from an archive row.
472 * @return array
474 public static function selectArchiveFields() {
475 global $wgContentHandlerUseDB;
476 $fields = [
477 'ar_id',
478 'ar_page_id',
479 'ar_rev_id',
480 'ar_text',
481 'ar_text_id',
482 'ar_timestamp',
483 'ar_comment',
484 'ar_user_text',
485 'ar_user',
486 'ar_minor_edit',
487 'ar_deleted',
488 'ar_len',
489 'ar_parent_id',
490 'ar_sha1',
493 if ( $wgContentHandlerUseDB ) {
494 $fields[] = 'ar_content_format';
495 $fields[] = 'ar_content_model';
497 return $fields;
501 * Return the list of text fields that should be selected to read the
502 * revision text
503 * @return array
505 public static function selectTextFields() {
506 return [
507 'old_text',
508 'old_flags'
513 * Return the list of page fields that should be selected from page table
514 * @return array
516 public static function selectPageFields() {
517 return [
518 'page_namespace',
519 'page_title',
520 'page_id',
521 'page_latest',
522 'page_is_redirect',
523 'page_len',
528 * Return the list of user fields that should be selected from user table
529 * @return array
531 public static function selectUserFields() {
532 return [ 'user_name' ];
536 * Do a batched query to get the parent revision lengths
537 * @param IDatabase $db
538 * @param array $revIds
539 * @return array
541 public static function getParentLengths( $db, array $revIds ) {
542 $revLens = [];
543 if ( !$revIds ) {
544 return $revLens; // empty
546 $res = $db->select( 'revision',
547 [ 'rev_id', 'rev_len' ],
548 [ 'rev_id' => $revIds ],
549 __METHOD__ );
550 foreach ( $res as $row ) {
551 $revLens[$row->rev_id] = $row->rev_len;
553 return $revLens;
557 * Constructor
559 * @param object|array $row Either a database row or an array
560 * @throws MWException
561 * @access private
563 function __construct( $row ) {
564 if ( is_object( $row ) ) {
565 $this->mId = intval( $row->rev_id );
566 $this->mPage = intval( $row->rev_page );
567 $this->mTextId = intval( $row->rev_text_id );
568 $this->mComment = $row->rev_comment;
569 $this->mUser = intval( $row->rev_user );
570 $this->mMinorEdit = intval( $row->rev_minor_edit );
571 $this->mTimestamp = $row->rev_timestamp;
572 $this->mDeleted = intval( $row->rev_deleted );
574 if ( !isset( $row->rev_parent_id ) ) {
575 $this->mParentId = null;
576 } else {
577 $this->mParentId = intval( $row->rev_parent_id );
580 if ( !isset( $row->rev_len ) ) {
581 $this->mSize = null;
582 } else {
583 $this->mSize = intval( $row->rev_len );
586 if ( !isset( $row->rev_sha1 ) ) {
587 $this->mSha1 = null;
588 } else {
589 $this->mSha1 = $row->rev_sha1;
592 if ( isset( $row->page_latest ) ) {
593 $this->mCurrent = ( $row->rev_id == $row->page_latest );
594 $this->mTitle = Title::newFromRow( $row );
595 } else {
596 $this->mCurrent = false;
597 $this->mTitle = null;
600 if ( !isset( $row->rev_content_model ) ) {
601 $this->mContentModel = null; # determine on demand if needed
602 } else {
603 $this->mContentModel = strval( $row->rev_content_model );
606 if ( !isset( $row->rev_content_format ) ) {
607 $this->mContentFormat = null; # determine on demand if needed
608 } else {
609 $this->mContentFormat = strval( $row->rev_content_format );
612 // Lazy extraction...
613 $this->mText = null;
614 if ( isset( $row->old_text ) ) {
615 $this->mTextRow = $row;
616 } else {
617 // 'text' table row entry will be lazy-loaded
618 $this->mTextRow = null;
621 // Use user_name for users and rev_user_text for IPs...
622 $this->mUserText = null; // lazy load if left null
623 if ( $this->mUser == 0 ) {
624 $this->mUserText = $row->rev_user_text; // IP user
625 } elseif ( isset( $row->user_name ) ) {
626 $this->mUserText = $row->user_name; // logged-in user
628 $this->mOrigUserText = $row->rev_user_text;
629 } elseif ( is_array( $row ) ) {
630 // Build a new revision to be saved...
631 global $wgUser; // ugh
633 # if we have a content object, use it to set the model and type
634 if ( !empty( $row['content'] ) ) {
635 // @todo when is that set? test with external store setup! check out insertOn() [dk]
636 if ( !empty( $row['text_id'] ) ) {
637 throw new MWException( "Text already stored in external store (id {$row['text_id']}), " .
638 "can't serialize content object" );
641 $row['content_model'] = $row['content']->getModel();
642 # note: mContentFormat is initializes later accordingly
643 # note: content is serialized later in this method!
644 # also set text to null?
647 $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null;
648 $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null;
649 $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null;
650 $this->mUserText = isset( $row['user_text'] )
651 ? strval( $row['user_text'] ) : $wgUser->getName();
652 $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId();
653 $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0;
654 $this->mTimestamp = isset( $row['timestamp'] )
655 ? strval( $row['timestamp'] ) : wfTimestampNow();
656 $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0;
657 $this->mSize = isset( $row['len'] ) ? intval( $row['len'] ) : null;
658 $this->mParentId = isset( $row['parent_id'] ) ? intval( $row['parent_id'] ) : null;
659 $this->mSha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null;
661 $this->mContentModel = isset( $row['content_model'] )
662 ? strval( $row['content_model'] ) : null;
663 $this->mContentFormat = isset( $row['content_format'] )
664 ? strval( $row['content_format'] ) : null;
666 // Enforce spacing trimming on supplied text
667 $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null;
668 $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
669 $this->mTextRow = null;
671 $this->mTitle = isset( $row['title'] ) ? $row['title'] : null;
673 // if we have a Content object, override mText and mContentModel
674 if ( !empty( $row['content'] ) ) {
675 if ( !( $row['content'] instanceof Content ) ) {
676 throw new MWException( '`content` field must contain a Content object.' );
679 $handler = $this->getContentHandler();
680 $this->mContent = $row['content'];
682 $this->mContentModel = $this->mContent->getModel();
683 $this->mContentHandler = null;
685 $this->mText = $handler->serializeContent( $row['content'], $this->getContentFormat() );
686 } elseif ( $this->mText !== null ) {
687 $handler = $this->getContentHandler();
688 $this->mContent = $handler->unserializeContent( $this->mText );
691 // If we have a Title object, make sure it is consistent with mPage.
692 if ( $this->mTitle && $this->mTitle->exists() ) {
693 if ( $this->mPage === null ) {
694 // if the page ID wasn't known, set it now
695 $this->mPage = $this->mTitle->getArticleID();
696 } elseif ( $this->mTitle->getArticleID() !== $this->mPage ) {
697 // Got different page IDs. This may be legit (e.g. during undeletion),
698 // but it seems worth mentioning it in the log.
699 wfDebug( "Page ID " . $this->mPage . " mismatches the ID " .
700 $this->mTitle->getArticleID() . " provided by the Title object." );
704 $this->mCurrent = false;
706 // If we still have no length, see it we have the text to figure it out
707 if ( !$this->mSize && $this->mContent !== null ) {
708 $this->mSize = $this->mContent->getSize();
711 // Same for sha1
712 if ( $this->mSha1 === null ) {
713 $this->mSha1 = $this->mText === null ? null : self::base36Sha1( $this->mText );
716 // force lazy init
717 $this->getContentModel();
718 $this->getContentFormat();
719 } else {
720 throw new MWException( 'Revision constructor passed invalid row format.' );
722 $this->mUnpatrolled = null;
726 * Get revision ID
728 * @return int|null
730 public function getId() {
731 return $this->mId;
735 * Set the revision ID
737 * This should only be used for proposed revisions that turn out to be null edits
739 * @since 1.19
740 * @param int $id
742 public function setId( $id ) {
743 $this->mId = (int)$id;
747 * Set the user ID/name
749 * This should only be used for proposed revisions that turn out to be null edits
751 * @since 1.28
752 * @param integer $id User ID
753 * @param string $name User name
755 public function setUserIdAndName( $id, $name ) {
756 $this->mUser = (int)$id;
757 $this->mUserText = $name;
758 $this->mOrigUserText = $name;
762 * Get text row ID
764 * @return int|null
766 public function getTextId() {
767 return $this->mTextId;
771 * Get parent revision ID (the original previous page revision)
773 * @return int|null
775 public function getParentId() {
776 return $this->mParentId;
780 * Returns the length of the text in this revision, or null if unknown.
782 * @return int|null
784 public function getSize() {
785 return $this->mSize;
789 * Returns the base36 sha1 of the text in this revision, or null if unknown.
791 * @return string|null
793 public function getSha1() {
794 return $this->mSha1;
798 * Returns the title of the page associated with this entry or null.
800 * Will do a query, when title is not set and id is given.
802 * @return Title|null
804 public function getTitle() {
805 if ( $this->mTitle !== null ) {
806 return $this->mTitle;
808 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
809 if ( $this->mId !== null ) {
810 $dbr = wfGetLB( $this->mWiki )->getConnectionRef( DB_REPLICA, [], $this->mWiki );
811 $row = $dbr->selectRow(
812 [ 'page', 'revision' ],
813 self::selectPageFields(),
814 [ 'page_id=rev_page', 'rev_id' => $this->mId ],
815 __METHOD__
817 if ( $row ) {
818 // @TODO: better foreign title handling
819 $this->mTitle = Title::newFromRow( $row );
823 if ( $this->mWiki === false || $this->mWiki === wfWikiID() ) {
824 // Loading by ID is best, though not possible for foreign titles
825 if ( !$this->mTitle && $this->mPage !== null && $this->mPage > 0 ) {
826 $this->mTitle = Title::newFromID( $this->mPage );
830 return $this->mTitle;
834 * Set the title of the revision
836 * @param Title $title
838 public function setTitle( $title ) {
839 $this->mTitle = $title;
843 * Get the page ID
845 * @return int|null
847 public function getPage() {
848 return $this->mPage;
852 * Fetch revision's user id if it's available to the specified audience.
853 * If the specified audience does not have access to it, zero will be
854 * returned.
856 * @param int $audience One of:
857 * Revision::FOR_PUBLIC to be displayed to all users
858 * Revision::FOR_THIS_USER to be displayed to the given user
859 * Revision::RAW get the ID regardless of permissions
860 * @param User $user User object to check for, only if FOR_THIS_USER is passed
861 * to the $audience parameter
862 * @return int
864 public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) {
865 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
866 return 0;
867 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
868 return 0;
869 } else {
870 return $this->mUser;
875 * Fetch revision's user id without regard for the current user's permissions
877 * @return int
878 * @deprecated since 1.25, use getUser( Revision::RAW )
880 public function getRawUser() {
881 wfDeprecated( __METHOD__, '1.25' );
882 return $this->getUser( self::RAW );
886 * Fetch revision's username if it's available to the specified audience.
887 * If the specified audience does not have access to the username, an
888 * empty string will be returned.
890 * @param int $audience One of:
891 * Revision::FOR_PUBLIC to be displayed to all users
892 * Revision::FOR_THIS_USER to be displayed to the given user
893 * Revision::RAW get the text regardless of permissions
894 * @param User $user User object to check for, only if FOR_THIS_USER is passed
895 * to the $audience parameter
896 * @return string
898 public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) {
899 $this->loadMutableFields();
901 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
902 return '';
903 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) {
904 return '';
905 } else {
906 if ( $this->mUserText === null ) {
907 $this->mUserText = User::whoIs( $this->mUser ); // load on demand
908 if ( $this->mUserText === false ) {
909 # This shouldn't happen, but it can if the wiki was recovered
910 # via importing revs and there is no user table entry yet.
911 $this->mUserText = $this->mOrigUserText;
914 return $this->mUserText;
919 * Fetch revision's username without regard for view restrictions
921 * @return string
922 * @deprecated since 1.25, use getUserText( Revision::RAW )
924 public function getRawUserText() {
925 wfDeprecated( __METHOD__, '1.25' );
926 return $this->getUserText( self::RAW );
930 * Fetch revision comment if it's available to the specified audience.
931 * If the specified audience does not have access to the comment, an
932 * empty string will be returned.
934 * @param int $audience One of:
935 * Revision::FOR_PUBLIC to be displayed to all users
936 * Revision::FOR_THIS_USER to be displayed to the given user
937 * Revision::RAW get the text regardless of permissions
938 * @param User $user User object to check for, only if FOR_THIS_USER is passed
939 * to the $audience parameter
940 * @return string
942 function getComment( $audience = self::FOR_PUBLIC, User $user = null ) {
943 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
944 return '';
945 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $user ) ) {
946 return '';
947 } else {
948 return $this->mComment;
953 * Fetch revision comment without regard for the current user's permissions
955 * @return string
956 * @deprecated since 1.25, use getComment( Revision::RAW )
958 public function getRawComment() {
959 wfDeprecated( __METHOD__, '1.25' );
960 return $this->getComment( self::RAW );
964 * @return bool
966 public function isMinor() {
967 return (bool)$this->mMinorEdit;
971 * @return int Rcid of the unpatrolled row, zero if there isn't one
973 public function isUnpatrolled() {
974 if ( $this->mUnpatrolled !== null ) {
975 return $this->mUnpatrolled;
977 $rc = $this->getRecentChange();
978 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
979 $this->mUnpatrolled = $rc->getAttribute( 'rc_id' );
980 } else {
981 $this->mUnpatrolled = 0;
983 return $this->mUnpatrolled;
987 * Get the RC object belonging to the current revision, if there's one
989 * @param int $flags (optional) $flags include:
990 * Revision::READ_LATEST : Select the data from the master
992 * @since 1.22
993 * @return RecentChange|null
995 public function getRecentChange( $flags = 0 ) {
996 $dbr = wfGetDB( DB_REPLICA );
998 list( $dbType, ) = DBAccessObjectUtils::getDBOptions( $flags );
1000 return RecentChange::newFromConds(
1002 'rc_user_text' => $this->getUserText( Revision::RAW ),
1003 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
1004 'rc_this_oldid' => $this->getId()
1006 __METHOD__,
1007 $dbType
1012 * @param int $field One of DELETED_* bitfield constants
1014 * @return bool
1016 public function isDeleted( $field ) {
1017 if ( $this->isCurrent() && $field === self::DELETED_TEXT ) {
1018 // Current revisions of pages cannot have the content hidden. Skipping this
1019 // check is very useful for Parser as it fetches templates using newKnownCurrent().
1020 // Calling getVisibility() in that case triggers a verification database query.
1021 return false; // no need to check
1024 return ( $this->getVisibility() & $field ) == $field;
1028 * Get the deletion bitfield of the revision
1030 * @return int
1032 public function getVisibility() {
1033 $this->loadMutableFields();
1035 return (int)$this->mDeleted;
1039 * Fetch revision content if it's available to the specified audience.
1040 * If the specified audience does not have the ability to view this
1041 * revision, null will be returned.
1043 * @param int $audience One of:
1044 * Revision::FOR_PUBLIC to be displayed to all users
1045 * Revision::FOR_THIS_USER to be displayed to $wgUser
1046 * Revision::RAW get the text regardless of permissions
1047 * @param User $user User object to check for, only if FOR_THIS_USER is passed
1048 * to the $audience parameter
1049 * @since 1.21
1050 * @return Content|null
1052 public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) {
1053 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_TEXT ) ) {
1054 return null;
1055 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_TEXT, $user ) ) {
1056 return null;
1057 } else {
1058 return $this->getContentInternal();
1063 * Get original serialized data (without checking view restrictions)
1065 * @since 1.21
1066 * @return string
1068 public function getSerializedData() {
1069 if ( $this->mText === null ) {
1070 // Revision is immutable. Load on demand.
1071 $this->mText = $this->loadText();
1074 return $this->mText;
1078 * Gets the content object for the revision (or null on failure).
1080 * Note that for mutable Content objects, each call to this method will return a
1081 * fresh clone.
1083 * @since 1.21
1084 * @return Content|null The Revision's content, or null on failure.
1086 protected function getContentInternal() {
1087 if ( $this->mContent === null ) {
1088 $text = $this->getSerializedData();
1090 if ( $text !== null && $text !== false ) {
1091 // Unserialize content
1092 $handler = $this->getContentHandler();
1093 $format = $this->getContentFormat();
1095 $this->mContent = $handler->unserializeContent( $text, $format );
1099 // NOTE: copy() will return $this for immutable content objects
1100 return $this->mContent ? $this->mContent->copy() : null;
1104 * Returns the content model for this revision.
1106 * If no content model was stored in the database, the default content model for the title is
1107 * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT
1108 * is used as a last resort.
1110 * @return string The content model id associated with this revision,
1111 * see the CONTENT_MODEL_XXX constants.
1113 public function getContentModel() {
1114 if ( !$this->mContentModel ) {
1115 $title = $this->getTitle();
1116 if ( $title ) {
1117 $this->mContentModel = ContentHandler::getDefaultModelFor( $title );
1118 } else {
1119 $this->mContentModel = CONTENT_MODEL_WIKITEXT;
1122 assert( !empty( $this->mContentModel ) );
1125 return $this->mContentModel;
1129 * Returns the content format for this revision.
1131 * If no content format was stored in the database, the default format for this
1132 * revision's content model is returned.
1134 * @return string The content format id associated with this revision,
1135 * see the CONTENT_FORMAT_XXX constants.
1137 public function getContentFormat() {
1138 if ( !$this->mContentFormat ) {
1139 $handler = $this->getContentHandler();
1140 $this->mContentFormat = $handler->getDefaultFormat();
1142 assert( !empty( $this->mContentFormat ) );
1145 return $this->mContentFormat;
1149 * Returns the content handler appropriate for this revision's content model.
1151 * @throws MWException
1152 * @return ContentHandler
1154 public function getContentHandler() {
1155 if ( !$this->mContentHandler ) {
1156 $model = $this->getContentModel();
1157 $this->mContentHandler = ContentHandler::getForModelID( $model );
1159 $format = $this->getContentFormat();
1161 if ( !$this->mContentHandler->isSupportedFormat( $format ) ) {
1162 throw new MWException( "Oops, the content format $format is not supported for "
1163 . "this content model, $model" );
1167 return $this->mContentHandler;
1171 * @return string
1173 public function getTimestamp() {
1174 return wfTimestamp( TS_MW, $this->mTimestamp );
1178 * @return bool
1180 public function isCurrent() {
1181 return $this->mCurrent;
1185 * Get previous revision for this title
1187 * @return Revision|null
1189 public function getPrevious() {
1190 if ( $this->getTitle() ) {
1191 $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() );
1192 if ( $prev ) {
1193 return self::newFromTitle( $this->getTitle(), $prev );
1196 return null;
1200 * Get next revision for this title
1202 * @return Revision|null
1204 public function getNext() {
1205 if ( $this->getTitle() ) {
1206 $next = $this->getTitle()->getNextRevisionID( $this->getId() );
1207 if ( $next ) {
1208 return self::newFromTitle( $this->getTitle(), $next );
1211 return null;
1215 * Get previous revision Id for this page_id
1216 * This is used to populate rev_parent_id on save
1218 * @param IDatabase $db
1219 * @return int
1221 private function getPreviousRevisionId( $db ) {
1222 if ( $this->mPage === null ) {
1223 return 0;
1225 # Use page_latest if ID is not given
1226 if ( !$this->mId ) {
1227 $prevId = $db->selectField( 'page', 'page_latest',
1228 [ 'page_id' => $this->mPage ],
1229 __METHOD__ );
1230 } else {
1231 $prevId = $db->selectField( 'revision', 'rev_id',
1232 [ 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ],
1233 __METHOD__,
1234 [ 'ORDER BY' => 'rev_id DESC' ] );
1236 return intval( $prevId );
1240 * Get revision text associated with an old or archive row
1241 * $row is usually an object from wfFetchRow(), both the flags and the text
1242 * field must be included.
1244 * @param stdClass $row The text data
1245 * @param string $prefix Table prefix (default 'old_')
1246 * @param string|bool $wiki The name of the wiki to load the revision text from
1247 * (same as the the wiki $row was loaded from) or false to indicate the local
1248 * wiki (this is the default). Otherwise, it must be a symbolic wiki database
1249 * identifier as understood by the LoadBalancer class.
1250 * @return string|false Text the text requested or false on failure
1252 public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) {
1254 # Get data
1255 $textField = $prefix . 'text';
1256 $flagsField = $prefix . 'flags';
1258 if ( isset( $row->$flagsField ) ) {
1259 $flags = explode( ',', $row->$flagsField );
1260 } else {
1261 $flags = [];
1264 if ( isset( $row->$textField ) ) {
1265 $text = $row->$textField;
1266 } else {
1267 return false;
1270 # Use external methods for external objects, text in table is URL-only then
1271 if ( in_array( 'external', $flags ) ) {
1272 $url = $text;
1273 $parts = explode( '://', $url, 2 );
1274 if ( count( $parts ) == 1 || $parts[1] == '' ) {
1275 return false;
1277 $text = ExternalStore::fetchFromURL( $url, [ 'wiki' => $wiki ] );
1280 // If the text was fetched without an error, convert it
1281 if ( $text !== false ) {
1282 $text = self::decompressRevisionText( $text, $flags );
1284 return $text;
1288 * If $wgCompressRevisions is enabled, we will compress data.
1289 * The input string is modified in place.
1290 * Return value is the flags field: contains 'gzip' if the
1291 * data is compressed, and 'utf-8' if we're saving in UTF-8
1292 * mode.
1294 * @param mixed $text Reference to a text
1295 * @return string
1297 public static function compressRevisionText( &$text ) {
1298 global $wgCompressRevisions;
1299 $flags = [];
1301 # Revisions not marked this way will be converted
1302 # on load if $wgLegacyCharset is set in the future.
1303 $flags[] = 'utf-8';
1305 if ( $wgCompressRevisions ) {
1306 if ( function_exists( 'gzdeflate' ) ) {
1307 $deflated = gzdeflate( $text );
1309 if ( $deflated === false ) {
1310 wfLogWarning( __METHOD__ . ': gzdeflate() failed' );
1311 } else {
1312 $text = $deflated;
1313 $flags[] = 'gzip';
1315 } else {
1316 wfDebug( __METHOD__ . " -- no zlib support, not compressing\n" );
1319 return implode( ',', $flags );
1323 * Re-converts revision text according to it's flags.
1325 * @param mixed $text Reference to a text
1326 * @param array $flags Compression flags
1327 * @return string|bool Decompressed text, or false on failure
1329 public static function decompressRevisionText( $text, $flags ) {
1330 if ( in_array( 'gzip', $flags ) ) {
1331 # Deal with optional compression of archived pages.
1332 # This can be done periodically via maintenance/compressOld.php, and
1333 # as pages are saved if $wgCompressRevisions is set.
1334 $text = gzinflate( $text );
1336 if ( $text === false ) {
1337 wfLogWarning( __METHOD__ . ': gzinflate() failed' );
1338 return false;
1342 if ( in_array( 'object', $flags ) ) {
1343 # Generic compressed storage
1344 $obj = unserialize( $text );
1345 if ( !is_object( $obj ) ) {
1346 // Invalid object
1347 return false;
1349 $text = $obj->getText();
1352 global $wgLegacyEncoding;
1353 if ( $text !== false && $wgLegacyEncoding
1354 && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags )
1356 # Old revisions kept around in a legacy encoding?
1357 # Upconvert on demand.
1358 # ("utf8" checked for compatibility with some broken
1359 # conversion scripts 2008-12-30)
1360 global $wgContLang;
1361 $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text );
1364 return $text;
1368 * Insert a new revision into the database, returning the new revision ID
1369 * number on success and dies horribly on failure.
1371 * @param IDatabase $dbw (master connection)
1372 * @throws MWException
1373 * @return int
1375 public function insertOn( $dbw ) {
1376 global $wgDefaultExternalStore, $wgContentHandlerUseDB;
1378 // We're inserting a new revision, so we have to use master anyway.
1379 // If it's a null revision, it may have references to rows that
1380 // are not in the replica yet (the text row).
1381 $this->mQueryFlags |= self::READ_LATEST;
1383 // Not allowed to have rev_page equal to 0, false, etc.
1384 if ( !$this->mPage ) {
1385 $title = $this->getTitle();
1386 if ( $title instanceof Title ) {
1387 $titleText = ' for page ' . $title->getPrefixedText();
1388 } else {
1389 $titleText = '';
1391 throw new MWException( "Cannot insert revision$titleText: page ID must be nonzero" );
1394 $this->checkContentModel();
1396 $data = $this->mText;
1397 $flags = self::compressRevisionText( $data );
1399 # Write to external storage if required
1400 if ( $wgDefaultExternalStore ) {
1401 // Store and get the URL
1402 $data = ExternalStore::insertToDefault( $data );
1403 if ( !$data ) {
1404 throw new MWException( "Unable to store text to external storage" );
1406 if ( $flags ) {
1407 $flags .= ',';
1409 $flags .= 'external';
1412 # Record the text (or external storage URL) to the text table
1413 if ( $this->mTextId === null ) {
1414 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
1415 $dbw->insert( 'text',
1417 'old_id' => $old_id,
1418 'old_text' => $data,
1419 'old_flags' => $flags,
1420 ], __METHOD__
1422 $this->mTextId = $dbw->insertId();
1425 if ( $this->mComment === null ) {
1426 $this->mComment = "";
1429 # Record the edit in revisions
1430 $rev_id = $this->mId !== null
1431 ? $this->mId
1432 : $dbw->nextSequenceValue( 'revision_rev_id_seq' );
1433 $row = [
1434 'rev_id' => $rev_id,
1435 'rev_page' => $this->mPage,
1436 'rev_text_id' => $this->mTextId,
1437 'rev_comment' => $this->mComment,
1438 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
1439 'rev_user' => $this->mUser,
1440 'rev_user_text' => $this->mUserText,
1441 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
1442 'rev_deleted' => $this->mDeleted,
1443 'rev_len' => $this->mSize,
1444 'rev_parent_id' => $this->mParentId === null
1445 ? $this->getPreviousRevisionId( $dbw )
1446 : $this->mParentId,
1447 'rev_sha1' => $this->mSha1 === null
1448 ? Revision::base36Sha1( $this->mText )
1449 : $this->mSha1,
1452 if ( $wgContentHandlerUseDB ) {
1453 // NOTE: Store null for the default model and format, to save space.
1454 // XXX: Makes the DB sensitive to changed defaults.
1455 // Make this behavior optional? Only in miser mode?
1457 $model = $this->getContentModel();
1458 $format = $this->getContentFormat();
1460 $title = $this->getTitle();
1462 if ( $title === null ) {
1463 throw new MWException( "Insufficient information to determine the title of the "
1464 . "revision's page!" );
1467 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1468 $defaultFormat = ContentHandler::getForModelID( $defaultModel )->getDefaultFormat();
1470 $row['rev_content_model'] = ( $model === $defaultModel ) ? null : $model;
1471 $row['rev_content_format'] = ( $format === $defaultFormat ) ? null : $format;
1474 $dbw->insert( 'revision', $row, __METHOD__ );
1476 $this->mId = $rev_id !== null ? $rev_id : $dbw->insertId();
1478 // Assertion to try to catch T92046
1479 if ( (int)$this->mId === 0 ) {
1480 throw new UnexpectedValueException(
1481 'After insert, Revision mId is ' . var_export( $this->mId, 1 ) . ': ' .
1482 var_export( $row, 1 )
1486 // Avoid PHP 7.1 warning of passing $this by reference
1487 $revision = $this;
1488 Hooks::run( 'RevisionInsertComplete', [ &$revision, $data, $flags ] );
1490 return $this->mId;
1493 protected function checkContentModel() {
1494 global $wgContentHandlerUseDB;
1496 // Note: may return null for revisions that have not yet been inserted
1497 $title = $this->getTitle();
1499 $model = $this->getContentModel();
1500 $format = $this->getContentFormat();
1501 $handler = $this->getContentHandler();
1503 if ( !$handler->isSupportedFormat( $format ) ) {
1504 $t = $title->getPrefixedDBkey();
1506 throw new MWException( "Can't use format $format with content model $model on $t" );
1509 if ( !$wgContentHandlerUseDB && $title ) {
1510 // if $wgContentHandlerUseDB is not set,
1511 // all revisions must use the default content model and format.
1513 $defaultModel = ContentHandler::getDefaultModelFor( $title );
1514 $defaultHandler = ContentHandler::getForModelID( $defaultModel );
1515 $defaultFormat = $defaultHandler->getDefaultFormat();
1517 if ( $this->getContentModel() != $defaultModel ) {
1518 $t = $title->getPrefixedDBkey();
1520 throw new MWException( "Can't save non-default content model with "
1521 . "\$wgContentHandlerUseDB disabled: model is $model, "
1522 . "default for $t is $defaultModel" );
1525 if ( $this->getContentFormat() != $defaultFormat ) {
1526 $t = $title->getPrefixedDBkey();
1528 throw new MWException( "Can't use non-default content format with "
1529 . "\$wgContentHandlerUseDB disabled: format is $format, "
1530 . "default for $t is $defaultFormat" );
1534 $content = $this->getContent( Revision::RAW );
1535 $prefixedDBkey = $title->getPrefixedDBkey();
1536 $revId = $this->mId;
1538 if ( !$content ) {
1539 throw new MWException(
1540 "Content of revision $revId ($prefixedDBkey) could not be loaded for validation!"
1543 if ( !$content->isValid() ) {
1544 throw new MWException(
1545 "Content of revision $revId ($prefixedDBkey) is not valid! Content model is $model"
1551 * Get the base 36 SHA-1 value for a string of text
1552 * @param string $text
1553 * @return string
1555 public static function base36Sha1( $text ) {
1556 return Wikimedia\base_convert( sha1( $text ), 16, 36, 31 );
1560 * Lazy-load the revision's text.
1561 * Currently hardcoded to the 'text' table storage engine.
1563 * @return string|bool The revision's text, or false on failure
1565 private function loadText() {
1566 global $wgRevisionCacheExpiry;
1568 $cache = ObjectCache::getMainWANInstance();
1569 if ( $cache->getQoS( $cache::ATTR_EMULATION ) <= $cache::QOS_EMULATION_SQL ) {
1570 // Do not cache RDBMs blobs in...the RDBMs store
1571 $ttl = $cache::TTL_UNCACHEABLE;
1572 } else {
1573 $ttl = $wgRevisionCacheExpiry ?: $cache::TTL_UNCACHEABLE;
1576 // No negative caching; negative hits on text rows may be due to corrupted replica DBs
1577 return $cache->getWithSetCallback(
1578 $cache->makeKey( 'revisiontext', 'textid', $this->getTextId() ),
1579 $ttl,
1580 function () {
1581 return $this->fetchText();
1583 [ 'pcGroup' => self::TEXT_CACHE_GROUP, 'pcTTL' => $cache::TTL_PROC_LONG ]
1587 private function fetchText() {
1588 $textId = $this->getTextId();
1590 // If we kept data for lazy extraction, use it now...
1591 if ( $this->mTextRow !== null ) {
1592 $row = $this->mTextRow;
1593 $this->mTextRow = null;
1594 } else {
1595 $row = null;
1598 // Callers doing updates will pass in READ_LATEST as usual. Since the text/blob tables
1599 // do not normally get rows changed around, set READ_LATEST_IMMUTABLE in those cases.
1600 $flags = $this->mQueryFlags;
1601 $flags |= DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST )
1602 ? self::READ_LATEST_IMMUTABLE
1603 : 0;
1605 list( $index, $options, $fallbackIndex, $fallbackOptions ) =
1606 DBAccessObjectUtils::getDBOptions( $flags );
1608 if ( !$row ) {
1609 // Text data is immutable; check replica DBs first.
1610 $row = wfGetDB( $index )->selectRow(
1611 'text',
1612 [ 'old_text', 'old_flags' ],
1613 [ 'old_id' => $textId ],
1614 __METHOD__,
1615 $options
1619 // Fallback to DB_MASTER in some cases if the row was not found
1620 if ( !$row && $fallbackIndex !== null ) {
1621 // Use FOR UPDATE if it was used to fetch this revision. This avoids missing the row
1622 // due to REPEATABLE-READ. Also fallback to the master if READ_LATEST is provided.
1623 $row = wfGetDB( $fallbackIndex )->selectRow(
1624 'text',
1625 [ 'old_text', 'old_flags' ],
1626 [ 'old_id' => $textId ],
1627 __METHOD__,
1628 $fallbackOptions
1632 if ( !$row ) {
1633 wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." );
1636 $text = self::getRevisionText( $row );
1637 if ( $row && $text === false ) {
1638 wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." );
1641 return is_string( $text ) ? $text : false;
1645 * Create a new null-revision for insertion into a page's
1646 * history. This will not re-save the text, but simply refer
1647 * to the text from the previous version.
1649 * Such revisions can for instance identify page rename
1650 * operations and other such meta-modifications.
1652 * @param IDatabase $dbw
1653 * @param int $pageId ID number of the page to read from
1654 * @param string $summary Revision's summary
1655 * @param bool $minor Whether the revision should be considered as minor
1656 * @param User|null $user User object to use or null for $wgUser
1657 * @return Revision|null Revision or null on error
1659 public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) {
1660 global $wgContentHandlerUseDB, $wgContLang;
1662 $fields = [ 'page_latest', 'page_namespace', 'page_title',
1663 'rev_text_id', 'rev_len', 'rev_sha1' ];
1665 if ( $wgContentHandlerUseDB ) {
1666 $fields[] = 'rev_content_model';
1667 $fields[] = 'rev_content_format';
1670 $current = $dbw->selectRow(
1671 [ 'page', 'revision' ],
1672 $fields,
1674 'page_id' => $pageId,
1675 'page_latest=rev_id',
1677 __METHOD__,
1678 [ 'FOR UPDATE' ] // T51581
1681 if ( $current ) {
1682 if ( !$user ) {
1683 global $wgUser;
1684 $user = $wgUser;
1687 // Truncate for whole multibyte characters
1688 $summary = $wgContLang->truncate( $summary, 255 );
1690 $row = [
1691 'page' => $pageId,
1692 'user_text' => $user->getName(),
1693 'user' => $user->getId(),
1694 'comment' => $summary,
1695 'minor_edit' => $minor,
1696 'text_id' => $current->rev_text_id,
1697 'parent_id' => $current->page_latest,
1698 'len' => $current->rev_len,
1699 'sha1' => $current->rev_sha1
1702 if ( $wgContentHandlerUseDB ) {
1703 $row['content_model'] = $current->rev_content_model;
1704 $row['content_format'] = $current->rev_content_format;
1707 $row['title'] = Title::makeTitle( $current->page_namespace, $current->page_title );
1709 $revision = new Revision( $row );
1710 } else {
1711 $revision = null;
1714 return $revision;
1718 * Determine if the current user is allowed to view a particular
1719 * field of this revision, if it's marked as deleted.
1721 * @param int $field One of self::DELETED_TEXT,
1722 * self::DELETED_COMMENT,
1723 * self::DELETED_USER
1724 * @param User|null $user User object to check, or null to use $wgUser
1725 * @return bool
1727 public function userCan( $field, User $user = null ) {
1728 return self::userCanBitfield( $this->getVisibility(), $field, $user );
1732 * Determine if the current user is allowed to view a particular
1733 * field of this revision, if it's marked as deleted. This is used
1734 * by various classes to avoid duplication.
1736 * @param int $bitfield Current field
1737 * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE,
1738 * self::DELETED_COMMENT = File::DELETED_COMMENT,
1739 * self::DELETED_USER = File::DELETED_USER
1740 * @param User|null $user User object to check, or null to use $wgUser
1741 * @param Title|null $title A Title object to check for per-page restrictions on,
1742 * instead of just plain userrights
1743 * @return bool
1745 public static function userCanBitfield( $bitfield, $field, User $user = null,
1746 Title $title = null
1748 if ( $bitfield & $field ) { // aspect is deleted
1749 if ( $user === null ) {
1750 global $wgUser;
1751 $user = $wgUser;
1753 if ( $bitfield & self::DELETED_RESTRICTED ) {
1754 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
1755 } elseif ( $field & self::DELETED_TEXT ) {
1756 $permissions = [ 'deletedtext' ];
1757 } else {
1758 $permissions = [ 'deletedhistory' ];
1760 $permissionlist = implode( ', ', $permissions );
1761 if ( $title === null ) {
1762 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
1763 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
1764 } else {
1765 $text = $title->getPrefixedText();
1766 wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" );
1767 foreach ( $permissions as $perm ) {
1768 if ( $title->userCan( $perm, $user ) ) {
1769 return true;
1772 return false;
1774 } else {
1775 return true;
1780 * Get rev_timestamp from rev_id, without loading the rest of the row
1782 * @param Title $title
1783 * @param int $id
1784 * @return string|bool False if not found
1786 static function getTimestampFromId( $title, $id, $flags = 0 ) {
1787 $db = ( $flags & self::READ_LATEST )
1788 ? wfGetDB( DB_MASTER )
1789 : wfGetDB( DB_REPLICA );
1790 // Casting fix for databases that can't take '' for rev_id
1791 if ( $id == '' ) {
1792 $id = 0;
1794 $conds = [ 'rev_id' => $id ];
1795 $conds['rev_page'] = $title->getArticleID();
1796 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ );
1798 return ( $timestamp !== false ) ? wfTimestamp( TS_MW, $timestamp ) : false;
1802 * Get count of revisions per page...not very efficient
1804 * @param IDatabase $db
1805 * @param int $id Page id
1806 * @return int
1808 static function countByPageId( $db, $id ) {
1809 $row = $db->selectRow( 'revision', [ 'revCount' => 'COUNT(*)' ],
1810 [ 'rev_page' => $id ], __METHOD__ );
1811 if ( $row ) {
1812 return $row->revCount;
1814 return 0;
1818 * Get count of revisions per page...not very efficient
1820 * @param IDatabase $db
1821 * @param Title $title
1822 * @return int
1824 static function countByTitle( $db, $title ) {
1825 $id = $title->getArticleID();
1826 if ( $id ) {
1827 return self::countByPageId( $db, $id );
1829 return 0;
1833 * Check if no edits were made by other users since
1834 * the time a user started editing the page. Limit to
1835 * 50 revisions for the sake of performance.
1837 * @since 1.20
1838 * @deprecated since 1.24
1840 * @param IDatabase|int $db The Database to perform the check on. May be given as a
1841 * Database object or a database identifier usable with wfGetDB.
1842 * @param int $pageId The ID of the page in question
1843 * @param int $userId The ID of the user in question
1844 * @param string $since Look at edits since this time
1846 * @return bool True if the given user was the only one to edit since the given timestamp
1848 public static function userWasLastToEdit( $db, $pageId, $userId, $since ) {
1849 if ( !$userId ) {
1850 return false;
1853 if ( is_int( $db ) ) {
1854 $db = wfGetDB( $db );
1857 $res = $db->select( 'revision',
1858 'rev_user',
1860 'rev_page' => $pageId,
1861 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1863 __METHOD__,
1864 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ] );
1865 foreach ( $res as $row ) {
1866 if ( $row->rev_user != $userId ) {
1867 return false;
1870 return true;
1874 * Load a revision based on a known page ID and current revision ID from the DB
1876 * This method allows for the use of caching, though accessing anything that normally
1877 * requires permission checks (aside from the text) will trigger a small DB lookup.
1878 * The title will also be lazy loaded, though setTitle() can be used to preload it.
1880 * @param IDatabase $db
1881 * @param int $pageId Page ID
1882 * @param int $revId Known current revision of this page
1883 * @return Revision|bool Returns false if missing
1884 * @since 1.28
1886 public static function newKnownCurrent( IDatabase $db, $pageId, $revId ) {
1887 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1888 return $cache->getWithSetCallback(
1889 // Page/rev IDs passed in from DB to reflect history merges
1890 $cache->makeGlobalKey( 'revision', $db->getWikiID(), $pageId, $revId ),
1891 $cache::TTL_WEEK,
1892 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1893 $setOpts += Database::getCacheSetOptions( $db );
1895 $rev = Revision::loadFromPageId( $db, $pageId, $revId );
1896 // Reflect revision deletion and user renames
1897 if ( $rev ) {
1898 $rev->mTitle = null; // mutable; lazy-load
1899 $rev->mRefreshMutableFields = true;
1902 return $rev ?: false; // don't cache negatives
1908 * For cached revisions, make sure the user name and rev_deleted is up-to-date
1910 private function loadMutableFields() {
1911 if ( !$this->mRefreshMutableFields ) {
1912 return; // not needed
1915 $this->mRefreshMutableFields = false;
1916 $dbr = wfGetLB( $this->mWiki )->getConnectionRef( DB_REPLICA, [], $this->mWiki );
1917 $row = $dbr->selectRow(
1918 [ 'revision', 'user' ],
1919 [ 'rev_deleted', 'user_name' ],
1920 [ 'rev_id' => $this->mId, 'user_id = rev_user' ],
1921 __METHOD__
1923 if ( $row ) { // update values
1924 $this->mDeleted = (int)$row->rev_deleted;
1925 $this->mUserText = $row->user_name;