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