975dbb28365a4591c89092d97f3926e0be6bf7f0
[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 © 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 }
71 $this->tables = array_merge( $this->tables, $tables );
72 } else {
73 if ( !is_null( $alias ) ) {
74 $tables = $this->getAliasedName( $tables, $alias );
75 }
76 $this->tables[] = $tables;
77 }
78 }
79
80 /**
81 * Get the SQL for a table name with alias
82 * @param $table string Table name
83 * @param $alias string Alias
84 * @return string SQL
85 */
86 protected function getAliasedName( $table, $alias ) {
87 return $this->getDB()->tableName( $table ) . ' ' . $alias;
88 }
89
90 /**
91 * Add a set of JOIN conditions to the internal array
92 *
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
98 */
99 protected function addJoinConds( $join_conds ) {
100 if ( !is_array( $join_conds ) ) {
101 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
102 }
103 $this->join_conds = array_merge( $this->join_conds, $join_conds );
104 }
105
106 /**
107 * Add a set of fields to select to the internal array
108 * @param $value mixed Field name or array of field names
109 */
110 protected function addFields( $value ) {
111 if ( is_array( $value ) ) {
112 $this->fields = array_merge( $this->fields, $value );
113 } else {
114 $this->fields[] = $value;
115 }
116 }
117
118 /**
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
123 */
124 protected function addFieldsIf( $value, $condition ) {
125 if ( $condition ) {
126 $this->addFields( $value );
127 return true;
128 }
129 return false;
130 }
131
132 /**
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)
136 *
137 * If $value is an empty array, this function does nothing.
138 *
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
142 */
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 );
149 }
150 } else {
151 $this->where[] = $value;
152 }
153 }
154
155 /**
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
160 */
161 protected function addWhereIf( $value, $condition ) {
162 if ( $condition ) {
163 $this->addWhere( $value );
164 return true;
165 }
166 return false;
167 }
168
169 /**
170 * Equivalent to addWhere(array($field => $value))
171 * @param $field string Field name
172 * @param $value string Value; ignored if null or empty array;
173 */
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;
179 }
180 }
181
182 /**
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
193 */
194 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
195 $isDirNewer = ( $dir === 'newer' );
196 $after = ( $isDirNewer ? '>=' : '<=' );
197 $before = ( $isDirNewer ? '<=' : '>=' );
198 $db = $this->getDB();
199
200 if ( !is_null( $start ) ) {
201 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
202 }
203
204 if ( !is_null( $end ) ) {
205 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
206 }
207
208 if ( $sort ) {
209 $order = $field . ( $isDirNewer ? '' : ' DESC' );
210 if ( !isset( $this->options['ORDER BY'] ) ) {
211 $this->addOption( 'ORDER BY', $order );
212 } else {
213 $this->addOption( 'ORDER BY', $this->options['ORDER BY'] . ', ' . $order );
214 }
215 }
216 }
217
218 /**
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
223 */
224 protected function addOption( $name, $value = null ) {
225 if ( is_null( $value ) ) {
226 $this->options[] = $name;
227 } else {
228 $this->options[$name] = $value;
229 }
230 }
231
232 /**
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
237 */
238 protected function select( $method ) {
239 // getDB has its own profileDBIn/Out calls
240 $db = $this->getDB();
241
242 $this->profileDBIn();
243 $res = $db->select( $this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds );
244 $this->profileDBOut();
245
246 return $res;
247 }
248
249 /**
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
253 */
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();
259
260 global $wgAPIMaxDBRows;
261 if ( $rowcount > $wgAPIMaxDBRows ) {
262 return false;
263 }
264 return true;
265 }
266
267 /**
268 * Add information (title and namespace) about a Title object to a
269 * result array
270 * @param $arr array Result array à la ApiResult
271 * @param $title Title
272 * @param $prefix string Module prefix
273 */
274 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
275 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
276 $arr[$prefix . 'title'] = $title->getPrefixedText();
277 }
278
279 /**
280 * Override this method to request extra fields from the pageSet
281 * using $pageSet->requestField('fieldName')
282 * @param $pageSet ApiPageSet
283 */
284 public function requestExtraData( $pageSet ) {
285 }
286
287 /**
288 * Get the main Query module
289 * @return ApiQuery
290 */
291 public function getQuery() {
292 return $this->mQueryModule;
293 }
294
295 /**
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
300 */
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(),
306 $data );
307 }
308
309 /**
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()
314 * is used
315 * @return bool Whether the element fit in the result
316 */
317 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
318 if ( is_null( $elemname ) ) {
319 $elemname = $this->getModulePrefix();
320 }
321 $result = $this->getResult();
322 $fit = $result->addValue( array( 'query', 'pages', $pageId,
323 $this->getModuleName() ), null, $item );
324 if ( !$fit ) {
325 return false;
326 }
327 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
328 $this->getModuleName() ), $elemname );
329 return true;
330 }
331
332 /**
333 * Set a query-continue value
334 * @param $paramName string Parameter name
335 * @param $paramValue string Parameter value
336 */
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();
343 }
344
345 /**
346 * Get the Query database connection (read-only)
347 * @return Database
348 */
349 protected function getDB() {
350 if ( is_null( $this->mDb ) ) {
351 $this->mDb = $this->getQuery()->getDB();
352 }
353 return $this->mDb;
354 }
355
356 /**
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
362 * @return Database
363 */
364 public function selectNamedDB( $name, $db, $groups ) {
365 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
366 }
367
368 /**
369 * Get the PageSet object to work on
370 * @return ApiPageSet
371 */
372 protected function getPageSet() {
373 return $this->getQuery()->getPageSet();
374 }
375
376 /**
377 * Convert a title to a DB key
378 * @param $title string Page title with spaces
379 * @return string Page title with underscores
380 */
381 public function titleToKey( $title ) {
382 // Don't throw an error if we got an empty string
383 if ( trim( $title ) == '' ) {
384 return '';
385 }
386 $t = Title::newFromText( $title );
387 if ( !$t ) {
388 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
389 }
390 return $t->getPrefixedDbKey();
391 }
392
393 /**
394 * The inverse of titleToKey()
395 * @param $key string Page title with underscores
396 * @return string Page title with spaces
397 */
398 public function keyToTitle( $key ) {
399 // Don't throw an error if we got an empty string
400 if ( trim( $key ) == '' ) {
401 return '';
402 }
403 $t = Title::newFromDbKey( $key );
404 // This really shouldn't happen but we gotta check anyway
405 if ( !$t ) {
406 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
407 }
408 return $t->getPrefixedText();
409 }
410
411 /**
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
415 */
416 public function titlePartToKey( $titlePart ) {
417 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
418 }
419
420 /**
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
424 */
425 public function keyPartToTitle( $keyPart ) {
426 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
427 }
428
429 public function getPossibleErrors() {
430 return array_merge( parent::getPossibleErrors(), array(
431 array( 'invalidtitle', 'title' ),
432 array( 'invalidtitle', 'key' ),
433 ) );
434 }
435
436 /**
437 * Get version string for use in the API help output
438 * @return string
439 */
440 public static function getBaseVersion() {
441 return __CLASS__ . ': $Id$';
442 }
443 }
444
445 /**
446 * @ingroup API
447 */
448 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
449
450 private $mIsGenerator;
451
452 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
453 parent::__construct( $query, $moduleName, $paramPrefix );
454 $this->mIsGenerator = false;
455 }
456
457 /**
458 * Switch this module to generator mode. By default, generator mode is
459 * switched off and the module acts like a normal query module.
460 */
461 public function setGeneratorMode() {
462 $this->mIsGenerator = true;
463 }
464
465 /**
466 * Overrides base class to prepend 'g' to every generator parameter
467 * @param $paramName string Parameter name
468 * @return string Prefixed parameter name
469 */
470 public function encodeParamName( $paramName ) {
471 if ( $this->mIsGenerator ) {
472 return 'g' . parent::encodeParamName( $paramName );
473 } else {
474 return parent::encodeParamName( $paramName );
475 }
476 }
477
478 /**
479 * Execute this module as a generator
480 * @param $resultPageSet ApiPageSet: All output should be appended to
481 * this object
482 */
483 public abstract function executeGenerator( $resultPageSet );
484 }