MediaWiki  master
ApiBlock.php
Go to the documentation of this file.
1 <?php
24 
31 class ApiBlock extends ApiBase {
32 
34 
41  public function execute() {
42  $this->checkUserRightsAny( 'block' );
43 
44  $user = $this->getUser();
45  $params = $this->extractRequestParams();
46 
47  $this->requireOnlyOneParameter( $params, 'user', 'userid' );
48 
49  # T17810: blocked admins should have limited access here
50  $block = $user->getBlock();
51  if ( $block ) {
52  $status = SpecialBlock::checkUnblockSelf( $params['user'], $user );
53  if ( $status !== true ) {
54  $this->dieWithError(
55  $status,
56  null,
57  [ 'blockinfo' => $this->getBlockDetails( $block ) ]
58  );
59  }
60  }
61 
62  $editingRestriction = 'sitewide';
63  $pageRestrictions = '';
64  $namespaceRestrictions = '';
65  if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
66  if ( $params['partial'] ) {
67  $editingRestriction = 'partial';
68  }
69 
70  $pageRestrictions = implode( "\n", (array)$params['pagerestrictions'] );
71  $namespaceRestrictions = implode( "\n", (array)$params['namespacerestrictions'] );
72  }
73 
74  if ( $params['userid'] !== null ) {
75  $username = User::whoIs( $params['userid'] );
76 
77  if ( $username === false ) {
78  $this->dieWithError( [ 'apierror-nosuchuserid', $params['userid'] ], 'nosuchuserid' );
79  } else {
80  $params['user'] = $username;
81  }
82  } else {
83  list( $target, $type ) = SpecialBlock::getTargetAndType( $params['user'] );
84 
85  // T40633 - if the target is a user (not an IP address), but it
86  // doesn't exist or is unusable, error.
87  if ( $type === DatabaseBlock::TYPE_USER &&
88  ( $target->isAnon() /* doesn't exist */ || !User::isUsableName( $params['user'] ) )
89  ) {
90  $this->dieWithError( [ 'nosuchusershort', $params['user'] ], 'nosuchuser' );
91  }
92  }
93 
94  if ( $params['tags'] ) {
95  $ableToTag = ChangeTags::canAddTagsAccompanyingChange( $params['tags'], $user );
96  if ( !$ableToTag->isOK() ) {
97  $this->dieStatus( $ableToTag );
98  }
99  }
100 
101  if ( $params['hidename'] &&
102  !$this->getPermissionManager()->userHasRight( $user, 'hideuser' ) ) {
103  $this->dieWithError( 'apierror-canthide' );
104  }
105  if ( $params['noemail'] && !SpecialBlock::canBlockEmail( $user ) ) {
106  $this->dieWithError( 'apierror-cantblock-email' );
107  }
108 
109  $data = [
110  'PreviousTarget' => $params['user'],
111  'Target' => $params['user'],
112  'Reason' => [
113  $params['reason'],
114  'other',
115  $params['reason']
116  ],
117  'Expiry' => $params['expiry'],
118  'HardBlock' => !$params['anononly'],
119  'CreateAccount' => $params['nocreate'],
120  'AutoBlock' => $params['autoblock'],
121  'DisableEmail' => $params['noemail'],
122  'HideUser' => $params['hidename'],
123  'DisableUTEdit' => !$params['allowusertalk'],
124  'Reblock' => $params['reblock'],
125  'Watch' => $params['watchuser'],
126  'Confirm' => true,
127  'Tags' => $params['tags'],
128  'EditingRestriction' => $editingRestriction,
129  'PageRestrictions' => $pageRestrictions,
130  'NamespaceRestrictions' => $namespaceRestrictions,
131  ];
132 
133  $status = SpecialBlock::validateTarget( $params['user'], $user );
134  if ( !$status->isOK() ) {
135  $this->dieStatus( $status );
136  }
137 
138  $retval = SpecialBlock::processForm( $data, $this->getContext() );
139  if ( $retval !== true ) {
140  $this->dieStatus( $this->errorArrayToStatus( $retval ) );
141  }
142 
143  $res = [];
144 
145  $res['user'] = $params['user'];
146  list( $target, /*...*/ ) = SpecialBlock::getTargetAndType( $params['user'] );
147  $res['userID'] = $target instanceof User ? $target->getId() : 0;
148 
149  $block = DatabaseBlock::newFromTarget( $target, null, true );
150  if ( $block instanceof DatabaseBlock ) {
151  $res['expiry'] = ApiResult::formatExpiry( $block->getExpiry(), 'infinite' );
152  $res['id'] = $block->getId();
153  } else {
154  # should be unreachable
155  $res['expiry'] = ''; // @codeCoverageIgnore
156  $res['id'] = ''; // @codeCoverageIgnore
157  }
158 
159  $res['reason'] = $params['reason'];
160  $res['anononly'] = $params['anononly'];
161  $res['nocreate'] = $params['nocreate'];
162  $res['autoblock'] = $params['autoblock'];
163  $res['noemail'] = $params['noemail'];
164  $res['hidename'] = $params['hidename'];
165  $res['allowusertalk'] = $params['allowusertalk'];
166  $res['watchuser'] = $params['watchuser'];
167 
168  if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
169  $res['partial'] = $params['partial'];
170  $res['pagerestrictions'] = $params['pagerestrictions'];
171  $res['namespacerestrictions'] = $params['namespacerestrictions'];
172  }
173 
174  $this->getResult()->addValue( null, $this->getModuleName(), $res );
175  }
176 
177  public function mustBePosted() {
178  return true;
179  }
180 
181  public function isWriteMode() {
182  return true;
183  }
184 
185  public function getAllowedParams() {
186  $params = [
187  'user' => [
188  ApiBase::PARAM_TYPE => 'user',
189  ],
190  'userid' => [
191  ApiBase::PARAM_TYPE => 'integer',
192  ],
193  'expiry' => 'never',
194  'reason' => '',
195  'anononly' => false,
196  'nocreate' => false,
197  'autoblock' => false,
198  'noemail' => false,
199  'hidename' => false,
200  'allowusertalk' => false,
201  'reblock' => false,
202  'watchuser' => false,
203  'tags' => [
204  ApiBase::PARAM_TYPE => 'tags',
205  ApiBase::PARAM_ISMULTI => true,
206  ],
207  ];
208 
209  if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
210  $params['partial'] = false;
211  $params['pagerestrictions'] = [
212  ApiBase::PARAM_ISMULTI => true,
215  ];
216  $params['namespacerestrictions'] = [
217  ApiBase::PARAM_ISMULTI => true,
218  ApiBase::PARAM_TYPE => 'namespace',
219  ];
220  }
221 
222  return $params;
223  }
224 
225  public function needsToken() {
226  return 'csrf';
227  }
228 
229  protected function getExamplesMessages() {
230  // phpcs:disable Generic.Files.LineLength
231  return [
232  'action=block&user=192.0.2.5&expiry=3%20days&reason=First%20strike&token=123ABC'
233  => 'apihelp-block-example-ip-simple',
234  'action=block&user=Vandal&expiry=never&reason=Vandalism&nocreate=&autoblock=&noemail=&token=123ABC'
235  => 'apihelp-block-example-user-complex',
236  ];
237  // phpcs:enable
238  }
239 
240  public function getHelpUrls() {
241  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Block';
242  }
243 }
mustBePosted()
Definition: ApiBlock.php:177
static checkUnblockSelf( $target, User $performer)
T17810: blocked admins should not be able to block/unblock others, and probably shouldn&#39;t be able to ...
needsToken()
Definition: ApiBlock.php:225
getExamplesMessages()
Definition: ApiBlock.php:229
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
static processForm(array $data, IContextSource $context)
Given the form data, actually implement a block.
static validateTarget( $value, User $user)
Validate a block target.
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:865
getResult()
Get the result object.
Definition: ApiBase.php:640
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:2078
getHelpUrls()
Definition: ApiBlock.php:240
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2006
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:761
trait ApiBlockInfoTrait
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
requireOnlyOneParameter( $params,... $required)
Die if none or more than one of a certain set of parameters is set and not false. ...
Definition: ApiBase.php:893
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
Definition: ApiBase.php:215
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1205
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
Definition: ApiBase.php:222
static getTargetAndType( $par, WebRequest $request=null)
Determine the target of the block, and the type of target.
getContext()
Get the base IContextSource object.
static canBlockEmail(UserIdentity $user)
Can we do an email block?
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
Definition: User.php:1022
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:520
errorArrayToStatus(array $errors, User $user=null)
Turn an array of message keys or key+param arrays into a Status.
Definition: ApiBase.php:1817
getAllowedParams()
Definition: ApiBlock.php:185
isWriteMode()
Definition: ApiBlock.php:181
getId()
Get the user&#39;s ID.
Definition: User.php:2254
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks...
Definition: ApiBase.php:710
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:42
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:525
API module that facilitates the blocking of users.
Definition: ApiBlock.php:31
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:2122
execute()
Blocks the user specified in the parameters for the given expiry, with the given reason, and with all other settings provided in the params.
Definition: ApiBlock.php:41