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