Reverted r42528. Links with href="#" make firefox scroll to the top of the page,...
[mediawiki.git] / includes / api / ApiQueryBase.php
blob26792a7a518a33651373ceca43081361d93c7f51
1 <?php
3 /*
4 * Created on Sep 7, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 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');
31 /**
32 * This is a base class for all Query modules.
33 * It provides some common functionality such as constructing various SQL queries.
35 * @ingroup API
37 abstract class ApiQueryBase extends ApiBase {
39 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
41 public function __construct($query, $moduleName, $paramPrefix = '') {
42 parent :: __construct($query->getMain(), $moduleName, $paramPrefix);
43 $this->mQueryModule = $query;
44 $this->mDb = null;
45 $this->resetQueryParams();
48 /**
49 * Blank the internal arrays with query parameters
51 protected function resetQueryParams() {
52 $this->tables = array ();
53 $this->where = array ();
54 $this->fields = array ();
55 $this->options = array ();
56 $this->join_conds = array ();
59 /**
60 * Add a set of tables to the internal array
61 * @param mixed $tables Table name or array of table names
62 * @param mixed $alias Table alias, or null for no alias. Cannot be used with multiple tables
64 protected function addTables($tables, $alias = null) {
65 if (is_array($tables)) {
66 if (!is_null($alias))
67 ApiBase :: dieDebug(__METHOD__, 'Multiple table aliases not supported');
68 $this->tables = array_merge($this->tables, $tables);
69 } else {
70 if (!is_null($alias))
71 $tables = $this->getAliasedName($tables, $alias);
72 $this->tables[] = $tables;
76 /**
77 * Get the SQL for a table name with alias
78 * @param string $table Table name
79 * @param string $alias Alias
80 * @return string SQL
82 protected function getAliasedName($table, $alias) {
83 return $this->getDB()->tableName($table) . ' ' . $alias;
86 /**
87 * Add a set of JOIN conditions to the internal array
89 * JOIN conditions are formatted as array( tablename => array(jointype, conditions)
90 * e.g. array('page' => array('LEFT JOIN', 'page_id=rev_page'))
91 * @param array $join_conds JOIN conditions
93 protected function addJoinConds($join_conds) {
94 if(!is_array($join_conds))
95 ApiBase::dieDebug(__METHOD__, 'Join conditions have to be arrays');
96 $this->join_conds = array_merge($this->join_conds, $join_conds);
99 /**
100 * Add a set of fields to select to the internal array
101 * @param mixed $value Field name or array of field names
103 protected function addFields($value) {
104 if (is_array($value))
105 $this->fields = array_merge($this->fields, $value);
106 else
107 $this->fields[] = $value;
111 * Same as addFields(), but add the fields only if a condition is met
112 * @param mixed $value See addFields()
113 * @param bool $condition If false, do nothing
114 * @return bool $condition
116 protected function addFieldsIf($value, $condition) {
117 if ($condition) {
118 $this->addFields($value);
119 return true;
121 return false;
125 * Add a set of WHERE clauses to the internal array.
126 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
127 * the latter only works if the value is a constant (i.e. not another field)
129 * If $value is an empty array, this function does nothing.
131 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
132 * to "foo=bar AND baz='3' AND bla='foo'"
133 * @param mixed $value String or array
135 protected function addWhere($value) {
136 if (is_array($value)) {
137 // Sanity check: don't insert empty arrays,
138 // Database::makeList() chokes on them
139 if(!empty($value))
140 $this->where = array_merge($this->where, $value);
142 else
143 $this->where[] = $value;
147 * Same as addWhere(), but add the WHERE clauses only if a condition is met
148 * @param mixed $value See addWhere()
149 * @param bool $condition If false, do nothing
150 * @return bool $condition
152 protected function addWhereIf($value, $condition) {
153 if ($condition) {
154 $this->addWhere($value);
155 return true;
157 return false;
161 * Equivalent to addWhere(array($field => $value))
162 * @param string $field Field name
163 * @param string $value Value; ignored if nul;
165 protected function addWhereFld($field, $value) {
166 if (!is_null($value) && !empty($value))
167 $this->where[$field] = $value;
171 * Add a WHERE clause corresponding to a range, and an ORDER BY
172 * clause to sort in the right direction
173 * @param string $field Field name
174 * @param string $dir If 'newer', sort in ascending order, otherwise sort in descending order
175 * @param string $start Value to start the list at. If $dir == 'newer' this is the lower boundary, otherwise it's the upper boundary
176 * @param string $end Value to end the list at. If $dir == 'newer' this is the upper boundary, otherwise it's the lower boundary
178 protected function addWhereRange($field, $dir, $start, $end) {
179 $isDirNewer = ($dir === 'newer');
180 $after = ($isDirNewer ? '>=' : '<=');
181 $before = ($isDirNewer ? '<=' : '>=');
182 $db = $this->getDB();
184 if (!is_null($start))
185 $this->addWhere($field . $after . $db->addQuotes($start));
187 if (!is_null($end))
188 $this->addWhere($field . $before . $db->addQuotes($end));
190 $order = $field . ($isDirNewer ? '' : ' DESC');
191 if (!isset($this->options['ORDER BY']))
192 $this->addOption('ORDER BY', $order);
193 else
194 $this->addOption('ORDER BY', $this->options['ORDER BY'] . ', ' . $order);
198 * Add an option such as LIMIT or USE INDEX
199 * @param string $name Option name
200 * @param string $value Option value
202 protected function addOption($name, $value = null) {
203 if (is_null($value))
204 $this->options[] = $name;
205 else
206 $this->options[$name] = $value;
210 * Execute a SELECT query based on the values in the internal arrays
211 * @param string $method Function the query should be attributed to. You should usually use __METHOD__ here
212 * @return ResultWrapper
214 protected function select($method) {
216 // getDB has its own profileDBIn/Out calls
217 $db = $this->getDB();
219 $this->profileDBIn();
220 $res = $db->select($this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds);
221 $this->profileDBOut();
223 return $res;
227 * Estimate the row count for the SELECT query that would be run if we
228 * called select() right now, and check if it's acceptable.
229 * @return bool true if acceptable, false otherwise
231 protected function checkRowCount() {
232 $db = $this->getDB();
233 $this->profileDBIn();
234 $rowcount = $db->estimateRowCount($this->tables, $this->fields, $this->where, __METHOD__, $this->options);
235 $this->profileDBOut();
237 global $wgAPIMaxDBRows;
238 if($rowcount > $wgAPIMaxDBRows)
239 return false;
240 return true;
244 * Add information (title and namespace) about a Title object to a result array
245 * @param array $arr Result array à la ApiResult
246 * @param Title $title Title object
247 * @param string $prefix Module prefix
249 public static function addTitleInfo(&$arr, $title, $prefix='') {
250 $arr[$prefix . 'ns'] = intval($title->getNamespace());
251 $arr[$prefix . 'title'] = $title->getPrefixedText();
255 * Override this method to request extra fields from the pageSet
256 * using $pageSet->requestField('fieldName')
257 * @param ApiPageSet $pageSet
259 public function requestExtraData($pageSet) {
263 * Get the main Query module
264 * @return ApiQuery
266 public function getQuery() {
267 return $this->mQueryModule;
271 * Add a sub-element under the page element with the given page ID
272 * @param int $pageId Page ID
273 * @param array $data Data array à la ApiResult
275 protected function addPageSubItems($pageId, $data) {
276 $result = $this->getResult();
277 $result->setIndexedTagName($data, $this->getModulePrefix());
278 $result->addValue(array ('query', 'pages', intval($pageId)),
279 $this->getModuleName(),
280 $data);
284 * Set a query-continue value
285 * @param $paramName Parameter name
286 * @param $paramValue Parameter value
288 protected function setContinueEnumParameter($paramName, $paramValue) {
290 $paramName = $this->encodeParamName($paramName);
291 $msg = array( $paramName => $paramValue );
292 $this->getResult()->addValue('query-continue', $this->getModuleName(), $msg);
296 * Get the Query database connection (readonly)
297 * @return Database
299 protected function getDB() {
300 if (is_null($this->mDb))
301 $this->mDb = $this->getQuery()->getDB();
302 return $this->mDb;
306 * Selects the query database connection with the given name.
307 * If no such connection has been requested before, it will be created.
308 * Subsequent calls with the same $name will return the same connection
309 * as the first, regardless of $db or $groups new values.
310 * @param string $name Name to assign to the database connection
311 * @param int $db One of the DB_* constants
312 * @param array $groups Query groups
313 * @return Database
315 public function selectNamedDB($name, $db, $groups) {
316 $this->mDb = $this->getQuery()->getNamedDB($name, $db, $groups);
320 * Get the PageSet object to work on
321 * @return ApiPageSet
323 protected function getPageSet() {
324 return $this->getQuery()->getPageSet();
328 * Convert a title to a DB key
329 * @param string $title Page title with spaces
330 * @return string Page title with underscores
332 public function titleToKey($title) {
333 # Don't throw an error if we got an empty string
334 if(trim($title) == '')
335 return '';
336 $t = Title::newFromText($title);
337 if(!$t)
338 $this->dieUsageMsg(array('invalidtitle', $title));
339 return $t->getDbKey();
343 * The inverse of titleToKey()
344 * @param string $key Page title with underscores
345 * @return string Page title with spaces
347 public function keyToTitle($key) {
348 # Don't throw an error if we got an empty string
349 if(trim($key) == '')
350 return '';
351 $t = Title::newFromDbKey($key);
352 # This really shouldn't happen but we gotta check anyway
353 if(!$t)
354 $this->dieUsageMsg(array('invalidtitle', $key));
355 return $t->getPrefixedText();
359 * An alternative to titleToKey() that doesn't trim trailing spaces
360 * @param string $titlePart Title part with spaces
361 * @return string Title part with underscores
363 public function titlePartToKey($titlePart) {
364 return substr($this->titleToKey($titlePart . 'x'), 0, -1);
368 * An alternative to keyToTitle() that doesn't trim trailing spaces
369 * @param string $keyPart Key part with spaces
370 * @return string Key part with underscores
372 public function keyPartToTitle($keyPart) {
373 return substr($this->keyToTitle($keyPart . 'x'), 0, -1);
377 * Get version string for use in the API help output
378 * @return string
380 public static function getBaseVersion() {
381 return __CLASS__ . ': $Id$';
386 * @ingroup API
388 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
390 private $mIsGenerator;
392 public function __construct($query, $moduleName, $paramPrefix = '') {
393 parent :: __construct($query, $moduleName, $paramPrefix);
394 $this->mIsGenerator = false;
398 * Switch this module to generator mode. By default, generator mode is
399 * switched off and the module acts like a normal query module.
401 public function setGeneratorMode() {
402 $this->mIsGenerator = true;
406 * Overrides base class to prepend 'g' to every generator parameter
408 public function encodeParamName($paramName) {
409 if ($this->mIsGenerator)
410 return 'g' . parent :: encodeParamName($paramName);
411 else
412 return parent :: encodeParamName($paramName);
416 * Execute this module as a generator
417 * @param $resultPageSet PageSet: All output should be appended to this object
419 public abstract function executeGenerator($resultPageSet);