3 * Copyright © 2007 Roan Kattouw <roan.kattouw@gmail.com>
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.
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.
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
23 use MediaWiki\Block\BlockActionInfo
;
24 use MediaWiki\Block\BlockRestrictionStore
;
25 use MediaWiki\Block\Restriction\PageRestriction
;
26 use MediaWiki\CommentStore\CommentStore
;
27 use MediaWiki\MainConfigNames
;
28 use MediaWiki\ParamValidator\TypeDef\UserDef
;
29 use Wikimedia\IPUtils
;
30 use Wikimedia\ParamValidator\ParamValidator
;
31 use Wikimedia\ParamValidator\TypeDef\IntegerDef
;
32 use Wikimedia\Rdbms\IResultWrapper
;
35 * Query module to enumerate all user blocks
39 class ApiQueryBlocks
extends ApiQueryBase
{
41 private BlockActionInfo
$blockActionInfo;
42 private BlockRestrictionStore
$blockRestrictionStore;
43 private CommentStore
$commentStore;
46 * @param ApiQuery $query
47 * @param string $moduleName
48 * @param BlockActionInfo $blockActionInfo
49 * @param BlockRestrictionStore $blockRestrictionStore
50 * @param CommentStore $commentStore
52 public function __construct(
55 BlockActionInfo
$blockActionInfo,
56 BlockRestrictionStore
$blockRestrictionStore,
57 CommentStore
$commentStore
59 parent
::__construct( $query, $moduleName, 'bk' );
60 $this->blockActionInfo
= $blockActionInfo;
61 $this->blockRestrictionStore
= $blockRestrictionStore;
62 $this->commentStore
= $commentStore;
65 public function execute() {
67 $params = $this->extractRequestParams();
68 $this->requireMaxOneParameter( $params, 'users', 'ip' );
70 $prop = array_fill_keys( $params['prop'], true );
71 $fld_id = isset( $prop['id'] );
72 $fld_user = isset( $prop['user'] );
73 $fld_userid = isset( $prop['userid'] );
74 $fld_by = isset( $prop['by'] );
75 $fld_byid = isset( $prop['byid'] );
76 $fld_timestamp = isset( $prop['timestamp'] );
77 $fld_expiry = isset( $prop['expiry'] );
78 $fld_reason = isset( $prop['reason'] );
79 $fld_range = isset( $prop['range'] );
80 $fld_flags = isset( $prop['flags'] );
81 $fld_restrictions = isset( $prop['restrictions'] );
83 $result = $this->getResult();
85 $this->addTables( 'ipblocks' );
86 $this->addFields( [ 'ipb_auto', 'ipb_id', 'ipb_timestamp' ] );
88 $this->addFieldsIf( [ 'ipb_address', 'ipb_user' ], $fld_user ||
$fld_userid );
89 if ( $fld_by ||
$fld_byid ) {
90 $this->addTables( 'actor' );
91 $this->addFields( [ 'actor_user', 'actor_name' ] );
92 $this->addJoinConds( [ 'actor' => [ 'JOIN', 'actor_id=ipb_by_actor' ] ] );
94 $this->addFieldsIf( 'ipb_expiry', $fld_expiry );
95 $this->addFieldsIf( [ 'ipb_range_start', 'ipb_range_end' ], $fld_range );
96 $this->addFieldsIf( [ 'ipb_anon_only', 'ipb_create_account', 'ipb_enable_autoblock',
97 'ipb_block_email', 'ipb_deleted', 'ipb_allow_usertalk', 'ipb_sitewide' ],
99 $this->addFieldsIf( 'ipb_sitewide', $fld_restrictions );
102 $commentQuery = $this->commentStore
->getJoin( 'ipb_reason' );
103 $this->addTables( $commentQuery['tables'] );
104 $this->addFields( $commentQuery['fields'] );
105 $this->addJoinConds( $commentQuery['joins'] );
108 $this->addOption( 'LIMIT', $params['limit'] +
1 );
109 $this->addTimestampWhereRange(
115 // Include in ORDER BY for uniqueness
116 $this->addWhereRange( 'ipb_id', $params['dir'], null, null );
118 if ( $params['continue'] !== null ) {
119 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'timestamp', 'int' ] );
120 $op = ( $params['dir'] == 'newer' ?
'>=' : '<=' );
121 $this->addWhere( $db->buildComparison( $op, [
122 'ipb_timestamp' => $db->timestamp( $cont[0] ),
123 'ipb_id' => $cont[1],
127 if ( $params['ids'] ) {
128 $this->addWhereIDsFld( 'ipblocks', 'ipb_id', $params['ids'] );
130 if ( $params['users'] ) {
131 $this->addWhereFld( 'ipb_address', $params['users'] );
132 $this->addWhereFld( 'ipb_auto', 0 );
134 if ( $params['ip'] !== null ) {
135 $blockCIDRLimit = $this->getConfig()->get( MainConfigNames
::BlockCIDRLimit
);
136 if ( IPUtils
::isIPv4( $params['ip'] ) ) {
138 $cidrLimit = $blockCIDRLimit['IPv4'];
140 } elseif ( IPUtils
::isIPv6( $params['ip'] ) ) {
142 $cidrLimit = $blockCIDRLimit['IPv6'];
143 $prefixLen = 3; // IPUtils::toHex output is prefixed with "v6-"
145 $this->dieWithError( 'apierror-badip', 'param_ip' );
148 // Check range validity, if it's a CIDR
149 [ $ip, $range ] = IPUtils
::parseCIDR( $params['ip'] );
150 if ( $ip !== false && $range !== false && $range < $cidrLimit ) {
151 $this->dieWithError( [ 'apierror-cidrtoobroad', $type, $cidrLimit ] );
154 // Let IPUtils::parseRange handle calculating $upper, instead of duplicating the logic here.
155 [ $lower, $upper ] = IPUtils
::parseRange( $params['ip'] );
157 // Extract the common prefix to any range block affecting this IP/CIDR
158 $prefix = substr( $lower, 0, $prefixLen +
(int)floor( $cidrLimit / 4 ) );
160 $lower = $db->addQuotes( $lower );
161 $upper = $db->addQuotes( $upper );
164 'ipb_range_start' . $db->buildLike( $prefix, $db->anyString() ),
165 'ipb_range_start <= ' . $lower,
166 'ipb_range_end >= ' . $upper,
171 if ( $params['show'] !== null ) {
172 $show = array_fill_keys( $params['show'], true );
174 // Check for conflicting parameters.
175 if ( ( isset( $show['account'] ) && isset( $show['!account'] ) )
176 ||
( isset( $show['ip'] ) && isset( $show['!ip'] ) )
177 ||
( isset( $show['range'] ) && isset( $show['!range'] ) )
178 ||
( isset( $show['temp'] ) && isset( $show['!temp'] ) )
180 $this->dieWithError( 'apierror-show' );
183 $this->addWhereIf( [ 'ipb_user' => 0 ], isset( $show['!account'] ) );
184 $this->addWhereIf( 'ipb_user != 0', isset( $show['account'] ) );
185 $this->addWhereIf( 'ipb_user != 0 OR ipb_range_end > ipb_range_start', isset( $show['!ip'] ) );
186 $this->addWhereIf( 'ipb_user = 0 AND ipb_range_end = ipb_range_start', isset( $show['ip'] ) );
187 $this->addWhereIf( [ 'ipb_expiry' => $db->getInfinity() ], isset( $show['!temp'] ) );
188 $this->addWhereIf( 'ipb_expiry != ' .
189 $db->addQuotes( $db->getInfinity() ), isset( $show['temp'] ) );
190 $this->addWhereIf( 'ipb_range_end = ipb_range_start', isset( $show['!range'] ) );
191 $this->addWhereIf( 'ipb_range_end > ipb_range_start', isset( $show['range'] ) );
194 if ( !$this->getAuthority()->isAllowed( 'hideuser' ) ) {
195 $this->addWhereFld( 'ipb_deleted', 0 );
198 // Filter out expired rows
199 $this->addWhere( 'ipb_expiry > ' . $db->addQuotes( $db->timestamp() ) );
201 $res = $this->select( __METHOD__
);
204 if ( $fld_restrictions ) {
205 $restrictions = $this->getRestrictionData( $res, $params['limit'] );
209 foreach ( $res as $row ) {
210 if ( ++
$count > $params['limit'] ) {
212 $this->setContinueEnumParameter( 'continue', "$row->ipb_timestamp|$row->ipb_id" );
216 ApiResult
::META_TYPE
=> 'assoc',
219 $block['id'] = (int)$row->ipb_id
;
221 if ( $fld_user && !$row->ipb_auto
) {
222 $block['user'] = $row->ipb_address
;
224 if ( $fld_userid && !$row->ipb_auto
) {
225 $block['userid'] = (int)$row->ipb_user
;
228 $block['by'] = $row->actor_name
;
231 $block['byid'] = (int)$row->actor_user
;
233 if ( $fld_timestamp ) {
234 $block['timestamp'] = wfTimestamp( TS_ISO_8601
, $row->ipb_timestamp
);
237 $block['expiry'] = ApiResult
::formatExpiry( $row->ipb_expiry
);
240 $block['reason'] = $this->commentStore
->getComment( 'ipb_reason', $row )->text
;
242 if ( $fld_range && !$row->ipb_auto
) {
243 $block['rangestart'] = IPUtils
::formatHex( $row->ipb_range_start
);
244 $block['rangeend'] = IPUtils
::formatHex( $row->ipb_range_end
);
247 // For clarity, these flags use the same names as their action=block counterparts
248 $block['automatic'] = (bool)$row->ipb_auto
;
249 $block['anononly'] = (bool)$row->ipb_anon_only
;
250 $block['nocreate'] = (bool)$row->ipb_create_account
;
251 $block['autoblock'] = (bool)$row->ipb_enable_autoblock
;
252 $block['noemail'] = (bool)$row->ipb_block_email
;
253 $block['hidden'] = (bool)$row->ipb_deleted
;
254 $block['allowusertalk'] = (bool)$row->ipb_allow_usertalk
;
255 $block['partial'] = !(bool)$row->ipb_sitewide
;
258 if ( $fld_restrictions ) {
259 $block['restrictions'] = [];
260 if ( !$row->ipb_sitewide
&& isset( $restrictions[$row->ipb_id
] ) ) {
261 $block['restrictions'] = $restrictions[$row->ipb_id
];
265 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $block );
267 $this->setContinueEnumParameter( 'continue', "$row->ipb_timestamp|$row->ipb_id" );
271 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'block' );
275 * Retrieves the restrictions based on the query result.
277 * @param IResultWrapper $result
282 private function getRestrictionData( IResultWrapper
$result, $limit ) {
285 foreach ( $result as $row ) {
286 if ( ++
$count <= $limit && !$row->ipb_sitewide
) {
287 $partialIds[] = (int)$row->ipb_id
;
291 $restrictions = $this->blockRestrictionStore
->loadByBlockId( $partialIds );
296 'ns' => 'namespaces',
298 if ( $this->getConfig()->get( MainConfigNames
::EnablePartialActionBlocks
) ) {
299 $keys['action'] = 'actions';
302 foreach ( $restrictions as $restriction ) {
303 $key = $keys[$restriction->getType()];
304 $id = $restriction->getBlockId();
305 switch ( $restriction->getType() ) {
307 /** @var PageRestriction $restriction */
308 '@phan-var \MediaWiki\Block\Restriction\PageRestriction $restriction';
309 $value = [ 'id' => $restriction->getValue() ];
310 if ( $restriction->getTitle() ) {
311 self
::addTitleInfo( $value, $restriction->getTitle() );
315 $value = $this->blockActionInfo
->getActionFromId( $restriction->getValue() );
318 $value = $restriction->getValue();
321 if ( !isset( $data[$id][$key] ) ) {
322 $data[$id][$key] = [];
323 ApiResult
::setIndexedTagName( $data[$id][$key], $restriction->getType() );
325 $data[$id][$key][] = $value;
331 public function getAllowedParams() {
332 $blockCIDRLimit = $this->getConfig()->get( MainConfigNames
::BlockCIDRLimit
);
336 ParamValidator
::PARAM_TYPE
=> 'timestamp'
339 ParamValidator
::PARAM_TYPE
=> 'timestamp',
342 ParamValidator
::PARAM_TYPE
=> [
346 ParamValidator
::PARAM_DEFAULT
=> 'older',
347 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-direction',
348 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [
349 'newer' => 'api-help-paramvalue-direction-newer',
350 'older' => 'api-help-paramvalue-direction-older',
354 ParamValidator
::PARAM_TYPE
=> 'integer',
355 ParamValidator
::PARAM_ISMULTI
=> true
358 ParamValidator
::PARAM_TYPE
=> 'user',
359 UserDef
::PARAM_ALLOWED_USER_TYPES
=> [ 'name', 'ip', 'cidr' ],
360 ParamValidator
::PARAM_ISMULTI
=> true
363 ApiBase
::PARAM_HELP_MSG
=> [
364 'apihelp-query+blocks-param-ip',
365 $blockCIDRLimit['IPv4'],
366 $blockCIDRLimit['IPv6'],
370 ParamValidator
::PARAM_DEFAULT
=> 10,
371 ParamValidator
::PARAM_TYPE
=> 'limit',
372 IntegerDef
::PARAM_MIN
=> 1,
373 IntegerDef
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
374 IntegerDef
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
377 ParamValidator
::PARAM_DEFAULT
=> 'id|user|by|timestamp|expiry|reason|flags',
378 ParamValidator
::PARAM_TYPE
=> [
391 ParamValidator
::PARAM_ISMULTI
=> true,
392 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
395 ParamValidator
::PARAM_TYPE
=> [
405 ParamValidator
::PARAM_ISMULTI
=> true
408 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
413 protected function getExamplesMessages() {
415 'action=query&list=blocks'
416 => 'apihelp-query+blocks-example-simple',
417 'action=query&list=blocks&bkusers=Alice|Bob'
418 => 'apihelp-query+blocks-example-users',
422 public function getHelpUrls() {
423 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Blocks';