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