Merge "Follow-up I0b781c11 (2a55449): use User::getAutomaticGroups()."
[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( $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 $db = $this->getDB();
49 $params = $this->extractRequestParams();
50
51 $prop = $params['prop'];
52 if ( !is_null( $prop ) ) {
53 $prop = array_flip( $prop );
54 $fld_blockinfo = isset( $prop['blockinfo'] );
55 $fld_editcount = isset( $prop['editcount'] );
56 $fld_groups = isset( $prop['groups'] );
57 $fld_rights = isset( $prop['rights'] );
58 $fld_registration = isset( $prop['registration'] );
59 $fld_implicitgroups = isset( $prop['implicitgroups'] );
60 } else {
61 $fld_blockinfo = $fld_editcount = $fld_groups = $fld_registration = $fld_rights = $fld_implicitgroups = false;
62 }
63
64 $limit = $params['limit'];
65
66 $this->addTables( 'user' );
67 $useIndex = true;
68
69 $dir = ( $params['dir'] == 'descending' ? 'older' : 'newer' );
70 $from = is_null( $params['from'] ) ? null : $this->getCanonicalUserName( $params['from'] );
71 $to = is_null( $params['to'] ) ? null : $this->getCanonicalUserName( $params['to'] );
72
73 # MySQL doesn't seem to use 'equality propagation' here, so like the
74 # ActiveUsers special page, we have to use rc_user_text for some cases.
75 $userFieldToSort = $params['activeusers'] ? 'rc_user_text' : 'user_name';
76
77 $this->addWhereRange( $userFieldToSort, $dir, $from, $to );
78
79 if ( !is_null( $params['prefix'] ) ) {
80 $this->addWhere( $userFieldToSort .
81 $db->buildLike( $this->getCanonicalUserName( $params['prefix'] ), $db->anyString() ) );
82 }
83
84 if ( !is_null( $params['rights'] ) ) {
85 $groups = array();
86 foreach( $params['rights'] as $r ) {
87 $groups = array_merge( $groups, User::getGroupsWithPermission( $r ) );
88 }
89
90 $groups = array_unique( $groups );
91
92 if ( is_null( $params['group'] ) ) {
93 $params['group'] = $groups;
94 } else {
95 $params['group'] = array_unique( array_merge( $params['group'], $groups ) );
96 }
97 }
98
99 if ( !is_null( $params['group'] ) && !is_null( $params['excludegroup'] ) ) {
100 $this->dieUsage( 'group and excludegroup cannot be used together', 'group-excludegroup' );
101 }
102
103 if ( !is_null( $params['group'] ) && count( $params['group'] ) ) {
104 $useIndex = false;
105 // Filter only users that belong to a given group
106 $this->addTables( 'user_groups', 'ug1' );
107 $this->addJoinConds( array( 'ug1' => array( 'INNER JOIN', array( 'ug1.ug_user=user_id',
108 'ug1.ug_group' => $params['group'] ) ) ) );
109 }
110
111 if ( !is_null( $params['excludegroup'] ) && count( $params['excludegroup'] ) ) {
112 $useIndex = false;
113 // Filter only users don't belong to a given group
114 $this->addTables( 'user_groups', 'ug1' );
115
116 if ( count( $params['excludegroup'] ) == 1 ) {
117 $exclude = array( 'ug1.ug_group' => $params['excludegroup'][0] );
118 } else {
119 $exclude = array( $db->makeList( array( 'ug1.ug_group' => $params['excludegroup'] ), LIST_OR ) );
120 }
121 $this->addJoinConds( array( 'ug1' => array( 'LEFT OUTER JOIN',
122 array_merge( array( 'ug1.ug_user=user_id' ), $exclude )
123 )
124 ) );
125 $this->addWhere( 'ug1.ug_user IS NULL' );
126 }
127
128 if ( $params['witheditsonly'] ) {
129 $this->addWhere( 'user_editcount > 0' );
130 }
131
132 $this->showHiddenUsersAddBlockInfo( $fld_blockinfo );
133
134 if ( $fld_groups || $fld_rights ) {
135 // Show the groups the given users belong to
136 // request more than needed to avoid not getting all rows that belong to one user
137 $groupCount = count( User::getAllGroups() );
138 $sqlLimit = $limit + $groupCount + 1;
139
140 $this->addTables( 'user_groups', 'ug2' );
141 $this->addJoinConds( array( 'ug2' => array( 'LEFT JOIN', 'ug2.ug_user=user_id' ) ) );
142 $this->addFields( 'ug2.ug_group ug_group2' );
143 } else {
144 $sqlLimit = $limit + 1;
145 }
146
147 if ( $params['activeusers'] ) {
148 global $wgActiveUserDays;
149 $this->addTables( 'recentchanges' );
150
151 $this->addJoinConds( array( 'recentchanges' => array(
152 'INNER JOIN', 'rc_user_text=user_name'
153 ) ) );
154
155 $this->addFields( array( 'recentedits' => 'COUNT(*)' ) );
156
157 $this->addWhere( 'rc_log_type IS NULL OR rc_log_type != ' . $db->addQuotes( 'newusers' ) );
158 $timestamp = $db->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays*24*3600 );
159 $this->addWhere( 'rc_timestamp >= ' . $db->addQuotes( $timestamp ) );
160
161 $this->addOption( 'GROUP BY', $userFieldToSort );
162 }
163
164 $this->addOption( 'LIMIT', $sqlLimit );
165
166 $this->addFields( array(
167 'user_name',
168 'user_id'
169 ) );
170 $this->addFieldsIf( 'user_editcount', $fld_editcount );
171 $this->addFieldsIf( 'user_registration', $fld_registration );
172
173 if ( $useIndex ) {
174 $this->addOption( 'USE INDEX', array( 'user' => 'user_name' ) );
175 }
176
177 $res = $this->select( __METHOD__ );
178
179 $count = 0;
180 $lastUserData = false;
181 $lastUser = false;
182 $result = $this->getResult();
183
184 //
185 // This loop keeps track of the last entry.
186 // For each new row, if the new row is for different user then the last, the last entry is added to results.
187 // Otherwise, the group of the new row is appended to the last entry.
188 // The setContinue... is more complex because of this, and takes into account the higher sql limit
189 // to make sure all rows that belong to the same user are received.
190
191 foreach ( $res as $row ) {
192 $count++;
193
194 if ( $lastUser !== $row->user_name ) {
195 // Save the last pass's user data
196 if ( is_array( $lastUserData ) ) {
197 $fit = $result->addValue( array( 'query', $this->getModuleName() ),
198 null, $lastUserData );
199
200 $lastUserData = null;
201
202 if ( !$fit ) {
203 $this->setContinueEnumParameter( 'from', $lastUserData['name'] );
204 break;
205 }
206 }
207
208 if ( $count > $limit ) {
209 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
210 $this->setContinueEnumParameter( 'from', $row->user_name );
211 break;
212 }
213
214 // Record new user's data
215 $lastUser = $row->user_name;
216 $lastUserData = array(
217 'userid' => $row->user_id,
218 'name' => $lastUser,
219 );
220 if ( $fld_blockinfo && !is_null( $row->ipb_by_text ) ) {
221 $lastUserData['blockid'] = $row->ipb_id;
222 $lastUserData['blockedby'] = $row->ipb_by_text;
223 $lastUserData['blockedbyid'] = $row->ipb_by;
224 $lastUserData['blockreason'] = $row->ipb_reason;
225 $lastUserData['blockexpiry'] = $row->ipb_expiry;
226 }
227 if ( $row->ipb_deleted ) {
228 $lastUserData['hidden'] = '';
229 }
230 if ( $fld_editcount ) {
231 $lastUserData['editcount'] = intval( $row->user_editcount );
232 }
233 if ( $params['activeusers'] ) {
234 $lastUserData['recenteditcount'] = intval( $row->recentedits );
235 }
236 if ( $fld_registration ) {
237 $lastUserData['registration'] = $row->user_registration ?
238 wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
239 }
240 }
241
242 if ( $sqlLimit == $count ) {
243 // BUG! database contains group name that User::getAllGroups() does not return
244 // TODO: should handle this more gracefully
245 ApiBase::dieDebug( __METHOD__,
246 'MediaWiki configuration error: the database contains more user groups than known to User::getAllGroups() function' );
247 }
248
249 $lastUserObj = User::newFromId( $row->user_id );
250
251 // Add user's group info
252 if ( $fld_groups ) {
253 if ( !isset( $lastUserData['groups'] ) ) {
254 if ( $lastUserObj ) {
255 $lastUserData['groups'] = $lastUserObj->getAutomaticGroups();
256 } else {
257 // This should not normally happen
258 $lastUserData['groups'] = array();
259 }
260 }
261
262 if ( !is_null( $row->ug_group2 ) ) {
263 $lastUserData['groups'][] = $row->ug_group2;
264 }
265
266 $result->setIndexedTagName( $lastUserData['groups'], 'g' );
267 }
268
269 if ( $fld_implicitgroups && !isset( $lastUserData['implicitgroups'] ) && $lastUserObj ) {
270 $lastUserData['implicitgroups'] = $lastUserObj->getAutomaticGroups();
271 $result->setIndexedTagName( $lastUserData['implicitgroups'], 'g' );
272 }
273 if ( $fld_rights ) {
274 if ( !isset( $lastUserData['rights'] ) ) {
275 if ( $lastUserObj ) {
276 $lastUserData['rights'] = User::getGroupPermissions( $lastUserObj->getAutomaticGroups() );
277 } else {
278 // This should not normally happen
279 $lastUserData['rights'] = array();
280 }
281 }
282
283 if ( !is_null( $row->ug_group2 ) ) {
284 $lastUserData['rights'] = array_unique( array_merge( $lastUserData['rights'],
285 User::getGroupPermissions( array( $row->ug_group2 ) ) ) );
286 }
287
288 $result->setIndexedTagName( $lastUserData['rights'], 'r' );
289 }
290 }
291
292 if ( is_array( $lastUserData ) ) {
293 $fit = $result->addValue( array( 'query', $this->getModuleName() ),
294 null, $lastUserData );
295 if ( !$fit ) {
296 $this->setContinueEnumParameter( 'from', $lastUserData['name'] );
297 }
298 }
299
300 $result->setIndexedTagName_internal( array( 'query', $this->getModuleName() ), 'u' );
301 }
302
303 public function getCacheMode( $params ) {
304 return 'anon-public-user-private';
305 }
306
307 public function getAllowedParams() {
308 $userGroups = User::getAllGroups();
309 return array(
310 'from' => null,
311 'to' => null,
312 'prefix' => null,
313 'dir' => array(
314 ApiBase::PARAM_DFLT => 'ascending',
315 ApiBase::PARAM_TYPE => array(
316 'ascending',
317 'descending'
318 ),
319 ),
320 'group' => array(
321 ApiBase::PARAM_TYPE => $userGroups,
322 ApiBase::PARAM_ISMULTI => true,
323 ),
324 'excludegroup' => array(
325 ApiBase::PARAM_TYPE => $userGroups,
326 ApiBase::PARAM_ISMULTI => true,
327 ),
328 'rights' => array(
329 ApiBase::PARAM_TYPE => User::getAllRights(),
330 ApiBase::PARAM_ISMULTI => true,
331 ),
332 'prop' => array(
333 ApiBase::PARAM_ISMULTI => true,
334 ApiBase::PARAM_TYPE => array(
335 'blockinfo',
336 'groups',
337 'implicitgroups',
338 'rights',
339 'editcount',
340 'registration'
341 )
342 ),
343 'limit' => array(
344 ApiBase::PARAM_DFLT => 10,
345 ApiBase::PARAM_TYPE => 'limit',
346 ApiBase::PARAM_MIN => 1,
347 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
348 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
349 ),
350 'witheditsonly' => false,
351 'activeusers' => false,
352 );
353 }
354
355 public function getParamDescription() {
356 global $wgActiveUserDays;
357 return array(
358 'from' => 'The user name to start enumerating from',
359 'to' => 'The user name to stop enumerating at',
360 'prefix' => 'Search for all users that begin with this value',
361 'dir' => 'Direction to sort in',
362 'group' => 'Limit users to given group name(s)',
363 'excludegroup' => 'Exclude users in given group name(s)',
364 'rights' => 'Limit users to given right(s) (does not include rights granted by implicit or auto-promoted groups like *, user, or autoconfirmed)',
365 'prop' => array(
366 'What pieces of information to include.',
367 ' blockinfo - Adds the information about a current block on the user',
368 ' groups - Lists groups that the user is in. This uses more server resources and may return fewer results than the limit',
369 ' implicitgroups - Lists all the groups the user is automatically in',
370 ' rights - Lists rights that the user has',
371 ' editcount - Adds the edit count of the user',
372 ' registration - Adds the timestamp of when the user registered if available (may be blank)',
373 ),
374 'limit' => 'How many total user names to return',
375 'witheditsonly' => 'Only list users who have made edits',
376 'activeusers' => "Only list users active in the last {$wgActiveUserDays} days(s)"
377 );
378 }
379
380 public function getResultProperties() {
381 return array(
382 '' => array(
383 'userid' => 'integer',
384 'name' => 'string',
385 'recenteditcount' => array(
386 ApiBase::PROP_TYPE => 'integer',
387 ApiBase::PROP_NULLABLE => true
388 )
389 ),
390 'blockinfo' => array(
391 'blockid' => array(
392 ApiBase::PROP_TYPE => 'integer',
393 ApiBase::PROP_NULLABLE => true
394 ),
395 'blockedby' => array(
396 ApiBase::PROP_TYPE => 'string',
397 ApiBase::PROP_NULLABLE => true
398 ),
399 'blockedbyid' => array(
400 ApiBase::PROP_TYPE => 'integer',
401 ApiBase::PROP_NULLABLE => true
402 ),
403 'blockedreason' => array(
404 ApiBase::PROP_TYPE => 'string',
405 ApiBase::PROP_NULLABLE => true
406 ),
407 'blockedexpiry' => array(
408 ApiBase::PROP_TYPE => 'string',
409 ApiBase::PROP_NULLABLE => true
410 ),
411 'hidden' => 'boolean'
412 ),
413 'editcount' => array(
414 'editcount' => 'integer'
415 ),
416 'registration' => array(
417 'registration' => 'string'
418 )
419 );
420 }
421
422 public function getDescription() {
423 return 'Enumerate all registered users';
424 }
425
426 public function getPossibleErrors() {
427 return array_merge( parent::getPossibleErrors(), array(
428 array( 'code' => 'group-excludegroup', 'info' => 'group and excludegroup cannot be used together' ),
429 ) );
430 }
431
432 public function getExamples() {
433 return array(
434 'api.php?action=query&list=allusers&aufrom=Y',
435 );
436 }
437
438 public function getHelpUrls() {
439 return 'https://www.mediawiki.org/wiki/API:Allusers';
440 }
441
442 public function getVersion() {
443 return __CLASS__ . ': $Id$';
444 }
445 }