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');
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 * Get the cache mode for the data generated by this module. Override this
51 * in the module subclass.
53 * Public caching will only be allowed if *all* the modules that supply
54 * data for a given request return a cache mode of public.
56 public function getCacheMode( $params ) {
61 * Blank the internal arrays with query parameters
63 protected function resetQueryParams() {
64 $this->tables = array ();
65 $this->where = array ();
66 $this->fields = array ();
67 $this->options = array ();
68 $this->join_conds = array ();
72 * Add a set of tables to the internal array
73 * @param $tables mixed Table name or array of table names
74 * @param $alias mixed Table alias, or null for no alias. Cannot be
75 * used with multiple tables
77 protected function addTables($tables, $alias = null) {
78 if (is_array($tables)) {
80 ApiBase :: dieDebug(__METHOD__, 'Multiple table aliases not supported');
81 $this->tables = array_merge($this->tables, $tables);
84 $tables = $this->getAliasedName($tables, $alias);
85 $this->tables[] = $tables;
90 * Get the SQL for a table name with alias
91 * @param $table string Table name
92 * @param $alias string Alias
95 protected function getAliasedName($table, $alias) {
96 return $this->getDB()->tableName($table) . ' ' . $alias;
100 * Add a set of JOIN conditions to the internal array
102 * JOIN conditions are formatted as array( tablename => array(jointype,
103 * conditions) e.g. array('page' => array('LEFT JOIN',
104 * 'page_id=rev_page')) . conditions may be a string or an
105 * addWhere()-style array
106 * @param $join_conds array JOIN conditions
108 protected function addJoinConds($join_conds) {
109 if(!is_array($join_conds))
110 ApiBase::dieDebug(__METHOD__, 'Join conditions have to be arrays');
111 $this->join_conds = array_merge($this->join_conds, $join_conds);
115 * Add a set of fields to select to the internal array
116 * @param $value mixed Field name or array of field names
118 protected function addFields($value) {
119 if (is_array($value))
120 $this->fields = array_merge($this->fields, $value);
122 $this->fields[] = $value;
126 * Same as addFields(), but add the fields only if a condition is met
127 * @param $value mixed See addFields()
128 * @param $condition bool If false, do nothing
129 * @return bool $condition
131 protected function addFieldsIf($value, $condition) {
133 $this->addFields($value);
140 * Add a set of WHERE clauses to the internal array.
141 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
142 * the latter only works if the value is a constant (i.e. not another field)
144 * If $value is an empty array, this function does nothing.
146 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
147 * to "foo=bar AND baz='3' AND bla='foo'"
148 * @param $value mixed String or array
150 protected function addWhere($value) {
151 if (is_array($value)) {
152 // Sanity check: don't insert empty arrays,
153 // Database::makeList() chokes on them
154 if ( count( $value ) )
155 $this->where = array_merge($this->where, $value);
158 $this->where[] = $value;
162 * Same as addWhere(), but add the WHERE clauses only if a condition is met
163 * @param $value mixed See addWhere()
164 * @param $condition boolIf false, do nothing
165 * @return bool $condition
167 protected function addWhereIf($value, $condition) {
169 $this->addWhere($value);
176 * Equivalent to addWhere(array($field => $value))
177 * @param $field string Field name
178 * @param $value string Value; ignored if null or empty array;
180 protected function addWhereFld($field, $value) {
181 // Use count() to its full documented capabilities to simultaneously
182 // test for null, empty array or empty countable object
183 if ( count( $value ) )
184 $this->where[$field] = $value;
188 * Add a WHERE clause corresponding to a range, and an ORDER BY
189 * clause to sort in the right direction
190 * @param $field string Field name
191 * @param $dir string If 'newer', sort in ascending order, otherwise
192 * sort in descending order
193 * @param $start string Value to start the list at. If $dir == 'newer'
194 * this is the lower boundary, otherwise it's the upper boundary
195 * @param $end string Value to end the list at. If $dir == 'newer' this
196 * is the upper boundary, otherwise it's the lower boundary
197 * @param $sort bool If false, don't add an ORDER BY clause
199 protected function addWhereRange($field, $dir, $start, $end, $sort = true) {
200 $isDirNewer = ($dir === 'newer');
201 $after = ($isDirNewer ? '>=' : '<=');
202 $before = ($isDirNewer ? '<=' : '>=');
203 $db = $this->getDB();
205 if (!is_null($start))
206 $this->addWhere($field . $after . $db->addQuotes($start));
209 $this->addWhere($field . $before . $db->addQuotes($end));
212 $order = $field . ($isDirNewer ? '' : ' DESC');
213 if (!isset($this->options['ORDER BY']))
214 $this->addOption('ORDER BY', $order);
216 $this->addOption('ORDER BY', $this->options['ORDER BY'] . ', ' . $order);
221 * Add an option such as LIMIT or USE INDEX. If an option was set
222 * before, the old value will be overwritten
223 * @param $name string Option name
224 * @param $value string Option value
226 protected function addOption($name, $value = null) {
228 $this->options[] = $name;
230 $this->options[$name] = $value;
234 * Execute a SELECT query based on the values in the internal arrays
235 * @param $method string Function the query should be attributed to.
236 * You should usually use __METHOD__ here
237 * @return ResultWrapper
239 protected function select($method) {
241 // getDB has its own profileDBIn/Out calls
242 $db = $this->getDB();
244 $this->profileDBIn();
245 $res = $db->select($this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds);
246 $this->profileDBOut();
252 * Estimate the row count for the SELECT query that would be run if we
253 * called select() right now, and check if it's acceptable.
254 * @return bool true if acceptable, false otherwise
256 protected function checkRowCount() {
257 $db = $this->getDB();
258 $this->profileDBIn();
259 $rowcount = $db->estimateRowCount($this->tables, $this->fields, $this->where, __METHOD__, $this->options);
260 $this->profileDBOut();
262 global $wgAPIMaxDBRows;
263 if($rowcount > $wgAPIMaxDBRows)
269 * Add information (title and namespace) about a Title object to a
271 * @param $arr array Result array à la ApiResult
272 * @param $title Title
273 * @param $prefix string Module prefix
275 public static function addTitleInfo(&$arr, $title, $prefix='') {
276 $arr[$prefix . 'ns'] = intval($title->getNamespace());
277 $arr[$prefix . 'title'] = $title->getPrefixedText();
281 * Override this method to request extra fields from the pageSet
282 * using $pageSet->requestField('fieldName')
283 * @param $pageSet ApiPageSet
285 public function requestExtraData($pageSet) {
289 * Get the main Query module
292 public function getQuery() {
293 return $this->mQueryModule;
297 * Add a sub-element under the page element with the given page ID
298 * @param $pageId int Page ID
299 * @param $data array Data array à la ApiResult
300 * @return bool Whether the element fit in the result
302 protected function addPageSubItems($pageId, $data) {
303 $result = $this->getResult();
304 $result->setIndexedTagName($data, $this->getModulePrefix());
305 return $result->addValue(array('query', 'pages', intval($pageId)),
306 $this->getModuleName(),
311 * Same as addPageSubItems(), but one element of $data at a time
312 * @param $pageId int Page ID
313 * @param $data array Data array à la ApiResult
314 * @param $elemname string XML element name. If null, getModuleName()
316 * @return bool Whether the element fit in the result
318 protected function addPageSubItem($pageId, $item, $elemname = null) {
319 if(is_null($elemname))
320 $elemname = $this->getModulePrefix();
321 $result = $this->getResult();
322 $fit = $result->addValue(array('query', 'pages', $pageId,
323 $this->getModuleName()), null, $item);
326 $result->setIndexedTagName_internal(array('query', 'pages', $pageId,
327 $this->getModuleName()), $elemname);
332 * Set a query-continue value
333 * @param $paramName string Parameter name
334 * @param $paramValue string Parameter value
336 protected function setContinueEnumParameter($paramName, $paramValue) {
337 $paramName = $this->encodeParamName($paramName);
338 $msg = array( $paramName => $paramValue );
339 $this->getResult()->disableSizeCheck();
340 $this->getResult()->addValue('query-continue', $this->getModuleName(), $msg);
341 $this->getResult()->enableSizeCheck();
345 * Get the Query database connection (read-only)
348 protected function getDB() {
349 if (is_null($this->mDb))
350 $this->mDb = $this->getQuery()->getDB();
355 * Selects the query database connection with the given name.
356 * See ApiQuery::getNamedDB() for more information
357 * @param $name string Name to assign to the database connection
358 * @param $db int One of the DB_* constants
359 * @param $groups array Query groups
362 public function selectNamedDB($name, $db, $groups) {
363 $this->mDb = $this->getQuery()->getNamedDB($name, $db, $groups);
367 * Get the PageSet object to work on
370 protected function getPageSet() {
371 return $this->getQuery()->getPageSet();
375 * Convert a title to a DB key
376 * @param $title string Page title with spaces
377 * @return string Page title with underscores
379 public function titleToKey($title) {
380 # Don't throw an error if we got an empty string
381 if(trim($title) == '')
383 $t = Title::newFromText($title);
385 $this->dieUsageMsg(array('invalidtitle', $title));
386 return $t->getPrefixedDbKey();
390 * The inverse of titleToKey()
391 * @param $key string Page title with underscores
392 * @return string Page title with spaces
394 public function keyToTitle($key) {
395 # Don't throw an error if we got an empty string
398 $t = Title::newFromDbKey($key);
399 # This really shouldn't happen but we gotta check anyway
401 $this->dieUsageMsg(array('invalidtitle', $key));
402 return $t->getPrefixedText();
406 * An alternative to titleToKey() that doesn't trim trailing spaces
407 * @param $titlePart string Title part with spaces
408 * @return string Title part with underscores
410 public function titlePartToKey($titlePart) {
411 return substr($this->titleToKey($titlePart . 'x'), 0, -1);
415 * An alternative to keyToTitle() that doesn't trim trailing spaces
416 * @param $keyPart string Key part with spaces
417 * @return string Key part with underscores
419 public function keyPartToTitle($keyPart) {
420 return substr($this->keyToTitle($keyPart . 'x'), 0, -1);
424 * Get version string for use in the API help output
427 public static function getBaseVersion() {
428 return __CLASS__ . ': $Id: ApiQueryBase.php 69986 2010-07-27 03:57:39Z tstarling $';
435 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
437 private $mIsGenerator;
439 public function __construct($query, $moduleName, $paramPrefix = '') {
440 parent :: __construct($query, $moduleName, $paramPrefix);
441 $this->mIsGenerator = false;
445 * Switch this module to generator mode. By default, generator mode is
446 * switched off and the module acts like a normal query module.
448 public function setGeneratorMode() {
449 $this->mIsGenerator = true;
453 * Overrides base class to prepend 'g' to every generator parameter
454 * @param $paramNames string Parameter name
455 * @return string Prefixed parameter name
457 public function encodeParamName($paramName) {
458 if ($this->mIsGenerator)
459 return 'g' . parent :: encodeParamName($paramName);
461 return parent :: encodeParamName($paramName);
465 * Execute this module as a generator
466 * @param $resultPageSet ApiPageSet: All output should be appended to
469 public abstract function executeGenerator($resultPageSet);