3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Revision\RevisionRecord
;
25 use MediaWiki\Storage\NameTableAccessException
;
28 * This query action adds a list of a specified user's contributions to the output.
32 class ApiQueryUserContribs
extends ApiQueryBase
{
34 public function __construct( ApiQuery
$query, $moduleName ) {
35 parent
::__construct( $query, $moduleName, 'uc' );
38 private $params, $multiUserMode, $orderBy, $parentLens, $commentStore;
40 private $fld_ids = false, $fld_title = false, $fld_timestamp = false,
41 $fld_comment = false, $fld_parsedcomment = false, $fld_flags = false,
42 $fld_patrolled = false, $fld_tags = false, $fld_size = false, $fld_sizediff = false;
44 public function execute() {
45 // Parse some parameters
46 $this->params
= $this->extractRequestParams();
48 $this->commentStore
= CommentStore
::getStore();
50 $prop = array_flip( $this->params
['prop'] );
51 $this->fld_ids
= isset( $prop['ids'] );
52 $this->fld_title
= isset( $prop['title'] );
53 $this->fld_comment
= isset( $prop['comment'] );
54 $this->fld_parsedcomment
= isset( $prop['parsedcomment'] );
55 $this->fld_size
= isset( $prop['size'] );
56 $this->fld_sizediff
= isset( $prop['sizediff'] );
57 $this->fld_flags
= isset( $prop['flags'] );
58 $this->fld_timestamp
= isset( $prop['timestamp'] );
59 $this->fld_patrolled
= isset( $prop['patrolled'] );
60 $this->fld_tags
= isset( $prop['tags'] );
62 // The main query may use the 'contributions' group DB, which can map to replica DBs
63 // with extra user based indexes or partioning by user. The additional metadata
64 // queries should use a regular replica DB since the lookup pattern is not all by user.
65 $dbSecondary = $this->getDB(); // any random replica DB
67 $sort = ( $this->params
['dir'] == 'newer' ?
'' : ' DESC' );
68 $op = ( $this->params
['dir'] == 'older' ?
'<' : '>' );
70 // Create an Iterator that produces the UserIdentity objects we need, depending
71 // on which of the 'userprefix', 'userids', or 'user' params was
73 $this->requireOnlyOneParameter( $this->params
, 'userprefix', 'userids', 'user' );
74 if ( isset( $this->params
['userprefix'] ) ) {
75 $this->multiUserMode
= true;
76 $this->orderBy
= 'name';
79 // Because 'userprefix' might produce a huge number of users (e.g.
80 // a wiki with users "Test00000001" to "Test99999999"), use a
81 // generator with batched lookup and continuation.
82 $userIter = call_user_func( function () use ( $dbSecondary, $sort, $op, $fname ) {
84 if ( !is_null( $this->params
['continue'] ) ) {
85 $continue = explode( '|', $this->params
['continue'] );
86 $this->dieContinueUsageIf( count( $continue ) != 4 );
87 $this->dieContinueUsageIf( $continue[0] !== 'name' );
88 $fromName = $continue[1];
90 $like = $dbSecondary->buildLike( $this->params
['userprefix'], $dbSecondary->anyString() );
95 $from = $fromName ?
"$op= " . $dbSecondary->addQuotes( $fromName ) : false;
96 $res = $dbSecondary->select(
98 [ 'actor_id', 'user_id' => 'COALESCE(actor_user,0)', 'user_name' => 'actor_name' ],
99 array_merge( [ "actor_name$like" ], $from ?
[ "actor_name $from" ] : [] ),
101 [ 'ORDER BY' => [ "user_name $sort" ], 'LIMIT' => $limit ]
106 foreach ( $res as $row ) {
107 if ( ++
$count >= $limit ) {
108 $fromName = $row->user_name
;
111 yield User
::newFromRow( $row );
113 } while ( $fromName !== false );
115 // Do the actual sorting client-side, because otherwise
116 // prepareQuery might try to sort by actor and confuse everything.
118 } elseif ( isset( $this->params
['userids'] ) ) {
119 if ( $this->params
['userids'] === [] ) {
120 $encParamName = $this->encodeParamName( 'userids' );
121 $this->dieWithError( [ 'apierror-paramempty', $encParamName ], "paramempty_$encParamName" );
125 foreach ( $this->params
['userids'] as $uid ) {
127 $this->dieWithError( [ 'apierror-invaliduserid', $uid ], 'invaliduserid' );
132 $this->orderBy
= 'id';
133 $this->multiUserMode
= count( $ids ) > 1;
135 $from = $fromId = false;
136 if ( $this->multiUserMode
&& !is_null( $this->params
['continue'] ) ) {
137 $continue = explode( '|', $this->params
['continue'] );
138 $this->dieContinueUsageIf( count( $continue ) != 4 );
139 $this->dieContinueUsageIf( $continue[0] !== 'id' && $continue[0] !== 'actor' );
140 $fromId = (int)$continue[1];
141 $this->dieContinueUsageIf( $continue[1] !== (string)$fromId );
142 $from = "$op= $fromId";
145 $res = $dbSecondary->select(
147 [ 'actor_id', 'user_id' => 'actor_user', 'user_name' => 'actor_name' ],
148 array_merge( [ 'actor_user' => $ids ], $from ?
[ "actor_id $from" ] : [] ),
150 [ 'ORDER BY' => "user_id $sort" ]
152 $userIter = UserArray
::newFromResult( $res );
153 $batchSize = count( $ids );
156 if ( !count( $this->params
['user'] ) ) {
157 $encParamName = $this->encodeParamName( 'user' );
159 [ 'apierror-paramempty', $encParamName ], "paramempty_$encParamName"
162 foreach ( $this->params
['user'] as $u ) {
164 $encParamName = $this->encodeParamName( 'user' );
166 [ 'apierror-paramempty', $encParamName ], "paramempty_$encParamName"
170 if ( User
::isIP( $u ) || ExternalUserNames
::isExternal( $u ) ) {
173 $name = User
::getCanonicalName( $u, 'valid' );
174 if ( $name === false ) {
175 $encParamName = $this->encodeParamName( 'user' );
177 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $u ) ], "baduser_$encParamName"
180 $names[$name] = null;
184 $this->orderBy
= 'name';
185 $this->multiUserMode
= count( $names ) > 1;
187 $from = $fromName = false;
188 if ( $this->multiUserMode
&& !is_null( $this->params
['continue'] ) ) {
189 $continue = explode( '|', $this->params
['continue'] );
190 $this->dieContinueUsageIf( count( $continue ) != 4 );
191 $this->dieContinueUsageIf( $continue[0] !== 'name' && $continue[0] !== 'actor' );
192 $fromName = $continue[1];
193 $from = "$op= " . $dbSecondary->addQuotes( $fromName );
196 $res = $dbSecondary->select(
198 [ 'actor_id', 'user_id' => 'actor_user', 'user_name' => 'actor_name' ],
199 array_merge( [ 'actor_name' => array_keys( $names ) ], $from ?
[ "actor_id $from" ] : [] ),
201 [ 'ORDER BY' => "actor_name $sort" ]
203 $userIter = UserArray
::newFromResult( $res );
204 $batchSize = count( $names );
207 // The DB query will order by actor so update $this->orderBy to match.
208 if ( $batchSize > 1 ) {
209 $this->orderBy
= 'actor';
213 $limit = $this->params
['limit'];
215 while ( $userIter->valid() ) {
217 while ( count( $users ) < $batchSize && $userIter->valid() ) {
218 $users[] = $userIter->current();
223 $this->prepareQuery( $users, $limit - $count );
224 $res = $this->select( __METHOD__
, [], $hookData );
226 if ( $this->fld_sizediff
) {
228 foreach ( $res as $row ) {
229 if ( $row->rev_parent_id
) {
230 $revIds[] = $row->rev_parent_id
;
233 $this->parentLens
= MediaWikiServices
::getInstance()->getRevisionStore()
234 ->listRevisionSizes( $dbSecondary, $revIds );
237 foreach ( $res as $row ) {
238 if ( ++
$count > $limit ) {
239 // We've reached the one extra which shows that there are
240 // additional pages to be had. Stop here...
241 $this->setContinueEnumParameter( 'continue', $this->continueStr( $row ) );
245 $vals = $this->extractRowInfo( $row );
246 $fit = $this->processRow( $row, $vals, $hookData ) &&
247 $this->getResult()->addValue( [ 'query', $this->getModuleName() ], null, $vals );
249 $this->setContinueEnumParameter( 'continue', $this->continueStr( $row ) );
255 $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], 'item' );
259 * Prepares the query and returns the limit of rows requested
260 * @param User[] $users
263 private function prepareQuery( array $users, $limit ) {
264 $this->resetQueryParams();
265 $db = $this->getDB();
267 $revQuery = MediaWikiServices
::getInstance()->getRevisionStore()->getQueryInfo( [ 'page' ] );
269 $revWhere = ActorMigration
::newMigration()->getWhere( $db, 'rev_user', $users );
270 $orderUserField = 'rev_actor';
271 $userField = $this->orderBy
=== 'actor' ?
'revactor_actor' : 'actor_name';
272 $tsField = 'revactor_timestamp';
273 $idField = 'revactor_rev';
275 // T221511: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor`
276 // before `revision_actor_temp` and filesorting is somehow better than querying $limit+1 rows
277 // from `revision_actor_temp`. Tell it not to reorder the query (and also reorder it ourselves
278 // because as generated by RevisionStore it'll have `revision` first rather than
279 // `revision_actor_temp`). But not when uctag is used, as it seems as likely to be harmed as
280 // helped in that case, and not when there's only one User because in that case it fetches
281 // the one `actor` row as a constant and doesn't filesort.
282 if ( count( $users ) > 1 && !isset( $this->params
['tag'] ) ) {
283 $revQuery['joins']['revision'] = $revQuery['joins']['temp_rev_user'];
284 unset( $revQuery['joins']['temp_rev_user'] );
285 $this->addOption( 'STRAIGHT_JOIN' );
286 // It isn't actually necesssary to reorder $revQuery['tables'] as Database does the right thing
287 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
288 // `revision_actor_temp` to the start.
289 $revQuery['tables'] =
290 [ 'temp_rev_user' => $revQuery['tables']['temp_rev_user'] ] +
$revQuery['tables'];
293 $this->addTables( $revQuery['tables'] );
294 $this->addJoinConds( $revQuery['joins'] );
295 $this->addFields( $revQuery['fields'] );
296 $this->addWhere( $revWhere['conds'] );
298 // Handle continue parameter
299 if ( !is_null( $this->params
['continue'] ) ) {
300 $continue = explode( '|', $this->params
['continue'] );
301 if ( $this->multiUserMode
) {
302 $this->dieContinueUsageIf( count( $continue ) != 4 );
303 $modeFlag = array_shift( $continue );
304 $this->dieContinueUsageIf( $modeFlag !== $this->orderBy
);
305 $encUser = $db->addQuotes( array_shift( $continue ) );
307 $this->dieContinueUsageIf( count( $continue ) != 2 );
309 $encTS = $db->addQuotes( $db->timestamp( $continue[0] ) );
310 $encId = (int)$continue[1];
311 $this->dieContinueUsageIf( $encId != $continue[1] );
312 $op = ( $this->params
['dir'] == 'older' ?
'<' : '>' );
313 if ( $this->multiUserMode
) {
315 "$userField $op $encUser OR " .
316 "($userField = $encUser AND " .
317 "($tsField $op $encTS OR " .
318 "($tsField = $encTS AND " .
319 "$idField $op= $encId)))"
323 "$tsField $op $encTS OR " .
324 "($tsField = $encTS AND " .
325 "$idField $op= $encId)"
330 // Don't include any revisions where we're not supposed to be able to
332 $user = $this->getUser();
333 if ( !$this->getPermissionManager()->userHasRight( $user, 'deletedhistory' ) ) {
334 $bitmask = RevisionRecord
::DELETED_USER
;
335 } elseif ( !$this->getPermissionManager()
336 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
338 $bitmask = RevisionRecord
::DELETED_USER | RevisionRecord
::DELETED_RESTRICTED
;
343 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
346 // Add the user field to ORDER BY if there are multiple users
347 if ( count( $users ) > 1 ) {
348 $this->addWhereRange( $orderUserField, $this->params
['dir'], null, null );
352 $this->addTimestampWhereRange( $tsField,
353 $this->params
['dir'], $this->params
['start'], $this->params
['end'] );
355 // Then rev_id for a total ordering
356 $this->addWhereRange( $idField, $this->params
['dir'], null, null );
358 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
360 $show = $this->params
['show'];
361 if ( $this->params
['toponly'] ) { // deprecated/old param
364 if ( !is_null( $show ) ) {
365 $show = array_flip( $show );
367 if ( ( isset( $show['minor'] ) && isset( $show['!minor'] ) )
368 ||
( isset( $show['patrolled'] ) && isset( $show['!patrolled'] ) )
369 ||
( isset( $show['autopatrolled'] ) && isset( $show['!autopatrolled'] ) )
370 ||
( isset( $show['autopatrolled'] ) && isset( $show['!patrolled'] ) )
371 ||
( isset( $show['top'] ) && isset( $show['!top'] ) )
372 ||
( isset( $show['new'] ) && isset( $show['!new'] ) )
374 $this->dieWithError( 'apierror-show' );
377 $this->addWhereIf( 'rev_minor_edit = 0', isset( $show['!minor'] ) );
378 $this->addWhereIf( 'rev_minor_edit != 0', isset( $show['minor'] ) );
380 'rc_patrolled = ' . RecentChange
::PRC_UNPATROLLED
,
381 isset( $show['!patrolled'] )
384 'rc_patrolled != ' . RecentChange
::PRC_UNPATROLLED
,
385 isset( $show['patrolled'] )
388 'rc_patrolled != ' . RecentChange
::PRC_AUTOPATROLLED
,
389 isset( $show['!autopatrolled'] )
392 'rc_patrolled = ' . RecentChange
::PRC_AUTOPATROLLED
,
393 isset( $show['autopatrolled'] )
395 $this->addWhereIf( $idField . ' != page_latest', isset( $show['!top'] ) );
396 $this->addWhereIf( $idField . ' = page_latest', isset( $show['top'] ) );
397 $this->addWhereIf( 'rev_parent_id != 0', isset( $show['!new'] ) );
398 $this->addWhereIf( 'rev_parent_id = 0', isset( $show['new'] ) );
400 $this->addOption( 'LIMIT', $limit +
1 );
402 if ( isset( $show['patrolled'] ) ||
isset( $show['!patrolled'] ) ||
403 isset( $show['autopatrolled'] ) ||
isset( $show['!autopatrolled'] ) ||
$this->fld_patrolled
405 if ( !$user->useRCPatrol() && !$user->useNPPatrol() ) {
406 $this->dieWithError( 'apierror-permissiondenied-patrolflag', 'permissiondenied' );
409 $isFilterset = isset( $show['patrolled'] ) ||
isset( $show['!patrolled'] ) ||
410 isset( $show['autopatrolled'] ) ||
isset( $show['!autopatrolled'] );
411 $this->addTables( 'recentchanges' );
412 $this->addJoinConds( [ 'recentchanges' => [
413 $isFilterset ?
'JOIN' : 'LEFT JOIN',
415 // This is a crazy hack. recentchanges has no index on rc_this_oldid, so instead of adding
416 // one T19237 did a join using rc_user_text and rc_timestamp instead. Now rc_user_text is
417 // probably unavailable, so just do rc_timestamp.
418 'rc_timestamp = ' . $tsField,
419 'rc_this_oldid = ' . $idField,
424 $this->addFieldsIf( 'rc_patrolled', $this->fld_patrolled
);
426 if ( $this->fld_tags
) {
427 $this->addFields( [ 'ts_tags' => ChangeTags
::makeTagSummarySubquery( 'revision' ) ] );
430 if ( isset( $this->params
['tag'] ) ) {
431 $this->addTables( 'change_tag' );
433 [ 'change_tag' => [ 'JOIN', [ $idField . ' = ct_rev_id' ] ] ]
435 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
437 $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $this->params
['tag'] ) );
438 } catch ( NameTableAccessException
$exception ) {
440 $this->addWhere( '1=0' );
446 * Extract fields from the database row and append them to a result array
448 * @param stdClass $row
451 private function extractRowInfo( $row ) {
455 if ( $row->rev_deleted
& RevisionRecord
::DELETED_TEXT
) {
456 $vals['texthidden'] = true;
460 // Any rows where we can't view the user were filtered out in the query.
461 $vals['userid'] = (int)$row->rev_user
;
462 $vals['user'] = $row->rev_user_text
;
463 if ( $row->rev_deleted
& RevisionRecord
::DELETED_USER
) {
464 $vals['userhidden'] = true;
467 if ( $this->fld_ids
) {
468 $vals['pageid'] = (int)$row->rev_page
;
469 $vals['revid'] = (int)$row->rev_id
;
471 if ( !is_null( $row->rev_parent_id
) ) {
472 $vals['parentid'] = (int)$row->rev_parent_id
;
476 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
478 if ( $this->fld_title
) {
479 ApiQueryBase
::addTitleInfo( $vals, $title );
482 if ( $this->fld_timestamp
) {
483 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $row->rev_timestamp
);
486 if ( $this->fld_flags
) {
487 $vals['new'] = $row->rev_parent_id
== 0 && !is_null( $row->rev_parent_id
);
488 $vals['minor'] = (bool)$row->rev_minor_edit
;
489 $vals['top'] = $row->page_latest
== $row->rev_id
;
492 if ( $this->fld_comment ||
$this->fld_parsedcomment
) {
493 if ( $row->rev_deleted
& RevisionRecord
::DELETED_COMMENT
) {
494 $vals['commenthidden'] = true;
498 $userCanView = RevisionRecord
::userCanBitfield(
500 RevisionRecord
::DELETED_COMMENT
, $this->getUser()
503 if ( $userCanView ) {
504 $comment = $this->commentStore
->getComment( 'rev_comment', $row )->text
;
505 if ( $this->fld_comment
) {
506 $vals['comment'] = $comment;
509 if ( $this->fld_parsedcomment
) {
510 $vals['parsedcomment'] = Linker
::formatComment( $comment, $title );
515 if ( $this->fld_patrolled
) {
516 $vals['patrolled'] = $row->rc_patrolled
!= RecentChange
::PRC_UNPATROLLED
;
517 $vals['autopatrolled'] = $row->rc_patrolled
== RecentChange
::PRC_AUTOPATROLLED
;
520 if ( $this->fld_size
&& !is_null( $row->rev_len
) ) {
521 $vals['size'] = (int)$row->rev_len
;
524 if ( $this->fld_sizediff
525 && !is_null( $row->rev_len
)
526 && !is_null( $row->rev_parent_id
)
528 $parentLen = $this->parentLens
[$row->rev_parent_id
] ??
0;
529 $vals['sizediff'] = (int)$row->rev_len
- $parentLen;
532 if ( $this->fld_tags
) {
533 if ( $row->ts_tags
) {
534 $tags = explode( ',', $row->ts_tags
);
535 ApiResult
::setIndexedTagName( $tags, 'tag' );
536 $vals['tags'] = $tags;
542 if ( $anyHidden && ( $row->rev_deleted
& RevisionRecord
::DELETED_RESTRICTED
) ) {
543 $vals['suppressed'] = true;
549 private function continueStr( $row ) {
550 if ( $this->multiUserMode
) {
551 switch ( $this->orderBy
) {
553 return "id|$row->rev_user|$row->rev_timestamp|$row->rev_id";
555 return "name|$row->rev_user_text|$row->rev_timestamp|$row->rev_id";
557 return "actor|$row->rev_actor|$row->rev_timestamp|$row->rev_id";
560 return "$row->rev_timestamp|$row->rev_id";
564 public function getCacheMode( $params ) {
565 // This module provides access to deleted revisions and patrol flags if
566 // the requester is logged in
567 return 'anon-public-user-private';
570 public function getAllowedParams() {
573 ApiBase
::PARAM_DFLT
=> 10,
574 ApiBase
::PARAM_TYPE
=> 'limit',
575 ApiBase
::PARAM_MIN
=> 1,
576 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
577 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
580 ApiBase
::PARAM_TYPE
=> 'timestamp'
583 ApiBase
::PARAM_TYPE
=> 'timestamp'
586 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
589 ApiBase
::PARAM_TYPE
=> 'user',
590 ApiBase
::PARAM_ISMULTI
=> true
593 ApiBase
::PARAM_TYPE
=> 'integer',
594 ApiBase
::PARAM_ISMULTI
=> true
596 'userprefix' => null,
598 ApiBase
::PARAM_DFLT
=> 'older',
599 ApiBase
::PARAM_TYPE
=> [
603 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-direction',
606 ApiBase
::PARAM_ISMULTI
=> true,
607 ApiBase
::PARAM_TYPE
=> 'namespace'
610 ApiBase
::PARAM_ISMULTI
=> true,
611 ApiBase
::PARAM_DFLT
=> 'ids|title|timestamp|comment|size|flags',
612 ApiBase
::PARAM_TYPE
=> [
624 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
627 ApiBase
::PARAM_ISMULTI
=> true,
628 ApiBase
::PARAM_TYPE
=> [
640 ApiBase
::PARAM_HELP_MSG
=> [
641 'apihelp-query+usercontribs-param-show',
642 $this->getConfig()->get( 'RCMaxAge' )
647 ApiBase
::PARAM_DFLT
=> false,
648 ApiBase
::PARAM_DEPRECATED
=> true,
653 protected function getExamplesMessages() {
655 'action=query&list=usercontribs&ucuser=Example'
656 => 'apihelp-query+usercontribs-example-user',
657 'action=query&list=usercontribs&ucuserprefix=192.0.2.'
658 => 'apihelp-query+usercontribs-example-ipprefix',
662 public function getHelpUrls() {
663 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Usercontribs';
669 * @deprecated since 1.32
671 class_alias( ApiQueryUserContribs
::class, 'ApiQueryContributions' );