Fixup spaces to tabs from r62404
[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
34 * queries.
35 *
36 * @ingroup API
37 */
38 abstract class ApiQueryBase extends ApiBase {
39
40 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
41
42 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
43 parent :: __construct( $query->getMain(), $moduleName, $paramPrefix );
44 $this->mQueryModule = $query;
45 $this->mDb = null;
46 $this->resetQueryParams();
47 }
48
49 /**
50 * Blank the internal arrays with query parameters
51 */
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 ();
58 }
59
60 /**
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
65 */
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' );
70 $this->tables = array_merge( $this->tables, $tables );
71 } else {
72 if ( !is_null( $alias ) )
73 $tables = $this->getAliasedName( $tables, $alias );
74 $this->tables[] = $tables;
75 }
76 }
77
78 /**
79 * Get the SQL for a table name with alias
80 * @param $table string Table name
81 * @param $alias string Alias
82 * @return string SQL
83 */
84 protected function getAliasedName( $table, $alias ) {
85 return $this->getDB()->tableName( $table ) . ' ' . $alias;
86 }
87
88 /**
89 * Add a set of JOIN conditions to the internal array
90 *
91 * JOIN conditions are formatted as array( tablename => array(jointype,
92 * conditions) e.g. array('page' => array('LEFT JOIN',
93 * 'page_id=rev_page')) . conditions may be a string or an
94 * addWhere()-style array
95 * @param $join_conds array JOIN conditions
96 */
97 protected function addJoinConds( $join_conds ) {
98 if ( !is_array( $join_conds ) )
99 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
100 $this->join_conds = array_merge( $this->join_conds, $join_conds );
101 }
102
103 /**
104 * Add a set of fields to select to the internal array
105 * @param $value mixed Field name or array of field names
106 */
107 protected function addFields( $value ) {
108 if ( is_array( $value ) )
109 $this->fields = array_merge( $this->fields, $value );
110 else
111 $this->fields[] = $value;
112 }
113
114 /**
115 * Same as addFields(), but add the fields only if a condition is met
116 * @param $value mixed See addFields()
117 * @param $condition bool If false, do nothing
118 * @return bool $condition
119 */
120 protected function addFieldsIf( $value, $condition ) {
121 if ( $condition ) {
122 $this->addFields( $value );
123 return true;
124 }
125 return false;
126 }
127
128 /**
129 * Add a set of WHERE clauses to the internal array.
130 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
131 * the latter only works if the value is a constant (i.e. not another field)
132 *
133 * If $value is an empty array, this function does nothing.
134 *
135 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
136 * to "foo=bar AND baz='3' AND bla='foo'"
137 * @param $value mixed String or array
138 */
139 protected function addWhere( $value ) {
140 if ( is_array( $value ) ) {
141 // Sanity check: don't insert empty arrays,
142 // Database::makeList() chokes on them
143 if ( count( $value ) )
144 $this->where = array_merge( $this->where, $value );
145 }
146 else
147 $this->where[] = $value;
148 }
149
150 /**
151 * Same as addWhere(), but add the WHERE clauses only if a condition is met
152 * @param $value mixed See addWhere()
153 * @param $condition boolIf false, do nothing
154 * @return bool $condition
155 */
156 protected function addWhereIf( $value, $condition ) {
157 if ( $condition ) {
158 $this->addWhere( $value );
159 return true;
160 }
161 return false;
162 }
163
164 /**
165 * Equivalent to addWhere(array($field => $value))
166 * @param $field string Field name
167 * @param $value string Value; ignored if null or empty array;
168 */
169 protected function addWhereFld( $field, $value ) {
170 // Use count() to its full documented capabilities to simultaneously
171 // test for null, empty array or empty countable object
172 if ( count( $value ) )
173 $this->where[$field] = $value;
174 }
175
176 /**
177 * Add a WHERE clause corresponding to a range, and an ORDER BY
178 * clause to sort in the right direction
179 * @param $field string Field name
180 * @param $dir string If 'newer', sort in ascending order, otherwise
181 * sort in descending order
182 * @param $start string Value to start the list at. If $dir == 'newer'
183 * this is the lower boundary, otherwise it's the upper boundary
184 * @param $end string Value to end the list at. If $dir == 'newer' this
185 * is the upper boundary, otherwise it's the lower boundary
186 * @param $sort bool If false, don't add an ORDER BY clause
187 */
188 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
189 $isDirNewer = ( $dir === 'newer' );
190 $after = ( $isDirNewer ? '>=' : '<=' );
191 $before = ( $isDirNewer ? '<=' : '>=' );
192 $db = $this->getDB();
193
194 if ( !is_null( $start ) )
195 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
196
197 if ( !is_null( $end ) )
198 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
199
200 if ( $sort ) {
201 $order = $field . ( $isDirNewer ? '' : ' DESC' );
202 if ( !isset( $this->options['ORDER BY'] ) )
203 $this->addOption( 'ORDER BY', $order );
204 else
205 $this->addOption( 'ORDER BY', $this->options['ORDER BY'] . ', ' . $order );
206 }
207 }
208
209 /**
210 * Add an option such as LIMIT or USE INDEX. If an option was set
211 * before, the old value will be overwritten
212 * @param $name string Option name
213 * @param $value string Option value
214 */
215 protected function addOption( $name, $value = null ) {
216 if ( is_null( $value ) )
217 $this->options[] = $name;
218 else
219 $this->options[$name] = $value;
220 }
221
222 /**
223 * Execute a SELECT query based on the values in the internal arrays
224 * @param $method string Function the query should be attributed to.
225 * You should usually use __METHOD__ here
226 * @return ResultWrapper
227 */
228 protected function select( $method ) {
229 // getDB has its own profileDBIn/Out calls
230 $db = $this->getDB();
231
232 $this->profileDBIn();
233 $res = $db->select( $this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds );
234 $this->profileDBOut();
235
236 return $res;
237 }
238
239 /**
240 * Estimate the row count for the SELECT query that would be run if we
241 * called select() right now, and check if it's acceptable.
242 * @return bool true if acceptable, false otherwise
243 */
244 protected function checkRowCount() {
245 $db = $this->getDB();
246 $this->profileDBIn();
247 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
248 $this->profileDBOut();
249
250 global $wgAPIMaxDBRows;
251 if ( $rowcount > $wgAPIMaxDBRows )
252 return false;
253 return true;
254 }
255
256 /**
257 * Add information (title and namespace) about a Title object to a
258 * result array
259 * @param $arr array Result array à la ApiResult
260 * @param $title Title
261 * @param $prefix string Module prefix
262 */
263 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
264 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
265 $arr[$prefix . 'title'] = $title->getPrefixedText();
266 }
267
268 /**
269 * Override this method to request extra fields from the pageSet
270 * using $pageSet->requestField('fieldName')
271 * @param $pageSet ApiPageSet
272 */
273 public function requestExtraData( $pageSet ) {
274 }
275
276 /**
277 * Get the main Query module
278 * @return ApiQuery
279 */
280 public function getQuery() {
281 return $this->mQueryModule;
282 }
283
284 /**
285 * Add a sub-element under the page element with the given page ID
286 * @param $pageId int Page ID
287 * @param $data array Data array à la ApiResult
288 * @return bool Whether the element fit in the result
289 */
290 protected function addPageSubItems( $pageId, $data ) {
291 $result = $this->getResult();
292 $result->setIndexedTagName( $data, $this->getModulePrefix() );
293 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
294 $this->getModuleName(),
295 $data );
296 }
297
298 /**
299 * Same as addPageSubItems(), but one element of $data at a time
300 * @param $pageId int Page ID
301 * @param $data array Data array à la ApiResult
302 * @param $elemname string XML element name. If null, getModuleName()
303 * is used
304 * @return bool Whether the element fit in the result
305 */
306 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
307 if ( is_null( $elemname ) )
308 $elemname = $this->getModulePrefix();
309 $result = $this->getResult();
310 $fit = $result->addValue( array( 'query', 'pages', $pageId,
311 $this->getModuleName() ), null, $item );
312 if ( !$fit )
313 return false;
314 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
315 $this->getModuleName() ), $elemname );
316 return true;
317 }
318
319 /**
320 * Set a query-continue value
321 * @param $paramName string Parameter name
322 * @param $paramValue string Parameter value
323 */
324 protected function setContinueEnumParameter( $paramName, $paramValue ) {
325 $paramName = $this->encodeParamName( $paramName );
326 $msg = array( $paramName => $paramValue );
327 $this->getResult()->disableSizeCheck();
328 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
329 $this->getResult()->enableSizeCheck();
330 }
331
332 /**
333 * Get the Query database connection (read-only)
334 * @return Database
335 */
336 protected function getDB() {
337 if ( is_null( $this->mDb ) )
338 $this->mDb = $this->getQuery()->getDB();
339 return $this->mDb;
340 }
341
342 /**
343 * Selects the query database connection with the given name.
344 * See ApiQuery::getNamedDB() for more information
345 * @param $name string Name to assign to the database connection
346 * @param $db int One of the DB_* constants
347 * @param $groups array Query groups
348 * @return Database
349 */
350 public function selectNamedDB( $name, $db, $groups ) {
351 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
352 }
353
354 /**
355 * Get the PageSet object to work on
356 * @return ApiPageSet
357 */
358 protected function getPageSet() {
359 return $this->getQuery()->getPageSet();
360 }
361
362 /**
363 * Convert a title to a DB key
364 * @param $title string Page title with spaces
365 * @return string Page title with underscores
366 */
367 public function titleToKey( $title ) {
368 // Don't throw an error if we got an empty string
369 if ( trim( $title ) == '' )
370 return '';
371 $t = Title::newFromText( $title );
372 if ( !$t )
373 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
374 return $t->getPrefixedDbKey();
375 }
376
377 /**
378 * The inverse of titleToKey()
379 * @param $key string Page title with underscores
380 * @return string Page title with spaces
381 */
382 public function keyToTitle( $key ) {
383 // Don't throw an error if we got an empty string
384 if ( trim( $key ) == '' )
385 return '';
386 $t = Title::newFromDbKey( $key );
387 // This really shouldn't happen but we gotta check anyway
388 if ( !$t )
389 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
390 return $t->getPrefixedText();
391 }
392
393 /**
394 * An alternative to titleToKey() that doesn't trim trailing spaces
395 * @param $titlePart string Title part with spaces
396 * @return string Title part with underscores
397 */
398 public function titlePartToKey( $titlePart ) {
399 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
400 }
401
402 /**
403 * An alternative to keyToTitle() that doesn't trim trailing spaces
404 * @param $keyPart string Key part with spaces
405 * @return string Key part with underscores
406 */
407 public function keyPartToTitle( $keyPart ) {
408 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
409 }
410
411 public function getPossibleErrors() {
412 return array_merge( parent::getPossibleErrors(), array(
413 array( 'invalidtitle', 'title' ),
414 array( 'invalidtitle', 'key' ),
415 ) );
416 }
417
418 /**
419 * Get version string for use in the API help output
420 * @return string
421 */
422 public static function getBaseVersion() {
423 return __CLASS__ . ': $Id$';
424 }
425 }
426
427 /**
428 * @ingroup API
429 */
430 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
431
432 private $mIsGenerator;
433
434 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
435 parent :: __construct( $query, $moduleName, $paramPrefix );
436 $this->mIsGenerator = false;
437 }
438
439 /**
440 * Switch this module to generator mode. By default, generator mode is
441 * switched off and the module acts like a normal query module.
442 */
443 public function setGeneratorMode() {
444 $this->mIsGenerator = true;
445 }
446
447 /**
448 * Overrides base class to prepend 'g' to every generator parameter
449 * @param $paramNames string Parameter name
450 * @return string Prefixed parameter name
451 */
452 public function encodeParamName( $paramName ) {
453 if ( $this->mIsGenerator )
454 return 'g' . parent :: encodeParamName( $paramName );
455 else
456 return parent :: encodeParamName( $paramName );
457 }
458
459 /**
460 * Execute this module as a generator
461 * @param $resultPageSet ApiPageSet: All output should be appended to
462 * this object
463 */
464 public abstract function executeGenerator( $resultPageSet );
465 }