5 * Created on Sep 7, 2006
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( 'ApiBase.php' );
33 * This is a base class for all Query modules.
34 * It provides some common functionality such as constructing various SQL
39 abstract class ApiQueryBase
extends ApiBase
{
41 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
43 public function __construct( ApiBase
$query, $moduleName, $paramPrefix = '' ) {
44 parent
::__construct( $query->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule
= $query;
47 $this->resetQueryParams();
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()
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.
58 public function getCacheMode( $params ) {
63 * Blank the internal arrays with query parameters
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();
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
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' );
84 $this->tables
= array_merge( $this->tables
, $tables );
86 if ( !is_null( $alias ) ) {
87 $tables = $this->getAliasedName( $tables, $alias );
89 $this->tables
[] = $tables;
94 * Get the SQL for a table name with alias
95 * @param $table string Table name
96 * @param $alias string Alias
99 protected function getAliasedName( $table, $alias ) {
100 return $this->getDB()->tableName( $table ) . ' ' . $alias;
104 * Add a set of JOIN conditions to the internal array
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
112 protected function addJoinConds( $join_conds ) {
113 if ( !is_array( $join_conds ) ) {
114 ApiBase
::dieDebug( __METHOD__
, 'Join conditions have to be arrays' );
116 $this->join_conds
= array_merge( $this->join_conds
, $join_conds );
120 * Add a set of fields to select to the internal array
121 * @param $value mixed Field name or array of field names
123 protected function addFields( $value ) {
124 if ( is_array( $value ) ) {
125 $this->fields
= array_merge( $this->fields
, $value );
127 $this->fields
[] = $value;
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
137 protected function addFieldsIf( $value, $condition ) {
139 $this->addFields( $value );
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)
150 * If $value is an empty array, this function does nothing.
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
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 );
164 $this->where
[] = $value;
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
174 protected function addWhereIf( $value, $condition ) {
176 $this->addWhere( $value );
183 * Equivalent to addWhere(array($field => $value))
184 * @param $field string Field name
185 * @param $value string Value; ignored if null or empty array;
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;
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
207 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
208 $isDirNewer = ( $dir === 'newer' );
209 $after = ( $isDirNewer ?
'>=' : '<=' );
210 $before = ( $isDirNewer ?
'<=' : '>=' );
211 $db = $this->getDB();
213 if ( !is_null( $start ) ) {
214 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
217 if ( !is_null( $end ) ) {
218 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
222 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
223 if ( !isset( $this->options
['ORDER BY'] ) ) {
224 $this->addOption( 'ORDER BY', $order );
226 $this->addOption( 'ORDER BY', $this->options
['ORDER BY'] . ', ' . $order );
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
237 protected function addOption( $name, $value = null ) {
238 if ( is_null( $value ) ) {
239 $this->options
[] = $name;
241 $this->options
[$name] = $value;
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
253 protected function select( $method, $extraQuery = array() ) {
254 $tables = $this->tables
;
255 $fields = $this->fields
;
256 $where = $this->where
;
257 $options = $this->options
;
258 $join_conds = $this->join_conds
;
260 // Merge $this->tables with $extraQuery['tables'], $this->fields with $extraQuery['fields'], etc.
261 foreach ( array( 'tables', 'fields', 'where', 'options', 'join_conds' ) as $var ) {
262 if ( isset( $extraQuery[$var] ) ) {
263 $
$var = array_merge( $
$var, (array)$extraQuery[$var] );
267 // getDB has its own profileDBIn/Out calls
268 $db = $this->getDB();
270 $this->profileDBIn();
271 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
272 $this->profileDBOut();
278 * Estimate the row count for the SELECT query that would be run if we
279 * called select() right now, and check if it's acceptable.
280 * @return bool true if acceptable, false otherwise
282 protected function checkRowCount() {
283 $db = $this->getDB();
284 $this->profileDBIn();
285 $rowcount = $db->estimateRowCount( $this->tables
, $this->fields
, $this->where
, __METHOD__
, $this->options
);
286 $this->profileDBOut();
288 global $wgAPIMaxDBRows;
289 if ( $rowcount > $wgAPIMaxDBRows ) {
296 * Add information (title and namespace) about a Title object to a
298 * @param $arr array Result array à la ApiResult
299 * @param $title Title
300 * @param $prefix string Module prefix
302 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
303 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
304 $arr[$prefix . 'title'] = $title->getPrefixedText();
308 * Override this method to request extra fields from the pageSet
309 * using $pageSet->requestField('fieldName')
310 * @param $pageSet ApiPageSet
312 public function requestExtraData( $pageSet ) {
316 * Get the main Query module
319 public function getQuery() {
320 return $this->mQueryModule
;
324 * Add a sub-element under the page element with the given page ID
325 * @param $pageId int Page ID
326 * @param $data array Data array à la ApiResult
327 * @return bool Whether the element fit in the result
329 protected function addPageSubItems( $pageId, $data ) {
330 $result = $this->getResult();
331 $result->setIndexedTagName( $data, $this->getModulePrefix() );
332 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
333 $this->getModuleName(),
338 * Same as addPageSubItems(), but one element of $data at a time
339 * @param $pageId int Page ID
340 * @param $item array Data array à la ApiResult
341 * @param $elemname string XML element name. If null, getModuleName()
343 * @return bool Whether the element fit in the result
345 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
346 if ( is_null( $elemname ) ) {
347 $elemname = $this->getModulePrefix();
349 $result = $this->getResult();
350 $fit = $result->addValue( array( 'query', 'pages', $pageId,
351 $this->getModuleName() ), null, $item );
355 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
356 $this->getModuleName() ), $elemname );
361 * Set a query-continue value
362 * @param $paramName string Parameter name
363 * @param $paramValue string Parameter value
365 protected function setContinueEnumParameter( $paramName, $paramValue ) {
366 $paramName = $this->encodeParamName( $paramName );
367 $msg = array( $paramName => $paramValue );
368 $this->getResult()->disableSizeCheck();
369 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
370 $this->getResult()->enableSizeCheck();
374 * Get the Query database connection (read-only)
377 protected function getDB() {
378 if ( is_null( $this->mDb
) ) {
379 $apiQuery = $this->getQuery();
380 $this->mDb
= $apiQuery->getDB();
386 * Selects the query database connection with the given name.
387 * See ApiQuery::getNamedDB() for more information
388 * @param $name string Name to assign to the database connection
389 * @param $db int One of the DB_* constants
390 * @param $groups array Query groups
393 public function selectNamedDB( $name, $db, $groups ) {
394 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
398 * Get the PageSet object to work on
401 protected function getPageSet() {
402 return $this->getQuery()->getPageSet();
406 * Convert a title to a DB key
407 * @param $title string Page title with spaces
408 * @return string Page title with underscores
410 public function titleToKey( $title ) {
411 // Don't throw an error if we got an empty string
412 if ( trim( $title ) == '' ) {
415 $t = Title
::newFromText( $title );
417 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
419 return $t->getPrefixedDbKey();
423 * The inverse of titleToKey()
424 * @param $key string Page title with underscores
425 * @return string Page title with spaces
427 public function keyToTitle( $key ) {
428 // Don't throw an error if we got an empty string
429 if ( trim( $key ) == '' ) {
432 $t = Title
::newFromDbKey( $key );
433 // This really shouldn't happen but we gotta check anyway
435 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
437 return $t->getPrefixedText();
441 * An alternative to titleToKey() that doesn't trim trailing spaces
442 * @param $titlePart string Title part with spaces
443 * @return string Title part with underscores
445 public function titlePartToKey( $titlePart ) {
446 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
450 * An alternative to keyToTitle() that doesn't trim trailing spaces
451 * @param $keyPart string Key part with spaces
452 * @return string Key part with underscores
454 public function keyPartToTitle( $keyPart ) {
455 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
459 * Gets the personalised direction parameter description
461 * @param string $p ModulePrefix
462 * @param string $extraDirText Any extra text to be appended on the description
465 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
467 "In which direction to enumerate{$extraDirText}",
468 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
469 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
474 * @param $query String
475 * @param $protocol String
476 * @return null|string
478 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
479 $db = $this->getDb();
480 if ( !is_null( $query ) ||
$query != '' ) {
481 if ( is_null( $protocol ) ) {
482 $protocol = 'http://';
485 $likeQuery = LinkFilter
::makeLikeArray( $query, $protocol );
487 $this->dieUsage( 'Invalid query', 'bad_query' );
490 $likeQuery = LinkFilter
::keepOneWildcard( $likeQuery );
491 return 'el_index ' . $db->buildLike( $likeQuery );
492 } elseif ( !is_null( $protocol ) ) {
493 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
500 * Filters hidden users (where the user doesn't have the right to view them)
501 * Also adds relevant block information
503 * @param bool $showBlockInfo
506 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
508 $userCanViewHiddenUsers = $wgUser->isAllowed( 'hideuser' );
510 if ( $showBlockInfo ||
!$userCanViewHiddenUsers ) {
511 $this->addTables( 'ipblocks' );
512 $this->addJoinConds( array(
513 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
516 $this->addFields( 'ipb_deleted' );
518 if ( $showBlockInfo ) {
519 $this->addFields( array( 'ipb_reason', 'ipb_by_text', 'ipb_expiry' ) );
522 // Don't show hidden names
523 if ( !$userCanViewHiddenUsers ) {
524 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
529 public function getPossibleErrors() {
530 return array_merge( parent
::getPossibleErrors(), array(
531 array( 'invalidtitle', 'title' ),
532 array( 'invalidtitle', 'key' ),
537 * Get version string for use in the API help output
540 public static function getBaseVersion() {
541 return __CLASS__
. ': $Id$';
548 abstract class ApiQueryGeneratorBase
extends ApiQueryBase
{
550 private $mIsGenerator;
552 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
553 parent
::__construct( $query, $moduleName, $paramPrefix );
554 $this->mIsGenerator
= false;
558 * Switch this module to generator mode. By default, generator mode is
559 * switched off and the module acts like a normal query module.
561 public function setGeneratorMode() {
562 $this->mIsGenerator
= true;
566 * Overrides base class to prepend 'g' to every generator parameter
567 * @param $paramName string Parameter name
568 * @return string Prefixed parameter name
570 public function encodeParamName( $paramName ) {
571 if ( $this->mIsGenerator
) {
572 return 'g' . parent
::encodeParamName( $paramName );
574 return parent
::encodeParamName( $paramName );
579 * Execute this module as a generator
580 * @param $resultPageSet ApiPageSet: All output should be appended to
583 public abstract function executeGenerator( $resultPageSet );