Move remaining LoadBalancer classes to Rdbms
[mediawiki.git] / includes / api / ApiQueryUsers.php
blob3a814c4c49f1bb411af0c7937644afb8a2dc008c
1 <?php
2 /**
5 * Created on July 30, 2007
7 * Copyright © 2007 Roan Kattouw "<Firstname>.<Lastname>@gmail.com"
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.
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.
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
24 * @file
27 /**
28 * Query module to get information about a list of users
30 * @ingroup API
32 class ApiQueryUsers extends ApiQueryBase {
34 private $tokenFunctions, $prop;
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
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',
56 public function __construct( ApiQuery $query, $moduleName ) {
57 parent::__construct( $query, $moduleName, 'us' );
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
67 protected function getTokenFunctions() {
68 // Don't call the hooks twice
69 if ( isset( $this->tokenFunctions ) ) {
70 return $this->tokenFunctions;
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 [];
79 $this->tokenFunctions = [
80 'userrights' => [ 'ApiQueryUsers', 'getUserrightsToken' ],
82 Hooks::run( 'APIQueryUsersTokens', [ &$this->tokenFunctions ] );
84 return $this->tokenFunctions;
87 /**
88 * @deprecated since 1.24
89 * @param User $user
90 * @return string
92 public static function getUserrightsToken( $user ) {
93 global $wgUser;
95 // Since the permissions check for userrights is non-trivial,
96 // don't bother with it here
97 return $wgUser->getEditToken( $user->getName() );
100 public function execute() {
101 $db = $this->getDB();
103 $params = $this->extractRequestParams();
104 $this->requireMaxOneParameter( $params, 'userids', 'users' );
106 if ( !is_null( $params['prop'] ) ) {
107 $this->prop = array_flip( $params['prop'] );
108 } else {
109 $this->prop = [];
111 $useNames = !is_null( $params['users'] );
113 $users = (array)$params['users'];
114 $userids = (array)$params['userids'];
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;
131 $done[] = $u;
132 } else {
133 $goodNames[] = $n;
137 if ( $useNames ) {
138 $parameters = &$goodNames;
139 } else {
140 $parameters = &$userids;
143 $result = $this->getResult();
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 );
154 $this->showHiddenUsersAddBlockInfo( isset( $this->prop['blockinfo'] ) );
156 $data = [];
157 $res = $this->select( __METHOD__ );
158 $this->resetQueryParams();
160 // get user groups if needed
161 if ( isset( $this->prop['groups'] ) || isset( $this->prop['rights'] ) ) {
162 $userGroups = [];
164 $this->addTables( 'user' );
165 if ( $useNames ) {
166 $this->addWhereFld( 'user_name', $goodNames );
167 } else {
168 $this->addWhereFld( 'user_id', $userids );
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 if ( !$this->getConfig()->get( 'DisableUserGroupExpiry' ) ) {
176 $this->addWhere( 'ug_expiry IS NULL OR ug_expiry >= ' .
177 $db->addQuotes( $db->timestamp() ) );
179 $userGroupsRes = $this->select( __METHOD__ );
181 foreach ( $userGroupsRes as $row ) {
182 $userGroups[$row->user_name][] = $row;
186 foreach ( $res as $row ) {
188 // create user object and pass along $userGroups if set
189 // that reduces the number of database queries needed in User dramatically
190 if ( !isset( $userGroups ) ) {
191 $user = User::newFromRow( $row );
192 } else {
193 if ( !isset( $userGroups[$row->user_name] ) || !is_array( $userGroups[$row->user_name] ) ) {
194 $userGroups[$row->user_name] = [];
196 $user = User::newFromRow( $row, [ 'user_groups' => $userGroups[$row->user_name] ] );
198 if ( $useNames ) {
199 $key = $user->getName();
200 } else {
201 $key = $user->getId();
203 $data[$key]['userid'] = $user->getId();
204 $data[$key]['name'] = $user->getName();
206 if ( isset( $this->prop['editcount'] ) ) {
207 $data[$key]['editcount'] = $user->getEditCount();
210 if ( isset( $this->prop['registration'] ) ) {
211 $data[$key]['registration'] = wfTimestampOrNull( TS_ISO_8601, $user->getRegistration() );
214 if ( isset( $this->prop['groups'] ) ) {
215 $data[$key]['groups'] = $user->getEffectiveGroups();
218 if ( isset( $this->prop['groupmemberships'] ) ) {
219 $data[$key]['groupmemberships'] = array_map( function( $ugm ) {
220 return [
221 'group' => $ugm->getGroup(),
222 'expiry' => ApiResult::formatExpiry( $ugm->getExpiry() ),
224 }, $user->getGroupMemberships() );
227 if ( isset( $this->prop['implicitgroups'] ) ) {
228 $data[$key]['implicitgroups'] = $user->getAutomaticGroups();
231 if ( isset( $this->prop['rights'] ) ) {
232 $data[$key]['rights'] = $user->getRights();
234 if ( $row->ipb_deleted ) {
235 $data[$key]['hidden'] = true;
237 if ( isset( $this->prop['blockinfo'] ) && !is_null( $row->ipb_by_text ) ) {
238 $data[$key]['blockid'] = (int)$row->ipb_id;
239 $data[$key]['blockedby'] = $row->ipb_by_text;
240 $data[$key]['blockedbyid'] = (int)$row->ipb_by;
241 $data[$key]['blockedtimestamp'] = wfTimestamp( TS_ISO_8601, $row->ipb_timestamp );
242 $data[$key]['blockreason'] = $row->ipb_reason;
243 $data[$key]['blockexpiry'] = $row->ipb_expiry;
246 if ( isset( $this->prop['emailable'] ) ) {
247 $data[$key]['emailable'] = $user->canReceiveEmail();
250 if ( isset( $this->prop['gender'] ) ) {
251 $gender = $user->getOption( 'gender' );
252 if ( strval( $gender ) === '' ) {
253 $gender = 'unknown';
255 $data[$key]['gender'] = $gender;
258 if ( isset( $this->prop['centralids'] ) ) {
259 $data[$key] += ApiQueryUserInfo::getCentralUserInfo(
260 $this->getConfig(), $user, $params['attachedwiki']
264 if ( !is_null( $params['token'] ) ) {
265 $tokenFunctions = $this->getTokenFunctions();
266 foreach ( $params['token'] as $t ) {
267 $val = call_user_func( $tokenFunctions[$t], $user );
268 if ( $val === false ) {
269 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
270 } else {
271 $data[$key][$t . 'token'] = $val;
278 $context = $this->getContext();
279 // Second pass: add result data to $retval
280 foreach ( $parameters as $u ) {
281 if ( !isset( $data[$u] ) ) {
282 if ( $useNames ) {
283 $data[$u] = [ 'name' => $u ];
284 $urPage = new UserrightsPage;
285 $urPage->setContext( $context );
287 $iwUser = $urPage->fetchUser( $u );
289 if ( $iwUser instanceof UserRightsProxy ) {
290 $data[$u]['interwiki'] = true;
292 if ( !is_null( $params['token'] ) ) {
293 $tokenFunctions = $this->getTokenFunctions();
295 foreach ( $params['token'] as $t ) {
296 $val = call_user_func( $tokenFunctions[$t], $iwUser );
297 if ( $val === false ) {
298 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
299 } else {
300 $data[$u][$t . 'token'] = $val;
304 } else {
305 $data[$u]['missing'] = true;
306 if ( isset( $this->prop['cancreate'] ) ) {
307 $status = MediaWiki\Auth\AuthManager::singleton()->canCreateAccount( $u );
308 $data[$u]['cancreate'] = $status->isGood();
309 if ( !$status->isGood() ) {
310 $data[$u]['cancreateerror'] = $this->getErrorFormatter()->arrayFromStatus( $status );
314 } else {
315 $data[$u] = [ 'userid' => $u, 'missing' => true ];
318 } else {
319 if ( isset( $this->prop['groups'] ) && isset( $data[$u]['groups'] ) ) {
320 ApiResult::setArrayType( $data[$u]['groups'], 'array' );
321 ApiResult::setIndexedTagName( $data[$u]['groups'], 'g' );
323 if ( isset( $this->prop['groupmemberships'] ) && isset( $data[$u]['groupmemberships'] ) ) {
324 ApiResult::setArrayType( $data[$u]['groupmemberships'], 'array' );
325 ApiResult::setIndexedTagName( $data[$u]['groupmemberships'], 'groupmembership' );
327 if ( isset( $this->prop['implicitgroups'] ) && isset( $data[$u]['implicitgroups'] ) ) {
328 ApiResult::setArrayType( $data[$u]['implicitgroups'], 'array' );
329 ApiResult::setIndexedTagName( $data[$u]['implicitgroups'], 'g' );
331 if ( isset( $this->prop['rights'] ) && isset( $data[$u]['rights'] ) ) {
332 ApiResult::setArrayType( $data[$u]['rights'], 'array' );
333 ApiResult::setIndexedTagName( $data[$u]['rights'], 'r' );
337 $fit = $result->addValue( [ 'query', $this->getModuleName() ],
338 null, $data[$u] );
339 if ( !$fit ) {
340 if ( $useNames ) {
341 $this->setContinueEnumParameter( 'users',
342 implode( '|', array_diff( $users, $done ) ) );
343 } else {
344 $this->setContinueEnumParameter( 'userids',
345 implode( '|', array_diff( $userids, $done ) ) );
347 break;
349 $done[] = $u;
351 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'user' );
354 public function getCacheMode( $params ) {
355 if ( isset( $params['token'] ) ) {
356 return 'private';
357 } elseif ( array_diff( (array)$params['prop'], static::$publicProps ) ) {
358 return 'anon-public-user-private';
359 } else {
360 return 'public';
364 public function getAllowedParams() {
365 return [
366 'prop' => [
367 ApiBase::PARAM_ISMULTI => true,
368 ApiBase::PARAM_TYPE => [
369 'blockinfo',
370 'groups',
371 'groupmemberships',
372 'implicitgroups',
373 'rights',
374 'editcount',
375 'registration',
376 'emailable',
377 'gender',
378 'centralids',
379 'cancreate',
380 // When adding a prop, consider whether it should be added
381 // to self::$publicProps
383 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
385 'attachedwiki' => null,
386 'users' => [
387 ApiBase::PARAM_ISMULTI => true
389 'userids' => [
390 ApiBase::PARAM_ISMULTI => true,
391 ApiBase::PARAM_TYPE => 'integer'
393 'token' => [
394 ApiBase::PARAM_DEPRECATED => true,
395 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
396 ApiBase::PARAM_ISMULTI => true
401 protected function getExamplesMessages() {
402 return [
403 'action=query&list=users&ususers=Example&usprop=groups|editcount|gender'
404 => 'apihelp-query+users-example-simple',
408 public function getHelpUrls() {
409 return 'https://www.mediawiki.org/wiki/API:Users';