Per r83812 CR, solve the categorymembers paging problem by doing separate queries...
[lhc/web/wiklou.git] / includes / api / ApiQueryBase.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 7, 2006
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( 'ApiBase.php' );
30 }
31
32 /**
33 * This is a base class for all Query modules.
34 * It provides some common functionality such as constructing various SQL
35 * queries.
36 *
37 * @ingroup API
38 */
39 abstract class ApiQueryBase extends ApiBase {
40
41 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
42
43 public function __construct( ApiBase $query, $moduleName, $paramPrefix = '' ) {
44 parent::__construct( $query->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule = $query;
46 $this->mDb = null;
47 $this->resetQueryParams();
48 }
49
50 /**
51 * Get the cache mode for the data generated by this module. Override
52 * this in the module subclass. For possible return values and other
53 * details about cache modes, see ApiMain::setCacheMode()
54 *
55 * Public caching will only be allowed if *all* the modules that supply
56 * data for a given request return a cache mode of public.
57 */
58 public function getCacheMode( $params ) {
59 return 'private';
60 }
61
62 /**
63 * Blank the internal arrays with query parameters
64 */
65 protected function resetQueryParams() {
66 $this->tables = array();
67 $this->where = array();
68 $this->fields = array();
69 $this->options = array();
70 $this->join_conds = array();
71 }
72
73 /**
74 * Add a set of tables to the internal array
75 * @param $tables mixed Table name or array of table names
76 * @param $alias mixed Table alias, or null for no alias. Cannot be
77 * used with multiple tables
78 */
79 protected function addTables( $tables, $alias = null ) {
80 if ( is_array( $tables ) ) {
81 if ( !is_null( $alias ) ) {
82 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
83 }
84 $this->tables = array_merge( $this->tables, $tables );
85 } else {
86 if ( !is_null( $alias ) ) {
87 $tables = $this->getAliasedName( $tables, $alias );
88 }
89 $this->tables[] = $tables;
90 }
91 }
92
93 /**
94 * Get the SQL for a table name with alias
95 * @param $table string Table name
96 * @param $alias string Alias
97 * @return string SQL
98 */
99 protected function getAliasedName( $table, $alias ) {
100 return $this->getDB()->tableName( $table ) . ' ' . $alias;
101 }
102
103 /**
104 * Add a set of JOIN conditions to the internal array
105 *
106 * JOIN conditions are formatted as array( tablename => array(jointype,
107 * conditions) e.g. array('page' => array('LEFT JOIN',
108 * 'page_id=rev_page')) . conditions may be a string or an
109 * addWhere()-style array
110 * @param $join_conds array JOIN conditions
111 */
112 protected function addJoinConds( $join_conds ) {
113 if ( !is_array( $join_conds ) ) {
114 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
115 }
116 $this->join_conds = array_merge( $this->join_conds, $join_conds );
117 }
118
119 /**
120 * Add a set of fields to select to the internal array
121 * @param $value mixed Field name or array of field names
122 */
123 protected function addFields( $value ) {
124 if ( is_array( $value ) ) {
125 $this->fields = array_merge( $this->fields, $value );
126 } else {
127 $this->fields[] = $value;
128 }
129 }
130
131 /**
132 * Same as addFields(), but add the fields only if a condition is met
133 * @param $value mixed See addFields()
134 * @param $condition bool If false, do nothing
135 * @return bool $condition
136 */
137 protected function addFieldsIf( $value, $condition ) {
138 if ( $condition ) {
139 $this->addFields( $value );
140 return true;
141 }
142 return false;
143 }
144
145 /**
146 * Add a set of WHERE clauses to the internal array.
147 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
148 * the latter only works if the value is a constant (i.e. not another field)
149 *
150 * If $value is an empty array, this function does nothing.
151 *
152 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
153 * to "foo=bar AND baz='3' AND bla='foo'"
154 * @param $value mixed String or array
155 */
156 protected function addWhere( $value ) {
157 if ( is_array( $value ) ) {
158 // Sanity check: don't insert empty arrays,
159 // Database::makeList() chokes on them
160 if ( count( $value ) ) {
161 $this->where = array_merge( $this->where, $value );
162 }
163 } else {
164 $this->where[] = $value;
165 }
166 }
167
168 /**
169 * Same as addWhere(), but add the WHERE clauses only if a condition is met
170 * @param $value mixed See addWhere()
171 * @param $condition bool If false, do nothing
172 * @return bool $condition
173 */
174 protected function addWhereIf( $value, $condition ) {
175 if ( $condition ) {
176 $this->addWhere( $value );
177 return true;
178 }
179 return false;
180 }
181
182 /**
183 * Equivalent to addWhere(array($field => $value))
184 * @param $field string Field name
185 * @param $value string Value; ignored if null or empty array;
186 */
187 protected function addWhereFld( $field, $value ) {
188 // Use count() to its full documented capabilities to simultaneously
189 // test for null, empty array or empty countable object
190 if ( count( $value ) ) {
191 $this->where[$field] = $value;
192 }
193 }
194
195 /**
196 * Add a WHERE clause corresponding to a range, and an ORDER BY
197 * clause to sort in the right direction
198 * @param $field string Field name
199 * @param $dir string If 'newer', sort in ascending order, otherwise
200 * sort in descending order
201 * @param $start string Value to start the list at. If $dir == 'newer'
202 * this is the lower boundary, otherwise it's the upper boundary
203 * @param $end string Value to end the list at. If $dir == 'newer' this
204 * is the upper boundary, otherwise it's the lower boundary
205 * @param $sort bool If false, don't add an ORDER BY clause
206 */
207 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
208 $isDirNewer = ( $dir === 'newer' );
209 $after = ( $isDirNewer ? '>=' : '<=' );
210 $before = ( $isDirNewer ? '<=' : '>=' );
211 $db = $this->getDB();
212
213 if ( !is_null( $start ) ) {
214 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
215 }
216
217 if ( !is_null( $end ) ) {
218 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
219 }
220
221 if ( $sort ) {
222 $order = $field . ( $isDirNewer ? '' : ' DESC' );
223 if ( !isset( $this->options['ORDER BY'] ) ) {
224 $this->addOption( 'ORDER BY', $order );
225 } else {
226 $this->addOption( 'ORDER BY', $this->options['ORDER BY'] . ', ' . $order );
227 }
228 }
229 }
230
231 /**
232 * Add an option such as LIMIT or USE INDEX. If an option was set
233 * before, the old value will be overwritten
234 * @param $name string Option name
235 * @param $value string Option value
236 */
237 protected function addOption( $name, $value = null ) {
238 if ( is_null( $value ) ) {
239 $this->options[] = $name;
240 } else {
241 $this->options[$name] = $value;
242 }
243 }
244
245 /**
246 * Execute a SELECT query based on the values in the internal arrays
247 * @param $method string Function the query should be attributed to.
248 * You should usually use __METHOD__ here
249 * @param $extraQuery array Query data to add but not store in the object
250 * Format is array( 'tables' => ..., 'fields' => ..., 'where' => ..., 'options' => ..., 'join_conds' => ... )
251 * @return ResultWrapper
252 */
253 protected function select( $method, $extraQuery = array() ) {
254 // Merge $this->tables with $extraQuery['tables'], $this->fields with $extraQuery['fields'], etc.
255 foreach ( array( 'tables', 'fields', 'where', 'options', 'join_conds' ) as $var ) {
256 $$var = array_merge( $this->{$var}, isset( $extraQuery[$var] ) ? (array)$extraQuery[$var] : array() );
257 }
258
259 // getDB has its own profileDBIn/Out calls
260 $db = $this->getDB();
261
262 $this->profileDBIn();
263 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
264 $this->profileDBOut();
265
266 return $res;
267 }
268
269 /**
270 * Estimate the row count for the SELECT query that would be run if we
271 * called select() right now, and check if it's acceptable.
272 * @return bool true if acceptable, false otherwise
273 */
274 protected function checkRowCount() {
275 $db = $this->getDB();
276 $this->profileDBIn();
277 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
278 $this->profileDBOut();
279
280 global $wgAPIMaxDBRows;
281 if ( $rowcount > $wgAPIMaxDBRows ) {
282 return false;
283 }
284 return true;
285 }
286
287 /**
288 * Add information (title and namespace) about a Title object to a
289 * result array
290 * @param $arr array Result array à la ApiResult
291 * @param $title Title
292 * @param $prefix string Module prefix
293 */
294 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
295 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
296 $arr[$prefix . 'title'] = $title->getPrefixedText();
297 }
298
299 /**
300 * Override this method to request extra fields from the pageSet
301 * using $pageSet->requestField('fieldName')
302 * @param $pageSet ApiPageSet
303 */
304 public function requestExtraData( $pageSet ) {
305 }
306
307 /**
308 * Get the main Query module
309 * @return ApiQuery
310 */
311 public function getQuery() {
312 return $this->mQueryModule;
313 }
314
315 /**
316 * Add a sub-element under the page element with the given page ID
317 * @param $pageId int Page ID
318 * @param $data array Data array à la ApiResult
319 * @return bool Whether the element fit in the result
320 */
321 protected function addPageSubItems( $pageId, $data ) {
322 $result = $this->getResult();
323 $result->setIndexedTagName( $data, $this->getModulePrefix() );
324 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
325 $this->getModuleName(),
326 $data );
327 }
328
329 /**
330 * Same as addPageSubItems(), but one element of $data at a time
331 * @param $pageId int Page ID
332 * @param $item array Data array à la ApiResult
333 * @param $elemname string XML element name. If null, getModuleName()
334 * is used
335 * @return bool Whether the element fit in the result
336 */
337 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
338 if ( is_null( $elemname ) ) {
339 $elemname = $this->getModulePrefix();
340 }
341 $result = $this->getResult();
342 $fit = $result->addValue( array( 'query', 'pages', $pageId,
343 $this->getModuleName() ), null, $item );
344 if ( !$fit ) {
345 return false;
346 }
347 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
348 $this->getModuleName() ), $elemname );
349 return true;
350 }
351
352 /**
353 * Set a query-continue value
354 * @param $paramName string Parameter name
355 * @param $paramValue string Parameter value
356 */
357 protected function setContinueEnumParameter( $paramName, $paramValue ) {
358 $paramName = $this->encodeParamName( $paramName );
359 $msg = array( $paramName => $paramValue );
360 $this->getResult()->disableSizeCheck();
361 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
362 $this->getResult()->enableSizeCheck();
363 }
364
365 /**
366 * Get the Query database connection (read-only)
367 * @return Database
368 */
369 protected function getDB() {
370 if ( is_null( $this->mDb ) ) {
371 $apiQuery = $this->getQuery();
372 $this->mDb = $apiQuery->getDB();
373 }
374 return $this->mDb;
375 }
376
377 /**
378 * Selects the query database connection with the given name.
379 * See ApiQuery::getNamedDB() for more information
380 * @param $name string Name to assign to the database connection
381 * @param $db int One of the DB_* constants
382 * @param $groups array Query groups
383 * @return Database
384 */
385 public function selectNamedDB( $name, $db, $groups ) {
386 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
387 }
388
389 /**
390 * Get the PageSet object to work on
391 * @return ApiPageSet
392 */
393 protected function getPageSet() {
394 return $this->getQuery()->getPageSet();
395 }
396
397 /**
398 * Convert a title to a DB key
399 * @param $title string Page title with spaces
400 * @return string Page title with underscores
401 */
402 public function titleToKey( $title ) {
403 // Don't throw an error if we got an empty string
404 if ( trim( $title ) == '' ) {
405 return '';
406 }
407 $t = Title::newFromText( $title );
408 if ( !$t ) {
409 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
410 }
411 return $t->getPrefixedDbKey();
412 }
413
414 /**
415 * The inverse of titleToKey()
416 * @param $key string Page title with underscores
417 * @return string Page title with spaces
418 */
419 public function keyToTitle( $key ) {
420 // Don't throw an error if we got an empty string
421 if ( trim( $key ) == '' ) {
422 return '';
423 }
424 $t = Title::newFromDbKey( $key );
425 // This really shouldn't happen but we gotta check anyway
426 if ( !$t ) {
427 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
428 }
429 return $t->getPrefixedText();
430 }
431
432 /**
433 * An alternative to titleToKey() that doesn't trim trailing spaces
434 * @param $titlePart string Title part with spaces
435 * @return string Title part with underscores
436 */
437 public function titlePartToKey( $titlePart ) {
438 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
439 }
440
441 /**
442 * An alternative to keyToTitle() that doesn't trim trailing spaces
443 * @param $keyPart string Key part with spaces
444 * @return string Key part with underscores
445 */
446 public function keyPartToTitle( $keyPart ) {
447 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
448 }
449
450 /**
451 * Gets the personalised direction parameter description
452 *
453 * @param string $p ModulePrefix
454 * @param string $extraDirText Any extra text to be appended on the description
455 * @return array
456 */
457 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
458 return array(
459 "In which direction to enumerate{$extraDirText}",
460 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
461 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
462 );
463 }
464
465 /**
466 * @param $query String
467 * @param $protocol String
468 * @return null|string
469 */
470 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
471 $db = $this->getDb();
472 if ( !is_null( $query ) || $query != '' ) {
473 if ( is_null( $protocol ) ) {
474 $protocol = 'http://';
475 }
476
477 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
478 if ( !$likeQuery ) {
479 $this->dieUsage( 'Invalid query', 'bad_query' );
480 }
481
482 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
483 return 'el_index ' . $db->buildLike( $likeQuery );
484 } elseif ( !is_null( $protocol ) ) {
485 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
486 }
487
488 return null;
489 }
490
491 /**
492 * Filters hidden users (where the user doesn't have the right to view them)
493 * Also adds relevant block information
494 *
495 * @param bool $showBlockInfo
496 * @return void
497 */
498 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
499 global $wgUser;
500 $userCanViewHiddenUsers = $wgUser->isAllowed( 'hideuser' );
501
502 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
503 $this->addTables( 'ipblocks' );
504 $this->addJoinConds( array(
505 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
506 ) );
507
508 $this->addFields( 'ipb_deleted' );
509
510 if ( $showBlockInfo ) {
511 $this->addFields( array( 'ipb_reason', 'ipb_by_text', 'ipb_expiry' ) );
512 }
513
514 // Don't show hidden names
515 if ( !$userCanViewHiddenUsers ) {
516 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
517 }
518 }
519 }
520
521 public function getPossibleErrors() {
522 return array_merge( parent::getPossibleErrors(), array(
523 array( 'invalidtitle', 'title' ),
524 array( 'invalidtitle', 'key' ),
525 ) );
526 }
527
528 /**
529 * Get version string for use in the API help output
530 * @return string
531 */
532 public static function getBaseVersion() {
533 return __CLASS__ . ': $Id$';
534 }
535 }
536
537 /**
538 * @ingroup API
539 */
540 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
541
542 private $mIsGenerator;
543
544 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
545 parent::__construct( $query, $moduleName, $paramPrefix );
546 $this->mIsGenerator = false;
547 }
548
549 /**
550 * Switch this module to generator mode. By default, generator mode is
551 * switched off and the module acts like a normal query module.
552 */
553 public function setGeneratorMode() {
554 $this->mIsGenerator = true;
555 }
556
557 /**
558 * Overrides base class to prepend 'g' to every generator parameter
559 * @param $paramName string Parameter name
560 * @return string Prefixed parameter name
561 */
562 public function encodeParamName( $paramName ) {
563 if ( $this->mIsGenerator ) {
564 return 'g' . parent::encodeParamName( $paramName );
565 } else {
566 return parent::encodeParamName( $paramName );
567 }
568 }
569
570 /**
571 * Execute this module as a generator
572 * @param $resultPageSet ApiPageSet: All output should be appended to
573 * this object
574 */
575 public abstract function executeGenerator( $resultPageSet );
576 }