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