Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.75% covered (success)
91.75%
189 / 206
69.23% covered (warning)
69.23%
9 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiBlock
92.20% covered (success)
92.20%
189 / 205
69.23% covered (warning)
69.23%
9 / 13
37.65
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 execute
97.56% covered (success)
97.56%
80 / 82
0.00% covered (danger)
0.00%
0 / 1
19
 getBlockOptions
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 getRestrictions
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 checkEmailPermissions
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 updateBlock
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 insertBlock
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 mustBePosted
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isWriteMode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getAllowedParams
87.72% covered (warning)
87.72%
50 / 57
0.00% covered (danger)
0.00%
0 / 1
3.02
 needsToken
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Copyright © 2007 Roan Kattouw <roan.kattouw@gmail.com>
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Api;
10
11use MediaWiki\Block\AbstractBlock;
12use MediaWiki\Block\BlockActionInfo;
13use MediaWiki\Block\BlockPermissionCheckerFactory;
14use MediaWiki\Block\BlockTarget;
15use MediaWiki\Block\BlockTargetFactory;
16use MediaWiki\Block\BlockUser;
17use MediaWiki\Block\BlockUserFactory;
18use MediaWiki\Block\DatabaseBlock;
19use MediaWiki\Block\DatabaseBlockStore;
20use MediaWiki\Block\Restriction\ActionRestriction;
21use MediaWiki\Block\Restriction\NamespaceRestriction;
22use MediaWiki\Block\Restriction\PageRestriction;
23use MediaWiki\Block\Restriction\Restriction;
24use MediaWiki\MainConfigNames;
25use MediaWiki\ParamValidator\TypeDef\TitleDef;
26use MediaWiki\ParamValidator\TypeDef\UserDef;
27use MediaWiki\Status\Status;
28use MediaWiki\Title\Title;
29use MediaWiki\User\Options\UserOptionsLookup;
30use MediaWiki\User\UserIdentityLookup;
31use MediaWiki\Watchlist\WatchedItemStoreInterface;
32use MediaWiki\Watchlist\WatchlistManager;
33use RuntimeException;
34use Wikimedia\ParamValidator\ParamValidator;
35use Wikimedia\ParamValidator\TypeDef\ExpiryDef;
36use Wikimedia\Timestamp\TimestampFormat as TS;
37
38/**
39 * API module that facilitates the blocking of users. Requires API write mode
40 * to be enabled.
41 *
42 * @ingroup API
43 */
44class ApiBlock extends ApiBase {
45
46    use ApiWatchlistTrait;
47
48    public function __construct(
49        ApiMain $main,
50        string $action,
51        private readonly BlockPermissionCheckerFactory $blockPermissionCheckerFactory,
52        private readonly BlockUserFactory $blockUserFactory,
53        private readonly UserIdentityLookup $userIdentityLookup,
54        WatchedItemStoreInterface $watchedItemStore,
55        private readonly BlockTargetFactory $blockTargetFactory,
56        private readonly BlockActionInfo $blockActionInfo,
57        private readonly DatabaseBlockStore $blockStore,
58        WatchlistManager $watchlistManager,
59        UserOptionsLookup $userOptionsLookup,
60    ) {
61        parent::__construct( $main, $action );
62
63        $this->watchedItemStore = $watchedItemStore;
64
65        // Variables needed in ApiWatchlistTrait trait
66        $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
67        $this->watchlistMaxDuration =
68            $this->getConfig()->get( MainConfigNames::WatchlistExpiryMaxDuration );
69        $this->watchlistManager = $watchlistManager;
70        $this->userOptionsLookup = $userOptionsLookup;
71    }
72
73    /**
74     * Blocks the user specified in the parameters for the given expiry, with the
75     * given reason, and with all other settings provided in the params. If the block
76     * succeeds, produces a result containing the details of the block and notice
77     * of success. If it fails, the result will specify the nature of the error.
78     */
79    public function execute() {
80        $this->checkUserRightsAny( 'block' );
81        $params = $this->extractRequestParams();
82        $this->requireOnlyOneParameter( $params, 'id', 'user', 'userid' );
83        $this->requireMaxOneParameter( $params, 'newblock', 'reblock' );
84        $this->requireNoConflictingParameters( $params,
85            'id', [ 'newblock', 'reblock' ] );
86
87        $additionalBlocksStatuses = [];
88        if ( $params['id'] !== null ) {
89            $block = $this->blockStore->newFromID( $params['id'], true );
90            if ( !$block ) {
91                $this->dieWithError(
92                    [ 'apierror-nosuchblockid', $params['id'] ],
93                    'nosuchblockid' );
94            }
95            if ( $block->getType() === AbstractBlock::TYPE_AUTO ) {
96                $this->dieWithError( 'apierror-modify-autoblock' );
97            }
98            $status = $this->updateBlock( $block, $params );
99        } else {
100            if ( $params['user'] !== null ) {
101                $target = $this->blockTargetFactory->newFromUser( $params['user'] );
102            } else {
103                $targetUser = $this->userIdentityLookup->getUserIdentityByUserId( $params['userid'] );
104                if ( !$targetUser ) {
105                    $this->dieWithError( [ 'apierror-nosuchuserid', $params['userid'] ], 'nosuchuserid' );
106                }
107                $target = $this->blockTargetFactory->newUserBlockTarget( $targetUser );
108            }
109            if ( $params['newblock'] ) {
110                $status = $this->insertBlock( $target, $params );
111
112                // Don't allow post-processing if the base block fails
113                if ( !$status->isOK() ) {
114                    $this->dieStatus( $status );
115                }
116
117                // Only support additional blocks if multiblocks are enabled
118                if ( $this->getConfig()->get( MainConfigNames::EnableMultiBlocks ) ) {
119                    $targetUserIdentity = $this->userIdentityLookup->getUserIdentityByName( $target->toString() );
120                    if ( $targetUserIdentity ) {
121                        $this->getHookRunner()->onApiBlockSucceeded(
122                            $this,
123                            $this->getAuthority(),
124                            $targetUserIdentity,
125                            $params,
126                            $additionalBlocksStatuses
127                        );
128                    }
129                }
130            } else {
131                $blocks = $this->blockStore->newListFromTarget(
132                    $target, null, false, DatabaseBlockStore::AUTO_NONE );
133                if ( count( $blocks ) === 0 ) {
134                    $status = $this->insertBlock( $target, $params );
135                } elseif ( count( $blocks ) === 1 ) {
136                    if ( $params['reblock'] ) {
137                        $status = $this->updateBlock( $blocks[0], $params );
138                    } else {
139                        $status = Status::newFatal( 'ipb_already_blocked', $blocks[0]->getTargetName() );
140                    }
141                } else {
142                    $this->dieWithError( 'apierror-ambiguous-block', 'ambiguous-block' );
143                }
144            }
145        }
146
147        if ( !$status->isOK() ) {
148            $this->dieStatus( $status );
149        }
150
151        $block = $status->value;
152        if ( !( $block instanceof DatabaseBlock ) ) {
153            throw new RuntimeException( "Unexpected block class" );
154        }
155
156        $userPage = Title::makeTitle( NS_USER, $block->getTargetName() );
157        $watchlistExpiry = $this->getExpiryFromParams( $params, $userPage, $this->getUser() );
158
159        if ( $params['watchuser'] && $block->getType() !== AbstractBlock::TYPE_RANGE ) {
160            $this->setWatch( 'watch', $userPage, $this->getUser(), null, $watchlistExpiry );
161        }
162
163        $res = [];
164
165        $res['user'] = $block->getTargetName();
166
167        $blockedUser = $block->getTargetUserIdentity();
168        $res['userID'] = $blockedUser ? $blockedUser->getId() : 0;
169
170        $res['timestamp'] = wfTimestamp( TS::ISO_8601, $block->getTimestamp() );
171        $res['expiry'] = ApiResult::formatExpiry( $block->getExpiry(), 'infinite' );
172        $res['id'] = $block->getId();
173
174        $res['reason'] = $params['reason'];
175        $res['anononly'] = $params['anononly'];
176        $res['nocreate'] = $params['nocreate'];
177        $res['autoblock'] = $params['autoblock'];
178        $res['noemail'] = $params['noemail'];
179        $res['hidename'] = $block->getHideName();
180        $res['allowusertalk'] = $params['allowusertalk'];
181        $res['watchuser'] = $params['watchuser'];
182        if ( $watchlistExpiry ) {
183            $expiry = $this->getWatchlistExpiry(
184                $this->watchedItemStore,
185                $userPage,
186                $this->getUser()
187            );
188            $res['watchlistexpiry'] = $expiry;
189        }
190        $res['partial'] = $params['partial'];
191        $res['pagerestrictions'] = $params['pagerestrictions'];
192        $res['namespacerestrictions'] = $params['namespacerestrictions'];
193        $res['actionrestrictions'] = $params['actionrestrictions'];
194        $res['additionalBlocksStatuses'] = $additionalBlocksStatuses;
195
196        $this->getResult()->addValue( null, $this->getModuleName(), $res );
197    }
198
199    /**
200     * Get the block options to be used for an insert or update
201     *
202     * @param array $params
203     * @return array
204     */
205    private function getBlockOptions( $params ) {
206        return [
207            'isCreateAccountBlocked' => $params['nocreate'],
208            'isEmailBlocked' => $params['noemail'],
209            'isHardBlock' => !$params['anononly'],
210            'isAutoblocking' => $params['autoblock'],
211            'isUserTalkEditBlocked' => !$params['allowusertalk'],
212            'isHideUser' => $params['hidename'],
213            'isPartial' => $params['partial'],
214        ];
215    }
216
217    /**
218     * Get the new block restrictions
219     * @param array $params
220     * @return Restriction[]
221     */
222    private function getRestrictions( $params ) {
223        $restrictions = [];
224        if ( $params['partial'] ) {
225            $pageRestrictions = array_map(
226                PageRestriction::newFromTitle( ... ),
227                (array)$params['pagerestrictions']
228            );
229
230            $namespaceRestrictions = array_map( static function ( $id ) {
231                return new NamespaceRestriction( 0, $id );
232            }, (array)$params['namespacerestrictions'] );
233            $restrictions = array_merge( $pageRestrictions, $namespaceRestrictions );
234
235            $actionRestrictions = array_map( function ( $action ) {
236                return new ActionRestriction( 0, $this->blockActionInfo->getIdFromAction( $action ) );
237            }, (array)$params['actionrestrictions'] );
238            $restrictions = array_merge( $restrictions, $actionRestrictions );
239        }
240        return $restrictions;
241    }
242
243    /**
244     * Exit with an error if the user wants to block user-to-user email but is not allowed.
245     *
246     * @param array $params
247     */
248    private function checkEmailPermissions( $params ) {
249        if (
250            $params['noemail'] &&
251            !$this->blockPermissionCheckerFactory
252                ->newChecker( $this->getAuthority() )
253                ->checkEmailPermissions()
254        ) {
255            $this->dieWithError( 'apierror-cantblock-email' );
256        }
257    }
258
259    /**
260     * Update a block
261     *
262     * @param DatabaseBlock $block
263     * @param array $params
264     * @return Status
265     */
266    private function updateBlock( DatabaseBlock $block, $params ) {
267        $this->checkEmailPermissions( $params );
268        return $this->blockUserFactory->newUpdateBlock(
269            $block,
270            $this->getAuthority(),
271            $params['expiry'],
272            $params['reason'],
273            $this->getBlockOptions( $params ),
274            $this->getRestrictions( $params ),
275            $params['tags']
276        )->placeBlock();
277    }
278
279    /**
280     * Insert a block
281     *
282     * @param BlockTarget $target
283     * @param array $params
284     * @return Status
285     */
286    public function insertBlock( $target, $params ) {
287        $this->checkEmailPermissions( $params );
288        return $this->blockUserFactory->newBlockUser(
289            $target,
290            $this->getAuthority(),
291            $params['expiry'],
292            $params['reason'],
293            $this->getBlockOptions( $params ),
294            $this->getRestrictions( $params ),
295            $params['tags']
296        )->placeBlock( $params['newblock'] ? BlockUser::CONFLICT_NEW : BlockUser::CONFLICT_FAIL );
297    }
298
299    /** @inheritDoc */
300    public function mustBePosted() {
301        return true;
302    }
303
304    /** @inheritDoc */
305    public function isWriteMode() {
306        return true;
307    }
308
309    /** @inheritDoc */
310    public function getAllowedParams() {
311        $params = [
312            'id' => [ ParamValidator::PARAM_TYPE => 'integer' ],
313            'user' => [
314                ParamValidator::PARAM_TYPE => 'user',
315                UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'cidr', 'id' ],
316                UserDef::PARAM_RETURN_OBJECT => true,
317            ],
318            'userid' => [
319                ParamValidator::PARAM_TYPE => 'integer',
320                ParamValidator::PARAM_DEPRECATED => true,
321            ],
322            'expiry' => 'never',
323            'reason' => '',
324            'anononly' => false,
325            'nocreate' => false,
326            'autoblock' => false,
327            'noemail' => false,
328            'hidename' => false,
329            'allowusertalk' => false,
330            'reblock' => false,
331            'newblock' => false,
332            'watchuser' => false,
333        ];
334
335        // Params appear in the docs in the order they are defined,
336        // which is why this is here and not at the bottom.
337        if ( $this->watchlistExpiryEnabled ) {
338            $params += [
339                'watchlistexpiry' => [
340                    ParamValidator::PARAM_TYPE => 'expiry',
341                    ExpiryDef::PARAM_MAX => $this->watchlistMaxDuration,
342                    ExpiryDef::PARAM_USE_MAX => true,
343                ]
344            ];
345        }
346
347        $pageLimit = $this->getConfig()->get( MainConfigNames::EnableMultiBlocks ) ? 50 : 10;
348
349        $params += [
350            'tags' => [
351                ParamValidator::PARAM_TYPE => 'tags',
352                ParamValidator::PARAM_ISMULTI => true,
353            ],
354            'partial' => false,
355            'pagerestrictions' => [
356                ParamValidator::PARAM_TYPE => 'title',
357                TitleDef::PARAM_MUST_EXIST => true,
358
359                // TODO: TitleDef returns instances of TitleValue when PARAM_RETURN_OBJECT is
360                // truthy. At the time of writing,
361                // MediaWiki\Block\Restriction\PageRestriction::newFromTitle accepts either
362                // string or instance of Title.
363                //TitleDef::PARAM_RETURN_OBJECT => true,
364
365                ParamValidator::PARAM_ISMULTI => true,
366                ParamValidator::PARAM_ISMULTI_LIMIT1 => $pageLimit,
367                ParamValidator::PARAM_ISMULTI_LIMIT2 => $pageLimit,
368            ],
369            'namespacerestrictions' => [
370                ParamValidator::PARAM_ISMULTI => true,
371                ParamValidator::PARAM_TYPE => 'namespace',
372            ],
373            'actionrestrictions' => [
374                ParamValidator::PARAM_ISMULTI => true,
375                ParamValidator::PARAM_TYPE => array_keys(
376                    $this->blockActionInfo->getAllBlockActions()
377                ),
378            ],
379        ];
380
381        return $params;
382    }
383
384    /** @inheritDoc */
385    public function needsToken() {
386        return 'csrf';
387    }
388
389    /** @inheritDoc */
390    protected function getExamplesMessages() {
391        // phpcs:disable Generic.Files.LineLength
392        return [
393            'action=block&user=192.0.2.5&expiry=3%20days&reason=First%20strike&token=123ABC'
394                => 'apihelp-block-example-ip-simple',
395            'action=block&user=Vandal&expiry=never&reason=Vandalism&nocreate=&autoblock=&noemail=&token=123ABC'
396                => 'apihelp-block-example-user-complex',
397        ];
398        // phpcs:enable
399    }
400
401    /** @inheritDoc */
402    public function getHelpUrls() {
403        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Block';
404    }
405}
406
407/** @deprecated class alias since 1.43 */
408class_alias( ApiBlock::class, 'ApiBlock' );