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