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