MediaWiki master
ApiQueryCategoryMembers.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
11use Collation;
18use Wikimedia\Timestamp\TimestampFormat as TS;
19
26
27 private Collation $collation;
28
29 public function __construct(
30 ApiQuery $query,
31 string $moduleName,
32 CollationFactory $collationFactory
33 ) {
34 parent::__construct( $query, $moduleName, 'cm' );
35 $this->collation = $collationFactory->getCategoryCollation();
36 }
37
38 public function execute() {
39 $this->run();
40 }
41
43 public function getCacheMode( $params ) {
44 return 'public';
45 }
46
48 public function executeGenerator( $resultPageSet ) {
49 $this->run( $resultPageSet );
50 }
51
56 private function validateHexSortkey( $hexSortkey ) {
57 // A hex sortkey has an unbound number of 2 letter pairs
58 return (bool)preg_match( '/^(?:[a-fA-F0-9]{2})*$/D', $hexSortkey );
59 }
60
65 private function run( $resultPageSet = null ) {
66 $params = $this->extractRequestParams();
67
68 $categoryTitle = $this->getTitleOrPageId( $params )->getTitle();
69 if ( $categoryTitle->getNamespace() !== NS_CATEGORY ) {
70 $this->dieWithError( 'apierror-invalidcategory' );
71 }
72
73 $prop = array_fill_keys( $params['prop'], true );
74 $fld_ids = isset( $prop['ids'] );
75 $fld_title = isset( $prop['title'] );
76 $fld_sortkey = isset( $prop['sortkey'] );
77 $fld_sortkeyprefix = isset( $prop['sortkeyprefix'] );
78 $fld_timestamp = isset( $prop['timestamp'] );
79 $fld_type = isset( $prop['type'] );
80
82 $db = $this->getDB();
83
84 if ( $resultPageSet === null ) {
85 $this->addFields( [ 'cl_from', 'cl_sortkey', 'cl_type', 'page_namespace', 'page_title' ] );
86 $this->addFieldsIf( 'page_id', $fld_ids );
87 $this->addFieldsIf( 'cl_sortkey_prefix', $fld_sortkeyprefix );
88 } else {
89 $this->addFields( $resultPageSet->getPageTableFields() ); // will include page_ id, ns, title
90 $this->addFields( [ 'cl_from', 'cl_sortkey', 'cl_type' ] );
91 }
92
93 $this->addFieldsIf( 'cl_timestamp', $fld_timestamp || $params['sort'] == 'timestamp' );
94
95 $this->addTables( [ 'page', 'categorylinks', 'linktarget' ] );
96 $this->addJoinConds( [ 'categorylinks' => [ 'JOIN', 'cl_from=page_id' ] ] );
97 $this->addJoinConds( [ 'linktarget' => [ 'JOIN', 'cl_target_id = lt_id ' ] ] );
98 $this->addWhere( [
99 'lt_namespace' => NS_CATEGORY,
100 'lt_title' => $categoryTitle->getDBkey(),
101 ] );
102
103 $queryTypes = $params['type'];
104 $contWhere = false;
105
106 // Scanning large datasets for rare categories sucks, and I already told
107 // how to have efficient subcategory access :-) ~~~~ (oh well, domas)
108 $miser_ns = [];
109 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
110 $miser_ns = $params['namespace'] ?: [];
111 } else {
112 $this->addWhereFld( 'page_namespace', $params['namespace'] );
113 }
114
115 $dir = in_array( $params['dir'], [ 'asc', 'ascending', 'newer' ] ) ? 'newer' : 'older';
116
117 if ( $params['sort'] == 'timestamp' ) {
118 $this->addTimestampWhereRange( 'cl_timestamp',
119 $dir,
120 $params['start'],
121 $params['end'] );
122 // Include in ORDER BY for uniqueness
123 $this->addWhereRange( 'cl_from', $dir, null, null );
124
125 if ( $params['continue'] !== null ) {
126 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'timestamp', 'int' ] );
127 $op = ( $dir === 'newer' ? '>=' : '<=' );
128 $this->addWhere( $db->buildComparison( $op, [
129 'cl_timestamp' => $db->timestamp( $cont[0] ),
130 'cl_from' => $cont[1],
131 ] ) );
132 }
133 } else {
134 if ( $params['continue'] ) {
135 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'string', 'int' ] );
136
137 // Remove the types to skip from $queryTypes
138 $contTypeIndex = array_search( $cont[0], $queryTypes );
139 $queryTypes = array_slice( $queryTypes, $contTypeIndex );
140
141 // Add a WHERE clause for sortkey and from
142 $this->dieContinueUsageIf( !$this->validateHexSortkey( $cont[1] ) );
143 $op = $dir == 'newer' ? '>=' : '<=';
144 // $contWhere is used further down
145 $contWhere = $db->buildComparison( $op, [
146 'cl_sortkey' => hex2bin( $cont[1] ),
147 'cl_from' => $cont[2],
148 ] );
149 // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
150 $this->addWhereRange( 'cl_sortkey', $dir, null, null );
151 $this->addWhereRange( 'cl_from', $dir, null, null );
152 } else {
153 if ( $params['startsortkeyprefix'] !== null ) {
154 $startsortkey = $this->collation->getSortKey( $params['startsortkeyprefix'] );
155 } elseif ( $params['starthexsortkey'] !== null ) {
156 if ( !$this->validateHexSortkey( $params['starthexsortkey'] ) ) {
157 $encParamName = $this->encodeParamName( 'starthexsortkey' );
158 $this->dieWithError( [ 'apierror-badparameter', $encParamName ], "badvalue_$encParamName" );
159 }
160 $startsortkey = hex2bin( $params['starthexsortkey'] );
161 } else {
162 $startsortkey = $params['startsortkey'];
163 }
164 if ( $params['endsortkeyprefix'] !== null ) {
165 $endsortkey = $this->collation->getSortKey( $params['endsortkeyprefix'] );
166 } elseif ( $params['endhexsortkey'] !== null ) {
167 if ( !$this->validateHexSortkey( $params['endhexsortkey'] ) ) {
168 $encParamName = $this->encodeParamName( 'endhexsortkey' );
169 $this->dieWithError( [ 'apierror-badparameter', $encParamName ], "badvalue_$encParamName" );
170 }
171 $endsortkey = hex2bin( $params['endhexsortkey'] );
172 } else {
173 $endsortkey = $params['endsortkey'];
174 }
175
176 // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
177 $this->addWhereRange( 'cl_sortkey',
178 $dir,
179 $startsortkey,
180 $endsortkey );
181 $this->addWhereRange( 'cl_from', $dir, null, null );
182 }
183 $this->addOption( 'USE INDEX', [ 'categorylinks' => 'cl_sortkey_id' ] );
184 }
185
186 $limit = $params['limit'];
187 $this->addOption( 'LIMIT', $limit + 1 );
188
189 if ( $params['sort'] == 'sortkey' ) {
190 // Run a separate SELECT query for each value of cl_type.
191 // This is needed because cl_type is an enum, and MySQL has
192 // inconsistencies between ORDER BY cl_type and
193 // WHERE cl_type >= 'foo' making proper paging impossible
194 // and unindexed.
195 $rows = [];
196 $first = true;
197 foreach ( $queryTypes as $type ) {
198 $extraConds = [ 'cl_type' => $type ];
199 if ( $first && $contWhere ) {
200 // Continuation condition. Only added to the
201 // first query, otherwise we'll skip things
202 $extraConds[] = $contWhere;
203 }
204 $res = $this->select( __METHOD__, [ 'where' => $extraConds ] );
205 if ( $type === 'page' && $resultPageSet === null ) {
206 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
207 }
208 $rows = array_merge( $rows, iterator_to_array( $res ) );
209 if ( count( $rows ) >= $limit + 1 ) {
210 break;
211 }
212 $first = false;
213 }
214 } else {
215 // Sorting by timestamp
216 // No need to worry about per-type queries because we
217 // aren't sorting or filtering by type anyway
218 $res = $this->select( __METHOD__ );
219 if ( $resultPageSet === null ) {
220 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
221 }
222 $rows = iterator_to_array( $res );
223 }
224
225 $result = $this->getResult();
226 $count = 0;
227 foreach ( $rows as $row ) {
228 if ( ++$count > $limit ) {
229 // We've reached the one extra which shows that there are
230 // additional pages to be had. Stop here...
231 // @todo Security issue - if the user has no right to view next
232 // title, it will still be shown
233 if ( $params['sort'] == 'timestamp' ) {
235 'continue',
236 $db->timestamp( $row->cl_timestamp ) . "|$row->cl_from"
237 );
238 } else {
239 $sortkey = bin2hex( $row->cl_sortkey );
240 $this->setContinueEnumParameter( 'continue',
241 "{$row->cl_type}|$sortkey|{$row->cl_from}"
242 );
243 }
244 break;
245 }
246
247 // Since domas won't tell anyone what he told long ago, apply
248 // cmnamespace here. This means the query may return 0 actual
249 // results, but on the other hand it could save returning 5000
250 // useless results to the client. ~~~~
251 if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
252 continue;
253 }
254
255 if ( $resultPageSet === null ) {
256 $vals = [
257 ApiResult::META_TYPE => 'assoc',
258 ];
259 if ( $fld_ids ) {
260 $vals['pageid'] = (int)$row->page_id;
261 }
262 if ( $fld_title ) {
263 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
264 ApiQueryBase::addTitleInfo( $vals, $title );
265 }
266 if ( $fld_sortkey ) {
267 $vals['sortkey'] = bin2hex( $row->cl_sortkey );
268 }
269 if ( $fld_sortkeyprefix ) {
270 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
271 }
272 if ( $fld_type ) {
273 $vals['type'] = $row->cl_type;
274 }
275 if ( $fld_timestamp ) {
276 $vals['timestamp'] = wfTimestamp( TS::ISO_8601, $row->cl_timestamp );
277 }
278 $fit = $result->addValue( [ 'query', $this->getModuleName() ],
279 null, $vals );
280 if ( !$fit ) {
281 if ( $params['sort'] == 'timestamp' ) {
283 'continue',
284 $db->timestamp( $row->cl_timestamp ) . "|$row->cl_from"
285 );
286 } else {
287 $sortkey = bin2hex( $row->cl_sortkey );
288 $this->setContinueEnumParameter( 'continue',
289 "{$row->cl_type}|$sortkey|{$row->cl_from}"
290 );
291 }
292 break;
293 }
294 } else {
295 $resultPageSet->processDbRow( $row );
296 }
297 }
298
299 if ( $resultPageSet === null ) {
300 $result->addIndexedTagName(
301 [ 'query', $this->getModuleName() ], 'cm' );
302 }
303 }
304
306 public function getAllowedParams() {
307 $ret = [
308 'title' => [
309 ParamValidator::PARAM_TYPE => 'string',
310 ],
311 'pageid' => [
312 ParamValidator::PARAM_TYPE => 'integer'
313 ],
314 'prop' => [
315 ParamValidator::PARAM_DEFAULT => 'ids|title',
316 ParamValidator::PARAM_ISMULTI => true,
317 ParamValidator::PARAM_TYPE => [
318 'ids',
319 'title',
320 'sortkey',
321 'sortkeyprefix',
322 'type',
323 'timestamp',
324 ],
326 ],
327 'namespace' => [
328 ParamValidator::PARAM_ISMULTI => true,
329 ParamValidator::PARAM_TYPE => 'namespace',
330 ],
331 'type' => [
332 ParamValidator::PARAM_ISMULTI => true,
333 ParamValidator::PARAM_DEFAULT => 'page|subcat|file',
334 ParamValidator::PARAM_TYPE => [
335 'page',
336 'subcat',
337 'file'
338 ]
339 ],
340 'continue' => [
341 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
342 ],
343 'limit' => [
344 ParamValidator::PARAM_TYPE => 'limit',
345 ParamValidator::PARAM_DEFAULT => 10,
346 IntegerDef::PARAM_MIN => 1,
347 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
348 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
349 ],
350 'sort' => [
351 ParamValidator::PARAM_DEFAULT => 'sortkey',
352 ParamValidator::PARAM_TYPE => [
353 'sortkey',
354 'timestamp'
355 ]
356 ],
357 'dir' => [
358 ParamValidator::PARAM_DEFAULT => 'ascending',
359 ParamValidator::PARAM_TYPE => [
360 'asc',
361 'desc',
362 // Normalising with other modules
363 'ascending',
364 'descending',
365 'newer',
366 'older',
367 ]
368 ],
369 'start' => [
370 ParamValidator::PARAM_TYPE => 'timestamp'
371 ],
372 'end' => [
373 ParamValidator::PARAM_TYPE => 'timestamp'
374 ],
375 'starthexsortkey' => null,
376 'endhexsortkey' => null,
377 'startsortkeyprefix' => null,
378 'endsortkeyprefix' => null,
379 'startsortkey' => [
380 ParamValidator::PARAM_DEPRECATED => true,
381 ],
382 'endsortkey' => [
383 ParamValidator::PARAM_DEPRECATED => true,
384 ],
385 ];
386
387 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
388 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
389 'api-help-param-limited-in-miser-mode',
390 ];
391 }
392
393 return $ret;
394 }
395
397 protected function getExamplesMessages() {
398 return [
399 'action=query&list=categorymembers&cmtitle=Category:Physics'
400 => 'apihelp-query+categorymembers-example-simple',
401 'action=query&generator=categorymembers&gcmtitle=Category:Physics&prop=info'
402 => 'apihelp-query+categorymembers-example-generator',
403 ];
404 }
405
407 public function getHelpUrls() {
408 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Categorymembers';
409 }
410}
411
413class_alias( ApiQueryCategoryMembers::class, 'ApiQueryCategoryMembers' );
const NS_CATEGORY
Definition Defines.php:65
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1511
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:543
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition ApiBase.php:1735
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1696
getResult()
Get the result object.
Definition ApiBase.php:682
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:207
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:175
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:167
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:234
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:823
getTitleOrPageId( $params, $load=false)
Attempts to load a WikiPage object from a title or pageid parameter, if possible.
Definition ApiBase.php:1147
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:232
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
setVirtualDomain(string|false $virtualDomain)
Set the Query database connection (read-only)
getDB()
Get the Query database connection (read-only).
select( $method, $extraQuery=[], ?array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addFields( $value)
Add a set of fields to select to the internal array.
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction.
A query module to enumerate pages that belong to a category.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
executeGenerator( $resultPageSet)
Execute this module as a generator.
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
__construct(ApiQuery $query, string $moduleName, CollationFactory $collationFactory)
getCacheMode( $params)
Get the cache mode for the data generated by this module.Override this in the module subclass....
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
encodeParamName( $paramName)
Overrides ApiBase to prepend 'g' to every generator parameter.
This is the main query class.
Definition ApiQuery.php:36
const META_TYPE
Key for the 'type' metadata item.
Common factory to construct collation classes.
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
A class containing constants representing the names of configuration variables.
const MiserMode
Name constant for the MiserMode setting, for use with Config::get()
Represents a title within MediaWiki.
Definition Title.php:69
Service for formatting and validating API parameters.
Type definition for integer types.
array $params
The job parameters.