MediaWiki  1.34.0
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  $exclude = [ 'ug1.ug_group' => $params['excludegroup'][0] ];
141  } else {
142  $exclude = [ $db->makeList(
143  [ 'ug1.ug_group' => $params['excludegroup'] ],
144  LIST_OR
145  ) ];
146  }
147  $this->addJoinConds( [ 'ug1' => [ 'LEFT JOIN',
148  array_merge( [
149  'ug1.ug_user=user_id',
150  'ug1.ug_expiry IS NULL OR ug1.ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
151  ], $exclude )
152  ] ] );
153  $this->addWhere( 'ug1.ug_user IS NULL' );
154  }
155 
156  if ( $params['witheditsonly'] ) {
157  $this->addWhere( 'user_editcount > 0' );
158  }
159 
160  $this->addBlockInfoToQuery( $fld_blockinfo );
161 
162  if ( $fld_groups || $fld_rights ) {
163  $this->addFields( [ 'groups' =>
164  $db->buildGroupConcatField( '|', 'user_groups', 'ug_group', [
165  'ug_user=user_id',
166  'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
167  ] )
168  ] );
169  }
170 
171  if ( $params['activeusers'] ) {
172  $activeUserSeconds = $activeUserDays * 86400;
173 
174  // Filter query to only include users in the active users cache.
175  // There shouldn't be any duplicate rows in querycachetwo here.
176  $this->addTables( 'querycachetwo' );
177  $this->addJoinConds( [ 'querycachetwo' => [
178  'JOIN', [
179  'qcc_type' => 'activeusers',
180  'qcc_namespace' => NS_USER,
181  'qcc_title=user_name',
182  ],
183  ] ] );
184 
185  // Actually count the actions using a subquery (T66505 and T66507)
186  $tables = [ 'recentchanges', 'actor' ];
187  $joins = [
188  'actor' => [ 'JOIN', 'rc_actor = actor_id' ],
189  ];
190  $timestamp = $db->timestamp( wfTimestamp( TS_UNIX ) - $activeUserSeconds );
191  $this->addFields( [
192  'recentactions' => '(' . $db->selectSQLText(
193  $tables,
194  'COUNT(*)',
195  [
196  'actor_user = user_id',
197  'rc_type != ' . $db->addQuotes( RC_EXTERNAL ), // no wikidata
198  'rc_log_type IS NULL OR rc_log_type != ' . $db->addQuotes( 'newusers' ),
199  'rc_timestamp >= ' . $db->addQuotes( $timestamp ),
200  ],
201  __METHOD__,
202  [],
203  $joins
204  ) . ')'
205  ] );
206  }
207 
208  $sqlLimit = $limit + $maxDuplicateRows;
209  $this->addOption( 'LIMIT', $sqlLimit );
210 
211  $this->addFields( [
212  'user_name',
213  'user_id'
214  ] );
215  $this->addFieldsIf( 'user_editcount', $fld_editcount );
216  $this->addFieldsIf( 'user_registration', $fld_registration );
217 
218  $res = $this->select( __METHOD__ );
219  $count = 0;
220  $countDuplicates = 0;
221  $lastUser = false;
222  $result = $this->getResult();
223  foreach ( $res as $row ) {
224  $count++;
225 
226  if ( $lastUser === $row->user_name ) {
227  // Duplicate row due to one of the needed subtable joins.
228  // Ignore it, but count the number of them to sanely handle
229  // miscalculation of $maxDuplicateRows.
230  $countDuplicates++;
231  if ( $countDuplicates == $maxDuplicateRows ) {
232  ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
233  }
234  continue;
235  }
236 
237  $countDuplicates = 0;
238  $lastUser = $row->user_name;
239 
240  if ( $count > $limit ) {
241  // We've reached the one extra which shows that there are
242  // additional pages to be had. Stop here...
243  $this->setContinueEnumParameter( 'from', $row->user_name );
244  break;
245  }
246 
247  if ( $count == $sqlLimit ) {
248  // Should never hit this (either the $countDuplicates check or
249  // the $count > $limit check should hit first), but check it
250  // anyway just in case.
251  ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
252  }
253 
254  if ( $params['activeusers'] && $row->recentactions === 0 ) {
255  // activeusers cache was out of date
256  continue;
257  }
258 
259  $data = [
260  'userid' => (int)$row->user_id,
261  'name' => $row->user_name,
262  ];
263 
264  if ( $fld_centralids ) {
266  $this->getConfig(), User::newFromId( $row->user_id ), $params['attachedwiki']
267  );
268  }
269 
270  if ( $fld_blockinfo && !is_null( $row->ipb_id ) ) {
271  $data += $this->getBlockDetails( DatabaseBlock::newFromRow( $row ) );
272  }
273  if ( $row->ipb_deleted ) {
274  $data['hidden'] = true;
275  }
276  if ( $fld_editcount ) {
277  $data['editcount'] = (int)$row->user_editcount;
278  }
279  if ( $params['activeusers'] ) {
280  $data['recentactions'] = (int)$row->recentactions;
281  }
282  if ( $fld_registration ) {
283  $data['registration'] = $row->user_registration ?
284  wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
285  }
286 
287  if ( $fld_implicitgroups || $fld_groups || $fld_rights ) {
288  $implicitGroups = User::newFromId( $row->user_id )->getAutomaticGroups();
289  if ( isset( $row->groups ) && $row->groups !== '' ) {
290  $groups = array_merge( $implicitGroups, explode( '|', $row->groups ) );
291  } else {
292  $groups = $implicitGroups;
293  }
294 
295  if ( $fld_groups ) {
296  $data['groups'] = $groups;
297  ApiResult::setIndexedTagName( $data['groups'], 'g' );
298  ApiResult::setArrayType( $data['groups'], 'array' );
299  }
300 
301  if ( $fld_implicitgroups ) {
302  $data['implicitgroups'] = $implicitGroups;
303  ApiResult::setIndexedTagName( $data['implicitgroups'], 'g' );
304  ApiResult::setArrayType( $data['implicitgroups'], 'array' );
305  }
306 
307  if ( $fld_rights ) {
308  $data['rights'] = $this->getPermissionManager()->getGroupPermissions( $groups );
309  ApiResult::setIndexedTagName( $data['rights'], 'r' );
310  ApiResult::setArrayType( $data['rights'], 'array' );
311  }
312  }
313 
314  $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data );
315  if ( !$fit ) {
316  $this->setContinueEnumParameter( 'from', $data['name'] );
317  break;
318  }
319  }
320 
321  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'u' );
322  }
323 
324  public function getCacheMode( $params ) {
325  return 'anon-public-user-private';
326  }
327 
328  public function getAllowedParams() {
329  $userGroups = User::getAllGroups();
330 
331  return [
332  'from' => null,
333  'to' => null,
334  'prefix' => null,
335  'dir' => [
336  ApiBase::PARAM_DFLT => 'ascending',
338  'ascending',
339  'descending'
340  ],
341  ],
342  'group' => [
343  ApiBase::PARAM_TYPE => $userGroups,
344  ApiBase::PARAM_ISMULTI => true,
345  ],
346  'excludegroup' => [
347  ApiBase::PARAM_TYPE => $userGroups,
348  ApiBase::PARAM_ISMULTI => true,
349  ],
350  'rights' => [
351  ApiBase::PARAM_TYPE => $this->getPermissionManager()->getAllPermissions(),
352  ApiBase::PARAM_ISMULTI => true,
353  ],
354  'prop' => [
355  ApiBase::PARAM_ISMULTI => true,
357  'blockinfo',
358  'groups',
359  'implicitgroups',
360  'rights',
361  'editcount',
362  'registration',
363  'centralids',
364  ],
366  ],
367  'limit' => [
368  ApiBase::PARAM_DFLT => 10,
369  ApiBase::PARAM_TYPE => 'limit',
370  ApiBase::PARAM_MIN => 1,
373  ],
374  'witheditsonly' => false,
375  'activeusers' => [
376  ApiBase::PARAM_DFLT => false,
378  'apihelp-query+allusers-param-activeusers',
379  $this->getConfig()->get( 'ActiveUserDays' )
380  ],
381  ],
382  'attachedwiki' => null,
383  ];
384  }
385 
386  protected function getExamplesMessages() {
387  return [
388  'action=query&list=allusers&aufrom=Y'
389  => 'apihelp-query+allusers-example-y',
390  ];
391  }
392 
393  public function getHelpUrls() {
394  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allusers';
395  }
396 }
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:63
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:539
ApiQueryBase\addFields
addFields( $value)
Add a set of fields to select to the internal array.
Definition: ApiQueryBase.php:193
RC_EXTERNAL
const RC_EXTERNAL
Definition: Defines.php:125
ApiQuery
This is the main query class.
Definition: ApiQuery.php:37
ApiQueryAllUsers\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiQueryAllUsers.php:386
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:131
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1869
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:94
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:640
ApiQueryBase\addOption
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
Definition: ApiQueryBase.php:350
$res
$res
Definition: testCompression.php:52
ApiQueryBase\addFieldsIf
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
Definition: ApiQueryBase.php:207
ApiQueryAllUsers\getCacheMode
getCacheMode( $params)
Get the cache mode for the data generated by this module.
Definition: ApiQueryAllUsers.php:324
MediaWiki\Block\DatabaseBlock
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
Definition: DatabaseBlock.php:54
ApiQueryBlockInfoTrait
trait ApiQueryBlockInfoTrait
Definition: ApiQueryBlockInfoTrait.php:27
ApiBase\PARAM_MIN
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:106
ApiResult\setArrayType
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
Definition: ApiResult.php:728
LIST_OR
const LIST_OR
Definition: Defines.php:42
ApiQueryAllUsers\getCanonicalUserName
getCanonicalUserName( $name)
This function converts the user name to a canonical form which is stored in the database.
Definition: ApiQueryAllUsers.php:43
ApiQueryBase
This is a base class for all Query modules.
Definition: ApiQueryBase.php:34
ApiBase\LIMIT_BIG1
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:259
ApiQueryAllUsers\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiQueryAllUsers.php:328
ApiQueryBase\getDB
getDB()
Get the Query database connection (read-only)
Definition: ApiQueryBase.php:107
ApiBase\PARAM_MAX
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:97
ApiQueryBase\addTables
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
Definition: ApiQueryBase.php:161
ApiQueryBase\select
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
Definition: ApiQueryBase.php:375
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:761
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:303
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:616
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:710
ApiQueryBase\addJoinConds
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
Definition: ApiQueryBase.php:182
User\getAllGroups
static getAllGroups()
Return the set of defined explicit groups.
Definition: User.php:4808
ApiBase\requireMaxOneParameter
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:931
ApiBase\LIMIT_BIG2
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:261
ApiQueryBase\$tables
$tables
Definition: ApiQueryBase.php:37
ApiQueryAllUsers
Query module to enumerate all registered users.
Definition: ApiQueryAllUsers.php:30
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:520
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
NS_USER
const NS_USER
Definition: Defines.php:62
ApiBase\PARAM_MAX2
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
Definition: ApiBase.php:103
ApiQueryBase\addWhere
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Definition: ApiQueryBase.php:228
ApiQueryUserInfo\getCentralUserInfo
static getCentralUserInfo(Config $config, User $user, $attachedWiki=null)
Get central user info.
Definition: ApiQueryUserInfo.php:90
ApiQueryBase\setContinueEnumParameter
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
Definition: ApiQueryBase.php:492
ApiQueryAllUsers\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiQueryAllUsers.php:47
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:164
CommentStore\getStore
static getStore()
Definition: CommentStore.php:139
ApiQueryAllUsers\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiQueryAllUsers.php:393
ApiQueryAllUsers\__construct
__construct(ApiQuery $query, $moduleName)
Definition: ApiQueryAllUsers.php:33
ApiBase\dieDebug
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2220
if
if($IP===false)
Definition: initImageData.php:4
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:37