MediaWiki  master
ApiBlock.php
Go to the documentation of this file.
1 <?php
39 
46 class ApiBlock extends ApiBase {
47 
50 
53 
56 
58  private $titleFactory;
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',
285  ApiBase::PARAM_ISMULTI => true,
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 
298  ApiBase::PARAM_ISMULTI => true,
301  ],
302  'namespacerestrictions' => [
303  ApiBase::PARAM_ISMULTI => true,
304  ApiBase::PARAM_TYPE => 'namespace',
305  ],
306  ];
307 
308  if ( $this->getConfig()->get( 'EnablePartialActionBlocks' ) ) {
309  $params += [
310  'actionrestrictions' => [
311  ApiBase::PARAM_ISMULTI => true,
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 }
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
MediaWiki\Block\BlockPermissionCheckerFactory
Factory class for BlockPermissionChecker.
Definition: BlockPermissionCheckerFactory.php:33
$watchlistMaxDuration
string $watchlistMaxDuration
Relative maximum expiry.
Definition: ApiWatchlistTrait.php:27
MediaWiki\Block\BlockUserFactory
Definition: BlockUserFactory.php:30
getExpiryFromParams
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
Definition: ApiWatchlistTrait.php:164
ApiBlock\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiBlock.php:326
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1379
ApiBlock\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiBlock.php:239
ApiBlock\$blockUserFactory
BlockUserFactory $blockUserFactory
Definition: ApiBlock.php:55
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:72
MediaWiki\Block\BlockUtils
Backend class for blocking utils.
Definition: BlockUtils.php:45
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:571
ApiBlock\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBlock.php:243
ApiBase\checkUserRightsAny
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:1488
ApiBase\PARAM_ISMULTI_LIMIT1
const PARAM_ISMULTI_LIMIT1
Definition: ApiBase.php:85
MediaWiki\User\UserIdentity\getId
getId( $wikiId=self::LOCAL)
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Definition: ContextSource.php:136
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
ApiBlock\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiBlock.php:322
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:55
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:26
ApiBase\PARAM_ISMULTI_LIMIT2
const PARAM_ISMULTI_LIMIT2
Definition: ApiBase.php:86
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
Definition: ApiBase.php:77
MediaWiki\Block\DatabaseBlock
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
Definition: DatabaseBlock.php:52
Wikimedia\ParamValidator\TypeDef\ExpiryDef
Type definition for expiry timestamps.
Definition: ExpiryDef.php:17
ApiBlock
API module that facilitates the blocking of users.
Definition: ApiBlock.php:46
MediaWiki\Watchlist\WatchlistManager
WatchlistManager service.
Definition: WatchlistManager.php:52
ApiBlock\$watchedItemStore
WatchedItemStoreInterface $watchedItemStore
Definition: ApiBlock.php:64
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
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:707
$title
$title
Definition: testCompression.php:38
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:650
ApiBlock\$blockUtils
BlockUtils $blockUtils
Definition: ApiBlock.php:67
ApiBlockInfoTrait
trait ApiBlockInfoTrait
Definition: ApiBlockInfoTrait.php:27
MediaWiki\User\UserIdentityLookup
Definition: UserIdentityLookup.php:33
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
ApiBlock\$blockPermissionCheckerFactory
BlockPermissionCheckerFactory $blockPermissionCheckerFactory
Definition: ApiBlock.php:52
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:144
ApiBlock\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiBlock.php:337
MediaWiki\Block\BlockActionInfo
Defines the actions that can be blocked by a partial block.
Definition: BlockActionInfo.php:40
NS_USER
const NS_USER
Definition: Defines.php:66
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
MediaWiki\Block\Restriction\NamespaceRestriction
Definition: NamespaceRestriction.php:25
$watchlistManager
WatchlistManager $watchlistManager
Definition: ApiWatchlistTrait.php:30
$userOptionsLookup
UserOptionsLookup $userOptionsLookup
Definition: ApiWatchlistTrait.php:33
getWatchlistExpiry
getWatchlistExpiry(WatchedItemStoreInterface $store, Title $title, UserIdentity $user)
Get existing expiry from the database.
Definition: ApiWatchlistTrait.php:181
Wikimedia\ParamValidator\ParamValidator::TypeDef\TitleDef
Type definition for page titles.
Definition: TitleDef.php:22
MediaWiki\Block\Restriction\PageRestriction
Definition: PageRestriction.php:25
ApiBlock\execute
execute()
Blocks the user specified in the parameters for the given expiry, with the given reason,...
Definition: ApiBlock.php:121
TitleFactory
Creates Title objects.
Definition: TitleFactory.php:35
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
ApiBlock\$blockActionInfo
BlockActionInfo $blockActionInfo
Definition: ApiBlock.php:70
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1194
MediaWiki\Block\AbstractBlock
Definition: AbstractBlock.php:37
ApiBlock\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiBlock.php:247
WatchedItemStoreInterface
Definition: WatchedItemStoreInterface.php:31
ApiBlock\__construct
__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
MediaWiki\Block\Restriction\ActionRestriction
Restriction for partial blocks of actions.
Definition: ActionRestriction.php:30
ApiBlock\$titleFactory
TitleFactory $titleFactory
Definition: ApiBlock.php:58
ApiBlock\$userIdentityLookup
UserIdentityLookup $userIdentityLookup
Definition: ApiBlock.php:61