MediaWiki  1.29.1
ApiBlock.php
Go to the documentation of this file.
1 <?php
33 class ApiBlock extends ApiBase {
34 
41  public function execute() {
42  $this->checkUserRightsAny( 'block' );
43 
44  $user = $this->getUser();
45  $params = $this->extractRequestParams();
46 
47  $this->requireOnlyOneParameter( $params, 'user', 'userid' );
48 
49  # T17810: blocked admins should have limited access here
50  if ( $user->isBlocked() ) {
52  if ( $status !== true ) {
53  $this->dieWithError(
54  $status,
55  null,
56  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
57  );
58  }
59  }
60 
61  if ( $params['userid'] !== null ) {
62  $username = User::whoIs( $params['userid'] );
63 
64  if ( $username === false ) {
65  $this->dieWithError( [ 'apierror-nosuchuserid', $params['userid'] ], 'nosuchuserid' );
66  } else {
67  $params['user'] = $username;
68  }
69  } else {
70  $target = User::newFromName( $params['user'] );
71 
72  // T40633 - if the target is a user (not an IP address), but it
73  // doesn't exist or is unusable, error.
74  if ( $target instanceof User &&
75  ( $target->isAnon() /* doesn't exist */ || !User::isUsableName( $target->getName() ) )
76  ) {
77  $this->dieWithError( [ 'nosuchusershort', $params['user'] ], 'nosuchuser' );
78  }
79  }
80 
81  if ( $params['tags'] ) {
83  if ( !$ableToTag->isOK() ) {
84  $this->dieStatus( $ableToTag );
85  }
86  }
87 
88  if ( $params['hidename'] && !$user->isAllowed( 'hideuser' ) ) {
89  $this->dieWithError( 'apierror-canthide' );
90  }
91  if ( $params['noemail'] && !SpecialBlock::canBlockEmail( $user ) ) {
92  $this->dieWithError( 'apierror-cantblock-email' );
93  }
94 
95  $data = [
96  'PreviousTarget' => $params['user'],
97  'Target' => $params['user'],
98  'Reason' => [
99  $params['reason'],
100  'other',
101  $params['reason']
102  ],
103  'Expiry' => $params['expiry'],
104  'HardBlock' => !$params['anononly'],
105  'CreateAccount' => $params['nocreate'],
106  'AutoBlock' => $params['autoblock'],
107  'DisableEmail' => $params['noemail'],
108  'HideUser' => $params['hidename'],
109  'DisableUTEdit' => !$params['allowusertalk'],
110  'Reblock' => $params['reblock'],
111  'Watch' => $params['watchuser'],
112  'Confirm' => true,
113  'Tags' => $params['tags'],
114  ];
115 
116  $retval = SpecialBlock::processForm( $data, $this->getContext() );
117  if ( $retval !== true ) {
118  $this->dieStatus( $this->errorArrayToStatus( $retval ) );
119  }
120 
121  list( $target, /*...*/ ) = SpecialBlock::getTargetAndType( $params['user'] );
122  $res['user'] = $params['user'];
123  $res['userID'] = $target instanceof User ? $target->getId() : 0;
124 
125  $block = Block::newFromTarget( $target, null, true );
126  if ( $block instanceof Block ) {
127  $res['expiry'] = ApiResult::formatExpiry( $block->mExpiry, 'infinite' );
128  $res['id'] = $block->getId();
129  } else {
130  # should be unreachable
131  $res['expiry'] = '';
132  $res['id'] = '';
133  }
134 
135  $res['reason'] = $params['reason'];
136  $res['anononly'] = $params['anononly'];
137  $res['nocreate'] = $params['nocreate'];
138  $res['autoblock'] = $params['autoblock'];
139  $res['noemail'] = $params['noemail'];
140  $res['hidename'] = $params['hidename'];
141  $res['allowusertalk'] = $params['allowusertalk'];
142  $res['watchuser'] = $params['watchuser'];
143 
144  $this->getResult()->addValue( null, $this->getModuleName(), $res );
145  }
146 
147  public function mustBePosted() {
148  return true;
149  }
150 
151  public function isWriteMode() {
152  return true;
153  }
154 
155  public function getAllowedParams() {
156  return [
157  'user' => [
158  ApiBase::PARAM_TYPE => 'user',
159  ],
160  'userid' => [
161  ApiBase::PARAM_TYPE => 'integer',
162  ],
163  'expiry' => 'never',
164  'reason' => '',
165  'anononly' => false,
166  'nocreate' => false,
167  'autoblock' => false,
168  'noemail' => false,
169  'hidename' => false,
170  'allowusertalk' => false,
171  'reblock' => false,
172  'watchuser' => false,
173  'tags' => [
174  ApiBase::PARAM_TYPE => 'tags',
175  ApiBase::PARAM_ISMULTI => true,
176  ],
177  ];
178  }
179 
180  public function needsToken() {
181  return 'csrf';
182  }
183 
184  protected function getExamplesMessages() {
185  // @codingStandardsIgnoreStart Generic.Files.LineLength
186  return [
187  'action=block&user=192.0.2.5&expiry=3%20days&reason=First%20strike&token=123ABC'
188  => 'apihelp-block-example-ip-simple',
189  'action=block&user=Vandal&expiry=never&reason=Vandalism&nocreate=&autoblock=&noemail=&token=123ABC'
190  => 'apihelp-block-example-user-complex',
191  ];
192  // @codingStandardsIgnoreEnd
193  }
194 
195  public function getHelpUrls() {
196  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Block';
197  }
198 }
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:41
User\getId
getId()
Get the user's ID.
Definition: User.php:2200
ApiBlock\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiBlock.php:184
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1796
SpecialBlock\processForm
static processForm(array $data, IContextSource $context)
Given the form data, actually implement a block.
Definition: SpecialBlock.php:620
SpecialBlock\canBlockEmail
static canBlockEmail( $user)
Can we do an email block?
Definition: SpecialBlock.php:898
ApiBlock\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiBlock.php:147
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:91
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:610
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
ApiBlock\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBlock.php:151
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
ApiBase\checkUserRightsAny
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:1890
$params
$params
Definition: styleTest.css.php:40
Block\newFromTarget
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target's type, get an existing Block object if possible.
Definition: Block.php:1113
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:556
$res
$res
Definition: database.txt:21
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
ApiBlock\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiBlock.php:180
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:41
ApiBlock
API module that facilitates the blocking of users.
Definition: ApiBlock.php:33
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:718
User\whoIs
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:739
$retval
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account incomplete not yet checked for validity & $retval
Definition: hooks.txt:246
ApiBlock\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiBlock.php:195
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:754
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:395
ApiBlock\execute
execute()
Blocks the user specified in the parameters for the given expiry, with the given reason,...
Definition: ApiBlock.php:41
Block
Definition: Block.php:27
ApiBase\dieStatus
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:1861
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:490
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:55
SpecialBlock\checkUnblockSelf
static checkUnblockSelf( $user, User $performer)
T17810: blocked admins should not be able to block/unblock others, and probably shouldn't be able to ...
Definition: SpecialBlock.php:912
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1207
SpecialBlock\getTargetAndType
static getTargetAndType( $par, WebRequest $request=null)
Determine the target of the block, and the type of target.
Definition: SpecialBlock.php:489
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:884
ApiBlock\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiBlock.php:155
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:783
ApiBase\errorArrayToStatus
errorArrayToStatus(array $errors, User $user=null)
Turn an array of message keys or key+param arrays into a Status.
Definition: ApiBase.php:1667
ApiQueryUserInfo\getBlockInfo
static getBlockInfo(Block $block)
Get basic info about a given block.
Definition: ApiQueryUserInfo.php:69