Followup r85884
[lhc/web/wiklou.git] / includes / api / ApiQueryBase.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 7, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
30 }
31
32 /**
33 * This is a base class for all Query modules.
34 * It provides some common functionality such as constructing various SQL
35 * queries.
36 *
37 * @ingroup API
38 */
39 abstract class ApiQueryBase extends ApiBase {
40
41 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
42
43 public function __construct( ApiBase $query, $moduleName, $paramPrefix = '' ) {
44 parent::__construct( $query->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule = $query;
46 $this->mDb = null;
47 $this->resetQueryParams();
48 }
49
50 /**
51 * Get the cache mode for the data generated by this module. Override
52 * this in the module subclass. For possible return values and other
53 * details about cache modes, see ApiMain::setCacheMode()
54 *
55 * Public caching will only be allowed if *all* the modules that supply
56 * data for a given request return a cache mode of public.
57 */
58 public function getCacheMode( $params ) {
59 return 'private';
60 }
61
62 /**
63 * Blank the internal arrays with query parameters
64 */
65 protected function resetQueryParams() {
66 $this->tables = array();
67 $this->where = array();
68 $this->fields = array();
69 $this->options = array();
70 $this->join_conds = array();
71 }
72
73 /**
74 * Add a set of tables to the internal array
75 * @param $tables mixed Table name or array of table names
76 * @param $alias mixed Table alias, or null for no alias. Cannot be
77 * used with multiple tables
78 */
79 protected function addTables( $tables, $alias = null ) {
80 if ( is_array( $tables ) ) {
81 if ( !is_null( $alias ) ) {
82 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
83 }
84 $this->tables = array_merge( $this->tables, $tables );
85 } else {
86 if ( !is_null( $alias ) ) {
87 $this->tables[$alias] = $tables;
88 } else {
89 $this->tables[] = $tables;
90 }
91 }
92 }
93
94 /**
95 * Add a set of JOIN conditions to the internal array
96 *
97 * JOIN conditions are formatted as array( tablename => array(jointype,
98 * conditions) e.g. array('page' => array('LEFT JOIN',
99 * 'page_id=rev_page')) . conditions may be a string or an
100 * addWhere()-style array
101 * @param $join_conds array JOIN conditions
102 */
103 protected function addJoinConds( $join_conds ) {
104 if ( !is_array( $join_conds ) ) {
105 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
106 }
107 $this->join_conds = array_merge( $this->join_conds, $join_conds );
108 }
109
110 /**
111 * Add a set of fields to select to the internal array
112 * @param $value mixed Field name or array of field names
113 */
114 protected function addFields( $value ) {
115 if ( is_array( $value ) ) {
116 $this->fields = array_merge( $this->fields, $value );
117 } else {
118 $this->fields[] = $value;
119 }
120 }
121
122 /**
123 * Same as addFields(), but add the fields only if a condition is met
124 * @param $value mixed See addFields()
125 * @param $condition bool If false, do nothing
126 * @return bool $condition
127 */
128 protected function addFieldsIf( $value, $condition ) {
129 if ( $condition ) {
130 $this->addFields( $value );
131 return true;
132 }
133 return false;
134 }
135
136 /**
137 * Add a set of WHERE clauses to the internal array.
138 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
139 * the latter only works if the value is a constant (i.e. not another field)
140 *
141 * If $value is an empty array, this function does nothing.
142 *
143 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
144 * to "foo=bar AND baz='3' AND bla='foo'"
145 * @param $value mixed String or array
146 */
147 protected function addWhere( $value ) {
148 if ( is_array( $value ) ) {
149 // Sanity check: don't insert empty arrays,
150 // Database::makeList() chokes on them
151 if ( count( $value ) ) {
152 $this->where = array_merge( $this->where, $value );
153 }
154 } else {
155 $this->where[] = $value;
156 }
157 }
158
159 /**
160 * Same as addWhere(), but add the WHERE clauses only if a condition is met
161 * @param $value mixed See addWhere()
162 * @param $condition bool If false, do nothing
163 * @return bool $condition
164 */
165 protected function addWhereIf( $value, $condition ) {
166 if ( $condition ) {
167 $this->addWhere( $value );
168 return true;
169 }
170 return false;
171 }
172
173 /**
174 * Equivalent to addWhere(array($field => $value))
175 * @param $field string Field name
176 * @param $value string Value; ignored if null or empty array;
177 */
178 protected function addWhereFld( $field, $value ) {
179 // Use count() to its full documented capabilities to simultaneously
180 // test for null, empty array or empty countable object
181 if ( count( $value ) ) {
182 $this->where[$field] = $value;
183 }
184 }
185
186 /**
187 * Add a WHERE clause corresponding to a range, and an ORDER BY
188 * clause to sort in the right direction
189 * @param $field string Field name
190 * @param $dir string If 'newer', sort in ascending order, otherwise
191 * sort in descending order
192 * @param $start string Value to start the list at. If $dir == 'newer'
193 * this is the lower boundary, otherwise it's the upper boundary
194 * @param $end string Value to end the list at. If $dir == 'newer' this
195 * is the upper boundary, otherwise it's the lower boundary
196 * @param $sort bool If false, don't add an ORDER BY clause
197 */
198 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
199 $isDirNewer = ( $dir === 'newer' );
200 $after = ( $isDirNewer ? '>=' : '<=' );
201 $before = ( $isDirNewer ? '<=' : '>=' );
202 $db = $this->getDB();
203
204 if ( !is_null( $start ) ) {
205 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
206 }
207
208 if ( !is_null( $end ) ) {
209 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
210 }
211
212 if ( $sort ) {
213 $order = $field . ( $isDirNewer ? '' : ' DESC' );
214 if ( !isset( $this->options['ORDER BY'] ) ) {
215 $this->addOption( 'ORDER BY', $order );
216 } else {
217 $this->addOption( 'ORDER BY', $this->options['ORDER BY'] . ', ' . $order );
218 }
219 }
220 }
221
222 /**
223 * Add an option such as LIMIT or USE INDEX. If an option was set
224 * before, the old value will be overwritten
225 * @param $name string Option name
226 * @param $value string Option value
227 */
228 protected function addOption( $name, $value = null ) {
229 if ( is_null( $value ) ) {
230 $this->options[] = $name;
231 } else {
232 $this->options[$name] = $value;
233 }
234 }
235
236 /**
237 * Execute a SELECT query based on the values in the internal arrays
238 * @param $method string Function the query should be attributed to.
239 * You should usually use __METHOD__ here
240 * @param $extraQuery array Query data to add but not store in the object
241 * Format is array( 'tables' => ..., 'fields' => ..., 'where' => ..., 'options' => ..., 'join_conds' => ... )
242 * @return ResultWrapper
243 */
244 protected function select( $method, $extraQuery = array() ) {
245
246 $tables = array_merge( $this->tables, isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array() );
247 $fields = array_merge( $this->fields, isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array() );
248 $where = array_merge( $this->where, isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array() );
249 $options = array_merge( $this->options, isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array() );
250 $join_conds = array_merge( $this->join_conds, isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array() );
251
252 // getDB has its own profileDBIn/Out calls
253 $db = $this->getDB();
254
255 $this->profileDBIn();
256 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
257 $this->profileDBOut();
258
259 return $res;
260 }
261
262 /**
263 * Estimate the row count for the SELECT query that would be run if we
264 * called select() right now, and check if it's acceptable.
265 * @return bool true if acceptable, false otherwise
266 */
267 protected function checkRowCount() {
268 $db = $this->getDB();
269 $this->profileDBIn();
270 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
271 $this->profileDBOut();
272
273 global $wgAPIMaxDBRows;
274 if ( $rowcount > $wgAPIMaxDBRows ) {
275 return false;
276 }
277 return true;
278 }
279
280 /**
281 * Add information (title and namespace) about a Title object to a
282 * result array
283 * @param $arr array Result array à la ApiResult
284 * @param $title Title
285 * @param $prefix string Module prefix
286 */
287 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
288 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
289 $arr[$prefix . 'title'] = $title->getPrefixedText();
290 }
291
292 /**
293 * Override this method to request extra fields from the pageSet
294 * using $pageSet->requestField('fieldName')
295 * @param $pageSet ApiPageSet
296 */
297 public function requestExtraData( $pageSet ) {
298 }
299
300 /**
301 * Get the main Query module
302 * @return ApiQuery
303 */
304 public function getQuery() {
305 return $this->mQueryModule;
306 }
307
308 /**
309 * Add a sub-element under the page element with the given page ID
310 * @param $pageId int Page ID
311 * @param $data array Data array à la ApiResult
312 * @return bool Whether the element fit in the result
313 */
314 protected function addPageSubItems( $pageId, $data ) {
315 $result = $this->getResult();
316 $result->setIndexedTagName( $data, $this->getModulePrefix() );
317 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
318 $this->getModuleName(),
319 $data );
320 }
321
322 /**
323 * Same as addPageSubItems(), but one element of $data at a time
324 * @param $pageId int Page ID
325 * @param $item array Data array à la ApiResult
326 * @param $elemname string XML element name. If null, getModuleName()
327 * is used
328 * @return bool Whether the element fit in the result
329 */
330 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
331 if ( is_null( $elemname ) ) {
332 $elemname = $this->getModulePrefix();
333 }
334 $result = $this->getResult();
335 $fit = $result->addValue( array( 'query', 'pages', $pageId,
336 $this->getModuleName() ), null, $item );
337 if ( !$fit ) {
338 return false;
339 }
340 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
341 $this->getModuleName() ), $elemname );
342 return true;
343 }
344
345 /**
346 * Set a query-continue value
347 * @param $paramName string Parameter name
348 * @param $paramValue string Parameter value
349 */
350 protected function setContinueEnumParameter( $paramName, $paramValue ) {
351 $paramName = $this->encodeParamName( $paramName );
352 $msg = array( $paramName => $paramValue );
353 $this->getResult()->disableSizeCheck();
354 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
355 $this->getResult()->enableSizeCheck();
356 }
357
358 /**
359 * Get the Query database connection (read-only)
360 * @return Database
361 */
362 protected function getDB() {
363 if ( is_null( $this->mDb ) ) {
364 $apiQuery = $this->getQuery();
365 $this->mDb = $apiQuery->getDB();
366 }
367 return $this->mDb;
368 }
369
370 /**
371 * Selects the query database connection with the given name.
372 * See ApiQuery::getNamedDB() for more information
373 * @param $name string Name to assign to the database connection
374 * @param $db int One of the DB_* constants
375 * @param $groups array Query groups
376 * @return Database
377 */
378 public function selectNamedDB( $name, $db, $groups ) {
379 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
380 }
381
382 /**
383 * Get the PageSet object to work on
384 * @return ApiPageSet
385 */
386 protected function getPageSet() {
387 return $this->getQuery()->getPageSet();
388 }
389
390 /**
391 * Convert a title to a DB key
392 * @param $title string Page title with spaces
393 * @return string Page title with underscores
394 */
395 public function titleToKey( $title ) {
396 // Don't throw an error if we got an empty string
397 if ( trim( $title ) == '' ) {
398 return '';
399 }
400 $t = Title::newFromText( $title );
401 if ( !$t ) {
402 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
403 }
404 return $t->getPrefixedDbKey();
405 }
406
407 /**
408 * The inverse of titleToKey()
409 * @param $key string Page title with underscores
410 * @return string Page title with spaces
411 */
412 public function keyToTitle( $key ) {
413 // Don't throw an error if we got an empty string
414 if ( trim( $key ) == '' ) {
415 return '';
416 }
417 $t = Title::newFromDbKey( $key );
418 // This really shouldn't happen but we gotta check anyway
419 if ( !$t ) {
420 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
421 }
422 return $t->getPrefixedText();
423 }
424
425 /**
426 * An alternative to titleToKey() that doesn't trim trailing spaces
427 * @param $titlePart string Title part with spaces
428 * @return string Title part with underscores
429 */
430 public function titlePartToKey( $titlePart ) {
431 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
432 }
433
434 /**
435 * An alternative to keyToTitle() that doesn't trim trailing spaces
436 * @param $keyPart string Key part with spaces
437 * @return string Key part with underscores
438 */
439 public function keyPartToTitle( $keyPart ) {
440 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
441 }
442
443 /**
444 * Gets the personalised direction parameter description
445 *
446 * @param string $p ModulePrefix
447 * @param string $extraDirText Any extra text to be appended on the description
448 * @return array
449 */
450 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
451 return array(
452 "In which direction to enumerate{$extraDirText}",
453 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
454 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
455 );
456 }
457
458 /**
459 * @param $query String
460 * @param $protocol String
461 * @return null|string
462 */
463 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
464 $db = $this->getDb();
465 if ( !is_null( $query ) || $query != '' ) {
466 if ( is_null( $protocol ) ) {
467 $protocol = 'http://';
468 }
469
470 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
471 if ( !$likeQuery ) {
472 $this->dieUsage( 'Invalid query', 'bad_query' );
473 }
474
475 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
476 return 'el_index ' . $db->buildLike( $likeQuery );
477 } elseif ( !is_null( $protocol ) ) {
478 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
479 }
480
481 return null;
482 }
483
484 /**
485 * Filters hidden users (where the user doesn't have the right to view them)
486 * Also adds relevant block information
487 *
488 * @param bool $showBlockInfo
489 * @return void
490 */
491 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
492 global $wgUser;
493 $userCanViewHiddenUsers = $wgUser->isAllowed( 'hideuser' );
494
495 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
496 $this->addTables( 'ipblocks' );
497 $this->addJoinConds( array(
498 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
499 ) );
500
501 $this->addFields( 'ipb_deleted' );
502
503 if ( $showBlockInfo ) {
504 $this->addFields( array( 'ipb_reason', 'ipb_by_text', 'ipb_expiry' ) );
505 }
506
507 // Don't show hidden names
508 if ( !$userCanViewHiddenUsers ) {
509 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
510 }
511 }
512 }
513
514 public function getPossibleErrors() {
515 return array_merge( parent::getPossibleErrors(), array(
516 array( 'invalidtitle', 'title' ),
517 array( 'invalidtitle', 'key' ),
518 ) );
519 }
520
521 /**
522 * Get version string for use in the API help output
523 * @return string
524 */
525 public static function getBaseVersion() {
526 return __CLASS__ . ': $Id$';
527 }
528 }
529
530 /**
531 * @ingroup API
532 */
533 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
534
535 private $mIsGenerator;
536
537 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
538 parent::__construct( $query, $moduleName, $paramPrefix );
539 $this->mIsGenerator = false;
540 }
541
542 /**
543 * Switch this module to generator mode. By default, generator mode is
544 * switched off and the module acts like a normal query module.
545 */
546 public function setGeneratorMode() {
547 $this->mIsGenerator = true;
548 }
549
550 /**
551 * Overrides base class to prepend 'g' to every generator parameter
552 * @param $paramName string Parameter name
553 * @return string Prefixed parameter name
554 */
555 public function encodeParamName( $paramName ) {
556 if ( $this->mIsGenerator ) {
557 return 'g' . parent::encodeParamName( $paramName );
558 } else {
559 return parent::encodeParamName( $paramName );
560 }
561 }
562
563 /**
564 * Execute this module as a generator
565 * @param $resultPageSet ApiPageSet: All output should be appended to
566 * this object
567 */
568 public abstract function executeGenerator( $resultPageSet );
569 }