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