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