MediaWiki REL1_39
ApiQueryBlocks.php
Go to the documentation of this file.
1<?php
28use Wikimedia\IPUtils;
32
39
41 private $blockActionInfo;
42
44 private $blockRestrictionStore;
45
47 private $commentStore;
48
56 public function __construct(
57 ApiQuery $query,
58 $moduleName,
59 BlockActionInfo $blockActionInfo,
60 BlockRestrictionStore $blockRestrictionStore,
61 CommentStore $commentStore
62 ) {
63 parent::__construct( $query, $moduleName, 'bk' );
64 $this->blockActionInfo = $blockActionInfo;
65 $this->blockRestrictionStore = $blockRestrictionStore;
66 $this->commentStore = $commentStore;
67 }
68
69 public function execute() {
70 $db = $this->getDB();
71 $params = $this->extractRequestParams();
72 $this->requireMaxOneParameter( $params, 'users', 'ip' );
73
74 $prop = array_fill_keys( $params['prop'], true );
75 $fld_id = isset( $prop['id'] );
76 $fld_user = isset( $prop['user'] );
77 $fld_userid = isset( $prop['userid'] );
78 $fld_by = isset( $prop['by'] );
79 $fld_byid = isset( $prop['byid'] );
80 $fld_timestamp = isset( $prop['timestamp'] );
81 $fld_expiry = isset( $prop['expiry'] );
82 $fld_reason = isset( $prop['reason'] );
83 $fld_range = isset( $prop['range'] );
84 $fld_flags = isset( $prop['flags'] );
85 $fld_restrictions = isset( $prop['restrictions'] );
86
87 $result = $this->getResult();
88
89 $this->addTables( 'ipblocks' );
90 $this->addFields( [ 'ipb_auto', 'ipb_id', 'ipb_timestamp' ] );
91
92 $this->addFieldsIf( [ 'ipb_address', 'ipb_user' ], $fld_user || $fld_userid );
93 if ( $fld_by || $fld_byid ) {
94 $this->addTables( 'actor' );
95 $this->addFields( [ 'actor_user', 'actor_name' ] );
96 $this->addJoinConds( [ 'actor' => [ 'JOIN', 'actor_id=ipb_by_actor' ] ] );
97 }
98 $this->addFieldsIf( 'ipb_expiry', $fld_expiry );
99 $this->addFieldsIf( [ 'ipb_range_start', 'ipb_range_end' ], $fld_range );
100 $this->addFieldsIf( [ 'ipb_anon_only', 'ipb_create_account', 'ipb_enable_autoblock',
101 'ipb_block_email', 'ipb_deleted', 'ipb_allow_usertalk', 'ipb_sitewide' ],
102 $fld_flags );
103 $this->addFieldsIf( 'ipb_sitewide', $fld_restrictions );
104
105 if ( $fld_reason ) {
106 $commentQuery = $this->commentStore->getJoin( 'ipb_reason' );
107 $this->addTables( $commentQuery['tables'] );
108 $this->addFields( $commentQuery['fields'] );
109 $this->addJoinConds( $commentQuery['joins'] );
110 }
111
112 $this->addOption( 'LIMIT', $params['limit'] + 1 );
114 'ipb_timestamp',
115 $params['dir'],
116 $params['start'],
117 $params['end']
118 );
119 // Include in ORDER BY for uniqueness
120 $this->addWhereRange( 'ipb_id', $params['dir'], null, null );
121
122 if ( $params['continue'] !== null ) {
123 $cont = explode( '|', $params['continue'] );
124 $this->dieContinueUsageIf( count( $cont ) != 2 );
125 $op = ( $params['dir'] == 'newer' ? '>' : '<' );
126 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
127 $continueId = (int)$cont[1];
128 $this->dieContinueUsageIf( $continueId != $cont[1] );
129 $this->addWhere( "ipb_timestamp $op $continueTimestamp OR " .
130 "(ipb_timestamp = $continueTimestamp AND " .
131 "ipb_id $op= $continueId)"
132 );
133 }
134
135 if ( $params['ids'] ) {
136 $this->addWhereIDsFld( 'ipblocks', 'ipb_id', $params['ids'] );
137 }
138 if ( $params['users'] ) {
139 $this->addWhereFld( 'ipb_address', $params['users'] );
140 $this->addWhereFld( 'ipb_auto', 0 );
141 }
142 if ( $params['ip'] !== null ) {
143 $blockCIDRLimit = $this->getConfig()->get( MainConfigNames::BlockCIDRLimit );
144 if ( IPUtils::isIPv4( $params['ip'] ) ) {
145 $type = 'IPv4';
146 $cidrLimit = $blockCIDRLimit['IPv4'];
147 $prefixLen = 0;
148 } elseif ( IPUtils::isIPv6( $params['ip'] ) ) {
149 $type = 'IPv6';
150 $cidrLimit = $blockCIDRLimit['IPv6'];
151 $prefixLen = 3; // IPUtils::toHex output is prefixed with "v6-"
152 } else {
153 $this->dieWithError( 'apierror-badip', 'param_ip' );
154 }
155
156 # Check range validity, if it's a CIDR
157 list( $ip, $range ) = IPUtils::parseCIDR( $params['ip'] );
158 if ( $ip !== false && $range !== false && $range < $cidrLimit ) {
159 $this->dieWithError( [ 'apierror-cidrtoobroad', $type, $cidrLimit ] );
160 }
161
162 # Let IPUtils::parseRange handle calculating $upper, instead of duplicating the logic here.
163 list( $lower, $upper ) = IPUtils::parseRange( $params['ip'] );
164
165 # Extract the common prefix to any rangeblock affecting this IP/CIDR
166 $prefix = substr( $lower, 0, $prefixLen + (int)floor( $cidrLimit / 4 ) );
167
168 # Fairly hard to make a malicious SQL statement out of hex characters,
169 # but it is good practice to add quotes
170 $lower = $db->addQuotes( $lower );
171 $upper = $db->addQuotes( $upper );
172
173 $this->addWhere( [
174 'ipb_range_start' . $db->buildLike( $prefix, $db->anyString() ),
175 'ipb_range_start <= ' . $lower,
176 'ipb_range_end >= ' . $upper,
177 'ipb_auto' => 0
178 ] );
179 }
180
181 if ( $params['show'] !== null ) {
182 $show = array_fill_keys( $params['show'], true );
183
184 /* Check for conflicting parameters. */
185 if ( ( isset( $show['account'] ) && isset( $show['!account'] ) )
186 || ( isset( $show['ip'] ) && isset( $show['!ip'] ) )
187 || ( isset( $show['range'] ) && isset( $show['!range'] ) )
188 || ( isset( $show['temp'] ) && isset( $show['!temp'] ) )
189 ) {
190 $this->dieWithError( 'apierror-show' );
191 }
192
193 $this->addWhereIf( 'ipb_user = 0', isset( $show['!account'] ) );
194 $this->addWhereIf( 'ipb_user != 0', isset( $show['account'] ) );
195 $this->addWhereIf( 'ipb_user != 0 OR ipb_range_end > ipb_range_start', isset( $show['!ip'] ) );
196 $this->addWhereIf( 'ipb_user = 0 AND ipb_range_end = ipb_range_start', isset( $show['ip'] ) );
197 $this->addWhereIf( 'ipb_expiry = ' .
198 $db->addQuotes( $db->getInfinity() ), isset( $show['!temp'] ) );
199 $this->addWhereIf( 'ipb_expiry != ' .
200 $db->addQuotes( $db->getInfinity() ), isset( $show['temp'] ) );
201 $this->addWhereIf( 'ipb_range_end = ipb_range_start', isset( $show['!range'] ) );
202 $this->addWhereIf( 'ipb_range_end > ipb_range_start', isset( $show['range'] ) );
203 }
204
205 if ( !$this->getAuthority()->isAllowed( 'hideuser' ) ) {
206 $this->addWhereFld( 'ipb_deleted', 0 );
207 }
208
209 # Filter out expired rows
210 $this->addWhere( 'ipb_expiry > ' . $db->addQuotes( $db->timestamp() ) );
211
212 $res = $this->select( __METHOD__ );
213
214 $restrictions = [];
215 if ( $fld_restrictions ) {
216 $restrictions = $this->getRestrictionData( $res, $params['limit'] );
217 }
218
219 $count = 0;
220 foreach ( $res as $row ) {
221 if ( ++$count > $params['limit'] ) {
222 // We've had enough
223 $this->setContinueEnumParameter( 'continue', "$row->ipb_timestamp|$row->ipb_id" );
224 break;
225 }
226 $block = [
227 ApiResult::META_TYPE => 'assoc',
228 ];
229 if ( $fld_id ) {
230 $block['id'] = (int)$row->ipb_id;
231 }
232 if ( $fld_user && !$row->ipb_auto ) {
233 $block['user'] = $row->ipb_address;
234 }
235 if ( $fld_userid && !$row->ipb_auto ) {
236 $block['userid'] = (int)$row->ipb_user;
237 }
238 if ( $fld_by ) {
239 $block['by'] = $row->actor_name;
240 }
241 if ( $fld_byid ) {
242 $block['byid'] = (int)$row->actor_user;
243 }
244 if ( $fld_timestamp ) {
245 $block['timestamp'] = wfTimestamp( TS_ISO_8601, $row->ipb_timestamp );
246 }
247 if ( $fld_expiry ) {
248 $block['expiry'] = ApiResult::formatExpiry( $row->ipb_expiry );
249 }
250 if ( $fld_reason ) {
251 $block['reason'] = $this->commentStore->getComment( 'ipb_reason', $row )->text;
252 }
253 if ( $fld_range && !$row->ipb_auto ) {
254 $block['rangestart'] = IPUtils::formatHex( $row->ipb_range_start );
255 $block['rangeend'] = IPUtils::formatHex( $row->ipb_range_end );
256 }
257 if ( $fld_flags ) {
258 // For clarity, these flags use the same names as their action=block counterparts
259 $block['automatic'] = (bool)$row->ipb_auto;
260 $block['anononly'] = (bool)$row->ipb_anon_only;
261 $block['nocreate'] = (bool)$row->ipb_create_account;
262 $block['autoblock'] = (bool)$row->ipb_enable_autoblock;
263 $block['noemail'] = (bool)$row->ipb_block_email;
264 $block['hidden'] = (bool)$row->ipb_deleted;
265 $block['allowusertalk'] = (bool)$row->ipb_allow_usertalk;
266 $block['partial'] = !(bool)$row->ipb_sitewide;
267 }
268
269 if ( $fld_restrictions ) {
270 $block['restrictions'] = [];
271 if ( !$row->ipb_sitewide && isset( $restrictions[$row->ipb_id] ) ) {
272 $block['restrictions'] = $restrictions[$row->ipb_id];
273 }
274 }
275
276 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $block );
277 if ( !$fit ) {
278 $this->setContinueEnumParameter( 'continue', "$row->ipb_timestamp|$row->ipb_id" );
279 break;
280 }
281 }
282 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'block' );
283 }
284
293 private function getRestrictionData( IResultWrapper $result, $limit ) {
294 $partialIds = [];
295 $count = 0;
296 foreach ( $result as $row ) {
297 if ( ++$count <= $limit && !$row->ipb_sitewide ) {
298 $partialIds[] = (int)$row->ipb_id;
299 }
300 }
301
302 $restrictions = $this->blockRestrictionStore->loadByBlockId( $partialIds );
303
304 $data = [];
305 $keys = [
306 'page' => 'pages',
307 'ns' => 'namespaces',
308 ];
309 if ( $this->getConfig()->get( MainConfigNames::EnablePartialActionBlocks ) ) {
310 $keys['action'] = 'actions';
311 }
312
313 foreach ( $restrictions as $restriction ) {
314 $key = $keys[$restriction->getType()];
315 $id = $restriction->getBlockId();
316 switch ( $restriction->getType() ) {
317 case 'page':
319 '@phan-var \MediaWiki\Block\Restriction\PageRestriction $restriction';
320 $value = [ 'id' => $restriction->getValue() ];
321 if ( $restriction->getTitle() ) {
322 self::addTitleInfo( $value, $restriction->getTitle() );
323 }
324 break;
325 case 'action':
326 $value = $this->blockActionInfo->getActionFromId( $restriction->getValue() );
327 break;
328 default:
329 $value = $restriction->getValue();
330 }
331
332 if ( !isset( $data[$id][$key] ) ) {
333 $data[$id][$key] = [];
334 ApiResult::setIndexedTagName( $data[$id][$key], $restriction->getType() );
335 }
336 $data[$id][$key][] = $value;
337 }
338
339 return $data;
340 }
341
342 public function getAllowedParams() {
343 $blockCIDRLimit = $this->getConfig()->get( MainConfigNames::BlockCIDRLimit );
344
345 return [
346 'start' => [
347 ParamValidator::PARAM_TYPE => 'timestamp'
348 ],
349 'end' => [
350 ParamValidator::PARAM_TYPE => 'timestamp',
351 ],
352 'dir' => [
353 ParamValidator::PARAM_TYPE => [
354 'newer',
355 'older'
356 ],
357 ParamValidator::PARAM_DEFAULT => 'older',
358 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
360 'newer' => 'api-help-paramvalue-direction-newer',
361 'older' => 'api-help-paramvalue-direction-older',
362 ],
363 ],
364 'ids' => [
365 ParamValidator::PARAM_TYPE => 'integer',
366 ParamValidator::PARAM_ISMULTI => true
367 ],
368 'users' => [
369 ParamValidator::PARAM_TYPE => 'user',
370 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'cidr' ],
371 ParamValidator::PARAM_ISMULTI => true
372 ],
373 'ip' => [
375 'apihelp-query+blocks-param-ip',
376 $blockCIDRLimit['IPv4'],
377 $blockCIDRLimit['IPv6'],
378 ],
379 ],
380 'limit' => [
381 ParamValidator::PARAM_DEFAULT => 10,
382 ParamValidator::PARAM_TYPE => 'limit',
383 IntegerDef::PARAM_MIN => 1,
384 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
385 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
386 ],
387 'prop' => [
388 ParamValidator::PARAM_DEFAULT => 'id|user|by|timestamp|expiry|reason|flags',
389 ParamValidator::PARAM_TYPE => [
390 'id',
391 'user',
392 'userid',
393 'by',
394 'byid',
395 'timestamp',
396 'expiry',
397 'reason',
398 'range',
399 'flags',
400 'restrictions',
401 ],
402 ParamValidator::PARAM_ISMULTI => true,
404 ],
405 'show' => [
406 ParamValidator::PARAM_TYPE => [
407 'account',
408 '!account',
409 'temp',
410 '!temp',
411 'ip',
412 '!ip',
413 'range',
414 '!range',
415 ],
416 ParamValidator::PARAM_ISMULTI => true
417 ],
418 'continue' => [
419 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
420 ],
421 ];
422 }
423
424 protected function getExamplesMessages() {
425 return [
426 'action=query&list=blocks'
427 => 'apihelp-query+blocks-example-simple',
428 'action=query&list=blocks&bkusers=Alice|Bob'
429 => 'apihelp-query+blocks-example-users',
430 ];
431 }
432
433 public function getHelpUrls() {
434 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Blocks';
435 }
436}
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1454
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition ApiBase.php:1643
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition ApiBase.php:196
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:221
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:938
getResult()
Get the result object.
Definition ApiBase.php:629
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:765
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:163
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:223
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:498
This is a base class for all Query modules.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction.
addFields( $value)
Add a set of fields to select to the internal array.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
getDB()
Get the Query database connection (read-only)
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
addWhereIDsFld( $table, $field, $ids)
Like addWhereFld for an integer list of IDs.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Query module to enumerate all user blocks.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
__construct(ApiQuery $query, $moduleName, BlockActionInfo $blockActionInfo, BlockRestrictionStore $blockRestrictionStore, CommentStore $commentStore)
getExamplesMessages()
Returns usage examples for this module.
getHelpUrls()
Return links to more detailed help pages about the module.
This is the main query class.
Definition ApiQuery.php:41
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Handle database storage of comments such as edit summaries and log reasons.
Defines the actions that can be blocked by a partial block.
A class containing constants representing the names of configuration variables.
Type definition for user types.
Definition UserDef.php:27
Service for formatting and validating API parameters.
Type definition for integer types.
Result wrapper for grabbing data queried from an IDatabase object.
return true
Definition router.php:92