Merge "Handle missing namespace prefix in XML dumps more gracefully"
[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 if ( !$this->getConfig()->get( 'DisableUserGroupExpiry' ) ) {
176 $this->addWhere( 'ug_expiry IS NULL OR ug_expiry >= ' .
177 $db->addQuotes( $db->timestamp() ) );
178 }
179 $userGroupsRes = $this->select( __METHOD__ );
180
181 foreach ( $userGroupsRes as $row ) {
182 $userGroups[$row->user_name][] = $row;
183 }
184 }
185
186 foreach ( $res as $row ) {
187
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] = [];
195 }
196 $user = User::newFromRow( $row, [ 'user_groups' => $userGroups[$row->user_name] ] );
197 }
198 if ( $useNames ) {
199 $key = $user->getName();
200 } else {
201 $key = $user->getId();
202 }
203 $data[$key]['userid'] = $user->getId();
204 $data[$key]['name'] = $user->getName();
205
206 if ( isset( $this->prop['editcount'] ) ) {
207 $data[$key]['editcount'] = $user->getEditCount();
208 }
209
210 if ( isset( $this->prop['registration'] ) ) {
211 $data[$key]['registration'] = wfTimestampOrNull( TS_ISO_8601, $user->getRegistration() );
212 }
213
214 if ( isset( $this->prop['groups'] ) ) {
215 $data[$key]['groups'] = $user->getEffectiveGroups();
216 }
217
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() ),
223 ];
224 }, $user->getGroupMemberships() );
225 }
226
227 if ( isset( $this->prop['implicitgroups'] ) ) {
228 $data[$key]['implicitgroups'] = $user->getAutomaticGroups();
229 }
230
231 if ( isset( $this->prop['rights'] ) ) {
232 $data[$key]['rights'] = $user->getRights();
233 }
234 if ( $row->ipb_deleted ) {
235 $data[$key]['hidden'] = true;
236 }
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;
244 }
245
246 if ( isset( $this->prop['emailable'] ) ) {
247 $data[$key]['emailable'] = $user->canReceiveEmail();
248 }
249
250 if ( isset( $this->prop['gender'] ) ) {
251 $gender = $user->getOption( 'gender' );
252 if ( strval( $gender ) === '' ) {
253 $gender = 'unknown';
254 }
255 $data[$key]['gender'] = $gender;
256 }
257
258 if ( isset( $this->prop['centralids'] ) ) {
259 $data[$key] += ApiQueryUserInfo::getCentralUserInfo(
260 $this->getConfig(), $user, $params['attachedwiki']
261 );
262 }
263
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;
272 }
273 }
274 }
275 }
276 }
277
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 );
286
287 $iwUser = $urPage->fetchUser( $u );
288
289 if ( $iwUser instanceof UserRightsProxy ) {
290 $data[$u]['interwiki'] = true;
291
292 if ( !is_null( $params['token'] ) ) {
293 $tokenFunctions = $this->getTokenFunctions();
294
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;
301 }
302 }
303 }
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 );
311 }
312 }
313 }
314 } else {
315 $data[$u] = [ 'userid' => $u, 'missing' => true ];
316 }
317
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' );
322 }
323 if ( isset( $this->prop['groupmemberships'] ) && isset( $data[$u]['groupmemberships'] ) ) {
324 ApiResult::setArrayType( $data[$u]['groupmemberships'], 'array' );
325 ApiResult::setIndexedTagName( $data[$u]['groupmemberships'], 'groupmembership' );
326 }
327 if ( isset( $this->prop['implicitgroups'] ) && isset( $data[$u]['implicitgroups'] ) ) {
328 ApiResult::setArrayType( $data[$u]['implicitgroups'], 'array' );
329 ApiResult::setIndexedTagName( $data[$u]['implicitgroups'], 'g' );
330 }
331 if ( isset( $this->prop['rights'] ) && isset( $data[$u]['rights'] ) ) {
332 ApiResult::setArrayType( $data[$u]['rights'], 'array' );
333 ApiResult::setIndexedTagName( $data[$u]['rights'], 'r' );
334 }
335 }
336
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 ) ) );
346 }
347 break;
348 }
349 $done[] = $u;
350 }
351 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'user' );
352 }
353
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';
361 }
362 }
363
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
382 ],
383 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
384 ],
385 'attachedwiki' => null,
386 'users' => [
387 ApiBase::PARAM_ISMULTI => true
388 ],
389 'userids' => [
390 ApiBase::PARAM_ISMULTI => true,
391 ApiBase::PARAM_TYPE => 'integer'
392 ],
393 'token' => [
394 ApiBase::PARAM_DEPRECATED => true,
395 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
396 ApiBase::PARAM_ISMULTI => true
397 ],
398 ];
399 }
400
401 protected function getExamplesMessages() {
402 return [
403 'action=query&list=users&ususers=Example&usprop=groups|editcount|gender'
404 => 'apihelp-query+users-example-simple',
405 ];
406 }
407
408 public function getHelpUrls() {
409 return 'https://www.mediawiki.org/wiki/API:Users';
410 }
411 }