MediaWiki  master
ApiBlock.php
Go to the documentation of this file.
1 <?php
34 
41 class ApiBlock extends ApiBase {
42 
45 
48 
51 
53  private $titleFactory;
54 
56  private $userFactory;
57 
60 
62  private $blockUtils;
63 
74  public function __construct(
75  ApiMain $main,
76  $action,
83  ) {
84  parent::__construct( $main, $action );
85 
86  $this->blockPermissionCheckerFactory = $blockPermissionCheckerFactory;
87  $this->blockUserFactory = $blockUserFactory;
88  $this->titleFactory = $titleFactory;
89  $this->userFactory = $userFactory;
90  $this->watchedItemStore = $watchedItemStore;
91  $this->watchlistExpiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
92  $this->watchlistMaxDuration = $this->getConfig()->get( 'WatchlistExpiryMaxDuration' );
93  $this->blockUtils = $blockUtils;
94  }
95 
102  public function execute() {
103  $this->checkUserRightsAny( 'block' );
104  $params = $this->extractRequestParams();
105  $this->requireOnlyOneParameter( $params, 'user', 'userid' );
106 
107  // Make sure $target contains a parsed target
108  if ( $params['user'] !== null ) {
109  $target = $params['user'];
110  } else {
111  if ( User::whoIs( $params['userid'] ) === false ) {
112  $this->dieWithError( [ 'apierror-nosuchuserid', $params['userid'] ], 'nosuchuserid' );
113  }
114 
115  $target = $this->userFactory->newFromId( $params['userid'] );
116  }
117  list( $target, $targetType ) = $this->blockUtils->parseBlockTarget( $target );
118 
119  if (
120  $params['noemail'] &&
121  !$this->blockPermissionCheckerFactory
122  ->newBlockPermissionChecker(
123  $target,
124  $this->getUser()
125  )
126  ->checkEmailPermissions()
127  ) {
128  $this->dieWithError( 'apierror-cantblock-email' );
129  }
130 
131  $restrictions = [];
132  if ( $params['partial'] ) {
133  $pageRestrictions = [];
134  foreach ( (array)$params['pagerestrictions'] as $title ) {
135  $pageRestrictions[] = PageRestriction::newFromTitle( $title );
136  }
137 
138  $namespaceRestrictions = array_map( static function ( $id ) {
139  return new NamespaceRestriction( 0, $id );
140  }, (array)$params['namespacerestrictions'] );
141  $restrictions = array_merge( $pageRestrictions, $namespaceRestrictions );
142  }
143 
144  $status = $this->blockUserFactory->newBlockUser(
145  $target,
146  $this->getAuthority(),
147  $params['expiry'],
148  $params['reason'],
149  [
150  'isCreateAccountBlocked' => $params['nocreate'],
151  'isEmailBlocked' => $params['noemail'],
152  'isHardBlock' => !$params['anononly'],
153  'isAutoblocking' => $params['autoblock'],
154  'isUserTalkEditBlocked' => !$params['allowusertalk'],
155  'isHideUser' => $params['hidename'],
156  'isPartial' => $params['partial'],
157  ],
158  $restrictions,
159  $params['tags']
160  )->placeBlock( $params['reblock'] );
161 
162  if ( !$status->isOK() ) {
163  $this->dieStatus( $status );
164  }
165 
166  $watchlistExpiry = $this->getExpiryFromParams( $params );
167  $isUserObj = $target instanceof UserIdentity;
168  $userPage = $isUserObj ? $target->getUserPage() : Title::makeTitle( NS_USER, $target );
169 
170  if ( $params['watchuser'] && $targetType !== AbstractBlock::TYPE_RANGE ) {
171  $this->setWatch( 'watch', $userPage, $this->getUser(), null, $watchlistExpiry );
172  }
173 
174  $res = [];
175 
176  if ( $isUserObj ) {
177  $res['user'] = $target->getName();
178  } else {
179  $res['user'] = $target;
180  }
181  $res['userID'] = $isUserObj ? $target->getId() : 0;
182 
183  $block = DatabaseBlock::newFromTarget( $target, null, true );
184  if ( $block instanceof DatabaseBlock ) {
185  $res['expiry'] = ApiResult::formatExpiry( $block->getExpiry(), 'infinite' );
186  $res['id'] = $block->getId();
187  } else {
188  # should be unreachable
189  $res['expiry'] = ''; // @codeCoverageIgnore
190  $res['id'] = ''; // @codeCoverageIgnore
191  }
192 
193  $res['reason'] = $params['reason'];
194  $res['anononly'] = $params['anononly'];
195  $res['nocreate'] = $params['nocreate'];
196  $res['autoblock'] = $params['autoblock'];
197  $res['noemail'] = $params['noemail'];
198  $res['hidename'] = $params['hidename'];
199  $res['allowusertalk'] = $params['allowusertalk'];
200  $res['watchuser'] = $params['watchuser'];
201  if ( $watchlistExpiry ) {
202  $expiry = $this->getWatchlistExpiry(
203  $this->watchedItemStore,
204  $userPage,
205  $this->getUser()
206  );
207  $res['watchlistexpiry'] = $expiry;
208  }
209  $res['partial'] = $params['partial'];
210  $res['pagerestrictions'] = $params['pagerestrictions'];
211  $res['namespacerestrictions'] = $params['namespacerestrictions'];
212 
213  $this->getResult()->addValue( null, $this->getModuleName(), $res );
214  }
215 
216  public function mustBePosted() {
217  return true;
218  }
219 
220  public function isWriteMode() {
221  return true;
222  }
223 
224  public function getAllowedParams() {
225  $params = [
226  'user' => [
227  ApiBase::PARAM_TYPE => 'user',
228  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'cidr', 'id' ],
229  ],
230  'userid' => [
231  ApiBase::PARAM_TYPE => 'integer',
233  ],
234  'expiry' => 'never',
235  'reason' => '',
236  'anononly' => false,
237  'nocreate' => false,
238  'autoblock' => false,
239  'noemail' => false,
240  'hidename' => false,
241  'allowusertalk' => false,
242  'reblock' => false,
243  'watchuser' => false,
244  ];
245 
246  // Params appear in the docs in the order they are defined,
247  // which is why this is here and not at the bottom.
248  // @todo Find better way to support insertion at arbitrary position
249  if ( $this->watchlistExpiryEnabled ) {
250  $params += [
251  'watchlistexpiry' => [
252  ApiBase::PARAM_TYPE => 'expiry',
253  ExpiryDef::PARAM_MAX => $this->watchlistMaxDuration,
254  ExpiryDef::PARAM_USE_MAX => true,
255  ]
256  ];
257  }
258 
259  return $params + [
260  'tags' => [
261  ApiBase::PARAM_TYPE => 'tags',
262  ApiBase::PARAM_ISMULTI => true,
263  ],
264  'partial' => false,
265  'pagerestrictions' => [
266  ApiBase::PARAM_ISMULTI => true,
269  ],
270  'namespacerestrictions' => [
271  ApiBase::PARAM_ISMULTI => true,
272  ApiBase::PARAM_TYPE => 'namespace',
273  ],
274  ];
275  }
276 
277  public function needsToken() {
278  return 'csrf';
279  }
280 
281  protected function getExamplesMessages() {
282  // phpcs:disable Generic.Files.LineLength
283  return [
284  'action=block&user=192.0.2.5&expiry=3%20days&reason=First%20strike&token=123ABC'
285  => 'apihelp-block-example-ip-simple',
286  'action=block&user=Vandal&expiry=never&reason=Vandalism&nocreate=&autoblock=&noemail=&token=123ABC'
287  => 'apihelp-block-example-user-complex',
288  ];
289  // phpcs:enable
290  }
291 
292  public function getHelpUrls() {
293  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Block';
294  }
295 }
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:48
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:71
MediaWiki\Block\BlockPermissionCheckerFactory
Factory class for BlockPermissionChecker.
Definition: BlockPermissionCheckerFactory.php:34
$watchlistMaxDuration
string $watchlistMaxDuration
Relative maximum expiry.
Definition: ApiWatchlistTrait.php:24
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:140
ApiBlock\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiBlock.php:281
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1384
ApiBlock\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiBlock.php:216
ApiBlock\$blockUserFactory
BlockUserFactory $blockUserFactory
Definition: ApiBlock.php:50
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:72
MediaWiki\Block\BlockUtils
Backend class for blocking utils.
Definition: BlockUtils.php:44
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:561
ApiBlock\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBlock.php:220
ApiBase\checkUserRightsAny
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:1486
ApiBase\PARAM_ISMULTI_LIMIT1
const PARAM_ISMULTI_LIMIT1
Definition: ApiBase.php:85
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Definition: ContextSource.php:135
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:277
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:25
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:53
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:41
ApiBlock\$watchedItemStore
WatchedItemStoreInterface $watchedItemStore
Definition: ApiBlock.php:59
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:73
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:720
$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:626
ApiBlock\$blockUtils
BlockUtils $blockUtils
Definition: ApiBlock.php:62
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:857
User\whoIs
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:928
ApiBlock\$blockPermissionCheckerFactory
BlockPermissionCheckerFactory $blockPermissionCheckerFactory
Definition: ApiBlock.php:47
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:142
ApiBlock\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiBlock.php:292
NS_USER
const NS_USER
Definition: Defines.php:66
ApiWatchlistTrait
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
Definition: ApiWatchlistTrait.php:18
MediaWiki\Block\Restriction\NamespaceRestriction
Definition: NamespaceRestriction.php:25
getWatchlistExpiry
getWatchlistExpiry(WatchedItemStoreInterface $store, Title $title, UserIdentity $user)
Get existing expiry from the database.
Definition: ApiWatchlistTrait.php:157
ApiBlock\__construct
__construct(ApiMain $main, $action, BlockPermissionCheckerFactory $blockPermissionCheckerFactory, BlockUserFactory $blockUserFactory, TitleFactory $titleFactory, UserFactory $userFactory, WatchedItemStoreInterface $watchedItemStore, BlockUtils $blockUtils)
Definition: ApiBlock.php:74
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:102
TitleFactory
Creates Title objects.
Definition: TitleFactory.php:34
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
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1198
ApiBlock\$userFactory
UserFactory $userFactory
Definition: ApiBlock.php:56
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:224
WatchedItemStoreInterface
Definition: WatchedItemStoreInterface.php:30
MediaWiki\User\UserFactory
Creates User objects.
Definition: UserFactory.php:41
ApiBlock\$titleFactory
TitleFactory $titleFactory
Definition: ApiBlock.php:53