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  $timestamp = $db->timestamp( (int)wfTimestamp( TS_UNIX ) - $activeUserSeconds );
223  $subqueryBuilder = $db->newSelectQueryBuilder()
224  ->select( 'COUNT(*)' )
225  ->from( 'recentchanges' )
226  ->join( 'actor', null, 'rc_actor = actor_id' )
227  ->where( [
228  'actor_user = user_id',
229  'rc_type != ' . $db->addQuotes( RC_EXTERNAL ), // no wikidata
230  'rc_log_type IS NULL OR rc_log_type != ' . $db->addQuotes( 'newusers' ),
231  $db->buildComparison( '>=', [ 'rc_timestamp' => $timestamp ] ),
232  ] );
233  $this->addFields( [
234  'recentactions' => '(' . $subqueryBuilder->caller( __METHOD__ )->getSQL() . ')'
235  ] );
236  }
237 
238  $sqlLimit = $limit + $maxDuplicateRows;
239  $this->addOption( 'LIMIT', $sqlLimit );
240 
241  $this->addFields( [
242  'user_name',
243  'user_id'
244  ] );
245  $this->addFieldsIf( 'user_editcount', $fld_editcount );
246  $this->addFieldsIf( 'user_registration', $fld_registration );
247 
248  $res = $this->select( __METHOD__ );
249  $count = 0;
250  $countDuplicates = 0;
251  $lastUser = false;
252  $result = $this->getResult();
253  foreach ( $res as $row ) {
254  $count++;
255 
256  if ( $lastUser === $row->user_name ) {
257  // Duplicate row due to one of the needed subtable joins.
258  // Ignore it, but count the number of them to sensibly handle
259  // miscalculation of $maxDuplicateRows.
260  $countDuplicates++;
261  if ( $countDuplicates == $maxDuplicateRows ) {
262  ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
263  }
264  continue;
265  }
266 
267  $countDuplicates = 0;
268  $lastUser = $row->user_name;
269 
270  if ( $count > $limit ) {
271  // We've reached the one extra which shows that there are
272  // additional pages to be had. Stop here...
273  $this->setContinueEnumParameter( 'from', $row->user_name );
274  break;
275  }
276 
277  if ( $count == $sqlLimit ) {
278  // Should never hit this (either the $countDuplicates check or
279  // the $count > $limit check should hit first), but check it
280  // anyway just in case.
281  ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
282  }
283 
284  if ( $params['activeusers'] && (int)$row->recentactions === 0 ) {
285  // activeusers cache was out of date
286  continue;
287  }
288 
289  $data = [
290  'userid' => (int)$row->user_id,
291  'name' => $row->user_name,
292  ];
293 
294  if ( $fld_centralids ) {
296  $this->getConfig(), $this->userFactory->newFromId( (int)$row->user_id ), $params['attachedwiki']
297  );
298  }
299 
300  if ( $fld_blockinfo && $row->ipb_id !== null ) {
301  $data += $this->getBlockDetails( DatabaseBlock::newFromRow( $row ) );
302  }
303  if ( $row->ipb_deleted ) {
304  $data['hidden'] = true;
305  }
306  if ( $fld_editcount ) {
307  $data['editcount'] = (int)$row->user_editcount;
308  }
309  if ( $params['activeusers'] ) {
310  $data['recentactions'] = (int)$row->recentactions;
311  }
312  if ( $fld_registration ) {
313  $data['registration'] = $row->user_registration ?
314  wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
315  }
316 
317  if ( $fld_implicitgroups || $fld_groups || $fld_rights ) {
318  $implicitGroups = $this->userGroupManager
319  ->getUserImplicitGroups( $this->userFactory->newFromId( (int)$row->user_id ) );
320  if ( isset( $row->groups ) && $row->groups !== '' ) {
321  $groups = array_merge( $implicitGroups, explode( '|', $row->groups ) );
322  } else {
323  $groups = $implicitGroups;
324  }
325 
326  if ( $fld_groups ) {
327  $data['groups'] = $groups;
328  ApiResult::setIndexedTagName( $data['groups'], 'g' );
329  ApiResult::setArrayType( $data['groups'], 'array' );
330  }
331 
332  if ( $fld_implicitgroups ) {
333  $data['implicitgroups'] = $implicitGroups;
334  ApiResult::setIndexedTagName( $data['implicitgroups'], 'g' );
335  ApiResult::setArrayType( $data['implicitgroups'], 'array' );
336  }
337 
338  if ( $fld_rights ) {
339  $data['rights'] = $this->groupPermissionsLookup->getGroupPermissions( $groups );
340  ApiResult::setIndexedTagName( $data['rights'], 'r' );
341  ApiResult::setArrayType( $data['rights'], 'array' );
342  }
343  }
344 
345  $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data );
346  if ( !$fit ) {
347  $this->setContinueEnumParameter( 'from', $data['name'] );
348  break;
349  }
350  }
351 
352  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'u' );
353  }
354 
355  public function getCacheMode( $params ) {
356  return 'anon-public-user-private';
357  }
358 
359  public function getAllowedParams( $flags = 0 ) {
360  $userGroups = $this->userGroupManager->listAllGroups();
361 
362  if ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
363  sort( $userGroups );
364  }
365 
366  return [
367  'from' => null,
368  'to' => null,
369  'prefix' => null,
370  'dir' => [
371  ParamValidator::PARAM_DEFAULT => 'ascending',
372  ParamValidator::PARAM_TYPE => [
373  'ascending',
374  'descending'
375  ],
376  ],
377  'group' => [
378  ParamValidator::PARAM_TYPE => $userGroups,
379  ParamValidator::PARAM_ISMULTI => true,
380  ],
381  'excludegroup' => [
382  ParamValidator::PARAM_TYPE => $userGroups,
383  ParamValidator::PARAM_ISMULTI => true,
384  ],
385  'rights' => [
386  ParamValidator::PARAM_TYPE => $this->getPermissionManager()->getAllPermissions(),
387  ParamValidator::PARAM_ISMULTI => true,
388  ],
389  'prop' => [
390  ParamValidator::PARAM_ISMULTI => true,
391  ParamValidator::PARAM_TYPE => [
392  'blockinfo',
393  'groups',
394  'implicitgroups',
395  'rights',
396  'editcount',
397  'registration',
398  'centralids',
399  ],
401  ],
402  'limit' => [
403  ParamValidator::PARAM_DEFAULT => 10,
404  ParamValidator::PARAM_TYPE => 'limit',
405  IntegerDef::PARAM_MIN => 1,
406  IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
407  IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
408  ],
409  'witheditsonly' => false,
410  'activeusers' => [
411  ParamValidator::PARAM_DEFAULT => false,
413  'apihelp-query+allusers-param-activeusers',
414  $this->getConfig()->get( MainConfigNames::ActiveUserDays )
415  ],
416  ],
417  'attachedwiki' => null,
418  ];
419  }
420 
421  protected function getExamplesMessages() {
422  return [
423  'action=query&list=allusers&aufrom=Y'
424  => 'apihelp-query+allusers-example-y',
425  ];
426  }
427 
428  public function getHelpUrls() {
429  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allusers';
430  }
431 }
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:88
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1701
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:694
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition: ApiBase.php:204
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:229
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:946
getResult()
Get the result object.
Definition: ApiBase.php:637
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:773
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:166
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
Definition: ApiBase.php:242
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:231
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:506
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:42
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:56
ucfirst( $str)
Definition: Language.php:2632
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