Merge "Make DBAccessBase use DBConnRef, rename $wiki, and hide getLoadBalancer()"
[lhc/web/wiklou.git] / includes / api / ApiQueryUsers.php
1 <?php
2 /**
3 * Copyright © 2007 Roan Kattouw "<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 get information about a list of users
25 *
26 * @ingroup API
27 */
28 class ApiQueryUsers extends ApiQueryBase {
29
30 private $tokenFunctions, $prop;
31
32 /**
33 * Properties whose contents does not depend on who is looking at them. If the usprops field
34 * contains anything not listed here, the cache mode will never be public for logged-in users.
35 * @var array
36 */
37 protected static $publicProps = [
38 // everything except 'blockinfo' which might show hidden records if the user
39 // making the request has the appropriate permissions
40 'groups',
41 'groupmemberships',
42 'implicitgroups',
43 'rights',
44 'editcount',
45 'registration',
46 'emailable',
47 'gender',
48 'centralids',
49 'cancreate',
50 ];
51
52 public function __construct( ApiQuery $query, $moduleName ) {
53 parent::__construct( $query, $moduleName, 'us' );
54 }
55
56 /**
57 * Get an array mapping token names to their handler functions.
58 * The prototype for a token function is func($user)
59 * it should return a token or false (permission denied)
60 * @deprecated since 1.24
61 * @return array Array of tokenname => function
62 */
63 protected function getTokenFunctions() {
64 // Don't call the hooks twice
65 if ( isset( $this->tokenFunctions ) ) {
66 return $this->tokenFunctions;
67 }
68
69 // If we're in a mode that breaks the same-origin policy, no tokens can
70 // be obtained
71 if ( $this->lacksSameOriginSecurity() ) {
72 return [];
73 }
74
75 $this->tokenFunctions = [
76 'userrights' => [ self::class, 'getUserrightsToken' ],
77 ];
78 Hooks::run( 'APIQueryUsersTokens', [ &$this->tokenFunctions ] );
79
80 return $this->tokenFunctions;
81 }
82
83 /**
84 * @deprecated since 1.24
85 * @param User $user
86 * @return string
87 */
88 public static function getUserrightsToken( $user ) {
89 global $wgUser;
90
91 // Since the permissions check for userrights is non-trivial,
92 // don't bother with it here
93 return $wgUser->getEditToken( $user->getName() );
94 }
95
96 public function execute() {
97 $db = $this->getDB();
98 $commentStore = CommentStore::getStore();
99
100 $params = $this->extractRequestParams();
101 $this->requireMaxOneParameter( $params, 'userids', 'users' );
102
103 if ( !is_null( $params['prop'] ) ) {
104 $this->prop = array_flip( $params['prop'] );
105 } else {
106 $this->prop = [];
107 }
108 $useNames = !is_null( $params['users'] );
109
110 $users = (array)$params['users'];
111 $userids = (array)$params['userids'];
112
113 $goodNames = $done = [];
114 $result = $this->getResult();
115 // Canonicalize user names
116 foreach ( $users as $u ) {
117 $n = User::getCanonicalName( $u );
118 if ( $n === false || $n === '' ) {
119 $vals = [ 'name' => $u, 'invalid' => true ];
120 $fit = $result->addValue( [ 'query', $this->getModuleName() ],
121 null, $vals );
122 if ( !$fit ) {
123 $this->setContinueEnumParameter( 'users',
124 implode( '|', array_diff( $users, $done ) ) );
125 $goodNames = [];
126 break;
127 }
128 $done[] = $u;
129 } else {
130 $goodNames[] = $n;
131 }
132 }
133
134 if ( $useNames ) {
135 $parameters = &$goodNames;
136 } else {
137 $parameters = &$userids;
138 }
139
140 $result = $this->getResult();
141
142 if ( count( $parameters ) ) {
143 $userQuery = User::getQueryInfo();
144 $this->addTables( $userQuery['tables'] );
145 $this->addFields( $userQuery['fields'] );
146 $this->addJoinConds( $userQuery['joins'] );
147 if ( $useNames ) {
148 $this->addWhereFld( 'user_name', $goodNames );
149 } else {
150 $this->addWhereFld( 'user_id', $userids );
151 }
152
153 $this->showHiddenUsersAddBlockInfo( isset( $this->prop['blockinfo'] ) );
154
155 $data = [];
156 $res = $this->select( __METHOD__ );
157 $this->resetQueryParams();
158
159 // get user groups if needed
160 if ( isset( $this->prop['groups'] ) || isset( $this->prop['rights'] ) ) {
161 $userGroups = [];
162
163 $this->addTables( 'user' );
164 if ( $useNames ) {
165 $this->addWhereFld( 'user_name', $goodNames );
166 } else {
167 $this->addWhereFld( 'user_id', $userids );
168 }
169
170 $this->addTables( 'user_groups' );
171 $this->addJoinConds( [ 'user_groups' => [ 'JOIN', 'ug_user=user_id' ] ] );
172 $this->addFields( [ 'user_name' ] );
173 $this->addFields( UserGroupMembership::selectFields() );
174 $this->addWhere( 'ug_expiry IS NULL OR ug_expiry >= ' .
175 $db->addQuotes( $db->timestamp() ) );
176 $userGroupsRes = $this->select( __METHOD__ );
177
178 foreach ( $userGroupsRes as $row ) {
179 $userGroups[$row->user_name][] = $row;
180 }
181 }
182
183 foreach ( $res as $row ) {
184 // create user object and pass along $userGroups if set
185 // that reduces the number of database queries needed in User dramatically
186 if ( !isset( $userGroups ) ) {
187 $user = User::newFromRow( $row );
188 } else {
189 if ( !isset( $userGroups[$row->user_name] ) || !is_array( $userGroups[$row->user_name] ) ) {
190 $userGroups[$row->user_name] = [];
191 }
192 $user = User::newFromRow( $row, [ 'user_groups' => $userGroups[$row->user_name] ] );
193 }
194 if ( $useNames ) {
195 $key = $user->getName();
196 } else {
197 $key = $user->getId();
198 }
199 $data[$key]['userid'] = $user->getId();
200 $data[$key]['name'] = $user->getName();
201
202 if ( isset( $this->prop['editcount'] ) ) {
203 $data[$key]['editcount'] = $user->getEditCount();
204 }
205
206 if ( isset( $this->prop['registration'] ) ) {
207 $data[$key]['registration'] = wfTimestampOrNull( TS_ISO_8601, $user->getRegistration() );
208 }
209
210 if ( isset( $this->prop['groups'] ) ) {
211 $data[$key]['groups'] = $user->getEffectiveGroups();
212 }
213
214 if ( isset( $this->prop['groupmemberships'] ) ) {
215 $data[$key]['groupmemberships'] = array_map( function ( $ugm ) {
216 return [
217 'group' => $ugm->getGroup(),
218 'expiry' => ApiResult::formatExpiry( $ugm->getExpiry() ),
219 ];
220 }, $user->getGroupMemberships() );
221 }
222
223 if ( isset( $this->prop['implicitgroups'] ) ) {
224 $data[$key]['implicitgroups'] = $user->getAutomaticGroups();
225 }
226
227 if ( isset( $this->prop['rights'] ) ) {
228 $data[$key]['rights'] = $this->getPermissionManager()
229 ->getUserPermissions( $user );
230 }
231 if ( $row->ipb_deleted ) {
232 $data[$key]['hidden'] = true;
233 }
234 if ( isset( $this->prop['blockinfo'] ) && !is_null( $row->ipb_by_text ) ) {
235 $data[$key]['blockid'] = (int)$row->ipb_id;
236 $data[$key]['blockedby'] = $row->ipb_by_text;
237 $data[$key]['blockedbyid'] = (int)$row->ipb_by;
238 $data[$key]['blockedtimestamp'] = wfTimestamp( TS_ISO_8601, $row->ipb_timestamp );
239 $data[$key]['blockreason'] = $commentStore->getComment( 'ipb_reason', $row )
240 ->text;
241 $data[$key]['blockexpiry'] = $row->ipb_expiry;
242 }
243
244 if ( isset( $this->prop['emailable'] ) ) {
245 $data[$key]['emailable'] = $user->canReceiveEmail();
246 }
247
248 if ( isset( $this->prop['gender'] ) ) {
249 $gender = $user->getOption( 'gender' );
250 if ( strval( $gender ) === '' ) {
251 $gender = 'unknown';
252 }
253 $data[$key]['gender'] = $gender;
254 }
255
256 if ( isset( $this->prop['centralids'] ) ) {
257 $data[$key] += ApiQueryUserInfo::getCentralUserInfo(
258 $this->getConfig(), $user, $params['attachedwiki']
259 );
260 }
261
262 if ( !is_null( $params['token'] ) ) {
263 $tokenFunctions = $this->getTokenFunctions();
264 foreach ( $params['token'] as $t ) {
265 $val = call_user_func( $tokenFunctions[$t], $user );
266 if ( $val === false ) {
267 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
268 } else {
269 $data[$key][$t . 'token'] = $val;
270 }
271 }
272 }
273 }
274 }
275
276 $context = $this->getContext();
277 // Second pass: add result data to $retval
278 foreach ( $parameters as $u ) {
279 if ( !isset( $data[$u] ) ) {
280 if ( $useNames ) {
281 $data[$u] = [ 'name' => $u ];
282 $urPage = new UserrightsPage;
283 $urPage->setContext( $context );
284
285 $iwUser = $urPage->fetchUser( $u );
286
287 if ( $iwUser instanceof UserRightsProxy ) {
288 $data[$u]['interwiki'] = true;
289
290 if ( !is_null( $params['token'] ) ) {
291 $tokenFunctions = $this->getTokenFunctions();
292
293 foreach ( $params['token'] as $t ) {
294 $val = call_user_func( $tokenFunctions[$t], $iwUser );
295 if ( $val === false ) {
296 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
297 } else {
298 $data[$u][$t . 'token'] = $val;
299 }
300 }
301 }
302 } else {
303 $data[$u]['missing'] = true;
304 if ( isset( $this->prop['cancreate'] ) ) {
305 $status = MediaWiki\Auth\AuthManager::singleton()->canCreateAccount( $u );
306 $data[$u]['cancreate'] = $status->isGood();
307 if ( !$status->isGood() ) {
308 $data[$u]['cancreateerror'] = $this->getErrorFormatter()->arrayFromStatus( $status );
309 }
310 }
311 }
312 } else {
313 $data[$u] = [ 'userid' => $u, 'missing' => true ];
314 }
315
316 } else {
317 if ( isset( $this->prop['groups'] ) && isset( $data[$u]['groups'] ) ) {
318 ApiResult::setArrayType( $data[$u]['groups'], 'array' );
319 ApiResult::setIndexedTagName( $data[$u]['groups'], 'g' );
320 }
321 if ( isset( $this->prop['groupmemberships'] ) && isset( $data[$u]['groupmemberships'] ) ) {
322 ApiResult::setArrayType( $data[$u]['groupmemberships'], 'array' );
323 ApiResult::setIndexedTagName( $data[$u]['groupmemberships'], 'groupmembership' );
324 }
325 if ( isset( $this->prop['implicitgroups'] ) && isset( $data[$u]['implicitgroups'] ) ) {
326 ApiResult::setArrayType( $data[$u]['implicitgroups'], 'array' );
327 ApiResult::setIndexedTagName( $data[$u]['implicitgroups'], 'g' );
328 }
329 if ( isset( $this->prop['rights'] ) && isset( $data[$u]['rights'] ) ) {
330 ApiResult::setArrayType( $data[$u]['rights'], 'array' );
331 ApiResult::setIndexedTagName( $data[$u]['rights'], 'r' );
332 }
333 }
334
335 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
336 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data[$u] );
337 if ( !$fit ) {
338 if ( $useNames ) {
339 $this->setContinueEnumParameter( 'users',
340 implode( '|', array_diff( $users, $done ) ) );
341 } else {
342 $this->setContinueEnumParameter( 'userids',
343 implode( '|', array_diff( $userids, $done ) ) );
344 }
345 break;
346 }
347 $done[] = $u;
348 }
349 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'user' );
350 }
351
352 public function getCacheMode( $params ) {
353 if ( isset( $params['token'] ) ) {
354 return 'private';
355 } elseif ( array_diff( (array)$params['prop'], static::$publicProps ) ) {
356 return 'anon-public-user-private';
357 } else {
358 return 'public';
359 }
360 }
361
362 public function getAllowedParams() {
363 return [
364 'prop' => [
365 ApiBase::PARAM_ISMULTI => true,
366 ApiBase::PARAM_TYPE => [
367 'blockinfo',
368 'groups',
369 'groupmemberships',
370 'implicitgroups',
371 'rights',
372 'editcount',
373 'registration',
374 'emailable',
375 'gender',
376 'centralids',
377 'cancreate',
378 // When adding a prop, consider whether it should be added
379 // to self::$publicProps
380 ],
381 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
382 ],
383 'attachedwiki' => null,
384 'users' => [
385 ApiBase::PARAM_ISMULTI => true
386 ],
387 'userids' => [
388 ApiBase::PARAM_ISMULTI => true,
389 ApiBase::PARAM_TYPE => 'integer'
390 ],
391 'token' => [
392 ApiBase::PARAM_DEPRECATED => true,
393 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
394 ApiBase::PARAM_ISMULTI => true
395 ],
396 ];
397 }
398
399 protected function getExamplesMessages() {
400 return [
401 'action=query&list=users&ususers=Example&usprop=groups|editcount|gender'
402 => 'apihelp-query+users-example-simple',
403 ];
404 }
405
406 public function getHelpUrls() {
407 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Users';
408 }
409 }