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