Merge "Improve "selfmove" message's wording"
[lhc/web/wiklou.git] / includes / api / ApiQueryUsers.php
1 <?php
2 /**
3 *
4 *
5 * Created on July 30, 2007
6 *
7 * Copyright © 2007 Roan Kattouw "<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 get information about a list of users
29 *
30 * @ingroup API
31 */
32 class ApiQueryUsers extends ApiQueryBase {
33
34 private $tokenFunctions, $prop;
35
36 /**
37 * Properties whose contents does not depend on who is looking at them. If the usprops field
38 * contains anything not listed here, the cache mode will never be public for logged-in users.
39 * @var array
40 */
41 protected static $publicProps = [
42 // everything except 'blockinfo' which might show hidden records if the user
43 // making the request has the appropriate permissions
44 'groups',
45 'groupmemberships',
46 'implicitgroups',
47 'rights',
48 'editcount',
49 'registration',
50 'emailable',
51 'gender',
52 'centralids',
53 'cancreate',
54 ];
55
56 public function __construct( ApiQuery $query, $moduleName ) {
57 parent::__construct( $query, $moduleName, 'us' );
58 }
59
60 /**
61 * Get an array mapping token names to their handler functions.
62 * The prototype for a token function is func($user)
63 * it should return a token or false (permission denied)
64 * @deprecated since 1.24
65 * @return array Array of tokenname => function
66 */
67 protected function getTokenFunctions() {
68 // Don't call the hooks twice
69 if ( isset( $this->tokenFunctions ) ) {
70 return $this->tokenFunctions;
71 }
72
73 // If we're in a mode that breaks the same-origin policy, no tokens can
74 // be obtained
75 if ( $this->lacksSameOriginSecurity() ) {
76 return [];
77 }
78
79 $this->tokenFunctions = [
80 'userrights' => [ 'ApiQueryUsers', 'getUserrightsToken' ],
81 ];
82 Hooks::run( 'APIQueryUsersTokens', [ &$this->tokenFunctions ] );
83
84 return $this->tokenFunctions;
85 }
86
87 /**
88 * @deprecated since 1.24
89 * @param User $user
90 * @return string
91 */
92 public static function getUserrightsToken( $user ) {
93 global $wgUser;
94
95 // Since the permissions check for userrights is non-trivial,
96 // don't bother with it here
97 return $wgUser->getEditToken( $user->getName() );
98 }
99
100 public function execute() {
101 $db = $this->getDB();
102 $commentStore = new CommentStore( 'ipb_reason' );
103
104 $params = $this->extractRequestParams();
105 $this->requireMaxOneParameter( $params, 'userids', 'users' );
106
107 if ( !is_null( $params['prop'] ) ) {
108 $this->prop = array_flip( $params['prop'] );
109 } else {
110 $this->prop = [];
111 }
112 $useNames = !is_null( $params['users'] );
113
114 $users = (array)$params['users'];
115 $userids = (array)$params['userids'];
116
117 $goodNames = $done = [];
118 $result = $this->getResult();
119 // Canonicalize user names
120 foreach ( $users as $u ) {
121 $n = User::getCanonicalName( $u );
122 if ( $n === false || $n === '' ) {
123 $vals = [ 'name' => $u, 'invalid' => true ];
124 $fit = $result->addValue( [ 'query', $this->getModuleName() ],
125 null, $vals );
126 if ( !$fit ) {
127 $this->setContinueEnumParameter( 'users',
128 implode( '|', array_diff( $users, $done ) ) );
129 $goodNames = [];
130 break;
131 }
132 $done[] = $u;
133 } else {
134 $goodNames[] = $n;
135 }
136 }
137
138 if ( $useNames ) {
139 $parameters = &$goodNames;
140 } else {
141 $parameters = &$userids;
142 }
143
144 $result = $this->getResult();
145
146 if ( count( $parameters ) ) {
147 $this->addTables( 'user' );
148 $this->addFields( User::selectFields() );
149 if ( $useNames ) {
150 $this->addWhereFld( 'user_name', $goodNames );
151 } else {
152 $this->addWhereFld( 'user_id', $userids );
153 }
154
155 $this->showHiddenUsersAddBlockInfo( isset( $this->prop['blockinfo'] ) );
156
157 $data = [];
158 $res = $this->select( __METHOD__ );
159 $this->resetQueryParams();
160
161 // get user groups if needed
162 if ( isset( $this->prop['groups'] ) || isset( $this->prop['rights'] ) ) {
163 $userGroups = [];
164
165 $this->addTables( 'user' );
166 if ( $useNames ) {
167 $this->addWhereFld( 'user_name', $goodNames );
168 } else {
169 $this->addWhereFld( 'user_id', $userids );
170 }
171
172 $this->addTables( 'user_groups' );
173 $this->addJoinConds( [ 'user_groups' => [ 'INNER JOIN', 'ug_user=user_id' ] ] );
174 $this->addFields( [ 'user_name' ] );
175 $this->addFields( UserGroupMembership::selectFields() );
176 $this->addWhere( 'ug_expiry IS NULL OR ug_expiry >= ' .
177 $db->addQuotes( $db->timestamp() ) );
178 $userGroupsRes = $this->select( __METHOD__ );
179
180 foreach ( $userGroupsRes as $row ) {
181 $userGroups[$row->user_name][] = $row;
182 }
183 }
184
185 foreach ( $res as $row ) {
186 // create user object and pass along $userGroups if set
187 // that reduces the number of database queries needed in User dramatically
188 if ( !isset( $userGroups ) ) {
189 $user = User::newFromRow( $row );
190 } else {
191 if ( !isset( $userGroups[$row->user_name] ) || !is_array( $userGroups[$row->user_name] ) ) {
192 $userGroups[$row->user_name] = [];
193 }
194 $user = User::newFromRow( $row, [ 'user_groups' => $userGroups[$row->user_name] ] );
195 }
196 if ( $useNames ) {
197 $key = $user->getName();
198 } else {
199 $key = $user->getId();
200 }
201 $data[$key]['userid'] = $user->getId();
202 $data[$key]['name'] = $user->getName();
203
204 if ( isset( $this->prop['editcount'] ) ) {
205 $data[$key]['editcount'] = $user->getEditCount();
206 }
207
208 if ( isset( $this->prop['registration'] ) ) {
209 $data[$key]['registration'] = wfTimestampOrNull( TS_ISO_8601, $user->getRegistration() );
210 }
211
212 if ( isset( $this->prop['groups'] ) ) {
213 $data[$key]['groups'] = $user->getEffectiveGroups();
214 }
215
216 if ( isset( $this->prop['groupmemberships'] ) ) {
217 $data[$key]['groupmemberships'] = array_map( function ( $ugm ) {
218 return [
219 'group' => $ugm->getGroup(),
220 'expiry' => ApiResult::formatExpiry( $ugm->getExpiry() ),
221 ];
222 }, $user->getGroupMemberships() );
223 }
224
225 if ( isset( $this->prop['implicitgroups'] ) ) {
226 $data[$key]['implicitgroups'] = $user->getAutomaticGroups();
227 }
228
229 if ( isset( $this->prop['rights'] ) ) {
230 $data[$key]['rights'] = $user->getRights();
231 }
232 if ( $row->ipb_deleted ) {
233 $data[$key]['hidden'] = true;
234 }
235 if ( isset( $this->prop['blockinfo'] ) && !is_null( $row->ipb_by_text ) ) {
236 $data[$key]['blockid'] = (int)$row->ipb_id;
237 $data[$key]['blockedby'] = $row->ipb_by_text;
238 $data[$key]['blockedbyid'] = (int)$row->ipb_by;
239 $data[$key]['blockedtimestamp'] = wfTimestamp( TS_ISO_8601, $row->ipb_timestamp );
240 $data[$key]['blockreason'] = $commentStore->getComment( $row )->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 $fit = $result->addValue( [ 'query', $this->getModuleName() ],
336 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 }