ApiQueryUsers.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. /**
  3. * Copyright © 2007 Roan Kattouw "<Firstname>.<Lastname>@gmail.com"
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\Block\DatabaseBlock;
  23. /**
  24. * Query module to get information about a list of users
  25. *
  26. * @ingroup API
  27. */
  28. class ApiQueryUsers extends ApiQueryBase {
  29. use ApiQueryBlockInfoTrait;
  30. private $tokenFunctions, $prop;
  31. /**
  32. * Properties whose contents does not depend on who is looking at them. If the usprops field
  33. * contains anything not listed here, the cache mode will never be public for logged-in users.
  34. * @var array
  35. */
  36. protected static $publicProps = [
  37. // everything except 'blockinfo' which might show hidden records if the user
  38. // making the request has the appropriate permissions
  39. 'groups',
  40. 'groupmemberships',
  41. 'implicitgroups',
  42. 'rights',
  43. 'editcount',
  44. 'registration',
  45. 'emailable',
  46. 'gender',
  47. 'centralids',
  48. 'cancreate',
  49. ];
  50. public function __construct( ApiQuery $query, $moduleName ) {
  51. parent::__construct( $query, $moduleName, 'us' );
  52. }
  53. /**
  54. * Get an array mapping token names to their handler functions.
  55. * The prototype for a token function is func($user)
  56. * it should return a token or false (permission denied)
  57. * @deprecated since 1.24
  58. * @return array Array of tokenname => function
  59. */
  60. protected function getTokenFunctions() {
  61. // Don't call the hooks twice
  62. if ( isset( $this->tokenFunctions ) ) {
  63. return $this->tokenFunctions;
  64. }
  65. // If we're in a mode that breaks the same-origin policy, no tokens can
  66. // be obtained
  67. if ( $this->lacksSameOriginSecurity() ) {
  68. return [];
  69. }
  70. $this->tokenFunctions = [
  71. 'userrights' => [ self::class, 'getUserrightsToken' ],
  72. ];
  73. Hooks::run( 'APIQueryUsersTokens', [ &$this->tokenFunctions ] );
  74. return $this->tokenFunctions;
  75. }
  76. /**
  77. * @deprecated since 1.24
  78. * @param User $user
  79. * @return string
  80. */
  81. public static function getUserrightsToken( $user ) {
  82. global $wgUser;
  83. // Since the permissions check for userrights is non-trivial,
  84. // don't bother with it here
  85. return $wgUser->getEditToken( $user->getName() );
  86. }
  87. public function execute() {
  88. $db = $this->getDB();
  89. $commentStore = CommentStore::getStore();
  90. $params = $this->extractRequestParams();
  91. $this->requireMaxOneParameter( $params, 'userids', 'users' );
  92. if ( !is_null( $params['prop'] ) ) {
  93. $this->prop = array_flip( $params['prop'] );
  94. } else {
  95. $this->prop = [];
  96. }
  97. $useNames = !is_null( $params['users'] );
  98. $users = (array)$params['users'];
  99. $userids = (array)$params['userids'];
  100. $goodNames = $done = [];
  101. $result = $this->getResult();
  102. // Canonicalize user names
  103. foreach ( $users as $u ) {
  104. $n = User::getCanonicalName( $u );
  105. if ( $n === false || $n === '' ) {
  106. $vals = [ 'name' => $u, 'invalid' => true ];
  107. $fit = $result->addValue( [ 'query', $this->getModuleName() ],
  108. null, $vals );
  109. if ( !$fit ) {
  110. $this->setContinueEnumParameter( 'users',
  111. implode( '|', array_diff( $users, $done ) ) );
  112. $goodNames = [];
  113. break;
  114. }
  115. $done[] = $u;
  116. } else {
  117. $goodNames[] = $n;
  118. }
  119. }
  120. if ( $useNames ) {
  121. $parameters = &$goodNames;
  122. } else {
  123. $parameters = &$userids;
  124. }
  125. $result = $this->getResult();
  126. if ( count( $parameters ) ) {
  127. $userQuery = User::getQueryInfo();
  128. $this->addTables( $userQuery['tables'] );
  129. $this->addFields( $userQuery['fields'] );
  130. $this->addJoinConds( $userQuery['joins'] );
  131. if ( $useNames ) {
  132. $this->addWhereFld( 'user_name', $goodNames );
  133. } else {
  134. $this->addWhereFld( 'user_id', $userids );
  135. }
  136. $this->addBlockInfoToQuery( isset( $this->prop['blockinfo'] ) );
  137. $data = [];
  138. $res = $this->select( __METHOD__ );
  139. $this->resetQueryParams();
  140. // get user groups if needed
  141. if ( isset( $this->prop['groups'] ) || isset( $this->prop['rights'] ) ) {
  142. $userGroups = [];
  143. $this->addTables( 'user' );
  144. if ( $useNames ) {
  145. $this->addWhereFld( 'user_name', $goodNames );
  146. } else {
  147. $this->addWhereFld( 'user_id', $userids );
  148. }
  149. $this->addTables( 'user_groups' );
  150. $this->addJoinConds( [ 'user_groups' => [ 'JOIN', 'ug_user=user_id' ] ] );
  151. $this->addFields( [ 'user_name' ] );
  152. $this->addFields( UserGroupMembership::selectFields() );
  153. $this->addWhere( 'ug_expiry IS NULL OR ug_expiry >= ' .
  154. $db->addQuotes( $db->timestamp() ) );
  155. $userGroupsRes = $this->select( __METHOD__ );
  156. foreach ( $userGroupsRes as $row ) {
  157. $userGroups[$row->user_name][] = $row;
  158. }
  159. }
  160. foreach ( $res as $row ) {
  161. // create user object and pass along $userGroups if set
  162. // that reduces the number of database queries needed in User dramatically
  163. if ( !isset( $userGroups ) ) {
  164. $user = User::newFromRow( $row );
  165. } else {
  166. if ( !isset( $userGroups[$row->user_name] ) || !is_array( $userGroups[$row->user_name] ) ) {
  167. $userGroups[$row->user_name] = [];
  168. }
  169. $user = User::newFromRow( $row, [ 'user_groups' => $userGroups[$row->user_name] ] );
  170. }
  171. if ( $useNames ) {
  172. $key = $user->getName();
  173. } else {
  174. $key = $user->getId();
  175. }
  176. $data[$key]['userid'] = $user->getId();
  177. $data[$key]['name'] = $user->getName();
  178. if ( isset( $this->prop['editcount'] ) ) {
  179. $data[$key]['editcount'] = $user->getEditCount();
  180. }
  181. if ( isset( $this->prop['registration'] ) ) {
  182. $data[$key]['registration'] = wfTimestampOrNull( TS_ISO_8601, $user->getRegistration() );
  183. }
  184. if ( isset( $this->prop['groups'] ) ) {
  185. $data[$key]['groups'] = $user->getEffectiveGroups();
  186. }
  187. if ( isset( $this->prop['groupmemberships'] ) ) {
  188. $data[$key]['groupmemberships'] = array_map( function ( $ugm ) {
  189. return [
  190. 'group' => $ugm->getGroup(),
  191. 'expiry' => ApiResult::formatExpiry( $ugm->getExpiry() ),
  192. ];
  193. }, $user->getGroupMemberships() );
  194. }
  195. if ( isset( $this->prop['implicitgroups'] ) ) {
  196. $data[$key]['implicitgroups'] = $user->getAutomaticGroups();
  197. }
  198. if ( isset( $this->prop['rights'] ) ) {
  199. $data[$key]['rights'] = $this->getPermissionManager()
  200. ->getUserPermissions( $user );
  201. }
  202. if ( $row->ipb_deleted ) {
  203. $data[$key]['hidden'] = true;
  204. }
  205. if ( isset( $this->prop['blockinfo'] ) && !is_null( $row->ipb_by_text ) ) {
  206. $data[$key] += $this->getBlockDetails( DatabaseBlock::newFromRow( $row ) );
  207. }
  208. if ( isset( $this->prop['emailable'] ) ) {
  209. $data[$key]['emailable'] = $user->canReceiveEmail();
  210. }
  211. if ( isset( $this->prop['gender'] ) ) {
  212. $gender = $user->getOption( 'gender' );
  213. if ( strval( $gender ) === '' ) {
  214. $gender = 'unknown';
  215. }
  216. $data[$key]['gender'] = $gender;
  217. }
  218. if ( isset( $this->prop['centralids'] ) ) {
  219. $data[$key] += ApiQueryUserInfo::getCentralUserInfo(
  220. $this->getConfig(), $user, $params['attachedwiki']
  221. );
  222. }
  223. if ( !is_null( $params['token'] ) ) {
  224. $tokenFunctions = $this->getTokenFunctions();
  225. foreach ( $params['token'] as $t ) {
  226. $val = call_user_func( $tokenFunctions[$t], $user );
  227. if ( $val === false ) {
  228. $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
  229. } else {
  230. $data[$key][$t . 'token'] = $val;
  231. }
  232. }
  233. }
  234. }
  235. }
  236. $context = $this->getContext();
  237. // Second pass: add result data to $retval
  238. foreach ( $parameters as $u ) {
  239. if ( !isset( $data[$u] ) ) {
  240. if ( $useNames ) {
  241. $data[$u] = [ 'name' => $u ];
  242. $urPage = new UserrightsPage;
  243. $urPage->setContext( $context );
  244. $iwUser = $urPage->fetchUser( $u );
  245. if ( $iwUser instanceof UserRightsProxy ) {
  246. $data[$u]['interwiki'] = true;
  247. if ( !is_null( $params['token'] ) ) {
  248. $tokenFunctions = $this->getTokenFunctions();
  249. foreach ( $params['token'] as $t ) {
  250. $val = call_user_func( $tokenFunctions[$t], $iwUser );
  251. if ( $val === false ) {
  252. $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
  253. } else {
  254. $data[$u][$t . 'token'] = $val;
  255. }
  256. }
  257. }
  258. } else {
  259. $data[$u]['missing'] = true;
  260. if ( isset( $this->prop['cancreate'] ) ) {
  261. $status = MediaWiki\Auth\AuthManager::singleton()->canCreateAccount( $u );
  262. $data[$u]['cancreate'] = $status->isGood();
  263. if ( !$status->isGood() ) {
  264. $data[$u]['cancreateerror'] = $this->getErrorFormatter()->arrayFromStatus( $status );
  265. }
  266. }
  267. }
  268. } else {
  269. $data[$u] = [ 'userid' => $u, 'missing' => true ];
  270. }
  271. } else {
  272. if ( isset( $this->prop['groups'] ) && isset( $data[$u]['groups'] ) ) {
  273. ApiResult::setArrayType( $data[$u]['groups'], 'array' );
  274. ApiResult::setIndexedTagName( $data[$u]['groups'], 'g' );
  275. }
  276. if ( isset( $this->prop['groupmemberships'] ) && isset( $data[$u]['groupmemberships'] ) ) {
  277. ApiResult::setArrayType( $data[$u]['groupmemberships'], 'array' );
  278. ApiResult::setIndexedTagName( $data[$u]['groupmemberships'], 'groupmembership' );
  279. }
  280. if ( isset( $this->prop['implicitgroups'] ) && isset( $data[$u]['implicitgroups'] ) ) {
  281. ApiResult::setArrayType( $data[$u]['implicitgroups'], 'array' );
  282. ApiResult::setIndexedTagName( $data[$u]['implicitgroups'], 'g' );
  283. }
  284. if ( isset( $this->prop['rights'] ) && isset( $data[$u]['rights'] ) ) {
  285. ApiResult::setArrayType( $data[$u]['rights'], 'array' );
  286. ApiResult::setIndexedTagName( $data[$u]['rights'], 'r' );
  287. }
  288. }
  289. // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
  290. $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data[$u] );
  291. if ( !$fit ) {
  292. if ( $useNames ) {
  293. $this->setContinueEnumParameter( 'users',
  294. implode( '|', array_diff( $users, $done ) ) );
  295. } else {
  296. $this->setContinueEnumParameter( 'userids',
  297. implode( '|', array_diff( $userids, $done ) ) );
  298. }
  299. break;
  300. }
  301. $done[] = $u;
  302. }
  303. $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'user' );
  304. }
  305. public function getCacheMode( $params ) {
  306. if ( isset( $params['token'] ) ) {
  307. return 'private';
  308. } elseif ( array_diff( (array)$params['prop'], static::$publicProps ) ) {
  309. return 'anon-public-user-private';
  310. } else {
  311. return 'public';
  312. }
  313. }
  314. public function getAllowedParams() {
  315. return [
  316. 'prop' => [
  317. ApiBase::PARAM_ISMULTI => true,
  318. ApiBase::PARAM_TYPE => [
  319. 'blockinfo',
  320. 'groups',
  321. 'groupmemberships',
  322. 'implicitgroups',
  323. 'rights',
  324. 'editcount',
  325. 'registration',
  326. 'emailable',
  327. 'gender',
  328. 'centralids',
  329. 'cancreate',
  330. // When adding a prop, consider whether it should be added
  331. // to self::$publicProps
  332. ],
  333. ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
  334. ],
  335. 'attachedwiki' => null,
  336. 'users' => [
  337. ApiBase::PARAM_ISMULTI => true
  338. ],
  339. 'userids' => [
  340. ApiBase::PARAM_ISMULTI => true,
  341. ApiBase::PARAM_TYPE => 'integer'
  342. ],
  343. 'token' => [
  344. ApiBase::PARAM_DEPRECATED => true,
  345. ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
  346. ApiBase::PARAM_ISMULTI => true
  347. ],
  348. ];
  349. }
  350. protected function getExamplesMessages() {
  351. return [
  352. 'action=query&list=users&ususers=Example&usprop=groups|editcount|gender'
  353. => 'apihelp-query+users-example-simple',
  354. ];
  355. }
  356. public function getHelpUrls() {
  357. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Users';
  358. }
  359. }