Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
73.24% covered (warning)
73.24%
219 / 299
50.00% covered (danger)
50.00%
3 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryBlocks
73.24% covered (warning)
73.24%
219 / 299
50.00% covered (danger)
50.00%
3 / 6
160.19
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 execute
58.76% covered (warning)
58.76%
104 / 177
0.00% covered (danger)
0.00%
0 / 1
258.57
 getRestrictionData
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
11
 getAllowedParams
100.00% covered (success)
100.00%
78 / 78
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 * 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
23use MediaWiki\Block\BlockActionInfo;
24use MediaWiki\Block\BlockRestrictionStore;
25use MediaWiki\Block\DatabaseBlockStore;
26use MediaWiki\Block\HideUserUtils;
27use MediaWiki\Block\Restriction\PageRestriction;
28use MediaWiki\CommentStore\CommentStore;
29use MediaWiki\MainConfigNames;
30use MediaWiki\ParamValidator\TypeDef\UserDef;
31use Wikimedia\IPUtils;
32use Wikimedia\ParamValidator\ParamValidator;
33use Wikimedia\ParamValidator\TypeDef\IntegerDef;
34use Wikimedia\Rdbms\IResultWrapper;
35
36/**
37 * Query module to enumerate all user blocks
38 *
39 * @ingroup API
40 */
41class ApiQueryBlocks extends ApiQueryBase {
42
43    private DatabaseBlockStore $blockStore;
44    private BlockActionInfo $blockActionInfo;
45    private BlockRestrictionStore $blockRestrictionStore;
46    private CommentStore $commentStore;
47    private HideUserUtils $hideUserUtils;
48
49    /**
50     * @param ApiQuery $query
51     * @param string $moduleName
52     * @param DatabaseBlockStore $blockStore
53     * @param BlockActionInfo $blockActionInfo
54     * @param BlockRestrictionStore $blockRestrictionStore
55     * @param CommentStore $commentStore
56     * @param HideUserUtils $hideUserUtils
57     */
58    public function __construct(
59        ApiQuery $query,
60        $moduleName,
61        DatabaseBlockStore $blockStore,
62        BlockActionInfo $blockActionInfo,
63        BlockRestrictionStore $blockRestrictionStore,
64        CommentStore $commentStore,
65        HideUserUtils $hideUserUtils
66    ) {
67        parent::__construct( $query, $moduleName, 'bk' );
68        $this->blockStore = $blockStore;
69        $this->blockActionInfo = $blockActionInfo;
70        $this->blockRestrictionStore = $blockRestrictionStore;
71        $this->commentStore = $commentStore;
72        $this->hideUserUtils = $hideUserUtils;
73    }
74
75    public function execute() {
76        $db = $this->getDB();
77        $params = $this->extractRequestParams();
78        $this->requireMaxOneParameter( $params, 'users', 'ip' );
79
80        $prop = array_fill_keys( $params['prop'], true );
81        $fld_id = isset( $prop['id'] );
82        $fld_user = isset( $prop['user'] );
83        $fld_userid = isset( $prop['userid'] );
84        $fld_by = isset( $prop['by'] );
85        $fld_byid = isset( $prop['byid'] );
86        $fld_timestamp = isset( $prop['timestamp'] );
87        $fld_expiry = isset( $prop['expiry'] );
88        $fld_reason = isset( $prop['reason'] );
89        $fld_range = isset( $prop['range'] );
90        $fld_flags = isset( $prop['flags'] );
91        $fld_restrictions = isset( $prop['restrictions'] );
92
93        $result = $this->getResult();
94
95        $this->addTables( [ 'block', 'block_target', 'block_target_user' => 'user' ] );
96        $this->addJoinConds( [
97            'block_target' => [ 'JOIN', 'bt_id=bl_target' ],
98            'block_target_user' => [ 'LEFT JOIN', 'user_id=bt_user' ]
99        ] );
100        $this->addFields( [ 'bt_auto', 'bl_id', 'bl_timestamp' ] );
101        $this->addFieldsIf(
102            [
103                'bt_address',
104                'bt_user',
105                'bt_address_or_user_name' => 'COALESCE(bt_address, bt_user_text)'
106            ],
107            $fld_user || $fld_userid
108        );
109
110        if ( $fld_by || $fld_byid ) {
111            $this->addTables( 'actor' );
112            $this->addFields( [ 'actor_user', 'actor_name' ] );
113            $this->addJoinConds( [ 'actor' => [ 'JOIN', 'actor_id=bl_by_actor' ] ] );
114        }
115        $this->addFieldsIf( 'bl_expiry', $fld_expiry );
116        $this->addFieldsIf( [ 'bt_range_start', 'bt_range_end' ], $fld_range );
117        $this->addFieldsIf( [ 'bl_anon_only', 'bl_create_account', 'bl_enable_autoblock',
118            'bl_block_email', 'bl_deleted', 'bl_allow_usertalk', 'bl_sitewide' ],
119            $fld_flags );
120        $this->addFieldsIf( 'bl_sitewide', $fld_restrictions );
121
122        if ( $fld_reason ) {
123            $commentQuery = $this->commentStore->getJoin( 'bl_reason' );
124            $this->addTables( $commentQuery['tables'] );
125            $this->addFields( $commentQuery['fields'] );
126            $this->addJoinConds( $commentQuery['joins'] );
127        }
128
129        $this->addOption( 'LIMIT', $params['limit'] + 1 );
130        $this->addTimestampWhereRange(
131            'bl_timestamp',
132            $params['dir'],
133            $params['start'],
134            $params['end']
135        );
136        // Include in ORDER BY for uniqueness
137        $this->addWhereRange( 'bl_id', $params['dir'], null, null );
138
139        if ( $params['continue'] !== null ) {
140            $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'timestamp', 'int' ] );
141            $op = ( $params['dir'] == 'newer' ? '>=' : '<=' );
142            $this->addWhere( $db->buildComparison( $op, [
143                'bl_timestamp' => $db->timestamp( $cont[0] ),
144                'bl_id' => $cont[1],
145            ] ) );
146        }
147
148        if ( $params['ids'] ) {
149            $this->addWhereIDsFld( 'block', 'bl_id', $params['ids'] );
150        }
151        if ( $params['users'] ) {
152            $addresses = [];
153            $userNames = [];
154            foreach ( $params['users'] as $target ) {
155                if ( IPUtils::isValid( $target ) || IPUtils::isValidRange( $target ) ) {
156                    $addresses[] = $target;
157                } else {
158                    $userNames[] = $target;
159                }
160            }
161            if ( $addresses && $userNames ) {
162                // Use a union, not "OR" (T360088)
163                $ids = $db->newUnionQueryBuilder()
164                    ->add( $db->newSelectQueryBuilder()
165                        ->select( 'bt_id' )
166                        ->from( 'block_target' )
167                        ->where( [ 'bt_address' => $addresses ] )
168                    )
169                    ->add( $db->newSelectQueryBuilder()
170                        ->select( 'bt_id' )
171                        ->from( 'block_target' )
172                        ->join( 'user', null, 'user_id=bt_user' )
173                        ->where( [ 'user_name' => $userNames ] )
174                    )
175                    ->caller( __METHOD__ )
176                    ->fetchFieldValues();
177                if ( $ids ) {
178                    $this->addWhere( [ 'bt_id' => $ids ] );
179                } else {
180                    $this->addWhere( '1=0' );
181                }
182            } elseif ( $addresses ) {
183                $this->addWhere( [ 'bt_address' => $addresses ] );
184            } elseif ( $userNames ) {
185                $this->addWhere( [ 'block_target_user.user_name' => $userNames ] );
186            } else {
187                // Unreachable since $params['users'] is non-empty
188                $this->addWhere( '1=0' );
189            }
190            $this->addWhereFld( 'bt_auto', 0 );
191        }
192        if ( $params['ip'] !== null ) {
193            $blockCIDRLimit = $this->getConfig()->get( MainConfigNames::BlockCIDRLimit );
194            if ( IPUtils::isIPv4( $params['ip'] ) ) {
195                $type = 'IPv4';
196                $cidrLimit = $blockCIDRLimit['IPv4'];
197            } elseif ( IPUtils::isIPv6( $params['ip'] ) ) {
198                $type = 'IPv6';
199                $cidrLimit = $blockCIDRLimit['IPv6'];
200            } else {
201                $this->dieWithError( 'apierror-badip', 'param_ip' );
202            }
203
204            // Check range validity, if it's a CIDR
205            [ $ip, $range ] = IPUtils::parseCIDR( $params['ip'] );
206            if ( $ip !== false && $range !== false && $range < $cidrLimit ) {
207                $this->dieWithError( [ 'apierror-cidrtoobroad', $type, $cidrLimit ] );
208            }
209
210            // Let IPUtils::parseRange handle calculating $upper, instead of duplicating the logic here.
211            [ $lower, $upper ] = IPUtils::parseRange( $params['ip'] );
212
213            $this->addWhere( $this->blockStore->getRangeCond( $lower, $upper ) );
214            $this->addWhere( [ 'bt_auto' => 0 ] );
215        }
216
217        if ( $params['show'] !== null ) {
218            $show = array_fill_keys( $params['show'], true );
219
220            // Check for conflicting parameters.
221            if ( ( isset( $show['account'] ) && isset( $show['!account'] ) )
222                || ( isset( $show['ip'] ) && isset( $show['!ip'] ) )
223                || ( isset( $show['range'] ) && isset( $show['!range'] ) )
224                || ( isset( $show['temp'] ) && isset( $show['!temp'] ) )
225            ) {
226                $this->dieWithError( 'apierror-show' );
227            }
228
229            $this->addWhereIf( [ 'bt_user' => 0 ], isset( $show['!account'] ) );
230            $this->addWhereIf( 'bt_user != 0', isset( $show['account'] ) );
231            $this->addWhereIf( 'bt_user != 0 OR bt_range_end > bt_range_start', isset( $show['!ip'] ) );
232            $this->addWhereIf( 'bt_user = 0 AND bt_range_end = bt_range_start', isset( $show['ip'] ) );
233            $this->addWhereIf( [ 'bl_expiry' => $db->getInfinity() ], isset( $show['!temp'] ) );
234            $this->addWhereIf( $db->expr( 'bl_expiry', '!=', $db->getInfinity() ), isset( $show['temp'] ) );
235            $this->addWhereIf( 'bt_range_end = bt_range_start', isset( $show['!range'] ) );
236            $this->addWhereIf( 'bt_range_end > bt_range_start', isset( $show['range'] ) );
237        }
238
239        if ( !$this->getAuthority()->isAllowed( 'hideuser' ) ) {
240            $this->addWhere(
241                $this->hideUserUtils->getExpression( $db, $db->tableName( 'block_target' ) . '.bt_user' )
242            );
243        }
244
245        // Filter out expired rows
246        $this->addWhere( $db->expr( 'bl_expiry', '>', $db->timestamp() ) );
247
248        $res = $this->select( __METHOD__ );
249
250        $restrictions = [];
251        if ( $fld_restrictions ) {
252            $restrictions = $this->getRestrictionData( $res, $params['limit'] );
253        }
254
255        $count = 0;
256        foreach ( $res as $row ) {
257            if ( ++$count > $params['limit'] ) {
258                // We've had enough
259                $this->setContinueEnumParameter( 'continue', "{$row->bl_timestamp}|{$row->bl_id}" );
260                break;
261            }
262            $block = [
263                ApiResult::META_TYPE => 'assoc',
264            ];
265            if ( $fld_id ) {
266                $block['id'] = (int)$row->bl_id;
267            }
268            if ( $fld_user && !$row->bt_auto ) {
269                $block['user'] = $row->bt_address_or_user_name;
270            }
271            if ( $fld_userid && !$row->bt_auto ) {
272                $block['userid'] = (int)$row->bt_user;
273            }
274            if ( $fld_by ) {
275                $block['by'] = $row->actor_name;
276            }
277            if ( $fld_byid ) {
278                $block['byid'] = (int)$row->actor_user;
279            }
280            if ( $fld_timestamp ) {
281                $block['timestamp'] = wfTimestamp( TS_ISO_8601, $row->bl_timestamp );
282            }
283            if ( $fld_expiry ) {
284                $block['expiry'] = ApiResult::formatExpiry( $row->bl_expiry );
285            }
286            if ( $fld_reason ) {
287                $block['reason'] = $this->commentStore->getComment( 'bl_reason', $row )->text;
288            }
289            if ( $fld_range && !$row->bt_auto && $row->bt_range_start !== null ) {
290                $block['rangestart'] = IPUtils::formatHex( $row->bt_range_start );
291                $block['rangeend'] = IPUtils::formatHex( $row->bt_range_end );
292            }
293            if ( $fld_flags ) {
294                // For clarity, these flags use the same names as their action=block counterparts
295                $block['automatic'] = (bool)$row->bt_auto;
296                $block['anononly'] = (bool)$row->bl_anon_only;
297                $block['nocreate'] = (bool)$row->bl_create_account;
298                $block['autoblock'] = (bool)$row->bl_enable_autoblock;
299                $block['noemail'] = (bool)$row->bl_block_email;
300                $block['hidden'] = (bool)$row->bl_deleted;
301                $block['allowusertalk'] = (bool)$row->bl_allow_usertalk;
302                $block['partial'] = !(bool)$row->bl_sitewide;
303            }
304
305            if ( $fld_restrictions ) {
306                $block['restrictions'] = [];
307                if ( !$row->bl_sitewide && isset( $restrictions[$row->bl_id] ) ) {
308                    $block['restrictions'] = $restrictions[$row->bl_id];
309                }
310            }
311
312            $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $block );
313            if ( !$fit ) {
314                $this->setContinueEnumParameter( 'continue', "{$row->bl_timestamp}|{$row->bl_id}" );
315                break;
316            }
317        }
318        $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'block' );
319    }
320
321    /**
322     * Retrieves the restrictions based on the query result.
323     *
324     * @param IResultWrapper $result
325     * @param int $limit
326     *
327     * @return array
328     */
329    private function getRestrictionData( IResultWrapper $result, $limit ) {
330        $partialIds = [];
331        $count = 0;
332        foreach ( $result as $row ) {
333            if ( ++$count <= $limit && !( $row->ipb_sitewide ?? $row->bl_sitewide ) ) {
334                $partialIds[] = (int)( $row->ipb_id ?? $row->bl_id );
335            }
336        }
337
338        $restrictions = $this->blockRestrictionStore->loadByBlockId( $partialIds );
339
340        $data = [];
341        $keys = [
342            'page' => 'pages',
343            'ns' => 'namespaces',
344        ];
345        if ( $this->getConfig()->get( MainConfigNames::EnablePartialActionBlocks ) ) {
346            $keys['action'] = 'actions';
347        }
348
349        foreach ( $restrictions as $restriction ) {
350            $key = $keys[$restriction->getType()];
351            $id = $restriction->getBlockId();
352            switch ( $restriction->getType() ) {
353                case 'page':
354                    /** @var PageRestriction $restriction */
355                    '@phan-var \MediaWiki\Block\Restriction\PageRestriction $restriction';
356                    $value = [ 'id' => $restriction->getValue() ];
357                    if ( $restriction->getTitle() ) {
358                        self::addTitleInfo( $value, $restriction->getTitle() );
359                    }
360                    break;
361                case 'action':
362                    $value = $this->blockActionInfo->getActionFromId( $restriction->getValue() );
363                    break;
364                default:
365                    $value = $restriction->getValue();
366            }
367
368            if ( !isset( $data[$id][$key] ) ) {
369                $data[$id][$key] = [];
370                ApiResult::setIndexedTagName( $data[$id][$key], $restriction->getType() );
371            }
372            $data[$id][$key][] = $value;
373        }
374
375        return $data;
376    }
377
378    public function getAllowedParams() {
379        $blockCIDRLimit = $this->getConfig()->get( MainConfigNames::BlockCIDRLimit );
380
381        return [
382            'start' => [
383                ParamValidator::PARAM_TYPE => 'timestamp'
384            ],
385            'end' => [
386                ParamValidator::PARAM_TYPE => 'timestamp',
387            ],
388            'dir' => [
389                ParamValidator::PARAM_TYPE => [
390                    'newer',
391                    'older'
392                ],
393                ParamValidator::PARAM_DEFAULT => 'older',
394                ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
395                ApiBase::PARAM_HELP_MSG_PER_VALUE => [
396                    'newer' => 'api-help-paramvalue-direction-newer',
397                    'older' => 'api-help-paramvalue-direction-older',
398                ],
399            ],
400            'ids' => [
401                ParamValidator::PARAM_TYPE => 'integer',
402                ParamValidator::PARAM_ISMULTI => true
403            ],
404            'users' => [
405                ParamValidator::PARAM_TYPE => 'user',
406                UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'cidr' ],
407                ParamValidator::PARAM_ISMULTI => true
408            ],
409            'ip' => [
410                ApiBase::PARAM_HELP_MSG => [
411                    'apihelp-query+blocks-param-ip',
412                    $blockCIDRLimit['IPv4'],
413                    $blockCIDRLimit['IPv6'],
414                ],
415            ],
416            'limit' => [
417                ParamValidator::PARAM_DEFAULT => 10,
418                ParamValidator::PARAM_TYPE => 'limit',
419                IntegerDef::PARAM_MIN => 1,
420                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
421                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
422            ],
423            'prop' => [
424                ParamValidator::PARAM_DEFAULT => 'id|user|by|timestamp|expiry|reason|flags',
425                ParamValidator::PARAM_TYPE => [
426                    'id',
427                    'user',
428                    'userid',
429                    'by',
430                    'byid',
431                    'timestamp',
432                    'expiry',
433                    'reason',
434                    'range',
435                    'flags',
436                    'restrictions',
437                ],
438                ParamValidator::PARAM_ISMULTI => true,
439                ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
440            ],
441            'show' => [
442                ParamValidator::PARAM_TYPE => [
443                    'account',
444                    '!account',
445                    'temp',
446                    '!temp',
447                    'ip',
448                    '!ip',
449                    'range',
450                    '!range',
451                ],
452                ParamValidator::PARAM_ISMULTI => true
453            ],
454            'continue' => [
455                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
456            ],
457        ];
458    }
459
460    protected function getExamplesMessages() {
461        return [
462            'action=query&list=blocks'
463                => 'apihelp-query+blocks-example-simple',
464            'action=query&list=blocks&bkusers=Alice|Bob'
465                => 'apihelp-query+blocks-example-users',
466        ];
467    }
468
469    public function getHelpUrls() {
470        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Blocks';
471    }
472}