Merge "Add support for PHP7 random_bytes in favor of mcrypt_create_iv"
[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 strtr( $name, '_', ' ' );
45 }
46
47 public function execute() {
48 $params = $this->extractRequestParams();
49 $activeUserDays = $this->getConfig()->get( 'ActiveUserDays' );
50
51 $db = $this->getDB();
52
53 $prop = $params['prop'];
54 if ( !is_null( $prop ) ) {
55 $prop = array_flip( $prop );
56 $fld_blockinfo = isset( $prop['blockinfo'] );
57 $fld_editcount = isset( $prop['editcount'] );
58 $fld_groups = isset( $prop['groups'] );
59 $fld_rights = isset( $prop['rights'] );
60 $fld_registration = isset( $prop['registration'] );
61 $fld_implicitgroups = isset( $prop['implicitgroups'] );
62 $fld_centralids = isset( $prop['centralids'] );
63 } else {
64 $fld_blockinfo = $fld_editcount = $fld_groups = $fld_registration =
65 $fld_rights = $fld_implicitgroups = $fld_centralids = false;
66 }
67
68 $limit = $params['limit'];
69
70 $this->addTables( 'user' );
71
72 $dir = ( $params['dir'] == 'descending' ? 'older' : 'newer' );
73 $from = is_null( $params['from'] ) ? null : $this->getCanonicalUserName( $params['from'] );
74 $to = is_null( $params['to'] ) ? null : $this->getCanonicalUserName( $params['to'] );
75
76 # MySQL can't figure out that 'user_name' and 'qcc_title' are the same
77 # despite the JOIN condition, so manually sort on the correct one.
78 $userFieldToSort = $params['activeusers'] ? 'qcc_title' : 'user_name';
79
80 # Some of these subtable joins are going to give us duplicate rows, so
81 # calculate the maximum number of duplicates we might see.
82 $maxDuplicateRows = 1;
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 = [];
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()->addIndexedTagName( [ '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 $this->requireMaxOneParameter( $params, 'group', 'excludegroup' );
114
115 if ( !is_null( $params['group'] ) && count( $params['group'] ) ) {
116 // Filter only users that belong to a given group. This might
117 // produce as many rows-per-user as there are groups being checked.
118 $this->addTables( 'user_groups', 'ug1' );
119 $this->addJoinConds( [
120 'ug1' => [
121 'INNER JOIN',
122 [
123 'ug1.ug_user=user_id',
124 'ug1.ug_group' => $params['group'],
125 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
126 '1' :
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 OUTER JOIN',
148 array_merge( [
149 'ug1.ug_user=user_id',
150 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
151 '1' :
152 'ug1.ug_expiry IS NULL OR ug1.ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
153 ], $exclude )
154 ] ] );
155 $this->addWhere( 'ug1.ug_user IS NULL' );
156 }
157
158 if ( $params['witheditsonly'] ) {
159 $this->addWhere( 'user_editcount > 0' );
160 }
161
162 $this->showHiddenUsersAddBlockInfo( $fld_blockinfo );
163
164 if ( $fld_groups || $fld_rights ) {
165 $this->addFields( [ 'groups' =>
166 $db->buildGroupConcatField( '|', 'user_groups', 'ug_group', [
167 'ug_user=user_id',
168 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
169 '1' :
170 'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
171 ] )
172 ] );
173 }
174
175 if ( $params['activeusers'] ) {
176 $activeUserSeconds = $activeUserDays * 86400;
177
178 // Filter query to only include users in the active users cache.
179 // There shouldn't be any duplicate rows in querycachetwo here.
180 $this->addTables( 'querycachetwo' );
181 $this->addJoinConds( [ 'querycachetwo' => [
182 'INNER JOIN', [
183 'qcc_type' => 'activeusers',
184 'qcc_namespace' => NS_USER,
185 'qcc_title=user_name',
186 ],
187 ] ] );
188
189 // Actually count the actions using a subquery (T66505 and T66507)
190 $timestamp = $db->timestamp( wfTimestamp( TS_UNIX ) - $activeUserSeconds );
191 $this->addFields( [
192 'recentactions' => '(' . $db->selectSQLText(
193 'recentchanges',
194 'COUNT(*)',
195 [
196 'rc_user_text = user_name',
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 ) . ')'
202 ] );
203 }
204
205 $sqlLimit = $limit + $maxDuplicateRows;
206 $this->addOption( 'LIMIT', $sqlLimit );
207
208 $this->addFields( [
209 'user_name',
210 'user_id'
211 ] );
212 $this->addFieldsIf( 'user_editcount', $fld_editcount );
213 $this->addFieldsIf( 'user_registration', $fld_registration );
214
215 $res = $this->select( __METHOD__ );
216 $count = 0;
217 $countDuplicates = 0;
218 $lastUser = false;
219 $result = $this->getResult();
220 foreach ( $res as $row ) {
221 $count++;
222
223 if ( $lastUser === $row->user_name ) {
224 // Duplicate row due to one of the needed subtable joins.
225 // Ignore it, but count the number of them to sanely handle
226 // miscalculation of $maxDuplicateRows.
227 $countDuplicates++;
228 if ( $countDuplicates == $maxDuplicateRows ) {
229 ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
230 }
231 continue;
232 }
233
234 $countDuplicates = 0;
235 $lastUser = $row->user_name;
236
237 if ( $count > $limit ) {
238 // We've reached the one extra which shows that there are
239 // additional pages to be had. Stop here...
240 $this->setContinueEnumParameter( 'from', $row->user_name );
241 break;
242 }
243
244 if ( $count == $sqlLimit ) {
245 // Should never hit this (either the $countDuplicates check or
246 // the $count > $limit check should hit first), but check it
247 // anyway just in case.
248 ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
249 }
250
251 if ( $params['activeusers'] && $row->recentactions === 0 ) {
252 // activeusers cache was out of date
253 continue;
254 }
255
256 $data = [
257 'userid' => (int)$row->user_id,
258 'name' => $row->user_name,
259 ];
260
261 if ( $fld_centralids ) {
262 $data += ApiQueryUserInfo::getCentralUserInfo(
263 $this->getConfig(), User::newFromId( $row->user_id ), $params['attachedwiki']
264 );
265 }
266
267 if ( $fld_blockinfo && !is_null( $row->ipb_by_text ) ) {
268 $data['blockid'] = (int)$row->ipb_id;
269 $data['blockedby'] = $row->ipb_by_text;
270 $data['blockedbyid'] = (int)$row->ipb_by;
271 $data['blockedtimestamp'] = wfTimestamp( TS_ISO_8601, $row->ipb_timestamp );
272 $data['blockreason'] = $row->ipb_reason;
273 $data['blockexpiry'] = $row->ipb_expiry;
274 }
275 if ( $row->ipb_deleted ) {
276 $data['hidden'] = true;
277 }
278 if ( $fld_editcount ) {
279 $data['editcount'] = intval( $row->user_editcount );
280 }
281 if ( $params['activeusers'] ) {
282 $data['recentactions'] = intval( $row->recentactions );
283 // @todo 'recenteditcount' is set for BC, remove in 1.25
284 $data['recenteditcount'] = $data['recentactions'];
285 }
286 if ( $fld_registration ) {
287 $data['registration'] = $row->user_registration ?
288 wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
289 }
290
291 if ( $fld_implicitgroups || $fld_groups || $fld_rights ) {
292 $implicitGroups = User::newFromId( $row->user_id )->getAutomaticGroups();
293 if ( isset( $row->groups ) && $row->groups !== '' ) {
294 $groups = array_merge( $implicitGroups, explode( '|', $row->groups ) );
295 } else {
296 $groups = $implicitGroups;
297 }
298
299 if ( $fld_groups ) {
300 $data['groups'] = $groups;
301 ApiResult::setIndexedTagName( $data['groups'], 'g' );
302 ApiResult::setArrayType( $data['groups'], 'array' );
303 }
304
305 if ( $fld_implicitgroups ) {
306 $data['implicitgroups'] = $implicitGroups;
307 ApiResult::setIndexedTagName( $data['implicitgroups'], 'g' );
308 ApiResult::setArrayType( $data['implicitgroups'], 'array' );
309 }
310
311 if ( $fld_rights ) {
312 $data['rights'] = User::getGroupPermissions( $groups );
313 ApiResult::setIndexedTagName( $data['rights'], 'r' );
314 ApiResult::setArrayType( $data['rights'], 'array' );
315 }
316 }
317
318 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data );
319 if ( !$fit ) {
320 $this->setContinueEnumParameter( 'from', $data['name'] );
321 break;
322 }
323 }
324
325 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'u' );
326 }
327
328 public function getCacheMode( $params ) {
329 return 'anon-public-user-private';
330 }
331
332 public function getAllowedParams() {
333 $userGroups = User::getAllGroups();
334
335 return [
336 'from' => null,
337 'to' => null,
338 'prefix' => null,
339 'dir' => [
340 ApiBase::PARAM_DFLT => 'ascending',
341 ApiBase::PARAM_TYPE => [
342 'ascending',
343 'descending'
344 ],
345 ],
346 'group' => [
347 ApiBase::PARAM_TYPE => $userGroups,
348 ApiBase::PARAM_ISMULTI => true,
349 ],
350 'excludegroup' => [
351 ApiBase::PARAM_TYPE => $userGroups,
352 ApiBase::PARAM_ISMULTI => true,
353 ],
354 'rights' => [
355 ApiBase::PARAM_TYPE => User::getAllRights(),
356 ApiBase::PARAM_ISMULTI => true,
357 ],
358 'prop' => [
359 ApiBase::PARAM_ISMULTI => true,
360 ApiBase::PARAM_TYPE => [
361 'blockinfo',
362 'groups',
363 'implicitgroups',
364 'rights',
365 'editcount',
366 'registration',
367 'centralids',
368 ],
369 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
370 ],
371 'limit' => [
372 ApiBase::PARAM_DFLT => 10,
373 ApiBase::PARAM_TYPE => 'limit',
374 ApiBase::PARAM_MIN => 1,
375 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
376 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
377 ],
378 'witheditsonly' => false,
379 'activeusers' => [
380 ApiBase::PARAM_DFLT => false,
381 ApiBase::PARAM_HELP_MSG => [
382 'apihelp-query+allusers-param-activeusers',
383 $this->getConfig()->get( 'ActiveUserDays' )
384 ],
385 ],
386 'attachedwiki' => null,
387 ];
388 }
389
390 protected function getExamplesMessages() {
391 return [
392 'action=query&list=allusers&aufrom=Y'
393 => 'apihelp-query+allusers-example-Y',
394 ];
395 }
396
397 public function getHelpUrls() {
398 return 'https://www.mediawiki.org/wiki/API:Allusers';
399 }
400 }