Debian Codegraph @

includes/api/ApiBlock.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright © 2007 Roan Kattouw <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace MediaWiki\Api;
24
25 use MediaWiki\Block\AbstractBlock;
26 use MediaWiki\Block\BlockActionInfo;
27 use MediaWiki\Block\BlockPermissionCheckerFactory;
28 use MediaWiki\Block\BlockUserFactory;
29 use MediaWiki\Block\BlockUtils;
30 use MediaWiki\Block\DatabaseBlock;
31 use MediaWiki\Block\Restriction\ActionRestriction;
32 use MediaWiki\Block\Restriction\NamespaceRestriction;
33 use MediaWiki\Block\Restriction\PageRestriction;
34 use MediaWiki\MainConfigNames;
35 use MediaWiki\ParamValidator\TypeDef\TitleDef;
36 use MediaWiki\ParamValidator\TypeDef\UserDef;
37 use MediaWiki\Title\Title;
38 use MediaWiki\Title\TitleFactory;
39 use MediaWiki\User\Options\UserOptionsLookup;
40 use MediaWiki\User\UserIdentity;
41 use MediaWiki\User\UserIdentityLookup;
42 use MediaWiki\Watchlist\WatchedItemStoreInterface;
43 use MediaWiki\Watchlist\WatchlistManager;
44 use Wikimedia\ParamValidator\ParamValidator;
45 use Wikimedia\ParamValidator\TypeDef\ExpiryDef;
46
47 /**
48 * API module that facilitates the blocking of users. Requires API write mode
49 * to be enabled.
50 *
51 * @ingroup API
52 */
53 class ApiBlock extends ApiBase {
54
55 use ApiBlockInfoTrait;
56 use ApiWatchlistTrait;
57
58 private BlockPermissionCheckerFactory $blockPermissionCheckerFactory;
59 private BlockUserFactory $blockUserFactory;
60 private TitleFactory $titleFactory;
61 private UserIdentityLookup $userIdentityLookup;
62 private WatchedItemStoreInterface $watchedItemStore;
63 private BlockUtils $blockUtils;
64 private BlockActionInfo $blockActionInfo;
65
66 public function __construct(
67 ApiMain $main,
68 string $action,
69 BlockPermissionCheckerFactory $blockPermissionCheckerFactory,
70 BlockUserFactory $blockUserFactory,
71 TitleFactory $titleFactory,
72 UserIdentityLookup $userIdentityLookup,
73 WatchedItemStoreInterface $watchedItemStore,
74 BlockUtils $blockUtils,
75 BlockActionInfo $blockActionInfo,
76 WatchlistManager $watchlistManager,
77 UserOptionsLookup $userOptionsLookup
78 ) {
79 parent::__construct( $main, $action );
80
81 $this->blockPermissionCheckerFactory = $blockPermissionCheckerFactory;
82 $this->blockUserFactory = $blockUserFactory;
83 $this->titleFactory = $titleFactory;
84 $this->userIdentityLookup = $userIdentityLookup;
85 $this->watchedItemStore = $watchedItemStore;
86 $this->blockUtils = $blockUtils;
87 $this->blockActionInfo = $blockActionInfo;
88
89 // Variables needed in ApiWatchlistTrait trait
90 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
91 $this->watchlistMaxDuration =
92 $this->getConfig()->get( MainConfigNames::WatchlistExpiryMaxDuration );
93 $this->watchlistManager = $watchlistManager;
94 $this->userOptionsLookup = $userOptionsLookup;
95 }
96
97 /**
98 * Blocks the user specified in the parameters for the given expiry, with the
99 * given reason, and with all other settings provided in the params. If the block
100 * succeeds, produces a result containing the details of the block and notice
101 * of success. If it fails, the result will specify the nature of the error.
102 */
103 public function execute() {
104 $this->checkUserRightsAny( 'block' );
105 $params = $this->extractRequestParams();
106 $this->requireOnlyOneParameter( $params, 'user', 'userid' );
107
108 // Make sure $target contains a parsed target
109 if ( $params['user'] !== null ) {
110 $target = $params['user'];
111 } else {
112 $target = $this->userIdentityLookup->getUserIdentityByUserId( $params['userid'] );
113 if ( !$target ) {
114 $this->dieWithError( [ 'apierror-nosuchuserid', $params['userid'] ], 'nosuchuserid' );
115 }
116 }
117 [ $target, $targetType ] = $this->blockUtils->parseBlockTarget( $target );
118
119 if (
120 $params['noemail'] &&
121 !$this->blockPermissionCheckerFactory
122 ->newBlockPermissionChecker(
123 $target,
124 $this->getAuthority()
125 )
126 ->checkEmailPermissions()
127 ) {
128 $this->dieWithError( 'apierror-cantblock-email' );
129 }
130
131 $restrictions = [];
132 if ( $params['partial'] ) {
133 $pageRestrictions = array_map(
134 [ PageRestriction::class, 'newFromTitle' ],
135 (array)$params['pagerestrictions']
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 if ( $this->getConfig()->get( MainConfigNames::EnablePartialActionBlocks ) ) {
144 $actionRestrictions = array_map( function ( $action ) {
145 return new ActionRestriction( 0, $this->blockActionInfo->getIdFromAction( $action ) );
146 }, (array)$params['actionrestrictions'] );
147 $restrictions = array_merge( $restrictions, $actionRestrictions );
148 }
149 }
150
151 $status = $this->blockUserFactory->newBlockUser(
152 $target,
153 $this->getAuthority(),
154 $params['expiry'],
155 $params['reason'],
156 [
157 'isCreateAccountBlocked' => $params['nocreate'],
158 'isEmailBlocked' => $params['noemail'],
159 'isHardBlock' => !$params['anononly'],
160 'isAutoblocking' => $params['autoblock'],
161 'isUserTalkEditBlocked' => !$params['allowusertalk'],
162 'isHideUser' => $params['hidename'],
163 'isPartial' => $params['partial'],
164 ],
165 $restrictions,
166 $params['tags']
167 )->placeBlock( $params['reblock'] );
168
169 if ( !$status->isOK() ) {
170 $this->dieStatus( $status );
171 }
172
173 $block = $status->value;
174
175 $watchlistExpiry = $this->getExpiryFromParams( $params );
176 $userPage = Title::makeTitle( NS_USER, $block->getTargetName() );
177
178 if ( $params['watchuser'] && $targetType !== AbstractBlock::TYPE_RANGE ) {
179 $this->setWatch( 'watch', $userPage, $this->getUser(), null, $watchlistExpiry );
180 }
181
182 $res = [];
183
184 $res['user'] = $block->getTargetName();
185 $res['userID'] = $target instanceof UserIdentity ? $target->getId() : 0;
186
187 if ( $block instanceof DatabaseBlock ) {
188 $res['expiry'] = ApiResult::formatExpiry( $block->getExpiry(), 'infinite' );
189 $res['id'] = $block->getId();
190 } else {
191 # should be unreachable
192 $res['expiry'] = ''; // @codeCoverageIgnore
193 $res['id'] = ''; // @codeCoverageIgnore
194 }
195
196 $res['reason'] = $params['reason'];
197 $res['anononly'] = $params['anononly'];
198 $res['nocreate'] = $params['nocreate'];
199 $res['autoblock'] = $params['autoblock'];
200 $res['noemail'] = $params['noemail'];
201 $res['hidename'] = $block->getHideName();
202 $res['allowusertalk'] = $params['allowusertalk'];
203 $res['watchuser'] = $params['watchuser'];
204 if ( $watchlistExpiry ) {
205 $expiry = $this->getWatchlistExpiry(
206 $this->watchedItemStore,
207 $userPage,
208 $this->getUser()
209 );
210 $res['watchlistexpiry'] = $expiry;
211 }
212 $res['partial'] = $params['partial'];
213 $res['pagerestrictions'] = $params['pagerestrictions'];
214 $res['namespacerestrictions'] = $params['namespacerestrictions'];
215 if ( $this->getConfig()->get( MainConfigNames::EnablePartialActionBlocks ) ) {
216 $res['actionrestrictions'] = $params['actionrestrictions'];
217 }
218
219 $this->getResult()->addValue( null, $this->getModuleName(), $res );
220 }
221
222 public function mustBePosted() {
223 return true;
224 }
225
226 public function isWriteMode() {
227 return true;
228 }
229
230 public function getAllowedParams() {
231 $params = [
232 'user' => [
233 ParamValidator::PARAM_TYPE => 'user',
234 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'cidr', 'id' ],
235 ],
236 'userid' => [
237 ParamValidator::PARAM_TYPE => 'integer',
238 ParamValidator::PARAM_DEPRECATED => true,
239 ],
240 'expiry' => 'never',
241 'reason' => '',
242 'anononly' => false,
243 'nocreate' => false,
244 'autoblock' => false,
245 'noemail' => false,
246 'hidename' => false,
247 'allowusertalk' => false,
248 'reblock' => false,
249 'watchuser' => false,
250 ];
251
252 // Params appear in the docs in the order they are defined,
253 // which is why this is here and not at the bottom.
254 // @todo Find better way to support insertion at arbitrary position
255 if ( $this->watchlistExpiryEnabled ) {
256 $params += [
257 'watchlistexpiry' => [
258 ParamValidator::PARAM_TYPE => 'expiry',
259 ExpiryDef::PARAM_MAX => $this->watchlistMaxDuration,
260 ExpiryDef::PARAM_USE_MAX => true,
261 ]
262 ];
263 }
264
265 $params += [
266 'tags' => [
267 ParamValidator::PARAM_TYPE => 'tags',
268 ParamValidator::PARAM_ISMULTI => true,
269 ],
270 'partial' => false,
271 'pagerestrictions' => [
272 ParamValidator::PARAM_TYPE => 'title',
273 TitleDef::PARAM_MUST_EXIST => true,
274
275 // TODO: TitleDef returns instances of TitleValue when PARAM_RETURN_OBJECT is
276 // truthy. At the time of writing,
277 // MediaWiki\Block\Restriction\PageRestriction::newFromTitle accepts either
278 // string or instance of Title.
279 //TitleDef::PARAM_RETURN_OBJECT => true,
280
281 ParamValidator::PARAM_ISMULTI => true,
282 ParamValidator::PARAM_ISMULTI_LIMIT1 => 10,
283 ParamValidator::PARAM_ISMULTI_LIMIT2 => 10,
284 ],
285 'namespacerestrictions' => [
286 ParamValidator::PARAM_ISMULTI => true,
287 ParamValidator::PARAM_TYPE => 'namespace',
288 ],
289 ];
290
291 if ( $this->getConfig()->get( MainConfigNames::EnablePartialActionBlocks ) ) {
292 $params += [
293 'actionrestrictions' => [
294 ParamValidator::PARAM_ISMULTI => true,
295 ParamValidator::PARAM_TYPE => array_keys(
296 $this->blockActionInfo->getAllBlockActions()
297 ),
298 ],
299 ];
300 }
301
302 return $params;
303 }
304
305 public function needsToken() {
306 return 'csrf';
307 }
308
309 protected function getExamplesMessages() {
310 // phpcs:disable Generic.Files.LineLength
311 return [
312 'action=block&user=192.0.2.5&expiry=3%20days&reason=First%20strike&token=123ABC'
313 => 'apihelp-block-example-ip-simple',
314 'action=block&user=Vandal&expiry=never&reason=Vandalism&nocreate=&autoblock=&noemail=&token=123ABC'
315 => 'apihelp-block-example-user-complex',
316 ];
317 // phpcs:enable
318 }
319
320 public function getHelpUrls() {
321 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Block';
322 }
323 }
324
325 /** @deprecated class alias since 1.43 */
326 class_alias( ApiBlock::class, 'ApiBlock' );