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