]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiQueryCategoryMembers.php
MediaWiki 1.17.4
[autoinstalls/mediawiki.git] / includes / api / ApiQueryCategoryMembers.php
1 <?php
2 /**
3  * API for MediaWiki 1.8+
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                 $categoryTitle = Title::newFromText( $params['title'] );
59
60                 if ( is_null( $categoryTitle ) || $categoryTitle->getNamespace() != NS_CATEGORY ) {
61                         $this->dieUsage( 'The category name you entered is not valid', 'invalidcategory' );
62                 }
63
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'] );
71
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 );
76                 } else {
77                         $this->addFields( $resultPageSet->getPageTableFields() ); // will include page_ id, ns, title
78                         $this->addFields( array( 'cl_from', 'cl_sortkey', 'cl_type' ) );
79                 }
80
81                 $this->addFieldsIf( 'cl_timestamp', $fld_timestamp || $params['sort'] == 'timestamp' );
82
83                 $this->addTables( array( 'page', 'categorylinks' ) );   // must be in this order for 'USE INDEX'
84
85                 $this->addWhereFld( 'cl_to', $categoryTitle->getDBkey() );
86                 $queryTypes = $params['type'];
87                 $contWhere = false;
88
89                 // Scanning large datasets for rare categories sucks, and I already told
90                 // how to have efficient subcategory access :-) ~~~~ (oh well, domas)
91                 global $wgMiserMode;
92                 $miser_ns = array();
93                 if ( $wgMiserMode ) {
94                         $miser_ns = $params['namespace'];
95                 } else {
96                         $this->addWhereFld( 'page_namespace', $params['namespace'] );
97                 }
98
99                 $dir = $params['dir'] == 'asc' ? 'newer' : 'older';
100
101                 if ( $params['sort'] == 'timestamp' ) {
102                         $this->addWhereRange( 'cl_timestamp',
103                                 $dir,
104                                 $params['start'],
105                                 $params['end'] );
106
107                         $this->addOption( 'USE INDEX', 'cl_timestamp' );
108                 } else {
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'
114                                         );
115                                 }
116                                 
117                                 // Remove the types to skip from $queryTypes
118                                 $contTypeIndex = array_search( $cont[0], $queryTypes );
119                                 $queryTypes = array_slice( $queryTypes, $contTypeIndex );
120                                 
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)";
130                                 
131                         } else {
132                                 // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
133                                 $this->addWhereRange( 'cl_sortkey',
134                                         $dir,
135                                         $params['startsortkey'],
136                                         $params['endsortkey'] );
137                                 $this->addWhereRange( 'cl_from', $dir, null, null );
138                         }
139                         $this->addOption( 'USE INDEX', 'cl_sortkey' );
140                 }
141
142                 $this->addWhere( 'cl_from=page_id' );
143
144                 $limit = $params['limit'];
145                 $this->addOption( 'LIMIT', $limit + 1 );
146
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
152                         // and unindexed.
153                         $rows = array();
154                         $first = true;
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;
161                                 }
162                                 $res = $this->select( __METHOD__, array( 'where' => $extraConds ) );
163                                 $rows = array_merge( $rows, iterator_to_array( $res ) );
164                                 if ( count( $rows ) >= $limit + 1 ) {
165                                         break;
166                                 }
167                                 $first = false;
168                         }
169                 } else {
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 );
175                 }
176                 $count = 0;
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 ) );
183                                 } else {
184                                         $sortkey = bin2hex( $row->cl_sortkey );
185                                         $this->setContinueEnumParameter( 'continue',
186                                                 "{$row->cl_type}|$sortkey|{$row->cl_from}"
187                                         );
188                                 }
189                                 break;
190                         }
191
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 ) ) {
197                                 continue;
198                         }
199
200                         if ( is_null( $resultPageSet ) ) {
201                                 $vals = array();
202                                 if ( $fld_ids ) {
203                                         $vals['pageid'] = intval( $row->page_id );
204                                 }
205                                 if ( $fld_title ) {
206                                         $title = Title::makeTitle( $row->page_namespace, $row->page_title );
207                                         ApiQueryBase::addTitleInfo( $vals, $title );
208                                 }
209                                 if ( $fld_sortkey ) {
210                                         $vals['sortkey'] = bin2hex( $row->cl_sortkey );
211                                 }
212                                 if ( $fld_sortkeyprefix ) {
213                                         $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
214                                 }
215                                 if ( $fld_type  ) {
216                                         $vals['type'] = $row->cl_type;
217                                 }
218                                 if ( $fld_timestamp ) {
219                                         $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->cl_timestamp );
220                                 }
221                                 $fit = $this->getResult()->addValue( array( 'query', $this->getModuleName() ),
222                                                 null, $vals );
223                                 if ( !$fit ) {
224                                         if ( $params['sort'] == 'timestamp' ) {
225                                                 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->cl_timestamp ) );
226                                         } else {
227                                                 $sortkey = bin2hex( $row->cl_sortkey );
228                                                 $this->setContinueEnumParameter( 'continue',
229                                                         "{$row->cl_type}|$sortkey|{$row->cl_from}"
230                                                 );
231                                         }
232                                         break;
233                                 }
234                         } else {
235                                 $resultPageSet->processDbRow( $row );
236                         }
237                 }
238
239                 if ( is_null( $resultPageSet ) ) {
240                         $this->getResult()->setIndexedTagName_internal(
241                                          array( 'query', $this->getModuleName() ), 'cm' );
242                 }
243         }
244
245         public function getAllowedParams() {
246                 return array(
247                         'title' => array(
248                                 ApiBase::PARAM_TYPE => 'string',
249                                 ApiBase::PARAM_REQUIRED => true
250                         ),
251                         'prop' => array(
252                                 ApiBase::PARAM_DFLT => 'ids|title',
253                                 ApiBase::PARAM_ISMULTI => true,
254                                 ApiBase::PARAM_TYPE => array (
255                                         'ids',
256                                         'title',
257                                         'sortkey',
258                                         'sortkeyprefix',
259                                         'type',
260                                         'timestamp',
261                                 )
262                         ),
263                         'namespace' => array (
264                                 ApiBase::PARAM_ISMULTI => true,
265                                 ApiBase::PARAM_TYPE => 'namespace',
266                         ),
267                         'type' => array(
268                                 ApiBase::PARAM_ISMULTI => true,
269                                 ApiBase::PARAM_DFLT => 'page|subcat|file',
270                                 ApiBase::PARAM_TYPE => array(
271                                         'page',
272                                         'subcat',
273                                         'file'
274                                 )
275                         ),
276                         'continue' => null,
277                         'limit' => 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
283                         ),
284                         'sort' => array(
285                                 ApiBase::PARAM_DFLT => 'sortkey',
286                                 ApiBase::PARAM_TYPE => array(
287                                         'sortkey',
288                                         'timestamp'
289                                 )
290                         ),
291                         'dir' => array(
292                                 ApiBase::PARAM_DFLT => 'asc',
293                                 ApiBase::PARAM_TYPE => array(
294                                         'asc',
295                                         'desc'
296                                 )
297                         ),
298                         'start' => array(
299                                 ApiBase::PARAM_TYPE => 'timestamp'
300                         ),
301                         'end' => array(
302                                 ApiBase::PARAM_TYPE => 'timestamp'
303                         ),
304                         'startsortkey' => null,
305                         'endsortkey' => null,
306                 );
307         }
308
309         public function getParamDescription() {
310                 global $wgMiserMode;
311                 $p = $this->getModulePrefix();
312                 $desc = array(
313                         'title' => 'Which category to enumerate (required). Must include Category: prefix',
314                         'prop' => array(
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',
322                         ),
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.',
333                 );
334                 if ( $wgMiserMode ) {
335                         $desc['namespace'] = array(
336                                 $desc['namespace'],
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.',
340                         );
341                 }
342                 return $desc;
343         }
344
345         public function getDescription() {
346                 return 'List all pages in a given category';
347         }
348
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' ),
354                 ) );
355         }
356
357         protected function getExamples() {
358                 return array(
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',
363                 );
364         }
365
366         public function getVersion() {
367                 return __CLASS__ . ': $Id$';
368         }
369 }