Merge "Allow wildcard searching in wiki IDs for interwiki user rights logs"
[lhc/web/wiklou.git] / includes / api / ApiQueryAllUsers.php
1 <?php
2 /**
3 *
4 *
5 * Created on July 7, 2007
6 *
7 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * Query module to enumerate all registered users.
29 *
30 * @ingroup API
31 */
32 class ApiQueryAllUsers extends ApiQueryBase {
33 public function __construct( ApiQuery $query, $moduleName ) {
34 parent::__construct( $query, $moduleName, 'au' );
35 }
36
37 /**
38 * This function converts the user name to a canonical form
39 * which is stored in the database.
40 * @param string $name
41 * @return string
42 */
43 private function getCanonicalUserName( $name ) {
44 return str_replace( '_', ' ', $name );
45 }
46
47 public function execute() {
48 $params = $this->extractRequestParams();
49
50 if ( $params['activeusers'] ) {
51 // Update active user cache
52 SpecialActiveUsers::mergeActiveUsers( 600 );
53 }
54
55 $db = $this->getDB();
56
57 $prop = $params['prop'];
58 if ( !is_null( $prop ) ) {
59 $prop = array_flip( $prop );
60 $fld_blockinfo = isset( $prop['blockinfo'] );
61 $fld_editcount = isset( $prop['editcount'] );
62 $fld_groups = isset( $prop['groups'] );
63 $fld_rights = isset( $prop['rights'] );
64 $fld_registration = isset( $prop['registration'] );
65 $fld_implicitgroups = isset( $prop['implicitgroups'] );
66 } else {
67 $fld_blockinfo = $fld_editcount = $fld_groups = $fld_registration =
68 $fld_rights = $fld_implicitgroups = false;
69 }
70
71 $limit = $params['limit'];
72
73 $this->addTables( 'user' );
74 $useIndex = true;
75
76 $dir = ( $params['dir'] == 'descending' ? 'older' : 'newer' );
77 $from = is_null( $params['from'] ) ? null : $this->getCanonicalUserName( $params['from'] );
78 $to = is_null( $params['to'] ) ? null : $this->getCanonicalUserName( $params['to'] );
79
80 # MySQL can't figure out that 'user_name' and 'qcc_title' are the same
81 # despite the JOIN condition, so manually sort on the correct one.
82 $userFieldToSort = $params['activeusers'] ? 'qcc_title' : 'user_name';
83
84 $this->addWhereRange( $userFieldToSort, $dir, $from, $to );
85
86 if ( !is_null( $params['prefix'] ) ) {
87 $this->addWhere( $userFieldToSort .
88 $db->buildLike( $this->getCanonicalUserName( $params['prefix'] ), $db->anyString() ) );
89 }
90
91 if ( !is_null( $params['rights'] ) && count( $params['rights'] ) ) {
92 $groups = array();
93 foreach ( $params['rights'] as $r ) {
94 $groups = array_merge( $groups, User::getGroupsWithPermission( $r ) );
95 }
96
97 // no group with the given right(s) exists, no need for a query
98 if ( !count( $groups ) ) {
99 $this->getResult()->setIndexedTagName_internal( array( 'query', $this->getModuleName() ), '' );
100
101 return;
102 }
103
104 $groups = array_unique( $groups );
105
106 if ( is_null( $params['group'] ) ) {
107 $params['group'] = $groups;
108 } else {
109 $params['group'] = array_unique( array_merge( $params['group'], $groups ) );
110 }
111 }
112
113 if ( !is_null( $params['group'] ) && !is_null( $params['excludegroup'] ) ) {
114 $this->dieUsage( 'group and excludegroup cannot be used together', 'group-excludegroup' );
115 }
116
117 if ( !is_null( $params['group'] ) && count( $params['group'] ) ) {
118 $useIndex = false;
119 // Filter only users that belong to a given group
120 $this->addTables( 'user_groups', 'ug1' );
121 $this->addJoinConds( array( 'ug1' => array( 'INNER JOIN', array( 'ug1.ug_user=user_id',
122 'ug1.ug_group' => $params['group'] ) ) ) );
123 }
124
125 if ( !is_null( $params['excludegroup'] ) && count( $params['excludegroup'] ) ) {
126 $useIndex = false;
127 // Filter only users don't belong to a given group
128 $this->addTables( 'user_groups', 'ug1' );
129
130 if ( count( $params['excludegroup'] ) == 1 ) {
131 $exclude = array( 'ug1.ug_group' => $params['excludegroup'][0] );
132 } else {
133 $exclude = array( $db->makeList(
134 array( 'ug1.ug_group' => $params['excludegroup'] ),
135 LIST_OR
136 ) );
137 }
138 $this->addJoinConds( array( 'ug1' => array( 'LEFT OUTER JOIN',
139 array_merge( array( 'ug1.ug_user=user_id' ), $exclude )
140 ) ) );
141 $this->addWhere( 'ug1.ug_user IS NULL' );
142 }
143
144 if ( $params['witheditsonly'] ) {
145 $this->addWhere( 'user_editcount > 0' );
146 }
147
148 $this->showHiddenUsersAddBlockInfo( $fld_blockinfo );
149
150 if ( $fld_groups || $fld_rights ) {
151 // Show the groups the given users belong to
152 // request more than needed to avoid not getting all rows that belong to one user
153 $groupCount = count( User::getAllGroups() );
154 $sqlLimit = $limit + $groupCount + 1;
155
156 $this->addTables( 'user_groups', 'ug2' );
157 $this->addJoinConds( array( 'ug2' => array( 'LEFT JOIN', 'ug2.ug_user=user_id' ) ) );
158 $this->addFields( 'ug2.ug_group ug_group2' );
159 } else {
160 $sqlLimit = $limit + 1;
161 }
162
163 if ( $params['activeusers'] ) {
164 $activeUserSeconds = $this->getConfig()->get( 'ActiveUserDays' ) * 86400;
165
166 // Filter query to only include users in the active users cache
167 $this->addTables( 'querycachetwo' );
168 $this->addJoinConds( array( 'querycachetwo' => array(
169 'INNER JOIN', array(
170 'qcc_type' => 'activeusers',
171 'qcc_namespace' => NS_USER,
172 'qcc_title=user_name',
173 ),
174 ) ) );
175
176 // Actually count the actions using a subquery (bug 64505 and bug 64507)
177 $timestamp = $db->timestamp( wfTimestamp( TS_UNIX ) - $activeUserSeconds );
178 $this->addFields( array(
179 'recentactions' => '(' . $db->selectSQLText(
180 'recentchanges',
181 'COUNT(*)',
182 array(
183 'rc_user_text = user_name',
184 'rc_type != ' . $db->addQuotes( RC_EXTERNAL ), // no wikidata
185 'rc_log_type IS NULL OR rc_log_type != ' . $db->addQuotes( 'newusers' ),
186 'rc_timestamp >= ' . $db->addQuotes( $timestamp ),
187 )
188 ) . ')'
189 ) );
190 }
191
192 $this->addOption( 'LIMIT', $sqlLimit );
193
194 $this->addFields( array(
195 'user_name',
196 'user_id'
197 ) );
198 $this->addFieldsIf( 'user_editcount', $fld_editcount );
199 $this->addFieldsIf( 'user_registration', $fld_registration );
200
201 if ( $useIndex ) {
202 $this->addOption( 'USE INDEX', array( 'user' => 'user_name' ) );
203 }
204
205 $res = $this->select( __METHOD__ );
206
207 $count = 0;
208 $lastUserData = false;
209 $lastUser = false;
210 $result = $this->getResult();
211
212 // This loop keeps track of the last entry. For each new row, if the
213 // new row is for different user then the last, the last entry is added
214 // to results. Otherwise, the group of the new row is appended to the
215 // last entry. The setContinue... is more complex because of this, and
216 // takes into account the higher sql limit to make sure all rows that
217 // belong to the same user are received.
218
219 foreach ( $res as $row ) {
220 $count++;
221
222 if ( $lastUser !== $row->user_name ) {
223 // Save the last pass's user data
224 if ( is_array( $lastUserData ) ) {
225 if ( $params['activeusers'] && $lastUserData['recentactions'] === 0 ) {
226 // activeusers cache was out of date
227 $fit = true;
228 } else {
229 $fit = $result->addValue( array( 'query', $this->getModuleName() ),
230 null, $lastUserData );
231 }
232
233 $lastUserData = null;
234
235 if ( !$fit ) {
236 $this->setContinueEnumParameter( 'from', $lastUserData['name'] );
237 break;
238 }
239 }
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 // Record new user's data
249 $lastUser = $row->user_name;
250 $lastUserData = array(
251 'userid' => $row->user_id,
252 'name' => $lastUser,
253 );
254 if ( $fld_blockinfo && !is_null( $row->ipb_by_text ) ) {
255 $lastUserData['blockid'] = $row->ipb_id;
256 $lastUserData['blockedby'] = $row->ipb_by_text;
257 $lastUserData['blockedbyid'] = $row->ipb_by;
258 $lastUserData['blockreason'] = $row->ipb_reason;
259 $lastUserData['blockexpiry'] = $row->ipb_expiry;
260 }
261 if ( $row->ipb_deleted ) {
262 $lastUserData['hidden'] = '';
263 }
264 if ( $fld_editcount ) {
265 $lastUserData['editcount'] = intval( $row->user_editcount );
266 }
267 if ( $params['activeusers'] ) {
268 $lastUserData['recentactions'] = intval( $row->recentactions );
269 // @todo 'recenteditcount' is set for BC, remove in 1.25
270 $lastUserData['recenteditcount'] = $lastUserData['recentactions'];
271 }
272 if ( $fld_registration ) {
273 $lastUserData['registration'] = $row->user_registration ?
274 wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
275 }
276 }
277
278 if ( $sqlLimit == $count ) {
279 // @todo BUG! database contains group name that User::getAllGroups() does not return
280 // Should handle this more gracefully
281 ApiBase::dieDebug(
282 __METHOD__,
283 'MediaWiki configuration error: The database contains more ' .
284 'user groups than known to User::getAllGroups() function'
285 );
286 }
287
288 $lastUserObj = User::newFromId( $row->user_id );
289
290 // Add user's group info
291 if ( $fld_groups ) {
292 if ( !isset( $lastUserData['groups'] ) ) {
293 if ( $lastUserObj ) {
294 $lastUserData['groups'] = $lastUserObj->getAutomaticGroups();
295 } else {
296 // This should not normally happen
297 $lastUserData['groups'] = array();
298 }
299 }
300
301 if ( !is_null( $row->ug_group2 ) ) {
302 $lastUserData['groups'][] = $row->ug_group2;
303 }
304
305 $result->setIndexedTagName( $lastUserData['groups'], 'g' );
306 }
307
308 if ( $fld_implicitgroups && !isset( $lastUserData['implicitgroups'] ) && $lastUserObj ) {
309 $lastUserData['implicitgroups'] = $lastUserObj->getAutomaticGroups();
310 $result->setIndexedTagName( $lastUserData['implicitgroups'], 'g' );
311 }
312 if ( $fld_rights ) {
313 if ( !isset( $lastUserData['rights'] ) ) {
314 if ( $lastUserObj ) {
315 $lastUserData['rights'] = User::getGroupPermissions( $lastUserObj->getAutomaticGroups() );
316 } else {
317 // This should not normally happen
318 $lastUserData['rights'] = array();
319 }
320 }
321
322 if ( !is_null( $row->ug_group2 ) ) {
323 $lastUserData['rights'] = array_unique( array_merge( $lastUserData['rights'],
324 User::getGroupPermissions( array( $row->ug_group2 ) ) ) );
325 }
326
327 $result->setIndexedTagName( $lastUserData['rights'], 'r' );
328 }
329 }
330
331 if ( is_array( $lastUserData ) &&
332 !( $params['activeusers'] && $lastUserData['recentactions'] === 0 )
333 ) {
334 $fit = $result->addValue( array( 'query', $this->getModuleName() ),
335 null, $lastUserData );
336 if ( !$fit ) {
337 $this->setContinueEnumParameter( 'from', $lastUserData['name'] );
338 }
339 }
340
341 $result->setIndexedTagName_internal( array( 'query', $this->getModuleName() ), 'u' );
342 }
343
344 public function getCacheMode( $params ) {
345 return 'anon-public-user-private';
346 }
347
348 public function getAllowedParams() {
349 $userGroups = User::getAllGroups();
350
351 return array(
352 'from' => null,
353 'to' => null,
354 'prefix' => null,
355 'dir' => array(
356 ApiBase::PARAM_DFLT => 'ascending',
357 ApiBase::PARAM_TYPE => array(
358 'ascending',
359 'descending'
360 ),
361 ),
362 'group' => array(
363 ApiBase::PARAM_TYPE => $userGroups,
364 ApiBase::PARAM_ISMULTI => true,
365 ),
366 'excludegroup' => array(
367 ApiBase::PARAM_TYPE => $userGroups,
368 ApiBase::PARAM_ISMULTI => true,
369 ),
370 'rights' => array(
371 ApiBase::PARAM_TYPE => User::getAllRights(),
372 ApiBase::PARAM_ISMULTI => true,
373 ),
374 'prop' => array(
375 ApiBase::PARAM_ISMULTI => true,
376 ApiBase::PARAM_TYPE => array(
377 'blockinfo',
378 'groups',
379 'implicitgroups',
380 'rights',
381 'editcount',
382 'registration'
383 )
384 ),
385 'limit' => array(
386 ApiBase::PARAM_DFLT => 10,
387 ApiBase::PARAM_TYPE => 'limit',
388 ApiBase::PARAM_MIN => 1,
389 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
390 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
391 ),
392 'witheditsonly' => false,
393 'activeusers' => false,
394 );
395 }
396
397 public function getParamDescription() {
398 return array(
399 'from' => 'The user name to start enumerating from',
400 'to' => 'The user name to stop enumerating at',
401 'prefix' => 'Search for all users that begin with this value',
402 'dir' => 'Direction to sort in',
403 'group' => 'Limit users to given group name(s)',
404 'excludegroup' => 'Exclude users in given group name(s)',
405 'rights' => 'Limit users to given right(s) (does not include rights ' .
406 'granted by implicit or auto-promoted groups like *, user, or autoconfirmed)',
407 'prop' => array(
408 'What pieces of information to include.',
409 ' blockinfo - Adds the information about a current block on the user',
410 ' groups - Lists groups that the user is in. This uses ' .
411 'more server resources and may return fewer results than the limit',
412 ' implicitgroups - Lists all the groups the user is automatically in',
413 ' rights - Lists rights that the user has',
414 ' editcount - Adds the edit count of the user',
415 ' registration - Adds the timestamp of when the user registered if available (may be blank)',
416 ),
417 'limit' => 'How many total user names to return',
418 'witheditsonly' => 'Only list users who have made edits',
419 'activeusers' => "Only list users active in the last {$this->getConfig()->get( 'ActiveUserDays' )} days(s)"
420 );
421 }
422
423 public function getResultProperties() {
424 return array(
425 '' => array(
426 'userid' => 'integer',
427 'name' => 'string',
428 'recentactions' => array(
429 ApiBase::PROP_TYPE => 'integer',
430 ApiBase::PROP_NULLABLE => true
431 )
432 ),
433 'blockinfo' => array(
434 'blockid' => array(
435 ApiBase::PROP_TYPE => 'integer',
436 ApiBase::PROP_NULLABLE => true
437 ),
438 'blockedby' => array(
439 ApiBase::PROP_TYPE => 'string',
440 ApiBase::PROP_NULLABLE => true
441 ),
442 'blockedbyid' => array(
443 ApiBase::PROP_TYPE => 'integer',
444 ApiBase::PROP_NULLABLE => true
445 ),
446 'blockedreason' => array(
447 ApiBase::PROP_TYPE => 'string',
448 ApiBase::PROP_NULLABLE => true
449 ),
450 'blockedexpiry' => array(
451 ApiBase::PROP_TYPE => 'string',
452 ApiBase::PROP_NULLABLE => true
453 ),
454 'hidden' => 'boolean'
455 ),
456 'editcount' => array(
457 'editcount' => 'integer'
458 ),
459 'registration' => array(
460 'registration' => 'string'
461 )
462 );
463 }
464
465 public function getDescription() {
466 return 'Enumerate all registered users.';
467 }
468
469 public function getPossibleErrors() {
470 return array_merge( parent::getPossibleErrors(), array(
471 array(
472 'code' => 'group-excludegroup',
473 'info' => 'group and excludegroup cannot be used together'
474 ),
475 ) );
476 }
477
478 public function getExamples() {
479 return array(
480 'api.php?action=query&list=allusers&aufrom=Y',
481 );
482 }
483
484 public function getHelpUrls() {
485 return 'https://www.mediawiki.org/wiki/API:Allusers';
486 }
487 }