Merge "Fix ParserOutput::getText 'unwrap' flag for end-of-doc comment"
[lhc/web/wiklou.git] / includes / api / ApiQueryAllUsers.php
1 <?php
2 /**
3 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Query module to enumerate all registered users.
25 *
26 * @ingroup API
27 */
28 class ApiQueryAllUsers extends ApiQueryBase {
29 public function __construct( ApiQuery $query, $moduleName ) {
30 parent::__construct( $query, $moduleName, 'au' );
31 }
32
33 /**
34 * This function converts the user name to a canonical form
35 * which is stored in the database.
36 * @param string $name
37 * @return string
38 */
39 private function getCanonicalUserName( $name ) {
40 return strtr( $name, '_', ' ' );
41 }
42
43 public function execute() {
44 $params = $this->extractRequestParams();
45 $activeUserDays = $this->getConfig()->get( 'ActiveUserDays' );
46
47 $db = $this->getDB();
48 $commentStore = CommentStore::getStore();
49
50 $prop = $params['prop'];
51 if ( !is_null( $prop ) ) {
52 $prop = array_flip( $prop );
53 $fld_blockinfo = isset( $prop['blockinfo'] );
54 $fld_editcount = isset( $prop['editcount'] );
55 $fld_groups = isset( $prop['groups'] );
56 $fld_rights = isset( $prop['rights'] );
57 $fld_registration = isset( $prop['registration'] );
58 $fld_implicitgroups = isset( $prop['implicitgroups'] );
59 $fld_centralids = isset( $prop['centralids'] );
60 } else {
61 $fld_blockinfo = $fld_editcount = $fld_groups = $fld_registration =
62 $fld_rights = $fld_implicitgroups = $fld_centralids = false;
63 }
64
65 $limit = $params['limit'];
66
67 $this->addTables( 'user' );
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 can't figure out that 'user_name' and 'qcc_title' are the same
74 # despite the JOIN condition, so manually sort on the correct one.
75 $userFieldToSort = $params['activeusers'] ? 'qcc_title' : 'user_name';
76
77 # Some of these subtable joins are going to give us duplicate rows, so
78 # calculate the maximum number of duplicates we might see.
79 $maxDuplicateRows = 1;
80
81 $this->addWhereRange( $userFieldToSort, $dir, $from, $to );
82
83 if ( !is_null( $params['prefix'] ) ) {
84 $this->addWhere( $userFieldToSort .
85 $db->buildLike( $this->getCanonicalUserName( $params['prefix'] ), $db->anyString() ) );
86 }
87
88 if ( !is_null( $params['rights'] ) && count( $params['rights'] ) ) {
89 $groups = [];
90 foreach ( $params['rights'] as $r ) {
91 $groups = array_merge( $groups, User::getGroupsWithPermission( $r ) );
92 }
93
94 // no group with the given right(s) exists, no need for a query
95 if ( !count( $groups ) ) {
96 $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], '' );
97
98 return;
99 }
100
101 $groups = array_unique( $groups );
102
103 if ( is_null( $params['group'] ) ) {
104 $params['group'] = $groups;
105 } else {
106 $params['group'] = array_unique( array_merge( $params['group'], $groups ) );
107 }
108 }
109
110 $this->requireMaxOneParameter( $params, 'group', 'excludegroup' );
111
112 if ( !is_null( $params['group'] ) && count( $params['group'] ) ) {
113 // Filter only users that belong to a given group. This might
114 // produce as many rows-per-user as there are groups being checked.
115 $this->addTables( 'user_groups', 'ug1' );
116 $this->addJoinConds( [
117 'ug1' => [
118 'INNER JOIN',
119 [
120 'ug1.ug_user=user_id',
121 'ug1.ug_group' => $params['group'],
122 'ug1.ug_expiry IS NULL OR ug1.ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
123 ]
124 ]
125 ] );
126 $maxDuplicateRows *= count( $params['group'] );
127 }
128
129 if ( !is_null( $params['excludegroup'] ) && count( $params['excludegroup'] ) ) {
130 // Filter only users don't belong to a given group. This can only
131 // produce one row-per-user, because we only keep on "no match".
132 $this->addTables( 'user_groups', 'ug1' );
133
134 if ( count( $params['excludegroup'] ) == 1 ) {
135 $exclude = [ 'ug1.ug_group' => $params['excludegroup'][0] ];
136 } else {
137 $exclude = [ $db->makeList(
138 [ 'ug1.ug_group' => $params['excludegroup'] ],
139 LIST_OR
140 ) ];
141 }
142 $this->addJoinConds( [ 'ug1' => [ 'LEFT OUTER JOIN',
143 array_merge( [
144 'ug1.ug_user=user_id',
145 'ug1.ug_expiry IS NULL OR ug1.ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
146 ], $exclude )
147 ] ] );
148 $this->addWhere( 'ug1.ug_user IS NULL' );
149 }
150
151 if ( $params['witheditsonly'] ) {
152 $this->addWhere( 'user_editcount > 0' );
153 }
154
155 $this->showHiddenUsersAddBlockInfo( $fld_blockinfo );
156
157 if ( $fld_groups || $fld_rights ) {
158 $this->addFields( [ 'groups' =>
159 $db->buildGroupConcatField( '|', 'user_groups', 'ug_group', [
160 'ug_user=user_id',
161 'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
162 ] )
163 ] );
164 }
165
166 if ( $params['activeusers'] ) {
167 $activeUserSeconds = $activeUserDays * 86400;
168
169 // Filter query to only include users in the active users cache.
170 // There shouldn't be any duplicate rows in querycachetwo here.
171 $this->addTables( 'querycachetwo' );
172 $this->addJoinConds( [ 'querycachetwo' => [
173 'INNER JOIN', [
174 'qcc_type' => 'activeusers',
175 'qcc_namespace' => NS_USER,
176 'qcc_title=user_name',
177 ],
178 ] ] );
179
180 // Actually count the actions using a subquery (T66505 and T66507)
181 $timestamp = $db->timestamp( wfTimestamp( TS_UNIX ) - $activeUserSeconds );
182 $this->addFields( [
183 'recentactions' => '(' . $db->selectSQLText(
184 'recentchanges',
185 'COUNT(*)',
186 [
187 'rc_user_text = user_name',
188 'rc_type != ' . $db->addQuotes( RC_EXTERNAL ), // no wikidata
189 'rc_log_type IS NULL OR rc_log_type != ' . $db->addQuotes( 'newusers' ),
190 'rc_timestamp >= ' . $db->addQuotes( $timestamp ),
191 ]
192 ) . ')'
193 ] );
194 }
195
196 $sqlLimit = $limit + $maxDuplicateRows;
197 $this->addOption( 'LIMIT', $sqlLimit );
198
199 $this->addFields( [
200 'user_name',
201 'user_id'
202 ] );
203 $this->addFieldsIf( 'user_editcount', $fld_editcount );
204 $this->addFieldsIf( 'user_registration', $fld_registration );
205
206 $res = $this->select( __METHOD__ );
207 $count = 0;
208 $countDuplicates = 0;
209 $lastUser = false;
210 $result = $this->getResult();
211 foreach ( $res as $row ) {
212 $count++;
213
214 if ( $lastUser === $row->user_name ) {
215 // Duplicate row due to one of the needed subtable joins.
216 // Ignore it, but count the number of them to sanely handle
217 // miscalculation of $maxDuplicateRows.
218 $countDuplicates++;
219 if ( $countDuplicates == $maxDuplicateRows ) {
220 ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
221 }
222 continue;
223 }
224
225 $countDuplicates = 0;
226 $lastUser = $row->user_name;
227
228 if ( $count > $limit ) {
229 // We've reached the one extra which shows that there are
230 // additional pages to be had. Stop here...
231 $this->setContinueEnumParameter( 'from', $row->user_name );
232 break;
233 }
234
235 if ( $count == $sqlLimit ) {
236 // Should never hit this (either the $countDuplicates check or
237 // the $count > $limit check should hit first), but check it
238 // anyway just in case.
239 ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
240 }
241
242 if ( $params['activeusers'] && $row->recentactions === 0 ) {
243 // activeusers cache was out of date
244 continue;
245 }
246
247 $data = [
248 'userid' => (int)$row->user_id,
249 'name' => $row->user_name,
250 ];
251
252 if ( $fld_centralids ) {
253 $data += ApiQueryUserInfo::getCentralUserInfo(
254 $this->getConfig(), User::newFromId( $row->user_id ), $params['attachedwiki']
255 );
256 }
257
258 if ( $fld_blockinfo && !is_null( $row->ipb_by_text ) ) {
259 $data['blockid'] = (int)$row->ipb_id;
260 $data['blockedby'] = $row->ipb_by_text;
261 $data['blockedbyid'] = (int)$row->ipb_by;
262 $data['blockedtimestamp'] = wfTimestamp( TS_ISO_8601, $row->ipb_timestamp );
263 $data['blockreason'] = $commentStore->getComment( 'ipb_reason', $row )->text;
264 $data['blockexpiry'] = $row->ipb_expiry;
265 }
266 if ( $row->ipb_deleted ) {
267 $data['hidden'] = true;
268 }
269 if ( $fld_editcount ) {
270 $data['editcount'] = intval( $row->user_editcount );
271 }
272 if ( $params['activeusers'] ) {
273 $data['recentactions'] = intval( $row->recentactions );
274 // @todo 'recenteditcount' is set for BC, remove in 1.25
275 $data['recenteditcount'] = $data['recentactions'];
276 }
277 if ( $fld_registration ) {
278 $data['registration'] = $row->user_registration ?
279 wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
280 }
281
282 if ( $fld_implicitgroups || $fld_groups || $fld_rights ) {
283 $implicitGroups = User::newFromId( $row->user_id )->getAutomaticGroups();
284 if ( isset( $row->groups ) && $row->groups !== '' ) {
285 $groups = array_merge( $implicitGroups, explode( '|', $row->groups ) );
286 } else {
287 $groups = $implicitGroups;
288 }
289
290 if ( $fld_groups ) {
291 $data['groups'] = $groups;
292 ApiResult::setIndexedTagName( $data['groups'], 'g' );
293 ApiResult::setArrayType( $data['groups'], 'array' );
294 }
295
296 if ( $fld_implicitgroups ) {
297 $data['implicitgroups'] = $implicitGroups;
298 ApiResult::setIndexedTagName( $data['implicitgroups'], 'g' );
299 ApiResult::setArrayType( $data['implicitgroups'], 'array' );
300 }
301
302 if ( $fld_rights ) {
303 $data['rights'] = User::getGroupPermissions( $groups );
304 ApiResult::setIndexedTagName( $data['rights'], 'r' );
305 ApiResult::setArrayType( $data['rights'], 'array' );
306 }
307 }
308
309 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data );
310 if ( !$fit ) {
311 $this->setContinueEnumParameter( 'from', $data['name'] );
312 break;
313 }
314 }
315
316 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'u' );
317 }
318
319 public function getCacheMode( $params ) {
320 return 'anon-public-user-private';
321 }
322
323 public function getAllowedParams() {
324 $userGroups = User::getAllGroups();
325
326 return [
327 'from' => null,
328 'to' => null,
329 'prefix' => null,
330 'dir' => [
331 ApiBase::PARAM_DFLT => 'ascending',
332 ApiBase::PARAM_TYPE => [
333 'ascending',
334 'descending'
335 ],
336 ],
337 'group' => [
338 ApiBase::PARAM_TYPE => $userGroups,
339 ApiBase::PARAM_ISMULTI => true,
340 ],
341 'excludegroup' => [
342 ApiBase::PARAM_TYPE => $userGroups,
343 ApiBase::PARAM_ISMULTI => true,
344 ],
345 'rights' => [
346 ApiBase::PARAM_TYPE => User::getAllRights(),
347 ApiBase::PARAM_ISMULTI => true,
348 ],
349 'prop' => [
350 ApiBase::PARAM_ISMULTI => true,
351 ApiBase::PARAM_TYPE => [
352 'blockinfo',
353 'groups',
354 'implicitgroups',
355 'rights',
356 'editcount',
357 'registration',
358 'centralids',
359 ],
360 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
361 ],
362 'limit' => [
363 ApiBase::PARAM_DFLT => 10,
364 ApiBase::PARAM_TYPE => 'limit',
365 ApiBase::PARAM_MIN => 1,
366 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
367 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
368 ],
369 'witheditsonly' => false,
370 'activeusers' => [
371 ApiBase::PARAM_DFLT => false,
372 ApiBase::PARAM_HELP_MSG => [
373 'apihelp-query+allusers-param-activeusers',
374 $this->getConfig()->get( 'ActiveUserDays' )
375 ],
376 ],
377 'attachedwiki' => null,
378 ];
379 }
380
381 protected function getExamplesMessages() {
382 return [
383 'action=query&list=allusers&aufrom=Y'
384 => 'apihelp-query+allusers-example-Y',
385 ];
386 }
387
388 public function getHelpUrls() {
389 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allusers';
390 }
391 }