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 );
56 * @param $resultPageSet ApiPageSet
59 private function run( $resultPageSet = null ) {
60 $params = $this->extractRequestParams();
62 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
64 if ( isset( $params['title'] ) ) {
65 $categoryTitle = Title
::newFromText( $params['title'] );
67 if ( is_null( $categoryTitle ) ||
$categoryTitle->getNamespace() != NS_CATEGORY
) {
68 $this->dieUsage( 'The category name you entered is not valid', 'invalidcategory' );
70 } elseif( isset( $params['pageid'] ) ) {
71 $categoryTitle = Title
::newFromID( $params['pageid'] );
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' );
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'] );
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 );
93 $this->addFields( $resultPageSet->getPageTableFields() ); // will include page_ id, ns, title
94 $this->addFields( array( 'cl_from', 'cl_sortkey', 'cl_type' ) );
97 $this->addFieldsIf( 'cl_timestamp', $fld_timestamp ||
$params['sort'] == 'timestamp' );
99 $this->addTables( array( 'page', 'categorylinks' ) ); // must be in this order for 'USE INDEX'
101 $this->addWhereFld( 'cl_to', $categoryTitle->getDBkey() );
102 $queryTypes = $params['type'];
105 // Scanning large datasets for rare categories sucks, and I already told
106 // how to have efficient subcategory access :-) ~~~~ (oh well, domas)
109 if ( $wgMiserMode ) {
110 $miser_ns = $params['namespace'];
112 $this->addWhereFld( 'page_namespace', $params['namespace'] );
115 $dir = $params['dir'] == 'asc' ?
'newer' : 'older';
117 if ( $params['sort'] == 'timestamp' ) {
118 $this->addWhereRange( 'cl_timestamp',
123 $this->addOption( 'USE INDEX', 'cl_timestamp' );
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'
133 // Remove the types to skip from $queryTypes
134 $contTypeIndex = array_search( $cont[0], $queryTypes );
135 $queryTypes = array_slice( $queryTypes, $contTypeIndex );
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)";
148 // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
149 $this->addWhereRange( 'cl_sortkey',
151 $params['startsortkey'],
152 $params['endsortkey'] );
153 $this->addWhereRange( 'cl_from', $dir, null, null );
155 $this->addOption( 'USE INDEX', 'cl_sortkey' );
158 $this->addWhere( 'cl_from=page_id' );
160 $limit = $params['limit'];
161 $this->addOption( 'LIMIT', $limit +
1 );
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
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;
178 $res = $this->select( __METHOD__
, array( 'where' => $extraConds ) );
179 $rows = array_merge( $rows, iterator_to_array( $res ) );
180 if ( count( $rows ) >= $limit +
1 ) {
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 );
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
) );
200 $sortkey = bin2hex( $row->cl_sortkey
);
201 $this->setContinueEnumParameter( 'continue',
202 "{$row->cl_type}|$sortkey|{$row->cl_from}"
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 ) ) {
216 if ( is_null( $resultPageSet ) ) {
219 $vals['pageid'] = intval( $row->page_id
);
222 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
223 ApiQueryBase
::addTitleInfo( $vals, $title );
225 if ( $fld_sortkey ) {
226 $vals['sortkey'] = bin2hex( $row->cl_sortkey
);
228 if ( $fld_sortkeyprefix ) {
229 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix
;
232 $vals['type'] = $row->cl_type
;
234 if ( $fld_timestamp ) {
235 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $row->cl_timestamp
);
237 $fit = $this->getResult()->addValue( array( 'query', $this->getModuleName() ),
240 if ( $params['sort'] == 'timestamp' ) {
241 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601
, $row->cl_timestamp
) );
243 $sortkey = bin2hex( $row->cl_sortkey
);
244 $this->setContinueEnumParameter( 'continue',
245 "{$row->cl_type}|$sortkey|{$row->cl_from}"
251 $resultPageSet->processDbRow( $row );
255 if ( is_null( $resultPageSet ) ) {
256 $this->getResult()->setIndexedTagName_internal(
257 array( 'query', $this->getModuleName() ), 'cm' );
261 public function getAllowedParams() {
264 ApiBase
::PARAM_TYPE
=> 'string',
267 ApiBase
::PARAM_TYPE
=> 'integer'
270 ApiBase
::PARAM_DFLT
=> 'ids|title',
271 ApiBase
::PARAM_ISMULTI
=> true,
272 ApiBase
::PARAM_TYPE
=> array (
281 'namespace' => array (
282 ApiBase
::PARAM_ISMULTI
=> true,
283 ApiBase
::PARAM_TYPE
=> 'namespace',
286 ApiBase
::PARAM_ISMULTI
=> true,
287 ApiBase
::PARAM_DFLT
=> 'page|subcat|file',
288 ApiBase
::PARAM_TYPE
=> 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
303 ApiBase
::PARAM_DFLT
=> 'sortkey',
304 ApiBase
::PARAM_TYPE
=> array(
310 ApiBase
::PARAM_DFLT
=> 'asc',
311 ApiBase
::PARAM_TYPE
=> array(
317 ApiBase
::PARAM_TYPE
=> 'timestamp'
320 ApiBase
::PARAM_TYPE
=> 'timestamp'
322 'startsortkey' => null,
323 'endsortkey' => null,
327 public function getParamDescription() {
329 $p = $this->getModulePrefix();
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",
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',
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.',
354 if ( $wgMiserMode ) {
355 $desc['namespace'] = array(
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.",
365 public function getDescription() {
366 return 'List all pages in a given category';
369 public function getPossibleErrors() {
370 return array_merge( parent
::getPossibleErrors(),
371 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
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' ),
380 protected function getExamples() {
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',
389 public function getVersion() {
390 return __CLASS__
. ': $Id$';