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