975dbb28365a4591c89092d97f3926e0be6bf7f0
4 * Created on Sep 7, 2006
6 * API for MediaWiki 1.8+
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
32 * This is a base class for all Query modules.
33 * It provides some common functionality such as constructing various SQL
38 abstract class ApiQueryBase
extends ApiBase
{
40 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
42 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
43 parent
::__construct( $query->getMain(), $moduleName, $paramPrefix );
44 $this->mQueryModule
= $query;
46 $this->resetQueryParams();
50 * Blank the internal arrays with query parameters
52 protected function resetQueryParams() {
53 $this->tables
= array();
54 $this->where
= array();
55 $this->fields
= array();
56 $this->options
= array();
57 $this->join_conds
= array();
61 * Add a set of tables to the internal array
62 * @param $tables mixed Table name or array of table names
63 * @param $alias mixed Table alias, or null for no alias. Cannot be
64 * used with multiple tables
66 protected function addTables( $tables, $alias = null ) {
67 if ( is_array( $tables ) ) {
68 if ( !is_null( $alias ) ) {
69 ApiBase
::dieDebug( __METHOD__
, 'Multiple table aliases not supported' );
71 $this->tables
= array_merge( $this->tables
, $tables );
73 if ( !is_null( $alias ) ) {
74 $tables = $this->getAliasedName( $tables, $alias );
76 $this->tables
[] = $tables;
81 * Get the SQL for a table name with alias
82 * @param $table string Table name
83 * @param $alias string Alias
86 protected function getAliasedName( $table, $alias ) {
87 return $this->getDB()->tableName( $table ) . ' ' . $alias;
91 * Add a set of JOIN conditions to the internal array
93 * JOIN conditions are formatted as array( tablename => array(jointype,
94 * conditions) e.g. array('page' => array('LEFT JOIN',
95 * 'page_id=rev_page')) . conditions may be a string or an
96 * addWhere()-style array
97 * @param $join_conds array JOIN conditions
99 protected function addJoinConds( $join_conds ) {
100 if ( !is_array( $join_conds ) ) {
101 ApiBase
::dieDebug( __METHOD__
, 'Join conditions have to be arrays' );
103 $this->join_conds
= array_merge( $this->join_conds
, $join_conds );
107 * Add a set of fields to select to the internal array
108 * @param $value mixed Field name or array of field names
110 protected function addFields( $value ) {
111 if ( is_array( $value ) ) {
112 $this->fields
= array_merge( $this->fields
, $value );
114 $this->fields
[] = $value;
119 * Same as addFields(), but add the fields only if a condition is met
120 * @param $value mixed See addFields()
121 * @param $condition bool If false, do nothing
122 * @return bool $condition
124 protected function addFieldsIf( $value, $condition ) {
126 $this->addFields( $value );
133 * Add a set of WHERE clauses to the internal array.
134 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
135 * the latter only works if the value is a constant (i.e. not another field)
137 * If $value is an empty array, this function does nothing.
139 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
140 * to "foo=bar AND baz='3' AND bla='foo'"
141 * @param $value mixed String or array
143 protected function addWhere( $value ) {
144 if ( is_array( $value ) ) {
145 // Sanity check: don't insert empty arrays,
146 // Database::makeList() chokes on them
147 if ( count( $value ) ) {
148 $this->where
= array_merge( $this->where
, $value );
151 $this->where
[] = $value;
156 * Same as addWhere(), but add the WHERE clauses only if a condition is met
157 * @param $value mixed See addWhere()
158 * @param $condition boolIf false, do nothing
159 * @return bool $condition
161 protected function addWhereIf( $value, $condition ) {
163 $this->addWhere( $value );
170 * Equivalent to addWhere(array($field => $value))
171 * @param $field string Field name
172 * @param $value string Value; ignored if null or empty array;
174 protected function addWhereFld( $field, $value ) {
175 // Use count() to its full documented capabilities to simultaneously
176 // test for null, empty array or empty countable object
177 if ( count( $value ) ) {
178 $this->where
[$field] = $value;
183 * Add a WHERE clause corresponding to a range, and an ORDER BY
184 * clause to sort in the right direction
185 * @param $field string Field name
186 * @param $dir string If 'newer', sort in ascending order, otherwise
187 * sort in descending order
188 * @param $start string Value to start the list at. If $dir == 'newer'
189 * this is the lower boundary, otherwise it's the upper boundary
190 * @param $end string Value to end the list at. If $dir == 'newer' this
191 * is the upper boundary, otherwise it's the lower boundary
192 * @param $sort bool If false, don't add an ORDER BY clause
194 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
195 $isDirNewer = ( $dir === 'newer' );
196 $after = ( $isDirNewer ?
'>=' : '<=' );
197 $before = ( $isDirNewer ?
'<=' : '>=' );
198 $db = $this->getDB();
200 if ( !is_null( $start ) ) {
201 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
204 if ( !is_null( $end ) ) {
205 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
209 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
210 if ( !isset( $this->options
['ORDER BY'] ) ) {
211 $this->addOption( 'ORDER BY', $order );
213 $this->addOption( 'ORDER BY', $this->options
['ORDER BY'] . ', ' . $order );
219 * Add an option such as LIMIT or USE INDEX. If an option was set
220 * before, the old value will be overwritten
221 * @param $name string Option name
222 * @param $value string Option value
224 protected function addOption( $name, $value = null ) {
225 if ( is_null( $value ) ) {
226 $this->options
[] = $name;
228 $this->options
[$name] = $value;
233 * Execute a SELECT query based on the values in the internal arrays
234 * @param $method string Function the query should be attributed to.
235 * You should usually use __METHOD__ here
236 * @return ResultWrapper
238 protected function select( $method ) {
239 // getDB has its own profileDBIn/Out calls
240 $db = $this->getDB();
242 $this->profileDBIn();
243 $res = $db->select( $this->tables
, $this->fields
, $this->where
, $method, $this->options
, $this->join_conds
);
244 $this->profileDBOut();
250 * Estimate the row count for the SELECT query that would be run if we
251 * called select() right now, and check if it's acceptable.
252 * @return bool true if acceptable, false otherwise
254 protected function checkRowCount() {
255 $db = $this->getDB();
256 $this->profileDBIn();
257 $rowcount = $db->estimateRowCount( $this->tables
, $this->fields
, $this->where
, __METHOD__
, $this->options
);
258 $this->profileDBOut();
260 global $wgAPIMaxDBRows;
261 if ( $rowcount > $wgAPIMaxDBRows ) {
268 * Add information (title and namespace) about a Title object to a
270 * @param $arr array Result array à la ApiResult
271 * @param $title Title
272 * @param $prefix string Module prefix
274 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
275 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
276 $arr[$prefix . 'title'] = $title->getPrefixedText();
280 * Override this method to request extra fields from the pageSet
281 * using $pageSet->requestField('fieldName')
282 * @param $pageSet ApiPageSet
284 public function requestExtraData( $pageSet ) {
288 * Get the main Query module
291 public function getQuery() {
292 return $this->mQueryModule
;
296 * Add a sub-element under the page element with the given page ID
297 * @param $pageId int Page ID
298 * @param $data array Data array à la ApiResult
299 * @return bool Whether the element fit in the result
301 protected function addPageSubItems( $pageId, $data ) {
302 $result = $this->getResult();
303 $result->setIndexedTagName( $data, $this->getModulePrefix() );
304 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
305 $this->getModuleName(),
310 * Same as addPageSubItems(), but one element of $data at a time
311 * @param $pageId int Page ID
312 * @param $item array Data array à la ApiResult
313 * @param $elemname string XML element name. If null, getModuleName()
315 * @return bool Whether the element fit in the result
317 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
318 if ( is_null( $elemname ) ) {
319 $elemname = $this->getModulePrefix();
321 $result = $this->getResult();
322 $fit = $result->addValue( array( 'query', 'pages', $pageId,
323 $this->getModuleName() ), null, $item );
327 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
328 $this->getModuleName() ), $elemname );
333 * Set a query-continue value
334 * @param $paramName string Parameter name
335 * @param $paramValue string Parameter value
337 protected function setContinueEnumParameter( $paramName, $paramValue ) {
338 $paramName = $this->encodeParamName( $paramName );
339 $msg = array( $paramName => $paramValue );
340 $this->getResult()->disableSizeCheck();
341 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
342 $this->getResult()->enableSizeCheck();
346 * Get the Query database connection (read-only)
349 protected function getDB() {
350 if ( is_null( $this->mDb
) ) {
351 $this->mDb
= $this->getQuery()->getDB();
357 * Selects the query database connection with the given name.
358 * See ApiQuery::getNamedDB() for more information
359 * @param $name string Name to assign to the database connection
360 * @param $db int One of the DB_* constants
361 * @param $groups array Query groups
364 public function selectNamedDB( $name, $db, $groups ) {
365 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
369 * Get the PageSet object to work on
372 protected function getPageSet() {
373 return $this->getQuery()->getPageSet();
377 * Convert a title to a DB key
378 * @param $title string Page title with spaces
379 * @return string Page title with underscores
381 public function titleToKey( $title ) {
382 // Don't throw an error if we got an empty string
383 if ( trim( $title ) == '' ) {
386 $t = Title
::newFromText( $title );
388 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
390 return $t->getPrefixedDbKey();
394 * The inverse of titleToKey()
395 * @param $key string Page title with underscores
396 * @return string Page title with spaces
398 public function keyToTitle( $key ) {
399 // Don't throw an error if we got an empty string
400 if ( trim( $key ) == '' ) {
403 $t = Title
::newFromDbKey( $key );
404 // This really shouldn't happen but we gotta check anyway
406 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
408 return $t->getPrefixedText();
412 * An alternative to titleToKey() that doesn't trim trailing spaces
413 * @param $titlePart string Title part with spaces
414 * @return string Title part with underscores
416 public function titlePartToKey( $titlePart ) {
417 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
421 * An alternative to keyToTitle() that doesn't trim trailing spaces
422 * @param $keyPart string Key part with spaces
423 * @return string Key part with underscores
425 public function keyPartToTitle( $keyPart ) {
426 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
429 public function getPossibleErrors() {
430 return array_merge( parent
::getPossibleErrors(), array(
431 array( 'invalidtitle', 'title' ),
432 array( 'invalidtitle', 'key' ),
437 * Get version string for use in the API help output
440 public static function getBaseVersion() {
441 return __CLASS__
. ': $Id$';
448 abstract class ApiQueryGeneratorBase
extends ApiQueryBase
{
450 private $mIsGenerator;
452 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
453 parent
::__construct( $query, $moduleName, $paramPrefix );
454 $this->mIsGenerator
= false;
458 * Switch this module to generator mode. By default, generator mode is
459 * switched off and the module acts like a normal query module.
461 public function setGeneratorMode() {
462 $this->mIsGenerator
= true;
466 * Overrides base class to prepend 'g' to every generator parameter
467 * @param $paramName string Parameter name
468 * @return string Prefixed parameter name
470 public function encodeParamName( $paramName ) {
471 if ( $this->mIsGenerator
) {
472 return 'g' . parent
::encodeParamName( $paramName );
474 return parent
::encodeParamName( $paramName );
479 * Execute this module as a generator
480 * @param $resultPageSet ApiPageSet: All output should be appended to
483 public abstract function executeGenerator( $resultPageSet );