3 * API for MediaWiki 1.8+
5 * Created on June 14, 2007
7 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiQueryBase.php" );
33 * A query module to enumerate pages that belong to a category.
37 class ApiQueryCategoryMembers extends ApiQueryGeneratorBase {
39 public function __construct( $query, $moduleName ) {
40 parent::__construct( $query, $moduleName, 'cm' );
43 public function execute() {
47 public function getCacheMode( $params ) {
51 public function executeGenerator( $resultPageSet ) {
52 $this->run( $resultPageSet );
55 private function run( $resultPageSet = null ) {
56 $params = $this->extractRequestParams();
58 $categoryTitle = Title::newFromText( $params['title'] );
60 if ( is_null( $categoryTitle ) || $categoryTitle->getNamespace() != NS_CATEGORY ) {
61 $this->dieUsage( 'The category name you entered is not valid', 'invalidcategory' );
64 $prop = array_flip( $params['prop'] );
65 $fld_ids = isset( $prop['ids'] );
66 $fld_title = isset( $prop['title'] );
67 $fld_sortkey = isset( $prop['sortkey'] );
68 $fld_sortkeyprefix = isset( $prop['sortkeyprefix'] );
69 $fld_timestamp = isset( $prop['timestamp'] );
70 $fld_type = isset( $prop['type'] );
72 if ( is_null( $resultPageSet ) ) {
73 $this->addFields( array( 'cl_from', 'cl_sortkey', 'cl_type', 'page_namespace', 'page_title' ) );
74 $this->addFieldsIf( 'page_id', $fld_ids );
75 $this->addFieldsIf( 'cl_sortkey_prefix', $fld_sortkeyprefix );
77 $this->addFields( $resultPageSet->getPageTableFields() ); // will include page_ id, ns, title
78 $this->addFields( array( 'cl_from', 'cl_sortkey', 'cl_type' ) );
81 $this->addFieldsIf( 'cl_timestamp', $fld_timestamp || $params['sort'] == 'timestamp' );
83 $this->addTables( array( 'page', 'categorylinks' ) ); // must be in this order for 'USE INDEX'
85 $this->addWhereFld( 'cl_to', $categoryTitle->getDBkey() );
86 $queryTypes = $params['type'];
89 // Scanning large datasets for rare categories sucks, and I already told
90 // how to have efficient subcategory access :-) ~~~~ (oh well, domas)
94 $miser_ns = $params['namespace'];
96 $this->addWhereFld( 'page_namespace', $params['namespace'] );
99 $dir = $params['dir'] == 'asc' ? 'newer' : 'older';
101 if ( $params['sort'] == 'timestamp' ) {
102 $this->addWhereRange( 'cl_timestamp',
107 $this->addOption( 'USE INDEX', 'cl_timestamp' );
109 if ( $params['continue'] ) {
110 $cont = explode( '|', $params['continue'], 3 );
111 if ( count( $cont ) != 3 ) {
112 $this->dieUsage( 'Invalid continue param. You should pass the original value returned '.
113 'by the previous query', '_badcontinue'
117 // Remove the types to skip from $queryTypes
118 $contTypeIndex = array_search( $cont[0], $queryTypes );
119 $queryTypes = array_slice( $queryTypes, $contTypeIndex );
121 // Add a WHERE clause for sortkey and from
122 // pack( "H*", $foo ) is used to convert hex back to binary
123 $escSortkey = $this->getDB()->addQuotes( pack( "H*", $cont[1] ) );
124 $from = intval( $cont[2] );
125 $op = $dir == 'newer' ? '>' : '<';
126 // $contWhere is used further down
127 $contWhere = "cl_sortkey $op $escSortkey OR " .
128 "(cl_sortkey = $escSortkey AND " .
129 "cl_from $op= $from)";
132 // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
133 $this->addWhereRange( 'cl_sortkey',
135 $params['startsortkey'],
136 $params['endsortkey'] );
137 $this->addWhereRange( 'cl_from', $dir, null, null );
139 $this->addOption( 'USE INDEX', 'cl_sortkey' );
142 $this->addWhere( 'cl_from=page_id' );
144 $limit = $params['limit'];
145 $this->addOption( 'LIMIT', $limit + 1 );
147 if ( $params['sort'] == 'sortkey' ) {
148 // Run a separate SELECT query for each value of cl_type.
149 // This is needed because cl_type is an enum, and MySQL has
150 // inconsistencies between ORDER BY cl_type and
151 // WHERE cl_type >= 'foo' making proper paging impossible
155 foreach ( $queryTypes as $type ) {
156 $extraConds = array( 'cl_type' => $type );
157 if ( $first && $contWhere ) {
158 // Continuation condition. Only added to the
159 // first query, otherwise we'll skip things
160 $extraConds[] = $contWhere;
162 $res = $this->select( __METHOD__, array( 'where' => $extraConds ) );
163 $rows = array_merge( $rows, iterator_to_array( $res ) );
164 if ( count( $rows ) >= $limit + 1 ) {
170 // Sorting by timestamp
171 // No need to worry about per-type queries because we
172 // aren't sorting or filtering by type anyway
173 $res = $this->select( __METHOD__ );
174 $rows = iterator_to_array( $res );
177 foreach ( $rows as $row ) {
178 if ( ++ $count > $limit ) {
179 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
180 // TODO: Security issue - if the user has no right to view next title, it will still be shown
181 if ( $params['sort'] == 'timestamp' ) {
182 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
184 $sortkey = bin2hex( $row->cl_sortkey );
185 $this->setContinueEnumParameter( 'continue',
186 "{$row->cl_type}|$sortkey|{$row->cl_from}"
192 // Since domas won't tell anyone what he told long ago, apply
193 // cmnamespace here. This means the query may return 0 actual
194 // results, but on the other hand it could save returning 5000
195 // useless results to the client. ~~~~
196 if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
200 if ( is_null( $resultPageSet ) ) {
203 $vals['pageid'] = intval( $row->page_id );
206 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
207 ApiQueryBase::addTitleInfo( $vals, $title );
209 if ( $fld_sortkey ) {
210 $vals['sortkey'] = bin2hex( $row->cl_sortkey );
212 if ( $fld_sortkeyprefix ) {
213 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
216 $vals['type'] = $row->cl_type;
218 if ( $fld_timestamp ) {
219 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->cl_timestamp );
221 $fit = $this->getResult()->addValue( array( 'query', $this->getModuleName() ),
224 if ( $params['sort'] == 'timestamp' ) {
225 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
227 $sortkey = bin2hex( $row->cl_sortkey );
228 $this->setContinueEnumParameter( 'continue',
229 "{$row->cl_type}|$sortkey|{$row->cl_from}"
235 $resultPageSet->processDbRow( $row );
239 if ( is_null( $resultPageSet ) ) {
240 $this->getResult()->setIndexedTagName_internal(
241 array( 'query', $this->getModuleName() ), 'cm' );
245 public function getAllowedParams() {
248 ApiBase::PARAM_TYPE => 'string',
249 ApiBase::PARAM_REQUIRED => true
252 ApiBase::PARAM_DFLT => 'ids|title',
253 ApiBase::PARAM_ISMULTI => true,
254 ApiBase::PARAM_TYPE => array (
263 'namespace' => array (
264 ApiBase::PARAM_ISMULTI => true,
265 ApiBase::PARAM_TYPE => 'namespace',
268 ApiBase::PARAM_ISMULTI => true,
269 ApiBase::PARAM_DFLT => 'page|subcat|file',
270 ApiBase::PARAM_TYPE => array(
278 ApiBase::PARAM_TYPE => 'limit',
279 ApiBase::PARAM_DFLT => 10,
280 ApiBase::PARAM_MIN => 1,
281 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
282 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
285 ApiBase::PARAM_DFLT => 'sortkey',
286 ApiBase::PARAM_TYPE => array(
292 ApiBase::PARAM_DFLT => 'asc',
293 ApiBase::PARAM_TYPE => array(
299 ApiBase::PARAM_TYPE => 'timestamp'
302 ApiBase::PARAM_TYPE => 'timestamp'
304 'startsortkey' => null,
305 'endsortkey' => null,
309 public function getParamDescription() {
311 $p = $this->getModulePrefix();
313 'title' => 'Which category to enumerate (required). Must include Category: prefix',
315 'What pieces of information to include',
316 ' ids - Adds the page ID',
317 ' title - Adds the title and namespace ID of the page',
318 ' sortkey - Adds the sortkey used for sorting in the category (hexadecimal string)',
319 ' sortkeyprefix - Adds the sortkey prefix used for sorting in the category (human-readable part of the sortkey)',
320 ' type - Adds the type that the page has been categorised as (page, subcat or file)',
321 ' timestamp - Adds the timestamp of when the page was included',
323 'namespace' => 'Only include pages in these namespaces',
324 'type' => "What type of category members to include. Ignored when {$p}sort=timestamp is set",
325 'sort' => 'Property to sort by',
326 'dir' => 'In which direction to sort',
327 'start' => "Timestamp to start listing from. Can only be used with {$p}sort=timestamp",
328 'end' => "Timestamp to end listing at. Can only be used with {$p}sort=timestamp",
329 'startsortkey' => "Sortkey to start listing from. Can only be used with {$p}sort=sortkey",
330 'endsortkey' => "Sortkey to end listing at. Can only be used with {$p}sort=sortkey",
331 'continue' => 'For large categories, give the value retured from previous query',
332 'limit' => 'The maximum number of pages to return.',
334 if ( $wgMiserMode ) {
335 $desc['namespace'] = array(
337 'NOTE: Due to $wgMiserMode, using this may result in fewer than "limit" results',
338 'returned before continuing; in extreme cases, zero results may be returned.',
339 'Note that you can use cmtype=subcat or cmtype=file instead of cmnamespace=14 or 6.',
345 public function getDescription() {
346 return 'List all pages in a given category';
349 public function getPossibleErrors() {
350 return array_merge( parent::getPossibleErrors(), array(
351 array( 'code' => 'notitle', 'info' => 'The cmtitle parameter is required' ),
352 array( 'code' => 'invalidcategory', 'info' => 'The category name you entered is not valid' ),
353 array( 'code' => 'badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
357 protected function getExamples() {
359 'Get first 10 pages in [[Category:Physics]]:',
360 ' api.php?action=query&list=categorymembers&cmtitle=Category:Physics',
361 'Get page info about first 10 pages in [[Category:Physics]]:',
362 ' api.php?action=query&generator=categorymembers&gcmtitle=Category:Physics&prop=info',
366 public function getVersion() {
367 return __CLASS__ . ': $Id: ApiQueryCategoryMembers.php 86474 2011-04-20 13:22:05Z catrope $';