MediaWiki master
ApiQueryAllUsers.php
Go to the documentation of this file.
1<?php
31
39
40 private UserFactory $userFactory;
41 private UserGroupManager $userGroupManager;
42 private GroupPermissionsLookup $groupPermissionsLookup;
43 private Language $contentLanguage;
44
53 public function __construct(
54 ApiQuery $query,
55 $moduleName,
56 UserFactory $userFactory,
57 UserGroupManager $userGroupManager,
58 GroupPermissionsLookup $groupPermissionsLookup,
59 Language $contentLanguage
60 ) {
61 parent::__construct( $query, $moduleName, 'au' );
62 $this->userFactory = $userFactory;
63 $this->userGroupManager = $userGroupManager;
64 $this->groupPermissionsLookup = $groupPermissionsLookup;
65 $this->contentLanguage = $contentLanguage;
66 }
67
74 private function getCanonicalUserName( $name ) {
75 $name = $this->contentLanguage->ucfirst( $name );
76 return strtr( $name, '_', ' ' );
77 }
78
79 public function execute() {
81 $activeUserDays = $this->getConfig()->get( MainConfigNames::ActiveUserDays );
82
83 $db = $this->getDB();
84
85 $prop = $params['prop'];
86 if ( $prop !== null ) {
87 $prop = array_fill_keys( $prop, true );
88 $fld_blockinfo = isset( $prop['blockinfo'] );
89 $fld_editcount = isset( $prop['editcount'] );
90 $fld_groups = isset( $prop['groups'] );
91 $fld_rights = isset( $prop['rights'] );
92 $fld_registration = isset( $prop['registration'] );
93 $fld_implicitgroups = isset( $prop['implicitgroups'] );
94 $fld_centralids = isset( $prop['centralids'] );
95 } else {
96 $fld_blockinfo = $fld_editcount = $fld_groups = $fld_registration =
97 $fld_rights = $fld_implicitgroups = $fld_centralids = false;
98 }
99
100 $limit = $params['limit'];
101
102 $this->addTables( 'user' );
103
104 $dir = ( $params['dir'] == 'descending' ? 'older' : 'newer' );
105 $from = $params['from'] === null ? null : $this->getCanonicalUserName( $params['from'] );
106 $to = $params['to'] === null ? null : $this->getCanonicalUserName( $params['to'] );
107
108 # MySQL can't figure out that 'user_name' and 'qcc_title' are the same
109 # despite the JOIN condition, so manually sort on the correct one.
110 $userFieldToSort = $params['activeusers'] ? 'qcc_title' : 'user_name';
111
112 # Some of these subtable joins are going to give us duplicate rows, so
113 # calculate the maximum number of duplicates we might see.
114 $maxDuplicateRows = 1;
115
116 $this->addWhereRange( $userFieldToSort, $dir, $from, $to );
117
118 if ( $params['prefix'] !== null ) {
119 $this->addWhere(
120 $db->expr(
121 $userFieldToSort,
122 IExpression::LIKE,
123 new LikeValue( $this->getCanonicalUserName( $params['prefix'] ), $db->anyString() )
124 )
125 );
126 }
127
128 if ( $params['rights'] !== null && count( $params['rights'] ) ) {
129 $groups = [];
130 // TODO: this does not properly account for $wgRevokePermissions
131 foreach ( $params['rights'] as $r ) {
132 if ( in_array( $r, $this->getPermissionManager()->getImplicitRights(), true ) ) {
133 $groups[] = '*';
134 } else {
135 $groups = array_merge(
136 $groups,
137 $this->groupPermissionsLookup->getGroupsWithPermission( $r )
138 );
139 }
140 }
141
142 if ( $groups === [] ) {
143 // No group with the given right(s) exists, no need for a query
144 $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], '' );
145
146 return;
147 }
148
149 $groups = array_unique( $groups );
150 if ( in_array( '*', $groups, true ) || in_array( 'user', $groups, true ) ) {
151 // All user rows logically match but there are no "*"/"user" user_groups rows
152 $groups = [];
153 }
154
155 if ( $params['group'] === null ) {
156 $params['group'] = $groups;
157 } else {
158 $params['group'] = array_unique( array_merge( $params['group'], $groups ) );
159 }
160 }
161
162 $this->requireMaxOneParameter( $params, 'group', 'excludegroup' );
163
164 if ( $params['group'] !== null && count( $params['group'] ) ) {
165 // Filter only users that belong to a given group. This might
166 // produce as many rows-per-user as there are groups being checked.
167 $this->addTables( 'user_groups', 'ug1' );
168 $this->addJoinConds( [
169 'ug1' => [
170 'JOIN',
171 [
172 'ug1.ug_user=user_id',
173 'ug1.ug_group' => $params['group'],
174 $db->expr( 'ug1.ug_expiry', '=', null )->or( 'ug1.ug_expiry', '>=', $db->timestamp() ),
175 ]
176 ]
177 ] );
178 $maxDuplicateRows *= count( $params['group'] );
179 }
180
181 if ( $params['excludegroup'] !== null && count( $params['excludegroup'] ) ) {
182 // Filter only users don't belong to a given group. This can only
183 // produce one row-per-user, because we only keep on "no match".
184 $this->addTables( 'user_groups', 'ug1' );
185
186 $this->addJoinConds( [ 'ug1' => [ 'LEFT JOIN',
187 [
188 'ug1.ug_user=user_id',
189 $db->expr( 'ug1.ug_expiry', '=', null )->or( 'ug1.ug_expiry', '>=', $db->timestamp() ),
190 'ug1.ug_group' => $params['excludegroup'],
191 ]
192 ] ] );
193 $this->addWhere( [ 'ug1.ug_user' => null ] );
194 }
195
196 if ( $params['witheditsonly'] ) {
197 $this->addWhere( $db->expr( 'user_editcount', '>', 0 ) );
198 }
199
200 $this->addDeletedUserFilter();
201
202 if ( $fld_groups || $fld_rights ) {
203 $this->addFields( [ 'groups' =>
204 $db->newSelectQueryBuilder()
205 ->table( 'user_groups' )
206 ->field( 'ug_group' )
207 ->where( [
208 'ug_user=user_id',
209 $db->expr( 'ug_expiry', '=', null )->or( 'ug_expiry', '>=', $db->timestamp() )
210 ] )
211 ->buildGroupConcatField( '|' )
212 ] );
213 }
214
215 if ( $params['activeusers'] ) {
216 $activeUserSeconds = $activeUserDays * 86400;
217
218 // Filter query to only include users in the active users cache.
219 // There shouldn't be any duplicate rows in querycachetwo here.
220 $this->addTables( 'querycachetwo' );
221 $this->addJoinConds( [ 'querycachetwo' => [
222 'JOIN', [
223 'qcc_type' => 'activeusers',
224 'qcc_namespace' => NS_USER,
225 'qcc_title=user_name',
226 ],
227 ] ] );
228
229 // Actually count the actions using a subquery (T66505 and T66507)
230 $timestamp = $db->timestamp( (int)wfTimestamp( TS_UNIX ) - $activeUserSeconds );
231 $subqueryBuilder = $db->newSelectQueryBuilder()
232 ->select( 'COUNT(*)' )
233 ->from( 'recentchanges' )
234 ->join( 'actor', null, 'rc_actor = actor_id' )
235 ->where( [
236 'actor_user = user_id',
237 $db->expr( 'rc_type', '!=', RC_EXTERNAL ), // no wikidata
238 $db->expr( 'rc_log_type', '=', null )
239 ->or( 'rc_log_type', '!=', 'newusers' ),
240 $db->expr( 'rc_timestamp', '>=', $timestamp ),
241 ] );
242 $this->addFields( [
243 'recentactions' => '(' . $subqueryBuilder->caller( __METHOD__ )->getSQL() . ')'
244 ] );
245 }
246
247 $sqlLimit = $limit + $maxDuplicateRows;
248 $this->addOption( 'LIMIT', $sqlLimit );
249
250 $this->addFields( [
251 'user_name',
252 'user_id'
253 ] );
254 $this->addFieldsIf( 'user_editcount', $fld_editcount );
255 $this->addFieldsIf( 'user_registration', $fld_registration );
256
257 $res = $this->select( __METHOD__ );
258 $count = 0;
259 $countDuplicates = 0;
260 $lastUser = false;
261 $result = $this->getResult();
262 $blockInfos = $fld_blockinfo ? $this->getBlockDetailsForRows( $res ) : null;
263 foreach ( $res as $row ) {
264 $count++;
265
266 if ( $lastUser === $row->user_name ) {
267 // Duplicate row due to one of the needed subtable joins.
268 // Ignore it, but count the number of them to sensibly handle
269 // miscalculation of $maxDuplicateRows.
270 $countDuplicates++;
271 if ( $countDuplicates == $maxDuplicateRows ) {
272 ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
273 }
274 continue;
275 }
276
277 $countDuplicates = 0;
278 $lastUser = $row->user_name;
279
280 if ( $count > $limit ) {
281 // We've reached the one extra which shows that there are
282 // additional pages to be had. Stop here...
283 $this->setContinueEnumParameter( 'from', $row->user_name );
284 break;
285 }
286
287 if ( $count == $sqlLimit ) {
288 // Should never hit this (either the $countDuplicates check or
289 // the $count > $limit check should hit first), but check it
290 // anyway just in case.
291 ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
292 }
293
294 if ( $params['activeusers'] && (int)$row->recentactions === 0 ) {
295 // activeusers cache was out of date
296 continue;
297 }
298
299 $data = [
300 'userid' => (int)$row->user_id,
301 'name' => $row->user_name,
302 ];
303
304 if ( $fld_centralids ) {
306 $this->getConfig(), $this->userFactory->newFromId( (int)$row->user_id ), $params['attachedwiki']
307 );
308 }
309
310 if ( $fld_blockinfo && isset( $blockInfos[$row->user_id] ) ) {
311 $data += $blockInfos[$row->user_id];
312 }
313 if ( $row->hu_deleted ) {
314 $data['hidden'] = true;
315 }
316 if ( $fld_editcount ) {
317 $data['editcount'] = (int)$row->user_editcount;
318 }
319 if ( $params['activeusers'] ) {
320 $data['recentactions'] = (int)$row->recentactions;
321 }
322 if ( $fld_registration ) {
323 $data['registration'] = $row->user_registration ?
324 wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
325 }
326
327 if ( $fld_implicitgroups || $fld_groups || $fld_rights ) {
328 $implicitGroups = $this->userGroupManager
329 ->getUserImplicitGroups( $this->userFactory->newFromId( (int)$row->user_id ) );
330 if ( isset( $row->groups ) && $row->groups !== '' ) {
331 $groups = array_merge( $implicitGroups, explode( '|', $row->groups ) );
332 } else {
333 $groups = $implicitGroups;
334 }
335
336 if ( $fld_groups ) {
337 $data['groups'] = $groups;
338 ApiResult::setIndexedTagName( $data['groups'], 'g' );
339 ApiResult::setArrayType( $data['groups'], 'array' );
340 }
341
342 if ( $fld_implicitgroups ) {
343 $data['implicitgroups'] = $implicitGroups;
344 ApiResult::setIndexedTagName( $data['implicitgroups'], 'g' );
345 ApiResult::setArrayType( $data['implicitgroups'], 'array' );
346 }
347
348 if ( $fld_rights ) {
349 $user = $this->userFactory->newFromId( (int)$row->user_id );
350 $data['rights'] = $this->getPermissionManager()->getUserPermissions( $user );
351 ApiResult::setIndexedTagName( $data['rights'], 'r' );
352 ApiResult::setArrayType( $data['rights'], 'array' );
353 }
354 }
355
356 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data );
357 if ( !$fit ) {
358 $this->setContinueEnumParameter( 'from', $data['name'] );
359 break;
360 }
361 }
362
363 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'u' );
364 }
365
366 public function getCacheMode( $params ) {
367 return 'anon-public-user-private';
368 }
369
370 public function getAllowedParams( $flags = 0 ) {
371 $userGroups = $this->userGroupManager->listAllGroups();
372
373 if ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
374 sort( $userGroups );
375 }
376
377 return [
378 'from' => null,
379 'to' => null,
380 'prefix' => null,
381 'dir' => [
382 ParamValidator::PARAM_DEFAULT => 'ascending',
383 ParamValidator::PARAM_TYPE => [
384 'ascending',
385 'descending'
386 ],
387 ],
388 'group' => [
389 ParamValidator::PARAM_TYPE => $userGroups,
390 ParamValidator::PARAM_ISMULTI => true,
391 ],
392 'excludegroup' => [
393 ParamValidator::PARAM_TYPE => $userGroups,
394 ParamValidator::PARAM_ISMULTI => true,
395 ],
396 'rights' => [
397 ParamValidator::PARAM_TYPE => array_unique( array_merge(
398 $this->getPermissionManager()->getAllPermissions(),
399 $this->getPermissionManager()->getImplicitRights()
400 ) ),
401 ParamValidator::PARAM_ISMULTI => true,
402 ],
403 'prop' => [
404 ParamValidator::PARAM_ISMULTI => true,
405 ParamValidator::PARAM_TYPE => [
406 'blockinfo',
407 'groups',
408 'implicitgroups',
409 'rights',
410 'editcount',
411 'registration',
412 'centralids',
413 ],
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 'witheditsonly' => false,
424 'activeusers' => [
425 ParamValidator::PARAM_DEFAULT => false,
427 'apihelp-query+allusers-param-activeusers',
428 $this->getConfig()->get( MainConfigNames::ActiveUserDays )
429 ],
430 ],
431 'attachedwiki' => null,
432 ];
433 }
434
435 protected function getExamplesMessages() {
436 return [
437 'action=query&list=allusers&aufrom=Y'
438 => 'apihelp-query+allusers-example-y',
439 ];
440 }
441
442 public function getHelpUrls() {
443 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allusers';
444 }
445}
const NS_USER
Definition Defines.php:67
const RC_EXTERNAL
Definition Defines.php:120
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
array $params
The job parameters.
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1783
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition ApiBase.php:741
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:212
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:237
requireMaxOneParameter( $params,... $required)
Dies if more than one parameter from a certain set of parameters are set and not false.
Definition ApiBase.php:995
getResult()
Get the result object.
Definition ApiBase.php:681
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:821
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:172
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When this is set, the result could take longer to generate,...
Definition ApiBase.php:250
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:239
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:542
Query module to enumerate all registered users.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
__construct(ApiQuery $query, $moduleName, UserFactory $userFactory, UserGroupManager $userGroupManager, GroupPermissionsLookup $groupPermissionsLookup, Language $contentLanguage)
getExamplesMessages()
Returns usage examples for this module.
getAllowedParams( $flags=0)
getCacheMode( $params)
Get the cache mode for the data generated by this module.
getHelpUrls()
Return links to more detailed help pages about the module.
This is a base class for all Query modules.
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
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.
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.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
static getCentralUserInfo(Config $config, UserIdentity $user, $attachedWiki=UserIdentity::LOCAL)
Get central user info.
This is the main query class.
Definition ApiQuery.php:43
Base class for language-specific code.
Definition Language.php:66
ucfirst( $str)
A class containing constants representing the names of configuration variables.
Creates User objects.
Service for formatting and validating API parameters.
Type definition for integer types.
Content of like value.
Definition LikeValue.php:14
trait ApiQueryBlockInfoTrait