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