MediaWiki  master
ApiRollback.php
Go to the documentation of this file.
1 <?php
28 
32 class ApiRollback extends ApiBase {
33 
35 
38 
39  public function __construct(
40  ApiMain $mainModule,
41  $moduleName,
45  ) {
46  parent::__construct( $mainModule, $moduleName );
47  $this->rollbackPageFactory = $rollbackPageFactory;
48 
49  // Variables needed in ApiWatchlistTrait trait
50  $this->watchlistExpiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
51  $this->watchlistMaxDuration = $this->getConfig()->get( 'WatchlistExpiryMaxDuration' );
52  $this->watchlistManager = $watchlistManager;
53  $this->userOptionsLookup = $userOptionsLookup;
54  }
55 
59  private $mTitleObj = null;
60 
64  private $mUser = null;
65 
66  public function execute() {
68 
69  $user = $this->getUser();
70  $params = $this->extractRequestParams();
71 
72  $titleObj = $this->getRbTitle( $params );
73 
74  // If change tagging was requested, check that the user is allowed to tag,
75  // and the tags are valid. TODO: move inside rollback command?
76  if ( $params['tags'] ) {
77  $tagStatus = ChangeTags::canAddTagsAccompanyingChange( $params['tags'], $this->getAuthority() );
78  if ( !$tagStatus->isOK() ) {
79  $this->dieStatus( $tagStatus );
80  }
81  }
82 
83  // @TODO: remove this hack once rollback uses POST (T88044)
84  $fname = __METHOD__;
85  $trxLimits = $this->getConfig()->get( 'TrxProfilerLimits' );
86  $trxProfiler = Profiler::instance()->getTransactionProfiler();
87  $trxProfiler->redefineExpectations( $trxLimits['POST'], $fname );
88  DeferredUpdates::addCallableUpdate( static function () use ( $trxProfiler, $trxLimits, $fname ) {
89  $trxProfiler->redefineExpectations( $trxLimits['PostSend-POST'], $fname );
90  } );
91 
92  $rollbackResult = $this->rollbackPageFactory
93  ->newRollbackPage( $titleObj, $this->getAuthority(), $this->getRbUser( $params ) )
94  ->setSummary( $params['summary'] )
95  ->markAsBot( $params['markbot'] )
96  ->setChangeTags( $params['tags'] )
97  ->rollbackIfAllowed();
98 
99  if ( !$rollbackResult->isGood() ) {
100  $this->dieStatus( $rollbackResult );
101  }
102 
103  $watch = $params['watchlist'] ?? 'preferences';
104  $watchlistExpiry = $this->getExpiryFromParams( $params );
105 
106  // Watch pages
107  $this->setWatch( $watch, $titleObj, $user, 'watchrollback', $watchlistExpiry );
108 
109  $details = $rollbackResult->getValue();
110  $currentRevisionRecord = $details['current-revision-record'];
111  $targetRevisionRecord = $details['target-revision-record'];
112 
113  $info = [
114  'title' => $titleObj->getPrefixedText(),
115  'pageid' => $currentRevisionRecord->getPageId(),
116  'summary' => $details['summary'],
117  'revid' => (int)$details['newid'],
118  // The revision being reverted (previously the current revision of the page)
119  'old_revid' => $currentRevisionRecord->getID(),
120  // The revision being restored (the last revision before revision(s) by the reverted user)
121  'last_revid' => $targetRevisionRecord->getID()
122  ];
123 
124  $this->getResult()->addValue( null, $this->getModuleName(), $info );
125  }
126 
127  public function mustBePosted() {
128  return true;
129  }
130 
131  public function isWriteMode() {
132  return true;
133  }
134 
135  public function getAllowedParams() {
136  $params = [
137  'title' => null,
138  'pageid' => [
139  ApiBase::PARAM_TYPE => 'integer'
140  ],
141  'tags' => [
142  ApiBase::PARAM_TYPE => 'tags',
143  ApiBase::PARAM_ISMULTI => true,
144  ],
145  'user' => [
146  ApiBase::PARAM_TYPE => 'user',
147  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
148  UserDef::PARAM_RETURN_OBJECT => true,
150  ],
151  'summary' => '',
152  'markbot' => false,
153  ];
154 
155  // Params appear in the docs in the order they are defined,
156  // which is why this is here (we want it above the token param).
157  $params += $this->getWatchlistParams();
158 
159  return $params + [
160  'token' => [
161  // Standard definition automatically inserted
162  ApiBase::PARAM_HELP_MSG_APPEND => [ 'api-help-param-token-webui' ],
163  ],
164  ];
165  }
166 
167  public function needsToken() {
168  return 'rollback';
169  }
170 
176  private function getRbUser( array $params ): UserIdentity {
177  if ( $this->mUser !== null ) {
178  return $this->mUser;
179  }
180 
181  $this->mUser = $params['user'];
182 
183  return $this->mUser;
184  }
185 
191  private function getRbTitle( array $params ) {
192  if ( $this->mTitleObj !== null ) {
193  return $this->mTitleObj;
194  }
195 
196  $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
197 
198  if ( isset( $params['title'] ) ) {
199  $this->mTitleObj = Title::newFromText( $params['title'] );
200  if ( !$this->mTitleObj || $this->mTitleObj->isExternal() ) {
201  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
202  }
203  } elseif ( isset( $params['pageid'] ) ) {
204  $this->mTitleObj = Title::newFromID( $params['pageid'] );
205  if ( !$this->mTitleObj ) {
206  $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
207  }
208  }
209 
210  if ( !$this->mTitleObj->exists() ) {
211  $this->dieWithError( 'apierror-missingtitle' );
212  }
213 
214  return $this->mTitleObj;
215  }
216 
217  protected function getExamplesMessages() {
218  return [
219  'action=rollback&title=Main%20Page&user=Example&token=123ABC' =>
220  'apihelp-rollback-example-simple',
221  'action=rollback&title=Main%20Page&user=192.0.2.5&' .
222  'token=123ABC&summary=Reverting%20vandalism&markbot=1' =>
223  'apihelp-rollback-example-summary',
224  ];
225  }
226 
227  public function getHelpUrls() {
228  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Rollback';
229  }
230 }
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:49
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:72
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:383
getExpiryFromParams
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
Definition: ApiWatchlistTrait.php:164
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
Definition: ApiBase.php:78
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
ApiRollback
Definition: ApiRollback.php:32
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1379
true
return true
Definition: router.php:90
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:72
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:571
ApiRollback\$mTitleObj
Title $mTitleObj
Definition: ApiRollback.php:59
Page\RollbackPageFactory
Definition: RollbackPageFactory.php:32
ContextSource\getUser
getUser()
Definition: ContextSource.php:136
ApiBase\PARAM_HELP_MSG_APPEND
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition: ApiBase.php:112
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:55
ApiRollback\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiRollback.php:66
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:26
ApiRollback\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiRollback.php:127
ApiRollback\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiRollback.php:217
MediaWiki\Watchlist\WatchlistManager
WatchlistManager service.
Definition: WatchlistManager.php:52
ApiRollback\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiRollback.php:131
setWatch
setWatch(string $watch, Title $title, User $user, ?string $userOption=null, ?string $expiry=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
Definition: ApiWatchlistTrait.php:96
ApiRollback\getRbTitle
getRbTitle(array $params)
Definition: ApiRollback.php:191
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:707
ApiRollback\getRbUser
getRbUser(array $params)
Definition: ApiRollback.php:176
ApiRollback\$mUser
UserIdentity $mUser
Definition: ApiRollback.php:64
ApiRollback\$rollbackPageFactory
RollbackPageFactory $rollbackPageFactory
Definition: ApiRollback.php:37
ChangeTags\canAddTagsAccompanyingChange
static canAddTagsAccompanyingChange(array $tags, Authority $performer=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:625
ApiBase\requireOnlyOneParameter
requireOnlyOneParameter( $params,... $required)
Die if none or more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:844
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:144
ApiBase\useTransactionalTimeLimit
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition: ApiBase.php:1236
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1459
MediaWiki\User\UserOptionsLookup
Provides access to user options.
Definition: UserOptionsLookup.php:29
ApiWatchlistTrait
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
Definition: ApiWatchlistTrait.php:21
$watchlistManager
WatchlistManager $watchlistManager
Definition: ApiWatchlistTrait.php:30
$userOptionsLookup
UserOptionsLookup $userOptionsLookup
Definition: ApiWatchlistTrait.php:33
ApiRollback\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiRollback.php:227
Title
Represents a title within MediaWiki.
Definition: Title.php:48
ApiRollback\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiRollback.php:167
getWatchlistParams
getWatchlistParams(array $watchOptions=[])
Get additional allow params specific to watchlisting.
Definition: ApiWatchlistTrait.php:59
ApiBase\dieStatus
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:1442
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:440
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
Definition: ApiBase.php:71
ApiRollback\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiRollback.php:135
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add an update to the pending update queue that invokes the specified callback when run.
Definition: DeferredUpdates.php:145
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:529
ApiRollback\__construct
__construct(ApiMain $mainModule, $moduleName, RollbackPageFactory $rollbackPageFactory, WatchlistManager $watchlistManager, UserOptionsLookup $userOptionsLookup)
Definition: ApiRollback.php:39