Merge "Allow SearchEngine users to access features data"
[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 $params = $this->extractRequestParams();
102 $this->requireMaxOneParameter( $params, 'userids', 'users' );
103
104 if ( !is_null( $params['prop'] ) ) {
105 $this->prop = array_flip( $params['prop'] );
106 } else {
107 $this->prop = [];
108 }
109 $useNames = !is_null( $params['users'] );
110
111 $users = (array)$params['users'];
112 $userids = (array)$params['userids'];
113
114 $goodNames = $done = [];
115 $result = $this->getResult();
116 // Canonicalize user names
117 foreach ( $users as $u ) {
118 $n = User::getCanonicalName( $u );
119 if ( $n === false || $n === '' ) {
120 $vals = [ 'name' => $u, 'invalid' => true ];
121 $fit = $result->addValue( [ 'query', $this->getModuleName() ],
122 null, $vals );
123 if ( !$fit ) {
124 $this->setContinueEnumParameter( 'users',
125 implode( '|', array_diff( $users, $done ) ) );
126 $goodNames = [];
127 break;
128 }
129 $done[] = $u;
130 } else {
131 $goodNames[] = $n;
132 }
133 }
134
135 if ( $useNames ) {
136 $parameters = &$goodNames;
137 } else {
138 $parameters = &$userids;
139 }
140
141 $result = $this->getResult();
142
143 if ( count( $parameters ) ) {
144 $this->addTables( 'user' );
145 $this->addFields( User::selectFields() );
146 if ( $useNames ) {
147 $this->addWhereFld( 'user_name', $goodNames );
148 } else {
149 $this->addWhereFld( 'user_id', $userids );
150 }
151
152 $this->showHiddenUsersAddBlockInfo( isset( $this->prop['blockinfo'] ) );
153
154 $data = [];
155 $res = $this->select( __METHOD__ );
156 $this->resetQueryParams();
157
158 // get user groups if needed
159 if ( isset( $this->prop['groups'] ) || isset( $this->prop['rights'] ) ) {
160 $userGroups = [];
161
162 $this->addTables( 'user' );
163 if ( $useNames ) {
164 $this->addWhereFld( 'user_name', $goodNames );
165 } else {
166 $this->addWhereFld( 'user_id', $userids );
167 }
168
169 $this->addTables( 'user_groups' );
170 $this->addJoinConds( [ 'user_groups' => [ 'INNER JOIN', 'ug_user=user_id' ] ] );
171 $this->addFields( [ 'user_name', 'ug_group' ] );
172 $userGroupsRes = $this->select( __METHOD__ );
173
174 foreach ( $userGroupsRes as $row ) {
175 $userGroups[$row->user_name][] = $row->ug_group;
176 }
177 }
178
179 foreach ( $res as $row ) {
180
181 // create user object and pass along $userGroups if set
182 // that reduces the number of database queries needed in User dramatically
183 if ( !isset( $userGroups ) ) {
184 $user = User::newFromRow( $row );
185 } else {
186 if ( !isset( $userGroups[$row->user_name] ) || !is_array( $userGroups[$row->user_name] ) ) {
187 $userGroups[$row->user_name] = [];
188 }
189 $user = User::newFromRow( $row, [ 'user_groups' => $userGroups[$row->user_name] ] );
190 }
191 if ( $useNames ) {
192 $key = $user->getName();
193 } else {
194 $key = $user->getId();
195 }
196 $data[$key]['userid'] = $user->getId();
197 $data[$key]['name'] = $user->getName();
198
199 if ( isset( $this->prop['editcount'] ) ) {
200 $data[$key]['editcount'] = $user->getEditCount();
201 }
202
203 if ( isset( $this->prop['registration'] ) ) {
204 $data[$key]['registration'] = wfTimestampOrNull( TS_ISO_8601, $user->getRegistration() );
205 }
206
207 if ( isset( $this->prop['groups'] ) ) {
208 $data[$key]['groups'] = $user->getEffectiveGroups();
209 }
210
211 if ( isset( $this->prop['groupmemberships'] ) ) {
212 $data[$key]['groupmemberships'] = array_map( function( $ugm ) {
213 return [
214 'group' => $ugm->getGroup(),
215 'expiry' => ApiResult::formatExpiry( $ugm->getExpiry() ),
216 ];
217 }, $user->getGroupMemberships() );
218 }
219
220 if ( isset( $this->prop['implicitgroups'] ) ) {
221 $data[$key]['implicitgroups'] = $user->getAutomaticGroups();
222 }
223
224 if ( isset( $this->prop['rights'] ) ) {
225 $data[$key]['rights'] = $user->getRights();
226 }
227 if ( $row->ipb_deleted ) {
228 $data[$key]['hidden'] = true;
229 }
230 if ( isset( $this->prop['blockinfo'] ) && !is_null( $row->ipb_by_text ) ) {
231 $data[$key]['blockid'] = (int)$row->ipb_id;
232 $data[$key]['blockedby'] = $row->ipb_by_text;
233 $data[$key]['blockedbyid'] = (int)$row->ipb_by;
234 $data[$key]['blockedtimestamp'] = wfTimestamp( TS_ISO_8601, $row->ipb_timestamp );
235 $data[$key]['blockreason'] = $row->ipb_reason;
236 $data[$key]['blockexpiry'] = $row->ipb_expiry;
237 }
238
239 if ( isset( $this->prop['emailable'] ) ) {
240 $data[$key]['emailable'] = $user->canReceiveEmail();
241 }
242
243 if ( isset( $this->prop['gender'] ) ) {
244 $gender = $user->getOption( 'gender' );
245 if ( strval( $gender ) === '' ) {
246 $gender = 'unknown';
247 }
248 $data[$key]['gender'] = $gender;
249 }
250
251 if ( isset( $this->prop['centralids'] ) ) {
252 $data[$key] += ApiQueryUserInfo::getCentralUserInfo(
253 $this->getConfig(), $user, $params['attachedwiki']
254 );
255 }
256
257 if ( !is_null( $params['token'] ) ) {
258 $tokenFunctions = $this->getTokenFunctions();
259 foreach ( $params['token'] as $t ) {
260 $val = call_user_func( $tokenFunctions[$t], $user );
261 if ( $val === false ) {
262 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
263 } else {
264 $data[$key][$t . 'token'] = $val;
265 }
266 }
267 }
268 }
269 }
270
271 $context = $this->getContext();
272 // Second pass: add result data to $retval
273 foreach ( $parameters as $u ) {
274 if ( !isset( $data[$u] ) ) {
275 if ( $useNames ) {
276 $data[$u] = [ 'name' => $u ];
277 $urPage = new UserrightsPage;
278 $urPage->setContext( $context );
279
280 $iwUser = $urPage->fetchUser( $u );
281
282 if ( $iwUser instanceof UserRightsProxy ) {
283 $data[$u]['interwiki'] = true;
284
285 if ( !is_null( $params['token'] ) ) {
286 $tokenFunctions = $this->getTokenFunctions();
287
288 foreach ( $params['token'] as $t ) {
289 $val = call_user_func( $tokenFunctions[$t], $iwUser );
290 if ( $val === false ) {
291 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
292 } else {
293 $data[$u][$t . 'token'] = $val;
294 }
295 }
296 }
297 } else {
298 $data[$u]['missing'] = true;
299 if ( isset( $this->prop['cancreate'] ) ) {
300 $status = MediaWiki\Auth\AuthManager::singleton()->canCreateAccount( $u );
301 $data[$u]['cancreate'] = $status->isGood();
302 if ( !$status->isGood() ) {
303 $data[$u]['cancreateerror'] = $this->getErrorFormatter()->arrayFromStatus( $status );
304 }
305 }
306 }
307 } else {
308 $data[$u] = [ 'userid' => $u, 'missing' => true ];
309 }
310
311 } else {
312 if ( isset( $this->prop['groups'] ) && isset( $data[$u]['groups'] ) ) {
313 ApiResult::setArrayType( $data[$u]['groups'], 'array' );
314 ApiResult::setIndexedTagName( $data[$u]['groups'], 'g' );
315 }
316 if ( isset( $this->prop['groupmemberships'] ) && isset( $data[$u]['groupmemberships'] ) ) {
317 ApiResult::setArrayType( $data[$u]['groupmemberships'], 'array' );
318 ApiResult::setIndexedTagName( $data[$u]['groupmemberships'], 'groupmembership' );
319 }
320 if ( isset( $this->prop['implicitgroups'] ) && isset( $data[$u]['implicitgroups'] ) ) {
321 ApiResult::setArrayType( $data[$u]['implicitgroups'], 'array' );
322 ApiResult::setIndexedTagName( $data[$u]['implicitgroups'], 'g' );
323 }
324 if ( isset( $this->prop['rights'] ) && isset( $data[$u]['rights'] ) ) {
325 ApiResult::setArrayType( $data[$u]['rights'], 'array' );
326 ApiResult::setIndexedTagName( $data[$u]['rights'], 'r' );
327 }
328 }
329
330 $fit = $result->addValue( [ 'query', $this->getModuleName() ],
331 null, $data[$u] );
332 if ( !$fit ) {
333 if ( $useNames ) {
334 $this->setContinueEnumParameter( 'users',
335 implode( '|', array_diff( $users, $done ) ) );
336 } else {
337 $this->setContinueEnumParameter( 'userids',
338 implode( '|', array_diff( $userids, $done ) ) );
339 }
340 break;
341 }
342 $done[] = $u;
343 }
344 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'user' );
345 }
346
347 public function getCacheMode( $params ) {
348 if ( isset( $params['token'] ) ) {
349 return 'private';
350 } elseif ( array_diff( (array)$params['prop'], static::$publicProps ) ) {
351 return 'anon-public-user-private';
352 } else {
353 return 'public';
354 }
355 }
356
357 public function getAllowedParams() {
358 return [
359 'prop' => [
360 ApiBase::PARAM_ISMULTI => true,
361 ApiBase::PARAM_TYPE => [
362 'blockinfo',
363 'groups',
364 'groupmemberships',
365 'implicitgroups',
366 'rights',
367 'editcount',
368 'registration',
369 'emailable',
370 'gender',
371 'centralids',
372 'cancreate',
373 // When adding a prop, consider whether it should be added
374 // to self::$publicProps
375 ],
376 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
377 ],
378 'attachedwiki' => null,
379 'users' => [
380 ApiBase::PARAM_ISMULTI => true
381 ],
382 'userids' => [
383 ApiBase::PARAM_ISMULTI => true,
384 ApiBase::PARAM_TYPE => 'integer'
385 ],
386 'token' => [
387 ApiBase::PARAM_DEPRECATED => true,
388 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
389 ApiBase::PARAM_ISMULTI => true
390 ],
391 ];
392 }
393
394 protected function getExamplesMessages() {
395 return [
396 'action=query&list=users&ususers=Example&usprop=groups|editcount|gender'
397 => 'apihelp-query+users-example-simple',
398 ];
399 }
400
401 public function getHelpUrls() {
402 return 'https://www.mediawiki.org/wiki/API:Users';
403 }
404 }