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