Merge "Declare visibility for class properties in DatabaseOracle.php"
[lhc/web/wiklou.git] / includes / api / ApiQueryCategoryMembers.php
1 <?php
2 /**
3 *
4 *
5 * Created on June 14, 2007
6 *
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * A query module to enumerate pages that belong to a category.
29 *
30 * @ingroup API
31 */
32 class ApiQueryCategoryMembers extends ApiQueryGeneratorBase {
33
34 public function __construct( $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
50 /**
51 * @param $resultPageSet ApiPageSet
52 * @return void
53 */
54 private function run( $resultPageSet = null ) {
55 $params = $this->extractRequestParams();
56
57 $categoryTitle = $this->getTitleOrPageId( $params )->getTitle();
58 if ( $categoryTitle->getNamespace() != NS_CATEGORY ) {
59 $this->dieUsage( 'The category name you entered is not valid', 'invalidcategory' );
60 }
61
62 $prop = array_flip( $params['prop'] );
63 $fld_ids = isset( $prop['ids'] );
64 $fld_title = isset( $prop['title'] );
65 $fld_sortkey = isset( $prop['sortkey'] );
66 $fld_sortkeyprefix = isset( $prop['sortkeyprefix'] );
67 $fld_timestamp = isset( $prop['timestamp'] );
68 $fld_type = isset( $prop['type'] );
69
70 if ( is_null( $resultPageSet ) ) {
71 $this->addFields( array( 'cl_from', 'cl_sortkey', 'cl_type', 'page_namespace', 'page_title' ) );
72 $this->addFieldsIf( 'page_id', $fld_ids );
73 $this->addFieldsIf( 'cl_sortkey_prefix', $fld_sortkeyprefix );
74 } else {
75 $this->addFields( $resultPageSet->getPageTableFields() ); // will include page_ id, ns, title
76 $this->addFields( array( 'cl_from', 'cl_sortkey', 'cl_type' ) );
77 }
78
79 $this->addFieldsIf( 'cl_timestamp', $fld_timestamp || $params['sort'] == 'timestamp' );
80
81 $this->addTables( array( 'page', 'categorylinks' ) ); // must be in this order for 'USE INDEX'
82
83 $this->addWhereFld( 'cl_to', $categoryTitle->getDBkey() );
84 $queryTypes = $params['type'];
85 $contWhere = false;
86
87 // Scanning large datasets for rare categories sucks, and I already told
88 // how to have efficient subcategory access :-) ~~~~ (oh well, domas)
89 global $wgMiserMode;
90 $miser_ns = array();
91 if ( $wgMiserMode ) {
92 $miser_ns = $params['namespace'];
93 } else {
94 $this->addWhereFld( 'page_namespace', $params['namespace'] );
95 }
96
97 $dir = in_array( $params['dir'], array( 'asc', 'ascending', 'newer' ) ) ? 'newer' : 'older';
98
99 if ( $params['sort'] == 'timestamp' ) {
100 $this->addTimestampWhereRange( 'cl_timestamp',
101 $dir,
102 $params['start'],
103 $params['end'] );
104
105 $this->addOption( 'USE INDEX', 'cl_timestamp' );
106 } else {
107 if ( $params['continue'] ) {
108 $cont = explode( '|', $params['continue'], 3 );
109 $this->dieContinueUsageIf( count( $cont ) != 3 );
110
111 // Remove the types to skip from $queryTypes
112 $contTypeIndex = array_search( $cont[0], $queryTypes );
113 $queryTypes = array_slice( $queryTypes, $contTypeIndex );
114
115 // Add a WHERE clause for sortkey and from
116 // pack( "H*", $foo ) is used to convert hex back to binary
117 $escSortkey = $this->getDB()->addQuotes( pack( 'H*', $cont[1] ) );
118 $from = intval( $cont[2] );
119 $op = $dir == 'newer' ? '>' : '<';
120 // $contWhere is used further down
121 $contWhere = "cl_sortkey $op $escSortkey OR " .
122 "(cl_sortkey = $escSortkey AND " .
123 "cl_from $op= $from)";
124 // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
125 $this->addWhereRange( 'cl_sortkey', $dir, null, null );
126 $this->addWhereRange( 'cl_from', $dir, null, null );
127 } else {
128 $startsortkey = $params['startsortkeyprefix'] !== null ?
129 Collation::singleton()->getSortkey( $params['startsortkeyprefix'] ) :
130 $params['startsortkey'];
131 $endsortkey = $params['endsortkeyprefix'] !== null ?
132 Collation::singleton()->getSortkey( $params['endsortkeyprefix'] ) :
133 $params['endsortkey'];
134
135 // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
136 $this->addWhereRange( 'cl_sortkey',
137 $dir,
138 $startsortkey,
139 $endsortkey );
140 $this->addWhereRange( 'cl_from', $dir, null, null );
141 }
142 $this->addOption( 'USE INDEX', 'cl_sortkey' );
143 }
144
145 $this->addWhere( 'cl_from=page_id' );
146
147 $limit = $params['limit'];
148 $this->addOption( 'LIMIT', $limit + 1 );
149
150 if ( $params['sort'] == 'sortkey' ) {
151 // Run a separate SELECT query for each value of cl_type.
152 // This is needed because cl_type is an enum, and MySQL has
153 // inconsistencies between ORDER BY cl_type and
154 // WHERE cl_type >= 'foo' making proper paging impossible
155 // and unindexed.
156 $rows = array();
157 $first = true;
158 foreach ( $queryTypes as $type ) {
159 $extraConds = array( 'cl_type' => $type );
160 if ( $first && $contWhere ) {
161 // Continuation condition. Only added to the
162 // first query, otherwise we'll skip things
163 $extraConds[] = $contWhere;
164 }
165 $res = $this->select( __METHOD__, array( 'where' => $extraConds ) );
166 $rows = array_merge( $rows, iterator_to_array( $res ) );
167 if ( count( $rows ) >= $limit + 1 ) {
168 break;
169 }
170 $first = false;
171 }
172 } else {
173 // Sorting by timestamp
174 // No need to worry about per-type queries because we
175 // aren't sorting or filtering by type anyway
176 $res = $this->select( __METHOD__ );
177 $rows = iterator_to_array( $res );
178 }
179
180 $result = $this->getResult();
181 $count = 0;
182 foreach ( $rows as $row ) {
183 if ( ++$count > $limit ) {
184 // We've reached the one extra which shows that there are
185 // additional pages to be had. Stop here...
186 // @todo Security issue - if the user has no right to view next
187 // title, it will still be shown
188 if ( $params['sort'] == 'timestamp' ) {
189 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
190 } else {
191 $sortkey = bin2hex( $row->cl_sortkey );
192 $this->setContinueEnumParameter( 'continue',
193 "{$row->cl_type}|$sortkey|{$row->cl_from}"
194 );
195 }
196 break;
197 }
198
199 // Since domas won't tell anyone what he told long ago, apply
200 // cmnamespace here. This means the query may return 0 actual
201 // results, but on the other hand it could save returning 5000
202 // useless results to the client. ~~~~
203 if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
204 continue;
205 }
206
207 if ( is_null( $resultPageSet ) ) {
208 $vals = array();
209 if ( $fld_ids ) {
210 $vals['pageid'] = intval( $row->page_id );
211 }
212 if ( $fld_title ) {
213 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
214 ApiQueryBase::addTitleInfo( $vals, $title );
215 }
216 if ( $fld_sortkey ) {
217 $vals['sortkey'] = bin2hex( $row->cl_sortkey );
218 }
219 if ( $fld_sortkeyprefix ) {
220 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
221 }
222 if ( $fld_type ) {
223 $vals['type'] = $row->cl_type;
224 }
225 if ( $fld_timestamp ) {
226 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->cl_timestamp );
227 }
228 $fit = $result->addValue( array( 'query', $this->getModuleName() ),
229 null, $vals );
230 if ( !$fit ) {
231 if ( $params['sort'] == 'timestamp' ) {
232 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
233 } else {
234 $sortkey = bin2hex( $row->cl_sortkey );
235 $this->setContinueEnumParameter( 'continue',
236 "{$row->cl_type}|$sortkey|{$row->cl_from}"
237 );
238 }
239 break;
240 }
241 } else {
242 $resultPageSet->processDbRow( $row );
243 }
244 }
245
246 if ( is_null( $resultPageSet ) ) {
247 $result->setIndexedTagName_internal(
248 array( 'query', $this->getModuleName() ), 'cm' );
249 }
250 }
251
252 public function getAllowedParams() {
253 return array(
254 'title' => array(
255 ApiBase::PARAM_TYPE => 'string',
256 ),
257 'pageid' => array(
258 ApiBase::PARAM_TYPE => 'integer'
259 ),
260 'prop' => array(
261 ApiBase::PARAM_DFLT => 'ids|title',
262 ApiBase::PARAM_ISMULTI => true,
263 ApiBase::PARAM_TYPE => array(
264 'ids',
265 'title',
266 'sortkey',
267 'sortkeyprefix',
268 'type',
269 'timestamp',
270 )
271 ),
272 'namespace' => array(
273 ApiBase::PARAM_ISMULTI => true,
274 ApiBase::PARAM_TYPE => 'namespace',
275 ),
276 'type' => array(
277 ApiBase::PARAM_ISMULTI => true,
278 ApiBase::PARAM_DFLT => 'page|subcat|file',
279 ApiBase::PARAM_TYPE => array(
280 'page',
281 'subcat',
282 'file'
283 )
284 ),
285 'continue' => null,
286 'limit' => array(
287 ApiBase::PARAM_TYPE => 'limit',
288 ApiBase::PARAM_DFLT => 10,
289 ApiBase::PARAM_MIN => 1,
290 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
291 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
292 ),
293 'sort' => array(
294 ApiBase::PARAM_DFLT => 'sortkey',
295 ApiBase::PARAM_TYPE => array(
296 'sortkey',
297 'timestamp'
298 )
299 ),
300 'dir' => array(
301 ApiBase::PARAM_DFLT => 'ascending',
302 ApiBase::PARAM_TYPE => array(
303 'asc',
304 'desc',
305 // Normalising with other modules
306 'ascending',
307 'descending',
308 'newer',
309 'older',
310 )
311 ),
312 'start' => array(
313 ApiBase::PARAM_TYPE => 'timestamp'
314 ),
315 'end' => array(
316 ApiBase::PARAM_TYPE => 'timestamp'
317 ),
318 'startsortkey' => null,
319 'endsortkey' => null,
320 'startsortkeyprefix' => null,
321 'endsortkeyprefix' => null,
322 );
323 }
324
325 public function getParamDescription() {
326 global $wgMiserMode;
327 $p = $this->getModulePrefix();
328 $desc = array(
329 'title' => "Which category to enumerate (required). Must include " .
330 "'Category:' prefix. Cannot be used together with {$p}pageid",
331 'pageid' => "Page ID of the category to enumerate. Cannot be used together with {$p}title",
332 'prop' => array(
333 'What pieces of information to include',
334 ' ids - Adds the page ID',
335 ' title - Adds the title and namespace ID of the page',
336 ' sortkey - Adds the sortkey used for sorting in the category (hexadecimal string)',
337 ' sortkeyprefix - Adds the sortkey prefix used for sorting in the ' .
338 'category (human-readable part of the sortkey)',
339 ' type - Adds the type that the page has been categorised as (page, subcat or file)',
340 ' timestamp - Adds the timestamp of when the page was included',
341 ),
342 'namespace' => 'Only include pages in these namespaces',
343 'type' => "What type of category members to include. Ignored when {$p}sort=timestamp is set",
344 'sort' => 'Property to sort by',
345 'dir' => 'In which direction to sort',
346 'start' => "Timestamp to start listing from. Can only be used with {$p}sort=timestamp",
347 'end' => "Timestamp to end listing at. Can only be used with {$p}sort=timestamp",
348 'startsortkey' => "Sortkey to start listing from. Must be given in " .
349 "binary format. Can only be used with {$p}sort=sortkey",
350 'endsortkey' => "Sortkey to end listing at. Must be given in binary " .
351 "format. Can only be used with {$p}sort=sortkey",
352 'startsortkeyprefix' => "Sortkey prefix to start listing from. Can " .
353 "only be used with {$p}sort=sortkey. Overrides {$p}startsortkey",
354 'endsortkeyprefix' => "Sortkey prefix to end listing BEFORE (not at, " .
355 "if this value occurs it will not be included!). Can only be used with " .
356 "{$p}sort=sortkey. Overrides {$p}endsortkey",
357 'continue' => 'For large categories, give the value returned from previous query',
358 'limit' => 'The maximum number of pages to return.',
359 );
360
361 if ( $wgMiserMode ) {
362 $desc['namespace'] = array(
363 $desc['namespace'],
364 "NOTE: Due to \$wgMiserMode, using this may result in fewer than \"{$p}limit\" results",
365 'returned before continuing; in extreme cases, zero results may be returned.',
366 "Note that you can use {$p}type=subcat or {$p}type=file instead of {$p}namespace=14 or 6.",
367 );
368 }
369
370 return $desc;
371 }
372
373 public function getResultProperties() {
374 return array(
375 'ids' => array(
376 'pageid' => 'integer'
377 ),
378 'title' => array(
379 'ns' => 'namespace',
380 'title' => 'string'
381 ),
382 'sortkey' => array(
383 'sortkey' => 'string'
384 ),
385 'sortkeyprefix' => array(
386 'sortkeyprefix' => 'string'
387 ),
388 'type' => array(
389 'type' => array(
390 ApiBase::PROP_TYPE => array(
391 'page',
392 'subcat',
393 'file'
394 )
395 )
396 ),
397 'timestamp' => array(
398 'timestamp' => 'timestamp'
399 )
400 );
401 }
402
403 public function getDescription() {
404 return 'List all pages in a given category';
405 }
406
407 public function getPossibleErrors() {
408 return array_merge( parent::getPossibleErrors(),
409 $this->getTitleOrPageIdErrorMessage(),
410 array(
411 array( 'code' => 'invalidcategory', 'info' => 'The category name you entered is not valid' ),
412 )
413 );
414 }
415
416 public function getExamples() {
417 return array(
418 'api.php?action=query&list=categorymembers&cmtitle=Category:Physics'
419 => 'Get first 10 pages in [[Category:Physics]]',
420 'api.php?action=query&generator=categorymembers&gcmtitle=Category:Physics&prop=info'
421 => 'Get page info about first 10 pages in [[Category:Physics]]',
422 );
423 }
424
425 public function getHelpUrls() {
426 return 'https://www.mediawiki.org/wiki/API:Categorymembers';
427 }
428 }