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 $result = $this->getResult();
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
) );
202 $sortkey = bin2hex( $row->cl_sortkey
);
203 $this->setContinueEnumParameter( 'continue',
204 "{$row->cl_type}|$sortkey|{$row->cl_from}"
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 ) ) {
218 if ( is_null( $resultPageSet ) ) {
221 $vals['pageid'] = intval( $row->page_id
);
224 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
225 ApiQueryBase
::addTitleInfo( $vals, $title );
227 if ( $fld_sortkey ) {
228 $vals['sortkey'] = bin2hex( $row->cl_sortkey
);
230 if ( $fld_sortkeyprefix ) {
231 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix
;
234 $vals['type'] = $row->cl_type
;
236 if ( $fld_timestamp ) {
237 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $row->cl_timestamp
);
239 $fit = $result->addValue( array( 'query', $this->getModuleName() ),
242 if ( $params['sort'] == 'timestamp' ) {
243 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601
, $row->cl_timestamp
) );
245 $sortkey = bin2hex( $row->cl_sortkey
);
246 $this->setContinueEnumParameter( 'continue',
247 "{$row->cl_type}|$sortkey|{$row->cl_from}"
253 $resultPageSet->processDbRow( $row );
257 if ( is_null( $resultPageSet ) ) {
258 $result->setIndexedTagName_internal(
259 array( 'query', $this->getModuleName() ), 'cm' );
263 public function getAllowedParams() {
266 ApiBase
::PARAM_TYPE
=> 'string',
269 ApiBase
::PARAM_TYPE
=> 'integer'
272 ApiBase
::PARAM_DFLT
=> 'ids|title',
273 ApiBase
::PARAM_ISMULTI
=> true,
274 ApiBase
::PARAM_TYPE
=> array (
283 'namespace' => array (
284 ApiBase
::PARAM_ISMULTI
=> true,
285 ApiBase
::PARAM_TYPE
=> 'namespace',
288 ApiBase
::PARAM_ISMULTI
=> true,
289 ApiBase
::PARAM_DFLT
=> 'page|subcat|file',
290 ApiBase
::PARAM_TYPE
=> 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
305 ApiBase
::PARAM_DFLT
=> 'sortkey',
306 ApiBase
::PARAM_TYPE
=> array(
312 ApiBase
::PARAM_DFLT
=> 'asc',
313 ApiBase
::PARAM_TYPE
=> array(
319 ApiBase
::PARAM_TYPE
=> 'timestamp'
322 ApiBase
::PARAM_TYPE
=> 'timestamp'
324 'startsortkey' => null,
325 'endsortkey' => null,
329 public function getParamDescription() {
331 $p = $this->getModulePrefix();
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",
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',
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.',
356 if ( $wgMiserMode ) {
357 $desc['namespace'] = array(
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.",
367 public function getDescription() {
368 return 'List all pages in a given category';
371 public function getPossibleErrors() {
372 return array_merge( parent
::getPossibleErrors(),
373 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
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' ),
382 public function getExamples() {
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',
391 public function getHelpUrls() {
392 return 'http://www.mediawiki.org/wiki/API:Categorymembers';
395 public function getVersion() {
396 return __CLASS__
. ': $Id$';