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