MediaWiki  master
ApiRollback.php
Go to the documentation of this file.
1 <?php
25 
29 class ApiRollback extends ApiBase {
30 
32 
33  public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
34  parent::__construct( $mainModule, $moduleName, $modulePrefix );
35 
36  $this->watchlistExpiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
37  $this->watchlistMaxDuration = $this->getConfig()->get( 'WatchlistExpiryMaxDuration' );
38  }
39 
43  private $mTitleObj = null;
44 
48  private $mUser = null;
49 
50  public function execute() {
52 
53  $user = $this->getUser();
54  $params = $this->extractRequestParams();
55 
56  $titleObj = $this->getRbTitle( $params );
57  $pageObj = WikiPage::factory( $titleObj );
58  $summary = $params['summary'];
59  $details = [];
60 
61  // If change tagging was requested, check that the user is allowed to tag,
62  // and the tags are valid
63  if ( $params['tags'] ) {
64  $tagStatus = ChangeTags::canAddTagsAccompanyingChange( $params['tags'], $user );
65  if ( !$tagStatus->isOK() ) {
66  $this->dieStatus( $tagStatus );
67  }
68  }
69 
70  // @TODO: remove this hack once rollback uses POST (T88044)
71  $fname = __METHOD__;
72  $trxLimits = $this->getConfig()->get( 'TrxProfilerLimits' );
73  $trxProfiler = Profiler::instance()->getTransactionProfiler();
74  $trxProfiler->redefineExpectations( $trxLimits['POST'], $fname );
75  DeferredUpdates::addCallableUpdate( function () use ( $trxProfiler, $trxLimits, $fname ) {
76  $trxProfiler->redefineExpectations( $trxLimits['PostSend-POST'], $fname );
77  } );
78 
79  $retval = $pageObj->doRollback(
80  $this->getRbUser( $params )->getName(),
81  $summary,
82  $params['token'],
83  $params['markbot'],
84  $details,
85  $user,
86  $params['tags']
87  );
88 
89  if ( $retval ) {
90  $this->dieStatus( $this->errorArrayToStatus( $retval, $user ) );
91  }
92 
93  $watch = $params['watchlist'] ?? 'preferences';
94  $watchlistExpiry = $this->getExpiryFromParams( $params );
95 
96  // Watch pages
97  $this->setWatch( $watch, $titleObj, $user, 'watchrollback', $watchlistExpiry );
98 
99  $currentRevisionRecord = $details['current-revision-record'];
100  $targetRevisionRecord = $details['target-revision-record'];
101 
102  $info = [
103  'title' => $titleObj->getPrefixedText(),
104  'pageid' => $currentRevisionRecord->getPageId(),
105  'summary' => $details['summary'],
106  'revid' => (int)$details['newid'],
107  // The revision being reverted (previously the current revision of the page)
108  'old_revid' => $currentRevisionRecord->getID(),
109  // The revision being restored (the last revision before revision(s) by the reverted user)
110  'last_revid' => $targetRevisionRecord->getID()
111  ];
112 
113  $this->getResult()->addValue( null, $this->getModuleName(), $info );
114  }
115 
116  public function mustBePosted() {
117  return true;
118  }
119 
120  public function isWriteMode() {
121  return true;
122  }
123 
124  public function getAllowedParams() {
125  $params = [
126  'title' => null,
127  'pageid' => [
128  ApiBase::PARAM_TYPE => 'integer'
129  ],
130  'tags' => [
131  ApiBase::PARAM_TYPE => 'tags',
132  ApiBase::PARAM_ISMULTI => true,
133  ],
134  'user' => [
135  ApiBase::PARAM_TYPE => 'user',
136  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
137  UserDef::PARAM_RETURN_OBJECT => true,
139  ],
140  'summary' => '',
141  'markbot' => false,
142  ];
143 
144  // Params appear in the docs in the order they are defined,
145  // which is why this is here (we want it above the token param).
146  $params += $this->getWatchlistParams();
147 
148  return $params + [
149  'token' => [
150  // Standard definition automatically inserted
151  ApiBase::PARAM_HELP_MSG_APPEND => [ 'api-help-param-token-webui' ],
152  ],
153  ];
154  }
155 
156  public function needsToken() {
157  return 'rollback';
158  }
159 
165  private function getRbUser( array $params ) : UserIdentity {
166  if ( $this->mUser !== null ) {
167  return $this->mUser;
168  }
169 
170  $this->mUser = $params['user'];
171 
172  return $this->mUser;
173  }
174 
180  private function getRbTitle( array $params ) {
181  if ( $this->mTitleObj !== null ) {
182  return $this->mTitleObj;
183  }
184 
185  $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
186 
187  if ( isset( $params['title'] ) ) {
188  $this->mTitleObj = Title::newFromText( $params['title'] );
189  if ( !$this->mTitleObj || $this->mTitleObj->isExternal() ) {
190  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
191  }
192  } elseif ( isset( $params['pageid'] ) ) {
193  $this->mTitleObj = Title::newFromID( $params['pageid'] );
194  if ( !$this->mTitleObj ) {
195  $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
196  }
197  }
198 
199  if ( !$this->mTitleObj->exists() ) {
200  $this->dieWithError( 'apierror-missingtitle' );
201  }
202 
203  return $this->mTitleObj;
204  }
205 
206  protected function getExamplesMessages() {
207  return [
208  'action=rollback&title=Main%20Page&user=Example&token=123ABC' =>
209  'apihelp-rollback-example-simple',
210  'action=rollback&title=Main%20Page&user=192.0.2.5&' .
211  'token=123ABC&summary=Reverting%20vandalism&markbot=1' =>
212  'apihelp-rollback-example-summary',
213  ];
214  }
215 
216  public function getHelpUrls() {
217  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Rollback';
218  }
219 }
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:48
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:70
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:328
getExpiryFromParams
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
Definition: ApiWatchlistTrait.php:135
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:76
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
ApiRollback
Definition: ApiRollback.php:29
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1378
true
return true
Definition: router.php:90
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:70
ApiRollback\__construct
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
Stable to call.
Definition: ApiRollback.php:33
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:564
ApiRollback\$mTitleObj
Title $mTitleObj
Definition: ApiRollback.php:43
ContextSource\getUser
getUser()
Stable to override.
Definition: ContextSource.php:134
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:113
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:32
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:52
ApiRollback\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiRollback.php:50
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:25
ApiRollback\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request Stable to override.
Definition: ApiRollback.php:116
ApiRollback\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiRollback.php:206
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:160
ApiRollback\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiRollback.php:120
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:72
ApiRollback\getRbTitle
getRbTitle(array $params)
Definition: ApiRollback.php:180
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:713
ApiRollback\getRbUser
getRbUser(array $params)
Definition: ApiRollback.php:165
ApiRollback\$mUser
UserIdentity $mUser
Definition: ApiRollback.php:48
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:850
ApiBase\useTransactionalTimeLimit
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition: ApiBase.php:1235
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1494
ApiWatchlistTrait
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
Definition: ApiWatchlistTrait.php:17
ChangeTags\canAddTagsAccompanyingChange
static canAddTagsAccompanyingChange(array $tags, User $user=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:598
ApiRollback\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiRollback.php:216
Title
Represents a title within MediaWiki.
Definition: Title.php:41
ApiRollback\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiRollback.php:156
getWatchlistParams
getWatchlistParams(array $watchOptions=[])
Get additional allow params specific to watchlisting.
Definition: ApiWatchlistTrait.php:35
ApiBase\dieStatus
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:1436
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:443
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:69
ApiRollback\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiRollback.php:124
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
Definition: DeferredUpdates.php:145
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:472
ApiBase\errorArrayToStatus
errorArrayToStatus(array $errors, User $user=null)
Turn an array of message keys or key+param arrays into a Status.
Definition: ApiBase.php:1189