ApiQueryAllUsers.php 12 KB

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