API: Page prop=imageinfo by (title, timestamp) rather than using an offset. Suggested...
[lhc/web/wiklou.git] / includes / api / ApiQueryBase.php
1 <?php
2
3 /*
4 * Created on Sep 7, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
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.
14 *
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.
19 *
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
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
29 }
30
31 /**
32 * This is a base class for all Query modules.
33 * It provides some common functionality such as constructing various SQL queries.
34 *
35 * @ingroup API
36 */
37 abstract class ApiQueryBase extends ApiBase {
38
39 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
40
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();
46 }
47
48 /**
49 * Blank the internal arrays with query parameters
50 */
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 ();
57 }
58
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
63 */
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;
73 }
74 }
75
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
81 */
82 protected function getAliasedName($table, $alias) {
83 return $this->getDB()->tableName($table) . ' ' . $alias;
84 }
85
86 /**
87 * Add a set of JOIN conditions to the internal array
88 *
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
92 */
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);
97 }
98
99 /**
100 * Add a set of fields to select to the internal array
101 * @param mixed $value Field name or array of field names
102 */
103 protected function addFields($value) {
104 if (is_array($value))
105 $this->fields = array_merge($this->fields, $value);
106 else
107 $this->fields[] = $value;
108 }
109
110 /**
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
115 */
116 protected function addFieldsIf($value, $condition) {
117 if ($condition) {
118 $this->addFields($value);
119 return true;
120 }
121 return false;
122 }
123
124 /**
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)
128 *
129 * If $value is an empty array, this function does nothing.
130 *
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
134 */
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 ( count( $value ) )
140 $this->where = array_merge($this->where, $value);
141 }
142 else
143 $this->where[] = $value;
144 }
145
146 /**
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
151 */
152 protected function addWhereIf($value, $condition) {
153 if ($condition) {
154 $this->addWhere($value);
155 return true;
156 }
157 return false;
158 }
159
160 /**
161 * Equivalent to addWhere(array($field => $value))
162 * @param string $field Field name
163 * @param string $value Value; ignored if null or empty array;
164 */
165 protected function addWhereFld($field, $value) {
166 // Use count() to its full documented capabilities to simultaneously
167 // test for null, empty array or empty countable object
168 if ( count( $value ) )
169 $this->where[$field] = $value;
170 }
171
172 /**
173 * Add a WHERE clause corresponding to a range, and an ORDER BY
174 * clause to sort in the right direction
175 * @param string $field Field name
176 * @param string $dir If 'newer', sort in ascending order, otherwise sort in descending order
177 * @param string $start Value to start the list at. If $dir == 'newer' this is the lower boundary, otherwise it's the upper boundary
178 * @param string $end Value to end the list at. If $dir == 'newer' this is the upper boundary, otherwise it's the lower boundary
179 */
180 protected function addWhereRange($field, $dir, $start, $end) {
181 $isDirNewer = ($dir === 'newer');
182 $after = ($isDirNewer ? '>=' : '<=');
183 $before = ($isDirNewer ? '<=' : '>=');
184 $db = $this->getDB();
185
186 if (!is_null($start))
187 $this->addWhere($field . $after . $db->addQuotes($start));
188
189 if (!is_null($end))
190 $this->addWhere($field . $before . $db->addQuotes($end));
191
192 $order = $field . ($isDirNewer ? '' : ' DESC');
193 if (!isset($this->options['ORDER BY']))
194 $this->addOption('ORDER BY', $order);
195 else
196 $this->addOption('ORDER BY', $this->options['ORDER BY'] . ', ' . $order);
197 }
198
199 /**
200 * Add an option such as LIMIT or USE INDEX
201 * @param string $name Option name
202 * @param string $value Option value
203 */
204 protected function addOption($name, $value = null) {
205 if (is_null($value))
206 $this->options[] = $name;
207 else
208 $this->options[$name] = $value;
209 }
210
211 /**
212 * Execute a SELECT query based on the values in the internal arrays
213 * @param string $method Function the query should be attributed to. You should usually use __METHOD__ here
214 * @return ResultWrapper
215 */
216 protected function select($method) {
217
218 // getDB has its own profileDBIn/Out calls
219 $db = $this->getDB();
220
221 $this->profileDBIn();
222 $res = $db->select($this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds);
223 $this->profileDBOut();
224
225 return $res;
226 }
227
228 /**
229 * Estimate the row count for the SELECT query that would be run if we
230 * called select() right now, and check if it's acceptable.
231 * @return bool true if acceptable, false otherwise
232 */
233 protected function checkRowCount() {
234 $db = $this->getDB();
235 $this->profileDBIn();
236 $rowcount = $db->estimateRowCount($this->tables, $this->fields, $this->where, __METHOD__, $this->options);
237 $this->profileDBOut();
238
239 global $wgAPIMaxDBRows;
240 if($rowcount > $wgAPIMaxDBRows)
241 return false;
242 return true;
243 }
244
245 /**
246 * Add information (title and namespace) about a Title object to a result array
247 * @param array $arr Result array à la ApiResult
248 * @param Title $title Title object
249 * @param string $prefix Module prefix
250 */
251 public static function addTitleInfo(&$arr, $title, $prefix='') {
252 $arr[$prefix . 'ns'] = intval($title->getNamespace());
253 $arr[$prefix . 'title'] = $title->getPrefixedText();
254 }
255
256 /**
257 * Override this method to request extra fields from the pageSet
258 * using $pageSet->requestField('fieldName')
259 * @param ApiPageSet $pageSet
260 */
261 public function requestExtraData($pageSet) {
262 }
263
264 /**
265 * Get the main Query module
266 * @return ApiQuery
267 */
268 public function getQuery() {
269 return $this->mQueryModule;
270 }
271
272 /**
273 * Add a sub-element under the page element with the given page ID
274 * @param int $pageId Page ID
275 * @param array $data Data array à la ApiResult
276 * @return bool Whether the element fit in the result
277 */
278 protected function addPageSubItems($pageId, $data) {
279 $result = $this->getResult();
280 $result->setIndexedTagName($data, $this->getModulePrefix());
281 return $result->addValue(array('query', 'pages', intval($pageId)),
282 $this->getModuleName(),
283 $data);
284 }
285
286 /**
287 * Same as addPageSubItems(), but one element of $data
288 * at a time
289 * @param int $pageId Page ID
290 * @param array $data Data array à la ApiResult
291 * @param string $elemname XML element name. If null, getModuleName() is used
292 * @return bool Whether the element fit in the result
293 */
294 protected function addPageSubItem($pageId, $item, $elemname = null) {
295 if(is_null($elemname))
296 $elemname = $this->getModulePrefix();
297 $result = $this->getResult();
298 $fit = $result->addValue(array('query', 'pages', $pageId,
299 $this->getModuleName()), null, $item);
300 if(!$fit)
301 return false;
302 $result->setIndexedTagName_internal(array('query', 'pages', $pageId,
303 $this->getModuleName()), $elemname);
304 return true;
305 }
306
307 /**
308 * Set a query-continue value
309 * @param $paramName Parameter name
310 * @param $paramValue Parameter value
311 */
312 protected function setContinueEnumParameter($paramName, $paramValue) {
313 $paramName = $this->encodeParamName($paramName);
314 $msg = array( $paramName => $paramValue );
315 $this->getResult()->disableSizeCheck();
316 $this->getResult()->addValue('query-continue', $this->getModuleName(), $msg);
317 $this->getResult()->enableSizeCheck();
318 }
319
320 /**
321 * Get the Query database connection (readonly)
322 * @return Database
323 */
324 protected function getDB() {
325 if (is_null($this->mDb))
326 $this->mDb = $this->getQuery()->getDB();
327 return $this->mDb;
328 }
329
330 /**
331 * Selects the query database connection with the given name.
332 * If no such connection has been requested before, it will be created.
333 * Subsequent calls with the same $name will return the same connection
334 * as the first, regardless of $db or $groups new values.
335 * @param string $name Name to assign to the database connection
336 * @param int $db One of the DB_* constants
337 * @param array $groups Query groups
338 * @return Database
339 */
340 public function selectNamedDB($name, $db, $groups) {
341 $this->mDb = $this->getQuery()->getNamedDB($name, $db, $groups);
342 }
343
344 /**
345 * Get the PageSet object to work on
346 * @return ApiPageSet
347 */
348 protected function getPageSet() {
349 return $this->getQuery()->getPageSet();
350 }
351
352 /**
353 * Convert a title to a DB key
354 * @param string $title Page title with spaces
355 * @return string Page title with underscores
356 */
357 public function titleToKey($title) {
358 # Don't throw an error if we got an empty string
359 if(trim($title) == '')
360 return '';
361 $t = Title::newFromText($title);
362 if(!$t)
363 $this->dieUsageMsg(array('invalidtitle', $title));
364 return $t->getPrefixedDbKey();
365 }
366
367 /**
368 * The inverse of titleToKey()
369 * @param string $key Page title with underscores
370 * @return string Page title with spaces
371 */
372 public function keyToTitle($key) {
373 # Don't throw an error if we got an empty string
374 if(trim($key) == '')
375 return '';
376 $t = Title::newFromDbKey($key);
377 # This really shouldn't happen but we gotta check anyway
378 if(!$t)
379 $this->dieUsageMsg(array('invalidtitle', $key));
380 return $t->getPrefixedText();
381 }
382
383 /**
384 * An alternative to titleToKey() that doesn't trim trailing spaces
385 * @param string $titlePart Title part with spaces
386 * @return string Title part with underscores
387 */
388 public function titlePartToKey($titlePart) {
389 return substr($this->titleToKey($titlePart . 'x'), 0, -1);
390 }
391
392 /**
393 * An alternative to keyToTitle() that doesn't trim trailing spaces
394 * @param string $keyPart Key part with spaces
395 * @return string Key part with underscores
396 */
397 public function keyPartToTitle($keyPart) {
398 return substr($this->keyToTitle($keyPart . 'x'), 0, -1);
399 }
400
401 /**
402 * Get version string for use in the API help output
403 * @return string
404 */
405 public static function getBaseVersion() {
406 return __CLASS__ . ': $Id$';
407 }
408 }
409
410 /**
411 * @ingroup API
412 */
413 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
414
415 private $mIsGenerator;
416
417 public function __construct($query, $moduleName, $paramPrefix = '') {
418 parent :: __construct($query, $moduleName, $paramPrefix);
419 $this->mIsGenerator = false;
420 }
421
422 /**
423 * Switch this module to generator mode. By default, generator mode is
424 * switched off and the module acts like a normal query module.
425 */
426 public function setGeneratorMode() {
427 $this->mIsGenerator = true;
428 }
429
430 /**
431 * Overrides base class to prepend 'g' to every generator parameter
432 */
433 public function encodeParamName($paramName) {
434 if ($this->mIsGenerator)
435 return 'g' . parent :: encodeParamName($paramName);
436 else
437 return parent :: encodeParamName($paramName);
438 }
439
440 /**
441 * Execute this module as a generator
442 * @param $resultPageSet PageSet: All output should be appended to this object
443 */
444 public abstract function executeGenerator($resultPageSet);
445 }