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