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