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