MediaWiki REL1_37
ApiBlock.php
Go to the documentation of this file.
1<?php
39
46class ApiBlock extends ApiBase {
47
50
53
56
59
62
65
67 private $blockUtils;
68
71
85 public function __construct(
86 ApiMain $main,
87 $action,
97 ) {
98 parent::__construct( $main, $action );
99
100 $this->blockPermissionCheckerFactory = $blockPermissionCheckerFactory;
101 $this->blockUserFactory = $blockUserFactory;
102 $this->titleFactory = $titleFactory;
103 $this->userIdentityLookup = $userIdentityLookup;
104 $this->watchedItemStore = $watchedItemStore;
105 $this->blockUtils = $blockUtils;
106 $this->blockActionInfo = $blockActionInfo;
107
108 // Variables needed in ApiWatchlistTrait trait
109 $this->watchlistExpiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
110 $this->watchlistMaxDuration = $this->getConfig()->get( 'WatchlistExpiryMaxDuration' );
111 $this->watchlistManager = $watchlistManager;
112 $this->userOptionsLookup = $userOptionsLookup;
113 }
114
121 public function execute() {
122 $this->checkUserRightsAny( 'block' );
123 $params = $this->extractRequestParams();
124 $this->requireOnlyOneParameter( $params, 'user', 'userid' );
125
126 // Make sure $target contains a parsed target
127 if ( $params['user'] !== null ) {
128 $target = $params['user'];
129 } else {
130 $target = $this->userIdentityLookup->getUserIdentityByUserId( $params['userid'] );
131 if ( !$target ) {
132 $this->dieWithError( [ 'apierror-nosuchuserid', $params['userid'] ], 'nosuchuserid' );
133 }
134 }
135 list( $target, $targetType ) = $this->blockUtils->parseBlockTarget( $target );
136
137 if (
138 $params['noemail'] &&
139 !$this->blockPermissionCheckerFactory
140 ->newBlockPermissionChecker(
141 $target,
142 $this->getUser()
143 )
144 ->checkEmailPermissions()
145 ) {
146 $this->dieWithError( 'apierror-cantblock-email' );
147 }
148
149 $restrictions = [];
150 if ( $params['partial'] ) {
151 $pageRestrictions = array_map( static function ( $title ) {
152 return PageRestriction::newFromTitle( $title );
153 }, (array)$params['pagerestrictions'] );
154
155 $namespaceRestrictions = array_map( static function ( $id ) {
156 return new NamespaceRestriction( 0, $id );
157 }, (array)$params['namespacerestrictions'] );
158 $restrictions = array_merge( $pageRestrictions, $namespaceRestrictions );
159
160 if ( $this->getConfig()->get( 'EnablePartialActionBlocks' ) ) {
161 $actionRestrictions = array_map( function ( $action ) {
162 return new ActionRestriction( 0, $this->blockActionInfo->getIdFromAction( $action ) );
163 }, (array)$params['actionrestrictions'] );
164 $restrictions = array_merge( $restrictions, $actionRestrictions );
165 }
166 }
167
168 $status = $this->blockUserFactory->newBlockUser(
169 $target,
170 $this->getAuthority(),
171 $params['expiry'],
172 $params['reason'],
173 [
174 'isCreateAccountBlocked' => $params['nocreate'],
175 'isEmailBlocked' => $params['noemail'],
176 'isHardBlock' => !$params['anononly'],
177 'isAutoblocking' => $params['autoblock'],
178 'isUserTalkEditBlocked' => !$params['allowusertalk'],
179 'isHideUser' => $params['hidename'],
180 'isPartial' => $params['partial'],
181 ],
182 $restrictions,
183 $params['tags']
184 )->placeBlock( $params['reblock'] );
185
186 if ( !$status->isOK() ) {
187 $this->dieStatus( $status );
188 }
189
190 $block = $status->value;
191
192 $watchlistExpiry = $this->getExpiryFromParams( $params );
193 $userPage = Title::makeTitle( NS_USER, $block->getTargetName() );
194
195 if ( $params['watchuser'] && $targetType !== AbstractBlock::TYPE_RANGE ) {
196 $this->setWatch( 'watch', $userPage, $this->getUser(), null, $watchlistExpiry );
197 }
198
199 $res = [];
200
201 $res['user'] = $block->getTargetName();
202 $res['userID'] = $target instanceof UserIdentity ? $target->getId() : 0;
203
204 if ( $block instanceof DatabaseBlock ) {
205 $res['expiry'] = ApiResult::formatExpiry( $block->getExpiry(), 'infinite' );
206 $res['id'] = $block->getId();
207 } else {
208 # should be unreachable
209 $res['expiry'] = ''; // @codeCoverageIgnore
210 $res['id'] = ''; // @codeCoverageIgnore
211 }
212
213 $res['reason'] = $params['reason'];
214 $res['anononly'] = $params['anononly'];
215 $res['nocreate'] = $params['nocreate'];
216 $res['autoblock'] = $params['autoblock'];
217 $res['noemail'] = $params['noemail'];
218 $res['hidename'] = $params['hidename'];
219 $res['allowusertalk'] = $params['allowusertalk'];
220 $res['watchuser'] = $params['watchuser'];
221 if ( $watchlistExpiry ) {
222 $expiry = $this->getWatchlistExpiry(
223 $this->watchedItemStore,
224 $userPage,
225 $this->getUser()
226 );
227 $res['watchlistexpiry'] = $expiry;
228 }
229 $res['partial'] = $params['partial'];
230 $res['pagerestrictions'] = $params['pagerestrictions'];
231 $res['namespacerestrictions'] = $params['namespacerestrictions'];
232 if ( $this->getConfig()->get( 'EnablePartialActionBlocks' ) ) {
233 $res['actionrestrictions'] = $params['actionrestrictions'];
234 }
235
236 $this->getResult()->addValue( null, $this->getModuleName(), $res );
237 }
238
239 public function mustBePosted() {
240 return true;
241 }
242
243 public function isWriteMode() {
244 return true;
245 }
246
247 public function getAllowedParams() {
248 $params = [
249 'user' => [
250 ApiBase::PARAM_TYPE => 'user',
251 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'cidr', 'id' ],
252 ],
253 'userid' => [
254 ApiBase::PARAM_TYPE => 'integer',
256 ],
257 'expiry' => 'never',
258 'reason' => '',
259 'anononly' => false,
260 'nocreate' => false,
261 'autoblock' => false,
262 'noemail' => false,
263 'hidename' => false,
264 'allowusertalk' => false,
265 'reblock' => false,
266 'watchuser' => false,
267 ];
268
269 // Params appear in the docs in the order they are defined,
270 // which is why this is here and not at the bottom.
271 // @todo Find better way to support insertion at arbitrary position
272 if ( $this->watchlistExpiryEnabled ) {
273 $params += [
274 'watchlistexpiry' => [
275 ApiBase::PARAM_TYPE => 'expiry',
276 ExpiryDef::PARAM_MAX => $this->watchlistMaxDuration,
277 ExpiryDef::PARAM_USE_MAX => true,
278 ]
279 ];
280 }
281
282 $params += [
283 'tags' => [
284 ApiBase::PARAM_TYPE => 'tags',
286 ],
287 'partial' => false,
288 'pagerestrictions' => [
289 ApiBase::PARAM_TYPE => 'title',
290 TitleDef::PARAM_MUST_EXIST => true,
291
292 // TODO: TitleDef returns instances of TitleValue when PARAM_RETURN_OBJECT is
293 // truthy. At the time of writing,
294 // MediaWiki\Block\Restriction\PageRestriction::newFromTitle accepts either
295 // string or instance of Title.
296 //TitleDef::PARAM_RETURN_OBJECT => true,
297
301 ],
302 'namespacerestrictions' => [
304 ApiBase::PARAM_TYPE => 'namespace',
305 ],
306 ];
307
308 if ( $this->getConfig()->get( 'EnablePartialActionBlocks' ) ) {
309 $params += [
310 'actionrestrictions' => [
312 ApiBase::PARAM_TYPE => array_keys(
313 $this->blockActionInfo->getAllBlockActions()
314 ),
315 ],
316 ];
317 }
318
319 return $params;
320 }
321
322 public function needsToken() {
323 return 'csrf';
324 }
325
326 protected function getExamplesMessages() {
327 // phpcs:disable Generic.Files.LineLength
328 return [
329 'action=block&user=192.0.2.5&expiry=3%20days&reason=First%20strike&token=123ABC'
330 => 'apihelp-block-example-ip-simple',
331 'action=block&user=Vandal&expiry=never&reason=Vandalism&nocreate=&autoblock=&noemail=&token=123ABC'
332 => 'apihelp-block-example-user-complex',
333 ];
334 // phpcs:enable
335 }
336
337 public function getHelpUrls() {
338 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Block';
339 }
340}
string $watchlistMaxDuration
Relative maximum expiry.
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
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.
getWatchlistExpiry(WatchedItemStoreInterface $store, Title $title, UserIdentity $user)
Get existing expiry from the database.
WatchlistManager $watchlistManager
UserOptionsLookup $userOptionsLookup
const NS_USER
Definition Defines.php:66
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:55
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1436
const PARAM_DEPRECATED
Definition ApiBase.php:101
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition ApiBase.php:1539
const PARAM_ISMULTI_LIMIT1
Definition ApiBase.php:133
const PARAM_TYPE
Definition ApiBase.php:81
requireOnlyOneParameter( $params,... $required)
Die if none or more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:901
const PARAM_ISMULTI_LIMIT2
Definition ApiBase.php:137
getResult()
Get the result object.
Definition ApiBase.php:628
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:764
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:497
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1495
const PARAM_ISMULTI
Definition ApiBase.php:77
API module that facilitates the blocking of users.
Definition ApiBlock.php:46
BlockUtils $blockUtils
Definition ApiBlock.php:67
needsToken()
Returns the token type this module requires in order to execute.
Definition ApiBlock.php:322
getExamplesMessages()
Returns usage examples for this module.
Definition ApiBlock.php:326
BlockUserFactory $blockUserFactory
Definition ApiBlock.php:55
isWriteMode()
Indicates whether this module requires write mode.
Definition ApiBlock.php:243
BlockPermissionCheckerFactory $blockPermissionCheckerFactory
Definition ApiBlock.php:52
__construct(ApiMain $main, $action, BlockPermissionCheckerFactory $blockPermissionCheckerFactory, BlockUserFactory $blockUserFactory, TitleFactory $titleFactory, UserIdentityLookup $userIdentityLookup, WatchedItemStoreInterface $watchedItemStore, BlockUtils $blockUtils, BlockActionInfo $blockActionInfo, WatchlistManager $watchlistManager, UserOptionsLookup $userOptionsLookup)
Definition ApiBlock.php:85
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition ApiBlock.php:239
WatchedItemStoreInterface $watchedItemStore
Definition ApiBlock.php:64
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition ApiBlock.php:247
execute()
Blocks the user specified in the parameters for the given expiry, with the given reason,...
Definition ApiBlock.php:121
UserIdentityLookup $userIdentityLookup
Definition ApiBlock.php:61
getHelpUrls()
Return links to more detailed help pages about the module.
Definition ApiBlock.php:337
TitleFactory $titleFactory
Definition ApiBlock.php:58
BlockActionInfo $blockActionInfo
Definition ApiBlock.php:70
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:49
Defines the actions that can be blocked by a partial block.
Backend class for blocking utils.
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
Restriction for partial blocks of actions.
Type definition for page titles.
Definition TitleDef.php:22
Type definition for user types.
Definition UserDef.php:25
Provides access to user options.
Creates Title objects.
Type definition for expiry timestamps.
Definition ExpiryDef.php:17
trait ApiBlockInfoTrait
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
Interface for objects representing user identity.
getId( $wikiId=self::LOCAL)