Remove one invalid errors, add 2 that could be returned
[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 private function run( $resultPageSet = null ) {
56 $params = $this->extractRequestParams();
57
58 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
59
60 if ( isset( $params['title'] ) ) {
61 $categoryTitle = Title::newFromText( $params['title'] );
62
63 if ( is_null( $categoryTitle ) || $categoryTitle->getNamespace() != NS_CATEGORY ) {
64 $this->dieUsage( 'The category name you entered is not valid', 'invalidcategory' );
65 }
66 } elseif( isset( $params['pageid'] ) ) {
67 $categoryTitle = Title::newFromID( $params['pageid'] );
68
69 if ( !$categoryTitle ) {
70 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
71 } elseif ( $categoryTitle->getNamespace() != NS_CATEGORY ) {
72 $this->dieUsage( 'The category name you entered is not valid', 'invalidcategory' );
73 }
74 }
75
76 $prop = array_flip( $params['prop'] );
77 $fld_ids = isset( $prop['ids'] );
78 $fld_title = isset( $prop['title'] );
79 $fld_sortkey = isset( $prop['sortkey'] );
80 $fld_timestamp = isset( $prop['timestamp'] );
81
82 if ( is_null( $resultPageSet ) ) {
83 $this->addFields( array( 'cl_from', 'cl_sortkey', 'page_namespace', 'page_title' ) );
84 $this->addFieldsIf( 'page_id', $fld_ids );
85 } else {
86 $this->addFields( $resultPageSet->getPageTableFields() ); // will include page_ id, ns, title
87 $this->addFields( array( 'cl_from', 'cl_sortkey' ) );
88 }
89
90 $this->addFieldsIf( 'cl_timestamp', $fld_timestamp || $params['sort'] == 'timestamp' );
91 $this->addTables( array( 'page', 'categorylinks' ) ); // must be in this order for 'USE INDEX'
92 // Not needed after bug 10280 is applied to servers
93 if ( $params['sort'] == 'timestamp' ) {
94 $this->addOption( 'USE INDEX', 'cl_timestamp' );
95 } else {
96 $this->addOption( 'USE INDEX', 'cl_sortkey' );
97 }
98
99 $this->addWhere( 'cl_from=page_id' );
100 $this->setContinuation( $params['continue'], $params['dir'] );
101 $this->addWhereFld( 'cl_to', $categoryTitle->getDBkey() );
102 // Scanning large datasets for rare categories sucks, and I already told
103 // how to have efficient subcategory access :-) ~~~~ (oh well, domas)
104 global $wgMiserMode;
105 $miser_ns = array();
106 if ( $wgMiserMode ) {
107 $miser_ns = $params['namespace'];
108 } else {
109 $this->addWhereFld( 'page_namespace', $params['namespace'] );
110 }
111 if ( $params['sort'] == 'timestamp' ) {
112 $this->addWhereRange( 'cl_timestamp', ( $params['dir'] == 'asc' ? 'newer' : 'older' ), $params['start'], $params['end'] );
113 } else {
114 $this->addWhereRange( 'cl_sortkey', ( $params['dir'] == 'asc' ? 'newer' : 'older' ), $params['startsortkey'], $params['endsortkey'] );
115 $this->addWhereRange( 'cl_from', ( $params['dir'] == 'asc' ? 'newer' : 'older' ), null, null );
116 }
117
118 $limit = $params['limit'];
119 $this->addOption( 'LIMIT', $limit + 1 );
120
121 $count = 0;
122 $lastSortKey = null;
123 $res = $this->select( __METHOD__ );
124 foreach ( $res as $row ) {
125 if ( ++ $count > $limit ) {
126 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
127 // TODO: Security issue - if the user has no right to view next title, it will still be shown
128 if ( $params['sort'] == 'timestamp' ) {
129 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
130 } else {
131 $this->setContinueEnumParameter( 'continue', $this->getContinueStr( $row, $lastSortKey ) );
132 }
133 break;
134 }
135
136 // Since domas won't tell anyone what he told long ago, apply
137 // cmnamespace here. This means the query may return 0 actual
138 // results, but on the other hand it could save returning 5000
139 // useless results to the client. ~~~~
140 if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
141 continue;
142 }
143
144 if ( is_null( $resultPageSet ) ) {
145 $vals = array();
146 if ( $fld_ids ) {
147 $vals['pageid'] = intval( $row->page_id );
148 }
149 if ( $fld_title ) {
150 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
151 ApiQueryBase::addTitleInfo( $vals, $title );
152 }
153 if ( $fld_sortkey ) {
154 $vals['sortkey'] = $row->cl_sortkey;
155 }
156 if ( $fld_timestamp ) {
157 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->cl_timestamp );
158 }
159 $fit = $this->getResult()->addValue( array( 'query', $this->getModuleName() ),
160 null, $vals );
161 if ( !$fit ) {
162 if ( $params['sort'] == 'timestamp' ) {
163 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
164 } else {
165 $this->setContinueEnumParameter( 'continue', $this->getContinueStr( $row, $lastSortKey ) );
166 }
167 break;
168 }
169 } else {
170 $resultPageSet->processDbRow( $row );
171 }
172 $lastSortKey = $row->cl_sortkey; // detect duplicate sortkeys
173 }
174
175 if ( is_null( $resultPageSet ) ) {
176 $this->getResult()->setIndexedTagName_internal(
177 array( 'query', $this->getModuleName() ), 'cm' );
178 }
179 }
180
181 private function getContinueStr( $row, $lastSortKey ) {
182 $ret = $row->cl_sortkey . '|';
183 if ( $row->cl_sortkey == $lastSortKey ) { // duplicate sort key, add cl_from
184 $ret .= $row->cl_from;
185 }
186 return $ret;
187 }
188
189 /**
190 * Add DB WHERE clause to continue previous query based on 'continue' parameter
191 */
192 private function setContinuation( $continue, $dir ) {
193 if ( is_null( $continue ) ) {
194 return; // This is not a continuation request
195 }
196
197 $pos = strrpos( $continue, '|' );
198 $sortkey = substr( $continue, 0, $pos );
199 $fromstr = substr( $continue, $pos + 1 );
200 $from = intval( $fromstr );
201
202 if ( $from == 0 && strlen( $fromstr ) > 0 ) {
203 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', 'badcontinue' );
204 }
205
206 $encSortKey = $this->getDB()->addQuotes( $sortkey );
207 $encFrom = $this->getDB()->addQuotes( $from );
208
209 $op = ( $dir == 'desc' ? '<' : '>' );
210
211 if ( $from != 0 ) {
212 // Duplicate sort key continue
213 $this->addWhere( "cl_sortkey$op$encSortKey OR (cl_sortkey=$encSortKey AND cl_from$op=$encFrom)" );
214 } else {
215 $this->addWhere( "cl_sortkey$op=$encSortKey" );
216 }
217 }
218
219 public function getAllowedParams() {
220 return array(
221 'title' => array(
222 ApiBase::PARAM_TYPE => 'string',
223 ),
224 'pageid' => array(
225 ApiBase::PARAM_TYPE => 'integer'
226 ),
227 'prop' => array(
228 ApiBase::PARAM_DFLT => 'ids|title',
229 ApiBase::PARAM_ISMULTI => true,
230 ApiBase::PARAM_TYPE => array (
231 'ids',
232 'title',
233 'sortkey',
234 'timestamp',
235 )
236 ),
237 'namespace' => array (
238 ApiBase::PARAM_ISMULTI => true,
239 ApiBase::PARAM_TYPE => 'namespace',
240 ),
241 'continue' => null,
242 'limit' => array(
243 ApiBase::PARAM_TYPE => 'limit',
244 ApiBase::PARAM_DFLT => 10,
245 ApiBase::PARAM_MIN => 1,
246 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
247 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
248 ),
249 'sort' => array(
250 ApiBase::PARAM_DFLT => 'sortkey',
251 ApiBase::PARAM_TYPE => array(
252 'sortkey',
253 'timestamp'
254 )
255 ),
256 'dir' => array(
257 ApiBase::PARAM_DFLT => 'asc',
258 ApiBase::PARAM_TYPE => array(
259 'asc',
260 'desc'
261 )
262 ),
263 'start' => array(
264 ApiBase::PARAM_TYPE => 'timestamp'
265 ),
266 'end' => array(
267 ApiBase::PARAM_TYPE => 'timestamp'
268 ),
269 'startsortkey' => null,
270 'endsortkey' => null,
271 );
272 }
273
274 public function getParamDescription() {
275 global $wgMiserMode;
276 $p = $this->getModulePrefix();
277 $desc = array(
278 'title' => 'Which category to enumerate (required). Must include Category: prefix. Cannot be used together with cmpageid',
279 'pageid' => 'Page ID of the category to enumerate. Cannot be used together with cmtitle',
280 'prop' => array(
281 'What pieces of information to include',
282 ' ids - Adds the page ID',
283 ' title - Adds the title and namespace ID of the page',
284 ' sortkey - Adds the sortkey used for the category',
285 ' timestamp - Adds the timestamp of when the page was included',
286 ),
287 'namespace' => 'Only include pages in these namespaces',
288 'sort' => 'Property to sort by',
289 'dir' => 'In which direction to sort',
290 'start' => "Timestamp to start listing from. Can only be used with {$p}sort=timestamp",
291 'end' => "Timestamp to end listing at. Can only be used with {$p}sort=timestamp",
292 'startsortkey' => "Sortkey to start listing from. Can only be used with {$p}sort=sortkey",
293 'endsortkey' => "Sortkey to end listing at. Can only be used with {$p}sort=sortkey",
294 'continue' => 'For large categories, give the value retured from previous query',
295 'limit' => 'The maximum number of pages to return.',
296 );
297 if ( $wgMiserMode ) {
298 $desc['namespace'] = array(
299 $desc['namespace'],
300 'NOTE: Due to $wgMiserMode, using this may result in fewer than "limit" results',
301 'returned before continuing; in extreme cases, zero results may be returned',
302 );
303 }
304 return $desc;
305 }
306
307 public function getDescription() {
308 return 'List all pages in a given category';
309 }
310
311 public function getPossibleErrors() {
312 return array_merge( parent::getPossibleErrors(), array(
313 array( 'code' => 'cmmissingparam', 'info' => 'One of the parameters title, pageid is required' ),
314 array( 'code' => 'cminvalidparammix', 'info' => 'The parameters title, pageid can not be used together' ),
315 array( 'code' => 'invalidcategory', 'info' => 'The category name you entered is not valid' ),
316 array( 'code' => 'badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
317 array( 'nosuchpageid', 'pageid' ),
318 ) );
319 }
320
321 protected function getExamples() {
322 return array(
323 'Get first 10 pages in [[Category:Physics]]:',
324 ' api.php?action=query&list=categorymembers&cmtitle=Category:Physics',
325 'Get page info about first 10 pages in [[Category:Physics]]:',
326 ' api.php?action=query&generator=categorymembers&gcmtitle=Category:Physics&prop=info',
327 );
328 }
329
330 public function getVersion() {
331 return __CLASS__ . ': $Id$';
332 }
333 }