ApiQueryAllUsers.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. <?php
  2. /**
  3. * Copyright © 2007 Yuri Astrakhan "<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 enumerate all registered users.
  25. *
  26. * @ingroup API
  27. */
  28. class ApiQueryAllUsers extends ApiQueryBase {
  29. use ApiQueryBlockInfoTrait;
  30. public function __construct( ApiQuery $query, $moduleName ) {
  31. parent::__construct( $query, $moduleName, 'au' );
  32. }
  33. /**
  34. * This function converts the user name to a canonical form
  35. * which is stored in the database.
  36. * @param string $name
  37. * @return string
  38. */
  39. private function getCanonicalUserName( $name ) {
  40. return strtr( $name, '_', ' ' );
  41. }
  42. public function execute() {
  43. $params = $this->extractRequestParams();
  44. $activeUserDays = $this->getConfig()->get( 'ActiveUserDays' );
  45. $db = $this->getDB();
  46. $commentStore = CommentStore::getStore();
  47. $prop = $params['prop'];
  48. if ( !is_null( $prop ) ) {
  49. $prop = array_flip( $prop );
  50. $fld_blockinfo = isset( $prop['blockinfo'] );
  51. $fld_editcount = isset( $prop['editcount'] );
  52. $fld_groups = isset( $prop['groups'] );
  53. $fld_rights = isset( $prop['rights'] );
  54. $fld_registration = isset( $prop['registration'] );
  55. $fld_implicitgroups = isset( $prop['implicitgroups'] );
  56. $fld_centralids = isset( $prop['centralids'] );
  57. } else {
  58. $fld_blockinfo = $fld_editcount = $fld_groups = $fld_registration =
  59. $fld_rights = $fld_implicitgroups = $fld_centralids = false;
  60. }
  61. $limit = $params['limit'];
  62. $this->addTables( 'user' );
  63. $dir = ( $params['dir'] == 'descending' ? 'older' : 'newer' );
  64. $from = is_null( $params['from'] ) ? null : $this->getCanonicalUserName( $params['from'] );
  65. $to = is_null( $params['to'] ) ? null : $this->getCanonicalUserName( $params['to'] );
  66. # MySQL can't figure out that 'user_name' and 'qcc_title' are the same
  67. # despite the JOIN condition, so manually sort on the correct one.
  68. $userFieldToSort = $params['activeusers'] ? 'qcc_title' : 'user_name';
  69. # Some of these subtable joins are going to give us duplicate rows, so
  70. # calculate the maximum number of duplicates we might see.
  71. $maxDuplicateRows = 1;
  72. $this->addWhereRange( $userFieldToSort, $dir, $from, $to );
  73. if ( !is_null( $params['prefix'] ) ) {
  74. $this->addWhere( $userFieldToSort .
  75. $db->buildLike( $this->getCanonicalUserName( $params['prefix'] ), $db->anyString() ) );
  76. }
  77. if ( !is_null( $params['rights'] ) && count( $params['rights'] ) ) {
  78. $groups = [];
  79. foreach ( $params['rights'] as $r ) {
  80. $groups = array_merge( $groups, $this->getPermissionManager()
  81. ->getGroupsWithPermission( $r ) );
  82. }
  83. // no group with the given right(s) exists, no need for a query
  84. if ( $groups === [] ) {
  85. $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], '' );
  86. return;
  87. }
  88. $groups = array_unique( $groups );
  89. if ( is_null( $params['group'] ) ) {
  90. $params['group'] = $groups;
  91. } else {
  92. $params['group'] = array_unique( array_merge( $params['group'], $groups ) );
  93. }
  94. }
  95. $this->requireMaxOneParameter( $params, 'group', 'excludegroup' );
  96. if ( !is_null( $params['group'] ) && count( $params['group'] ) ) {
  97. // Filter only users that belong to a given group. This might
  98. // produce as many rows-per-user as there are groups being checked.
  99. $this->addTables( 'user_groups', 'ug1' );
  100. $this->addJoinConds( [
  101. 'ug1' => [
  102. 'JOIN',
  103. [
  104. 'ug1.ug_user=user_id',
  105. 'ug1.ug_group' => $params['group'],
  106. 'ug1.ug_expiry IS NULL OR ug1.ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
  107. ]
  108. ]
  109. ] );
  110. $maxDuplicateRows *= count( $params['group'] );
  111. }
  112. if ( !is_null( $params['excludegroup'] ) && count( $params['excludegroup'] ) ) {
  113. // Filter only users don't belong to a given group. This can only
  114. // produce one row-per-user, because we only keep on "no match".
  115. $this->addTables( 'user_groups', 'ug1' );
  116. if ( count( $params['excludegroup'] ) == 1 ) {
  117. $exclude = [ 'ug1.ug_group' => $params['excludegroup'][0] ];
  118. } else {
  119. $exclude = [ $db->makeList(
  120. [ 'ug1.ug_group' => $params['excludegroup'] ],
  121. LIST_OR
  122. ) ];
  123. }
  124. $this->addJoinConds( [ 'ug1' => [ 'LEFT JOIN',
  125. array_merge( [
  126. 'ug1.ug_user=user_id',
  127. 'ug1.ug_expiry IS NULL OR ug1.ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
  128. ], $exclude )
  129. ] ] );
  130. $this->addWhere( 'ug1.ug_user IS NULL' );
  131. }
  132. if ( $params['witheditsonly'] ) {
  133. $this->addWhere( 'user_editcount > 0' );
  134. }
  135. $this->addBlockInfoToQuery( $fld_blockinfo );
  136. if ( $fld_groups || $fld_rights ) {
  137. $this->addFields( [ 'groups' =>
  138. $db->buildGroupConcatField( '|', 'user_groups', 'ug_group', [
  139. 'ug_user=user_id',
  140. 'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
  141. ] )
  142. ] );
  143. }
  144. if ( $params['activeusers'] ) {
  145. $activeUserSeconds = $activeUserDays * 86400;
  146. // Filter query to only include users in the active users cache.
  147. // There shouldn't be any duplicate rows in querycachetwo here.
  148. $this->addTables( 'querycachetwo' );
  149. $this->addJoinConds( [ 'querycachetwo' => [
  150. 'JOIN', [
  151. 'qcc_type' => 'activeusers',
  152. 'qcc_namespace' => NS_USER,
  153. 'qcc_title=user_name',
  154. ],
  155. ] ] );
  156. // Actually count the actions using a subquery (T66505 and T66507)
  157. $tables = [ 'recentchanges', 'actor' ];
  158. $joins = [
  159. 'actor' => [ 'JOIN', 'rc_actor = actor_id' ],
  160. ];
  161. $timestamp = $db->timestamp( wfTimestamp( TS_UNIX ) - $activeUserSeconds );
  162. $this->addFields( [
  163. 'recentactions' => '(' . $db->selectSQLText(
  164. $tables,
  165. 'COUNT(*)',
  166. [
  167. 'actor_user = user_id',
  168. 'rc_type != ' . $db->addQuotes( RC_EXTERNAL ), // no wikidata
  169. 'rc_log_type IS NULL OR rc_log_type != ' . $db->addQuotes( 'newusers' ),
  170. 'rc_timestamp >= ' . $db->addQuotes( $timestamp ),
  171. ],
  172. __METHOD__,
  173. [],
  174. $joins
  175. ) . ')'
  176. ] );
  177. }
  178. $sqlLimit = $limit + $maxDuplicateRows;
  179. $this->addOption( 'LIMIT', $sqlLimit );
  180. $this->addFields( [
  181. 'user_name',
  182. 'user_id'
  183. ] );
  184. $this->addFieldsIf( 'user_editcount', $fld_editcount );
  185. $this->addFieldsIf( 'user_registration', $fld_registration );
  186. $res = $this->select( __METHOD__ );
  187. $count = 0;
  188. $countDuplicates = 0;
  189. $lastUser = false;
  190. $result = $this->getResult();
  191. foreach ( $res as $row ) {
  192. $count++;
  193. if ( $lastUser === $row->user_name ) {
  194. // Duplicate row due to one of the needed subtable joins.
  195. // Ignore it, but count the number of them to sanely handle
  196. // miscalculation of $maxDuplicateRows.
  197. $countDuplicates++;
  198. if ( $countDuplicates == $maxDuplicateRows ) {
  199. ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
  200. }
  201. continue;
  202. }
  203. $countDuplicates = 0;
  204. $lastUser = $row->user_name;
  205. if ( $count > $limit ) {
  206. // We've reached the one extra which shows that there are
  207. // additional pages to be had. Stop here...
  208. $this->setContinueEnumParameter( 'from', $row->user_name );
  209. break;
  210. }
  211. if ( $count == $sqlLimit ) {
  212. // Should never hit this (either the $countDuplicates check or
  213. // the $count > $limit check should hit first), but check it
  214. // anyway just in case.
  215. ApiBase::dieDebug( __METHOD__, 'Saw more duplicate rows than expected' );
  216. }
  217. if ( $params['activeusers'] && $row->recentactions === 0 ) {
  218. // activeusers cache was out of date
  219. continue;
  220. }
  221. $data = [
  222. 'userid' => (int)$row->user_id,
  223. 'name' => $row->user_name,
  224. ];
  225. if ( $fld_centralids ) {
  226. $data += ApiQueryUserInfo::getCentralUserInfo(
  227. $this->getConfig(), User::newFromId( $row->user_id ), $params['attachedwiki']
  228. );
  229. }
  230. if ( $fld_blockinfo && !is_null( $row->ipb_id ) ) {
  231. $data += $this->getBlockDetails( DatabaseBlock::newFromRow( $row ) );
  232. }
  233. if ( $row->ipb_deleted ) {
  234. $data['hidden'] = true;
  235. }
  236. if ( $fld_editcount ) {
  237. $data['editcount'] = (int)$row->user_editcount;
  238. }
  239. if ( $params['activeusers'] ) {
  240. $data['recentactions'] = (int)$row->recentactions;
  241. }
  242. if ( $fld_registration ) {
  243. $data['registration'] = $row->user_registration ?
  244. wfTimestamp( TS_ISO_8601, $row->user_registration ) : '';
  245. }
  246. if ( $fld_implicitgroups || $fld_groups || $fld_rights ) {
  247. $implicitGroups = User::newFromId( $row->user_id )->getAutomaticGroups();
  248. if ( isset( $row->groups ) && $row->groups !== '' ) {
  249. $groups = array_merge( $implicitGroups, explode( '|', $row->groups ) );
  250. } else {
  251. $groups = $implicitGroups;
  252. }
  253. if ( $fld_groups ) {
  254. $data['groups'] = $groups;
  255. ApiResult::setIndexedTagName( $data['groups'], 'g' );
  256. ApiResult::setArrayType( $data['groups'], 'array' );
  257. }
  258. if ( $fld_implicitgroups ) {
  259. $data['implicitgroups'] = $implicitGroups;
  260. ApiResult::setIndexedTagName( $data['implicitgroups'], 'g' );
  261. ApiResult::setArrayType( $data['implicitgroups'], 'array' );
  262. }
  263. if ( $fld_rights ) {
  264. $data['rights'] = $this->getPermissionManager()->getGroupPermissions( $groups );
  265. ApiResult::setIndexedTagName( $data['rights'], 'r' );
  266. ApiResult::setArrayType( $data['rights'], 'array' );
  267. }
  268. }
  269. $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $data );
  270. if ( !$fit ) {
  271. $this->setContinueEnumParameter( 'from', $data['name'] );
  272. break;
  273. }
  274. }
  275. $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'u' );
  276. }
  277. public function getCacheMode( $params ) {
  278. return 'anon-public-user-private';
  279. }
  280. public function getAllowedParams() {
  281. $userGroups = User::getAllGroups();
  282. return [
  283. 'from' => null,
  284. 'to' => null,
  285. 'prefix' => null,
  286. 'dir' => [
  287. ApiBase::PARAM_DFLT => 'ascending',
  288. ApiBase::PARAM_TYPE => [
  289. 'ascending',
  290. 'descending'
  291. ],
  292. ],
  293. 'group' => [
  294. ApiBase::PARAM_TYPE => $userGroups,
  295. ApiBase::PARAM_ISMULTI => true,
  296. ],
  297. 'excludegroup' => [
  298. ApiBase::PARAM_TYPE => $userGroups,
  299. ApiBase::PARAM_ISMULTI => true,
  300. ],
  301. 'rights' => [
  302. ApiBase::PARAM_TYPE => $this->getPermissionManager()->getAllPermissions(),
  303. ApiBase::PARAM_ISMULTI => true,
  304. ],
  305. 'prop' => [
  306. ApiBase::PARAM_ISMULTI => true,
  307. ApiBase::PARAM_TYPE => [
  308. 'blockinfo',
  309. 'groups',
  310. 'implicitgroups',
  311. 'rights',
  312. 'editcount',
  313. 'registration',
  314. 'centralids',
  315. ],
  316. ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
  317. ],
  318. 'limit' => [
  319. ApiBase::PARAM_DFLT => 10,
  320. ApiBase::PARAM_TYPE => 'limit',
  321. ApiBase::PARAM_MIN => 1,
  322. ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
  323. ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
  324. ],
  325. 'witheditsonly' => false,
  326. 'activeusers' => [
  327. ApiBase::PARAM_DFLT => false,
  328. ApiBase::PARAM_HELP_MSG => [
  329. 'apihelp-query+allusers-param-activeusers',
  330. $this->getConfig()->get( 'ActiveUserDays' )
  331. ],
  332. ],
  333. 'attachedwiki' => null,
  334. ];
  335. }
  336. protected function getExamplesMessages() {
  337. return [
  338. 'action=query&list=allusers&aufrom=Y'
  339. => 'apihelp-query+allusers-example-y',
  340. ];
  341. }
  342. public function getHelpUrls() {
  343. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allusers';
  344. }
  345. }