c1871a5b41b6d580a275ffd1b876c4df005450c6
[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
193 $result = $this->getResult();
194 $count = 0;
195 foreach ( $rows as $row ) {
196 if ( ++ $count > $limit ) {
197 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
198 // TODO: Security issue - if the user has no right to view next title, it will still be shown
199 if ( $params['sort'] == 'timestamp' ) {
200 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
201 } else {
202 $sortkey = bin2hex( $row->cl_sortkey );
203 $this->setContinueEnumParameter( 'continue',
204 "{$row->cl_type}|$sortkey|{$row->cl_from}"
205 );
206 }
207 break;
208 }
209
210 // Since domas won't tell anyone what he told long ago, apply
211 // cmnamespace here. This means the query may return 0 actual
212 // results, but on the other hand it could save returning 5000
213 // useless results to the client. ~~~~
214 if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
215 continue;
216 }
217
218 if ( is_null( $resultPageSet ) ) {
219 $vals = array();
220 if ( $fld_ids ) {
221 $vals['pageid'] = intval( $row->page_id );
222 }
223 if ( $fld_title ) {
224 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
225 ApiQueryBase::addTitleInfo( $vals, $title );
226 }
227 if ( $fld_sortkey ) {
228 $vals['sortkey'] = bin2hex( $row->cl_sortkey );
229 }
230 if ( $fld_sortkeyprefix ) {
231 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
232 }
233 if ( $fld_type ) {
234 $vals['type'] = $row->cl_type;
235 }
236 if ( $fld_timestamp ) {
237 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->cl_timestamp );
238 }
239 $fit = $result->addValue( array( 'query', $this->getModuleName() ),
240 null, $vals );
241 if ( !$fit ) {
242 if ( $params['sort'] == 'timestamp' ) {
243 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
244 } else {
245 $sortkey = bin2hex( $row->cl_sortkey );
246 $this->setContinueEnumParameter( 'continue',
247 "{$row->cl_type}|$sortkey|{$row->cl_from}"
248 );
249 }
250 break;
251 }
252 } else {
253 $resultPageSet->processDbRow( $row );
254 }
255 }
256
257 if ( is_null( $resultPageSet ) ) {
258 $result->setIndexedTagName_internal(
259 array( 'query', $this->getModuleName() ), 'cm' );
260 }
261 }
262
263 public function getAllowedParams() {
264 return array(
265 'title' => array(
266 ApiBase::PARAM_TYPE => 'string',
267 ),
268 'pageid' => array(
269 ApiBase::PARAM_TYPE => 'integer'
270 ),
271 'prop' => array(
272 ApiBase::PARAM_DFLT => 'ids|title',
273 ApiBase::PARAM_ISMULTI => true,
274 ApiBase::PARAM_TYPE => array (
275 'ids',
276 'title',
277 'sortkey',
278 'sortkeyprefix',
279 'type',
280 'timestamp',
281 )
282 ),
283 'namespace' => array (
284 ApiBase::PARAM_ISMULTI => true,
285 ApiBase::PARAM_TYPE => 'namespace',
286 ),
287 'type' => array(
288 ApiBase::PARAM_ISMULTI => true,
289 ApiBase::PARAM_DFLT => 'page|subcat|file',
290 ApiBase::PARAM_TYPE => array(
291 'page',
292 'subcat',
293 'file'
294 )
295 ),
296 'continue' => null,
297 'limit' => array(
298 ApiBase::PARAM_TYPE => 'limit',
299 ApiBase::PARAM_DFLT => 10,
300 ApiBase::PARAM_MIN => 1,
301 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
302 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
303 ),
304 'sort' => array(
305 ApiBase::PARAM_DFLT => 'sortkey',
306 ApiBase::PARAM_TYPE => array(
307 'sortkey',
308 'timestamp'
309 )
310 ),
311 'dir' => array(
312 ApiBase::PARAM_DFLT => 'asc',
313 ApiBase::PARAM_TYPE => array(
314 'asc',
315 'desc'
316 )
317 ),
318 'start' => array(
319 ApiBase::PARAM_TYPE => 'timestamp'
320 ),
321 'end' => array(
322 ApiBase::PARAM_TYPE => 'timestamp'
323 ),
324 'startsortkey' => null,
325 'endsortkey' => null,
326 );
327 }
328
329 public function getParamDescription() {
330 global $wgMiserMode;
331 $p = $this->getModulePrefix();
332 $desc = array(
333 'title' => "Which category to enumerate (required). Must include Category: prefix. Cannot be used together with {$p}pageid",
334 'pageid' => "Page ID of the category to enumerate. Cannot be used together with {$p}title",
335 'prop' => array(
336 'What pieces of information to include',
337 ' ids - Adds the page ID',
338 ' title - Adds the title and namespace ID of the page',
339 ' sortkey - Adds the sortkey used for sorting in the category (hexadecimal string)',
340 ' sortkeyprefix - Adds the sortkey prefix used for sorting in the category (human-readable part of the sortkey)',
341 ' type - Adds the type that the page has been categorised as (page, subcat or file)',
342 ' timestamp - Adds the timestamp of when the page was included',
343 ),
344 'namespace' => 'Only include pages in these namespaces',
345 'type' => "What type of category members to include. Ignored when {$p}sort=timestamp is set",
346 'sort' => 'Property to sort by',
347 'dir' => 'In which direction to sort',
348 'start' => "Timestamp to start listing from. Can only be used with {$p}sort=timestamp",
349 'end' => "Timestamp to end listing at. Can only be used with {$p}sort=timestamp",
350 'startsortkey' => "Sortkey to start listing from. Must be given in binary format. Can only be used with {$p}sort=sortkey",
351 'endsortkey' => "Sortkey to end listing at. Must be given in binary format. Can only be used with {$p}sort=sortkey",
352 'continue' => 'For large categories, give the value retured from previous query',
353 'limit' => 'The maximum number of pages to return.',
354 );
355
356 if ( $wgMiserMode ) {
357 $desc['namespace'] = array(
358 $desc['namespace'],
359 "NOTE: Due to \$wgMiserMode, using this may result in fewer than \"{$p}limit\" results",
360 'returned before continuing; in extreme cases, zero results may be returned.',
361 "Note that you can use {$p}type=subcat or {$p}type=file instead of {$p}namespace=14 or 6.",
362 );
363 }
364 return $desc;
365 }
366
367 public function getDescription() {
368 return 'List all pages in a given category';
369 }
370
371 public function getPossibleErrors() {
372 return array_merge( parent::getPossibleErrors(),
373 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
374 array(
375 array( 'code' => 'invalidcategory', 'info' => 'The category name you entered is not valid' ),
376 array( 'code' => 'badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
377 array( 'nosuchpageid', 'pageid' ),
378 )
379 );
380 }
381
382 public function getExamples() {
383 return array(
384 'Get first 10 pages in [[Category:Physics]]:',
385 ' api.php?action=query&list=categorymembers&cmtitle=Category:Physics',
386 'Get page info about first 10 pages in [[Category:Physics]]:',
387 ' api.php?action=query&generator=categorymembers&gcmtitle=Category:Physics&prop=info',
388 );
389 }
390
391 public function getHelpUrls() {
392 return 'http://www.mediawiki.org/wiki/API:Categorymembers';
393 }
394
395 public function getVersion() {
396 return __CLASS__ . ': $Id$';
397 }
398 }