MediaWiki  master
ApiQueryContributors.php
Go to the documentation of this file.
1 <?php
28 
40  const MAX_PAGES = 100;
41 
42  public function __construct( ApiQuery $query, $moduleName ) {
43  // "pc" is short for "page contributors", "co" was already taken by the
44  // GeoData extension's prop=coordinates.
45  parent::__construct( $query, $moduleName, 'pc' );
46  }
47 
48  public function execute() {
50 
51  $db = $this->getDB();
52  $params = $this->extractRequestParams();
53  $this->requireMaxOneParameter( $params, 'group', 'excludegroup', 'rights', 'excluderights' );
54 
55  // Only operate on existing pages
56  $pages = array_keys( $this->getPageSet()->getGoodTitles() );
57 
58  // Filter out already-processed pages
59  if ( $params['continue'] !== null ) {
60  $cont = explode( '|', $params['continue'] );
61  $this->dieContinueUsageIf( count( $cont ) != 2 );
62  $cont_page = (int)$cont[0];
63  $pages = array_filter( $pages, function ( $v ) use ( $cont_page ) {
64  return $v >= $cont_page;
65  } );
66  }
67  if ( $pages === [] ) {
68  // Nothing to do
69  return;
70  }
71 
72  // Apply MAX_PAGES, leaving any over the limit for a continue.
73  sort( $pages );
74  $continuePages = null;
75  if ( count( $pages ) > self::MAX_PAGES ) {
76  $continuePages = $pages[self::MAX_PAGES] . '|0';
77  $pages = array_slice( $pages, 0, self::MAX_PAGES );
78  }
79 
80  $result = $this->getResult();
81  $revQuery = MediaWikiServices::getInstance()->getRevisionStore()->getQueryInfo();
82 
83  // For SCHEMA_COMPAT_READ_NEW, target indexes on the
84  // revision_actor_temp table, otherwise on the revision table.
85  $pageField = ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW )
86  ? 'revactor_page' : 'rev_page';
87  $idField = ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW )
88  ? 'revactor_actor' : $revQuery['fields']['rev_user'];
89  $countField = ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW )
90  ? 'revactor_actor' : $revQuery['fields']['rev_user_text'];
91 
92  // First, count anons
93  $this->addTables( $revQuery['tables'] );
94  $this->addJoinConds( $revQuery['joins'] );
95  $this->addFields( [
96  'page' => $pageField,
97  'anons' => "COUNT(DISTINCT $countField)",
98  ] );
99  $this->addWhereFld( $pageField, $pages );
100  $this->addWhere( ActorMigration::newMigration()->isAnon( $revQuery['fields']['rev_user'] ) );
101  $this->addWhere( $db->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0' );
102  $this->addOption( 'GROUP BY', $pageField );
103  $res = $this->select( __METHOD__ );
104  foreach ( $res as $row ) {
105  $fit = $result->addValue( [ 'query', 'pages', $row->page ],
106  'anoncontributors', (int)$row->anons
107  );
108  if ( !$fit ) {
109  // This not fitting isn't reasonable, so it probably means that
110  // some other module used up all the space. Just set a dummy
111  // continue and hope it works next time.
112  $this->setContinueEnumParameter( 'continue',
113  $params['continue'] ?? '0|0'
114  );
115 
116  return;
117  }
118  }
119 
120  // Next, add logged-in users
121  $this->resetQueryParams();
122  $this->addTables( $revQuery['tables'] );
123  $this->addJoinConds( $revQuery['joins'] );
124  $this->addFields( [
125  'page' => $pageField,
126  'id' => $idField,
127  // Non-MySQL databases don't like partial group-by
128  'userid' => 'MAX(' . $revQuery['fields']['rev_user'] . ')',
129  'username' => 'MAX(' . $revQuery['fields']['rev_user_text'] . ')',
130  ] );
131  $this->addWhereFld( $pageField, $pages );
132  $this->addWhere( ActorMigration::newMigration()->isNotAnon( $revQuery['fields']['rev_user'] ) );
133  $this->addWhere( $db->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0' );
134  $this->addOption( 'GROUP BY', [ $pageField, $idField ] );
135  $this->addOption( 'LIMIT', $params['limit'] + 1 );
136 
137  // Force a sort order to ensure that properties are grouped by page
138  // But only if rev_page is not constant in the WHERE clause.
139  if ( count( $pages ) > 1 ) {
140  $this->addOption( 'ORDER BY', [ 'page', 'id' ] );
141  } else {
142  $this->addOption( 'ORDER BY', 'id' );
143  }
144 
145  $limitGroups = [];
146  if ( $params['group'] ) {
147  $excludeGroups = false;
148  $limitGroups = $params['group'];
149  } elseif ( $params['excludegroup'] ) {
150  $excludeGroups = true;
151  $limitGroups = $params['excludegroup'];
152  } elseif ( $params['rights'] ) {
153  $excludeGroups = false;
154  foreach ( $params['rights'] as $r ) {
155  $limitGroups = array_merge( $limitGroups, User::getGroupsWithPermission( $r ) );
156  }
157 
158  // If no group has the rights requested, no need to query
159  if ( !$limitGroups ) {
160  if ( $continuePages !== null ) {
161  // But we still need to continue for the next page's worth
162  // of anoncontributors
163  $this->setContinueEnumParameter( 'continue', $continuePages );
164  }
165 
166  return;
167  }
168  } elseif ( $params['excluderights'] ) {
169  $excludeGroups = true;
170  foreach ( $params['excluderights'] as $r ) {
171  $limitGroups = array_merge( $limitGroups, User::getGroupsWithPermission( $r ) );
172  }
173  }
174 
175  if ( $limitGroups ) {
176  $limitGroups = array_unique( $limitGroups );
177  $this->addTables( 'user_groups' );
178  $this->addJoinConds( [ 'user_groups' => [
179  $excludeGroups ? 'LEFT JOIN' : 'JOIN',
180  [
181  'ug_user=' . $revQuery['fields']['rev_user'],
182  'ug_group' => $limitGroups,
183  'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
184  ]
185  ] ] );
186  $this->addWhereIf( 'ug_user IS NULL', $excludeGroups );
187  }
188 
189  if ( $params['continue'] !== null ) {
190  $cont = explode( '|', $params['continue'] );
191  $this->dieContinueUsageIf( count( $cont ) != 2 );
192  $cont_page = (int)$cont[0];
193  $cont_id = (int)$cont[1];
194  $this->addWhere(
195  "$pageField > $cont_page OR " .
196  "($pageField = $cont_page AND " .
197  "$idField >= $cont_id)"
198  );
199  }
200 
201  $res = $this->select( __METHOD__ );
202  $count = 0;
203  foreach ( $res as $row ) {
204  if ( ++$count > $params['limit'] ) {
205  // We've reached the one extra which shows that
206  // there are additional pages to be had. Stop here...
207  $this->setContinueEnumParameter( 'continue', $row->page . '|' . $row->id );
208  return;
209  }
210 
211  $fit = $this->addPageSubItem( $row->page,
212  [ 'userid' => (int)$row->userid, 'name' => $row->username ],
213  'user'
214  );
215  if ( !$fit ) {
216  $this->setContinueEnumParameter( 'continue', $row->page . '|' . $row->id );
217  return;
218  }
219  }
220 
221  if ( $continuePages !== null ) {
222  $this->setContinueEnumParameter( 'continue', $continuePages );
223  }
224  }
225 
226  public function getCacheMode( $params ) {
227  return 'public';
228  }
229 
230  public function getAllowedParams() {
231  $userGroups = User::getAllGroups();
232  $userRights = User::getAllRights();
233 
234  return [
235  'group' => [
236  ApiBase::PARAM_TYPE => $userGroups,
237  ApiBase::PARAM_ISMULTI => true,
238  ],
239  'excludegroup' => [
240  ApiBase::PARAM_TYPE => $userGroups,
241  ApiBase::PARAM_ISMULTI => true,
242  ],
243  'rights' => [
244  ApiBase::PARAM_TYPE => $userRights,
245  ApiBase::PARAM_ISMULTI => true,
246  ],
247  'excluderights' => [
248  ApiBase::PARAM_TYPE => $userRights,
249  ApiBase::PARAM_ISMULTI => true,
250  ],
251  'limit' => [
252  ApiBase::PARAM_DFLT => 10,
253  ApiBase::PARAM_TYPE => 'limit',
254  ApiBase::PARAM_MIN => 1,
257  ],
258  'continue' => [
259  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
260  ],
261  ];
262  }
263 
264  protected function getExamplesMessages() {
265  return [
266  'action=query&prop=contributors&titles=Main_Page'
267  => 'apihelp-query+contributors-example-simple',
268  ];
269  }
270 
271  public function getHelpUrls() {
272  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Contributors';
273  }
274 }
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
getDB()
Get the Query database connection (read-only)
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:261
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1585
getResult()
Get the result object.
Definition: ApiBase.php:639
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:259
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:97
This is a base class for all Query modules.
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:760
const SCHEMA_COMPAT_READ_NEW
Definition: Defines.php:283
getPageSet()
Get the PageSet object to work on.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
__construct(ApiQuery $query, $moduleName)
const MAX_PAGES
We don&#39;t want to process too many pages at once (it hits cold database pages too heavily), so only do the first MAX_PAGES input pages in each API call (leaving the rest for continuation).
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
static getAllGroups()
Return the set of defined explicit groups.
Definition: User.php:5000
static getAllRights()
Get a list of all available permissions.
Definition: User.php:5012
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
static newMigration()
Static constructor.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition: User.php:4908
$res
Definition: database.txt:21
dieContinueUsageIf( $condition)
Die with the &#39;badcontinue&#39; error.
Definition: ApiBase.php:2199
A query module to show contributors to a page.
$params
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
addFields( $value)
Add a set of fields to select to the internal array.
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE &#39;limit&#39;.
Definition: ApiBase.php:103
This is the main query class.
Definition: ApiQuery.php:36
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:930
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:131
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
addWhere( $value)
Add a set of WHERE clauses to the internal array.
$revQuery
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:106
resetQueryParams()
Blank the internal arrays with query parameters.
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.