(bug 19640) API: Unbreak cmnamespace in miser mode by filtering on the PHP side....
[lhc/web/wiklou.git] / includes / api / ApiQueryCategoryMembers.php
1 <?php
2
3 /*
4 * Created on June 14, 2007
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ("ApiQueryBase.php");
29 }
30
31 /**
32 * A query module to enumerate pages that belong to a category.
33 *
34 * @ingroup API
35 */
36 class ApiQueryCategoryMembers extends ApiQueryGeneratorBase {
37
38 public function __construct($query, $moduleName) {
39 parent :: __construct($query, $moduleName, 'cm');
40 }
41
42 public function execute() {
43 $this->run();
44 }
45
46 public function executeGenerator($resultPageSet) {
47 $this->run($resultPageSet);
48 }
49
50 private function run($resultPageSet = null) {
51
52 $params = $this->extractRequestParams();
53
54 if ( !isset($params['title']) || is_null($params['title']) )
55 $this->dieUsage("The cmtitle parameter is required", 'notitle');
56 $categoryTitle = Title::newFromText($params['title']);
57
58 if ( is_null( $categoryTitle ) || $categoryTitle->getNamespace() != NS_CATEGORY )
59 $this->dieUsage("The category name you entered is not valid", 'invalidcategory');
60
61 $prop = array_flip($params['prop']);
62 $fld_ids = isset($prop['ids']);
63 $fld_title = isset($prop['title']);
64 $fld_sortkey = isset($prop['sortkey']);
65 $fld_timestamp = isset($prop['timestamp']);
66
67 if (is_null($resultPageSet)) {
68 $this->addFields(array('cl_from', 'cl_sortkey', 'page_namespace', 'page_title'));
69 $this->addFieldsIf('page_id', $fld_ids);
70 } else {
71 $this->addFields($resultPageSet->getPageTableFields()); // will include page_ id, ns, title
72 $this->addFields(array('cl_from', 'cl_sortkey'));
73 }
74
75 $this->addFieldsIf('cl_timestamp', $fld_timestamp || $params['sort'] == 'timestamp');
76 $this->addTables(array('page','categorylinks')); // must be in this order for 'USE INDEX'
77 // Not needed after bug 10280 is applied to servers
78 if($params['sort'] == 'timestamp')
79 $this->addOption('USE INDEX', 'cl_timestamp');
80 else
81 $this->addOption('USE INDEX', 'cl_sortkey');
82
83 $this->addWhere('cl_from=page_id');
84 $this->setContinuation($params['continue'], $params['dir']);
85 $this->addWhereFld('cl_to', $categoryTitle->getDBkey());
86 # Scanning large datasets for rare categories sucks, and I already told
87 # how to have efficient subcategory access :-) ~~~~ (oh well, domas)
88 global $wgMiserMode;
89 $miser_ns = array();
90 if ($wgMiserMode) {
91 $miser_ns = $params['namespace'];
92 } else {
93 $this->addWhereFld('page_namespace', $params['namespace']);
94 }
95 if($params['sort'] == 'timestamp')
96 $this->addWhereRange('cl_timestamp', ($params['dir'] == 'asc' ? 'newer' : 'older'), $params['start'], $params['end']);
97 else
98 {
99 $this->addWhereRange('cl_sortkey', ($params['dir'] == 'asc' ? 'newer' : 'older'), $params['startsortkey'], $params['endsortkey']);
100 $this->addWhereRange('cl_from', ($params['dir'] == 'asc' ? 'newer' : 'older'), null, null);
101 }
102
103 $limit = $params['limit'];
104 $this->addOption('LIMIT', $limit +1);
105
106 $db = $this->getDB();
107
108 $data = array ();
109 $count = 0;
110 $lastSortKey = null;
111 $res = $this->select(__METHOD__);
112 while ($row = $db->fetchObject($res)) {
113 if (++ $count > $limit) {
114 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
115 // TODO: Security issue - if the user has no right to view next title, it will still be shown
116 if ($params['sort'] == 'timestamp')
117 $this->setContinueEnumParameter('start', wfTimestamp(TS_ISO_8601, $row->cl_timestamp));
118 else
119 $this->setContinueEnumParameter('continue', $this->getContinueStr($row, $lastSortKey));
120 break;
121 }
122
123 // Since domas won't tell anyone what he told long ago, apply
124 // cmnamespace here. This means the query may return 0 actual
125 // results, but on the other hand it could save returning 5000
126 // useless results to the client. ~~~~
127 if (count($miser_ns) && !in_array($row->page_namespace, $miser_ns))
128 continue;
129
130 if (is_null($resultPageSet)) {
131 $vals = array();
132 if ($fld_ids)
133 $vals['pageid'] = intval($row->page_id);
134 if ($fld_title) {
135 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
136 ApiQueryBase::addTitleInfo($vals, $title);
137 }
138 if ($fld_sortkey)
139 $vals['sortkey'] = $row->cl_sortkey;
140 if ($fld_timestamp)
141 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $row->cl_timestamp);
142 $fit = $this->getResult()->addValue(array('query', $this->getModuleName()),
143 null, $vals);
144 if(!$fit)
145 {
146 if ($params['sort'] == 'timestamp')
147 $this->setContinueEnumParameter('start', wfTimestamp(TS_ISO_8601, $row->cl_timestamp));
148 else
149 $this->setContinueEnumParameter('continue', $this->getContinueStr($row, $lastSortKey));
150 break;
151 }
152 } else {
153 $resultPageSet->processDbRow($row);
154 }
155 $lastSortKey = $row->cl_sortkey; // detect duplicate sortkeys
156 }
157 $db->freeResult($res);
158
159 if (is_null($resultPageSet)) {
160 $this->getResult()->setIndexedTagName_internal(
161 array('query', $this->getModuleName()), 'cm');
162 }
163 }
164
165 private function getContinueStr($row, $lastSortKey) {
166 $ret = $row->cl_sortkey . '|';
167 if ($row->cl_sortkey == $lastSortKey) // duplicate sort key, add cl_from
168 $ret .= $row->cl_from;
169 return $ret;
170 }
171
172 /**
173 * Add DB WHERE clause to continue previous query based on 'continue' parameter
174 */
175 private function setContinuation($continue, $dir) {
176 if (is_null($continue))
177 return; // This is not a continuation request
178
179 $pos = strrpos($continue, '|');
180 $sortkey = substr($continue, 0, $pos);
181 $fromstr = substr($continue, $pos + 1);
182 $from = intval($fromstr);
183
184 if ($from == 0 && strlen($fromstr) > 0)
185 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "badcontinue");
186
187 $encSortKey = $this->getDB()->addQuotes($sortkey);
188 $encFrom = $this->getDB()->addQuotes($from);
189
190 $op = ($dir == 'desc' ? '<' : '>');
191
192 if ($from != 0) {
193 // Duplicate sort key continue
194 $this->addWhere( "cl_sortkey$op$encSortKey OR (cl_sortkey=$encSortKey AND cl_from$op=$encFrom)" );
195 } else {
196 $this->addWhere( "cl_sortkey$op=$encSortKey" );
197 }
198 }
199
200 public function getAllowedParams() {
201 return array (
202 'title' => null,
203 'prop' => array (
204 ApiBase :: PARAM_DFLT => 'ids|title',
205 ApiBase :: PARAM_ISMULTI => true,
206 ApiBase :: PARAM_TYPE => array (
207 'ids',
208 'title',
209 'sortkey',
210 'timestamp',
211 )
212 ),
213 'namespace' => array (
214 ApiBase :: PARAM_ISMULTI => true,
215 ApiBase :: PARAM_TYPE => 'namespace',
216 ),
217 'continue' => null,
218 'limit' => array (
219 ApiBase :: PARAM_TYPE => 'limit',
220 ApiBase :: PARAM_DFLT => 10,
221 ApiBase :: PARAM_MIN => 1,
222 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
223 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
224 ),
225 'sort' => array(
226 ApiBase :: PARAM_DFLT => 'sortkey',
227 ApiBase :: PARAM_TYPE => array(
228 'sortkey',
229 'timestamp'
230 )
231 ),
232 'dir' => array(
233 ApiBase :: PARAM_DFLT => 'asc',
234 ApiBase :: PARAM_TYPE => array(
235 'asc',
236 'desc'
237 )
238 ),
239 'start' => array(
240 ApiBase :: PARAM_TYPE => 'timestamp'
241 ),
242 'end' => array(
243 ApiBase :: PARAM_TYPE => 'timestamp'
244 ),
245 'startsortkey' => null,
246 'endsortkey' => null,
247 );
248 }
249
250 public function getParamDescription() {
251 global $wgMiserMode;
252 $desc = array (
253 'title' => 'Which category to enumerate (required). Must include Category: prefix',
254 'prop' => 'What pieces of information to include',
255 'namespace' => 'Only include pages in these namespaces',
256 'sort' => 'Property to sort by',
257 'dir' => 'In which direction to sort',
258 'start' => 'Timestamp to start listing from. Can only be used with cmsort=timestamp',
259 'end' => 'Timestamp to end listing at. Can only be used with cmsort=timestamp',
260 'startsortkey' => 'Sortkey to start listing from. Can only be used with cmsort=sortkey',
261 'endsortkey' => 'Sortkey to end listing at. Can only be used with cmsort=sortkey',
262 'continue' => 'For large categories, give the value retured from previous query',
263 'limit' => 'The maximum number of pages to return.',
264 );
265 if ($wgMiserMode) {
266 $desc['namespace'] = array(
267 $desc['namespace'],
268 'NOTE: Due to $wgMiserMode, using this may result in fewer than "limit" results',
269 'returned before continuing; in extreme cases, zero results may be returned.',
270 );
271 }
272 return $desc;
273 }
274
275 public function getDescription() {
276 return 'List all pages in a given category';
277 }
278
279 protected function getExamples() {
280 return array (
281 "Get first 10 pages in [[Category:Physics]]:",
282 " api.php?action=query&list=categorymembers&cmtitle=Category:Physics",
283 "Get page info about first 10 pages in [[Category:Physics]]:",
284 " api.php?action=query&generator=categorymembers&gcmtitle=Category:Physics&prop=info",
285 );
286 }
287
288 public function getVersion() {
289 return __CLASS__ . ': $Id$';
290 }
291 }