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