1<?php
2/**
3 * Query the list of contributors to a page
4 *
5 * Copyright © 2013 Wikimedia Foundation and contributors
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @since 1.23
24 */
25
26use MediaWiki\Permissions\GroupPermissionsLookup;
27use MediaWiki\Revision\RevisionRecord;
28use MediaWiki\Revision\RevisionStore;
29use MediaWiki\User\UserGroupManager;
30
31/**
32 * A query module to show contributors to a page
33 *
34 * @ingroup API
35 * @since 1.23
36 */
37class ApiQueryContributors extends ApiQueryBase {
38	/** We don't want to process too many pages at once (it hits cold
39	 * database pages too heavily), so only do the first MAX_PAGES input pages
40	 * in each API call (leaving the rest for continuation).
41	 */
42	private const MAX_PAGES = 100;
43
44	/** @var RevisionStore */
45	private $revisionStore;
46
47	/** @var ActorMigration */
48	private $actorMigration;
49
50	/** @var UserGroupManager */
51	private $userGroupManager;
52
53	/** @var GroupPermissionsLookup */
54	private $groupPermissionsLookup;
55
56	/**
57	 * @param ApiQuery $query
58	 * @param string $moduleName
59	 * @param RevisionStore $revisionStore
60	 * @param ActorMigration $actorMigration
61	 * @param UserGroupManager $userGroupManager
62	 * @param GroupPermissionsLookup $groupPermissionsLookup
63	 */
64	public function __construct(
65		ApiQuery $query,
66		$moduleName,
67		RevisionStore $revisionStore,
68		ActorMigration $actorMigration,
69		UserGroupManager $userGroupManager,
70		GroupPermissionsLookup $groupPermissionsLookup
71	) {
72		// "pc" is short for "page contributors", "co" was already taken by the
73		// GeoData extension's prop=coordinates.
74		parent::__construct( $query, $moduleName, 'pc' );
75		$this->revisionStore = $revisionStore;
76		$this->actorMigration = $actorMigration;
77		$this->userGroupManager = $userGroupManager;
78		$this->groupPermissionsLookup = $groupPermissionsLookup;
79	}
80
81	public function execute() {
82		global $wgActorTableSchemaMigrationStage;
83
84		$db = $this->getDB();
85		$params = $this->extractRequestParams();
86		$this->requireMaxOneParameter( $params, 'group', 'excludegroup', 'rights', 'excluderights' );
87
88		// Only operate on existing pages
89		$pages = array_keys( $this->getPageSet()->getGoodTitles() );
90
91		// Filter out already-processed pages
92		if ( $params['continue'] !== null ) {
93			$cont = explode( '|', $params['continue'] );
94			$this->dieContinueUsageIf( count( $cont ) != 2 );
95			$cont_page = (int)$cont[0];
96			$pages = array_filter( $pages, static function ( $v ) use ( $cont_page ) {
97				return $v >= $cont_page;
98			} );
99		}
100		if ( $pages === [] ) {
101			// Nothing to do
102			return;
103		}
104
105		// Apply MAX_PAGES, leaving any over the limit for a continue.
106		sort( $pages );
107		$continuePages = null;
108		if ( count( $pages ) > self::MAX_PAGES ) {
109			$continuePages = $pages[self::MAX_PAGES] . '|0';
110			$pages = array_slice( $pages, 0, self::MAX_PAGES );
111		}
112
113		$result = $this->getResult();
114		$revQuery = $this->revisionStore->getQueryInfo();
115
116		// For SCHEMA_COMPAT_READ_TEMP, target indexes on the
117		// revision_actor_temp table, otherwise on the revision table.
118		$pageField = ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_TEMP )
119			? 'revactor_page' : 'rev_page';
120		$idField = ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_TEMP )
121			? 'revactor_actor' : 'rev_actor';
122		$countField = ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_TEMP )
123			? 'revactor_actor' : 'rev_actor';
124
125		// First, count anons
126		$this->addTables( $revQuery['tables'] );
127		$this->addJoinConds( $revQuery['joins'] );
128		$this->addFields( [
129			'page' => $pageField,
130			'anons' => "COUNT(DISTINCT $countField)",
131		] );
132		$this->addWhereFld( $pageField, $pages );
133		$this->addWhere( $this->actorMigration->isAnon( $revQuery['fields']['rev_user'] ) );
134		$this->addWhere( $db->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0' );
135		$this->addOption( 'GROUP BY', $pageField );
136		$res = $this->select( __METHOD__ );
137		foreach ( $res as $row ) {
138			$fit = $result->addValue( [ 'query', 'pages', $row->page ],
139				'anoncontributors', (int)$row->anons
140			);
141			if ( !$fit ) {
142				// This not fitting isn't reasonable, so it probably means that
143				// some other module used up all the space. Just set a dummy
144				// continue and hope it works next time.
145				$this->setContinueEnumParameter( 'continue',
146					$params['continue'] ?? '0|0'
147				);
148
149				return;
150			}
151		}
152
153		// Next, add logged-in users
154		$this->resetQueryParams();
155		$this->addTables( $revQuery['tables'] );
156		$this->addJoinConds( $revQuery['joins'] );
157		$this->addFields( [
158			'page' => $pageField,
159			'id' => $idField,
160			// Non-MySQL databases don't like partial group-by
161			'userid' => 'MAX(' . $revQuery['fields']['rev_user'] . ')',
162			'username' => 'MAX(' . $revQuery['fields']['rev_user_text'] . ')',
163		] );
164		$this->addWhereFld( $pageField, $pages );
165		$this->addWhere( $this->actorMigration->isNotAnon( $revQuery['fields']['rev_user'] ) );
166		$this->addWhere( $db->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0' );
167		$this->addOption( 'GROUP BY', [ $pageField, $idField ] );
168		$this->addOption( 'LIMIT', $params['limit'] + 1 );
169
170		// Force a sort order to ensure that properties are grouped by page
171		// But only if rev_page is not constant in the WHERE clause.
172		if ( count( $pages ) > 1 ) {
173			$this->addOption( 'ORDER BY', [ 'page', 'id' ] );
174		} else {
175			$this->addOption( 'ORDER BY', 'id' );
176		}
177
178		$limitGroups = [];
179		if ( $params['group'] ) {
180			$excludeGroups = false;
181			$limitGroups = $params['group'];
182		} elseif ( $params['excludegroup'] ) {
183			$excludeGroups = true;
184			$limitGroups = $params['excludegroup'];
185		} elseif ( $params['rights'] ) {
186			$excludeGroups = false;
187			foreach ( $params['rights'] as $r ) {
188				$limitGroups = array_merge( $limitGroups,
189					$this->groupPermissionsLookup->getGroupsWithPermission( $r ) );
190			}
191
192			// If no group has the rights requested, no need to query
193			if ( !$limitGroups ) {
194				if ( $continuePages !== null ) {
195					// But we still need to continue for the next page's worth
196					// of anoncontributors
197					$this->setContinueEnumParameter( 'continue', $continuePages );
198				}
199
200				return;
201			}
202		} elseif ( $params['excluderights'] ) {
203			$excludeGroups = true;
204			foreach ( $params['excluderights'] as $r ) {
205				$limitGroups = array_merge( $limitGroups,
206					$this->groupPermissionsLookup->getGroupsWithPermission( $r ) );
207			}
208		}
209
210		if ( $limitGroups ) {
211			$limitGroups = array_unique( $limitGroups );
212			$this->addTables( 'user_groups' );
213			$this->addJoinConds( [ 'user_groups' => [
214				$excludeGroups ? 'LEFT JOIN' : 'JOIN',
215				[
216					'ug_user=' . $revQuery['fields']['rev_user'],
217					'ug_group' => $limitGroups,
218					'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
219				]
220			] ] );
221			$this->addWhereIf( 'ug_user IS NULL', $excludeGroups );
222		}
223
224		if ( $params['continue'] !== null ) {
225			$cont = explode( '|', $params['continue'] );
226			$this->dieContinueUsageIf( count( $cont ) != 2 );
227			$cont_page = (int)$cont[0];
228			$cont_id = (int)$cont[1];
229			$this->addWhere(
230				"$pageField > $cont_page OR " .
231				"($pageField = $cont_page AND " .
232				"$idField >= $cont_id)"
233			);
234		}
235
236		$res = $this->select( __METHOD__ );
237		$count = 0;
238		foreach ( $res as $row ) {
239			if ( ++$count > $params['limit'] ) {
240				// We've reached the one extra which shows that
241				// there are additional pages to be had. Stop here...
242				$this->setContinueEnumParameter( 'continue', $row->page . '|' . $row->id );
243				return;
244			}
245
246			$fit = $this->addPageSubItem( $row->page,
247				[ 'userid' => (int)$row->userid, 'name' => $row->username ],
248				'user'
249			);
250			if ( !$fit ) {
251				$this->setContinueEnumParameter( 'continue', $row->page . '|' . $row->id );
252				return;
253			}
254		}
255
256		if ( $continuePages !== null ) {
257			$this->setContinueEnumParameter( 'continue', $continuePages );
258		}
259	}
260
261	public function getCacheMode( $params ) {
262		return 'public';
263	}
264
265	public function getAllowedParams( $flags = 0 ) {
266		$userGroups = $this->userGroupManager->listAllGroups();
267		$userRights = $this->getPermissionManager()->getAllPermissions();
268
269		if ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
270			sort( $userGroups );
271		}
272
273		return [
274			'group' => [
275				ApiBase::PARAM_TYPE => $userGroups,
276				ApiBase::PARAM_ISMULTI => true,
277			],
278			'excludegroup' => [
279				ApiBase::PARAM_TYPE => $userGroups,
280				ApiBase::PARAM_ISMULTI => true,
281			],
282			'rights' => [
283				ApiBase::PARAM_TYPE => $userRights,
284				ApiBase::PARAM_ISMULTI => true,
285			],
286			'excluderights' => [
287				ApiBase::PARAM_TYPE => $userRights,
288				ApiBase::PARAM_ISMULTI => true,
289			],
290			'limit' => [
291				ApiBase::PARAM_DFLT => 10,
292				ApiBase::PARAM_TYPE => 'limit',
293				ApiBase::PARAM_MIN => 1,
294				ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
295				ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
296			],
297			'continue' => [
298				ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
299			],
300		];
301	}
302
303	protected function getExamplesMessages() {
304		return [
305			'action=query&prop=contributors&titles=Main_Page'
306				=> 'apihelp-query+contributors-example-simple',
307		];
308	}
309
310	public function getHelpUrls() {
311		return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Contributors';
312	}
313}
314