Adding context to the API
[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 array|string 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 array|string 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 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
225 * but converts $start and $end to database timestamps.
226 * @see addWhereRange
227 */
228 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
229 $db = $this->getDb();
230 return $this->addWhereRange( $field, $dir,
231 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
232 }
233
234 /**
235 * Add an option such as LIMIT or USE INDEX. If an option was set
236 * before, the old value will be overwritten
237 * @param $name string Option name
238 * @param $value string Option value
239 */
240 protected function addOption( $name, $value = null ) {
241 if ( is_null( $value ) ) {
242 $this->options[] = $name;
243 } else {
244 $this->options[$name] = $value;
245 }
246 }
247
248 /**
249 * Execute a SELECT query based on the values in the internal arrays
250 * @param $method string Function the query should be attributed to.
251 * You should usually use __METHOD__ here
252 * @param $extraQuery array Query data to add but not store in the object
253 * Format is array( 'tables' => ..., 'fields' => ..., 'where' => ..., 'options' => ..., 'join_conds' => ... )
254 * @return ResultWrapper
255 */
256 protected function select( $method, $extraQuery = array() ) {
257
258 $tables = array_merge( $this->tables, isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array() );
259 $fields = array_merge( $this->fields, isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array() );
260 $where = array_merge( $this->where, isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array() );
261 $options = array_merge( $this->options, isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array() );
262 $join_conds = array_merge( $this->join_conds, isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array() );
263
264 // getDB has its own profileDBIn/Out calls
265 $db = $this->getDB();
266
267 $this->profileDBIn();
268 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
269 $this->profileDBOut();
270
271 return $res;
272 }
273
274 /**
275 * Estimate the row count for the SELECT query that would be run if we
276 * called select() right now, and check if it's acceptable.
277 * @return bool true if acceptable, false otherwise
278 */
279 protected function checkRowCount() {
280 $db = $this->getDB();
281 $this->profileDBIn();
282 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
283 $this->profileDBOut();
284
285 global $wgAPIMaxDBRows;
286 if ( $rowcount > $wgAPIMaxDBRows ) {
287 return false;
288 }
289 return true;
290 }
291
292 /**
293 * Add information (title and namespace) about a Title object to a
294 * result array
295 * @param $arr array Result array à la ApiResult
296 * @param $title Title
297 * @param $prefix string Module prefix
298 */
299 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
300 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
301 $arr[$prefix . 'title'] = $title->getPrefixedText();
302 }
303
304 /**
305 * Override this method to request extra fields from the pageSet
306 * using $pageSet->requestField('fieldName')
307 * @param $pageSet ApiPageSet
308 */
309 public function requestExtraData( $pageSet ) {
310 }
311
312 /**
313 * Get the main Query module
314 * @return ApiQuery
315 */
316 public function getQuery() {
317 return $this->mQueryModule;
318 }
319
320 /**
321 * Add a sub-element under the page element with the given page ID
322 * @param $pageId int Page ID
323 * @param $data array Data array à la ApiResult
324 * @return bool Whether the element fit in the result
325 */
326 protected function addPageSubItems( $pageId, $data ) {
327 $result = $this->getResult();
328 $result->setIndexedTagName( $data, $this->getModulePrefix() );
329 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
330 $this->getModuleName(),
331 $data );
332 }
333
334 /**
335 * Same as addPageSubItems(), but one element of $data at a time
336 * @param $pageId int Page ID
337 * @param $item array Data array à la ApiResult
338 * @param $elemname string XML element name. If null, getModuleName()
339 * is used
340 * @return bool Whether the element fit in the result
341 */
342 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
343 if ( is_null( $elemname ) ) {
344 $elemname = $this->getModulePrefix();
345 }
346 $result = $this->getResult();
347 $fit = $result->addValue( array( 'query', 'pages', $pageId,
348 $this->getModuleName() ), null, $item );
349 if ( !$fit ) {
350 return false;
351 }
352 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
353 $this->getModuleName() ), $elemname );
354 return true;
355 }
356
357 /**
358 * Set a query-continue value
359 * @param $paramName string Parameter name
360 * @param $paramValue string Parameter value
361 */
362 protected function setContinueEnumParameter( $paramName, $paramValue ) {
363 $paramName = $this->encodeParamName( $paramName );
364 $msg = array( $paramName => $paramValue );
365 $result = $this->getResult();
366 $result->disableSizeCheck();
367 $result->addValue( 'query-continue', $this->getModuleName(), $msg );
368 $result->enableSizeCheck();
369 }
370
371 /**
372 * Get the Query database connection (read-only)
373 * @return DatabaseBase
374 */
375 protected function getDB() {
376 if ( is_null( $this->mDb ) ) {
377 $apiQuery = $this->getQuery();
378 $this->mDb = $apiQuery->getDB();
379 }
380 return $this->mDb;
381 }
382
383 /**
384 * Selects the query database connection with the given name.
385 * See ApiQuery::getNamedDB() for more information
386 * @param $name string Name to assign to the database connection
387 * @param $db int One of the DB_* constants
388 * @param $groups array Query groups
389 * @return Database
390 */
391 public function selectNamedDB( $name, $db, $groups ) {
392 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
393 }
394
395 /**
396 * Get the PageSet object to work on
397 * @return ApiPageSet
398 */
399 protected function getPageSet() {
400 return $this->getQuery()->getPageSet();
401 }
402
403 /**
404 * Convert a title to a DB key
405 * @param $title string Page title with spaces
406 * @return string Page title with underscores
407 */
408 public function titleToKey( $title ) {
409 // Don't throw an error if we got an empty string
410 if ( trim( $title ) == '' ) {
411 return '';
412 }
413 $t = Title::newFromText( $title );
414 if ( !$t ) {
415 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
416 }
417 return $t->getPrefixedDbKey();
418 }
419
420 /**
421 * The inverse of titleToKey()
422 * @param $key string Page title with underscores
423 * @return string Page title with spaces
424 */
425 public function keyToTitle( $key ) {
426 // Don't throw an error if we got an empty string
427 if ( trim( $key ) == '' ) {
428 return '';
429 }
430 $t = Title::newFromDbKey( $key );
431 // This really shouldn't happen but we gotta check anyway
432 if ( !$t ) {
433 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
434 }
435 return $t->getPrefixedText();
436 }
437
438 /**
439 * An alternative to titleToKey() that doesn't trim trailing spaces
440 * @param $titlePart string Title part with spaces
441 * @return string Title part with underscores
442 */
443 public function titlePartToKey( $titlePart ) {
444 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
445 }
446
447 /**
448 * An alternative to keyToTitle() that doesn't trim trailing spaces
449 * @param $keyPart string Key part with spaces
450 * @return string Key part with underscores
451 */
452 public function keyPartToTitle( $keyPart ) {
453 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
454 }
455
456 /**
457 * Gets the personalised direction parameter description
458 *
459 * @param string $p ModulePrefix
460 * @param string $extraDirText Any extra text to be appended on the description
461 * @return array
462 */
463 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
464 return array(
465 "In which direction to enumerate{$extraDirText}",
466 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
467 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
468 );
469 }
470
471 /**
472 * @param $query String
473 * @param $protocol String
474 * @return null|string
475 */
476 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
477 $db = $this->getDb();
478 if ( !is_null( $query ) || $query != '' ) {
479 if ( is_null( $protocol ) ) {
480 $protocol = 'http://';
481 }
482
483 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
484 if ( !$likeQuery ) {
485 $this->dieUsage( 'Invalid query', 'bad_query' );
486 }
487
488 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
489 return 'el_index ' . $db->buildLike( $likeQuery );
490 } elseif ( !is_null( $protocol ) ) {
491 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
492 }
493
494 return null;
495 }
496
497 /**
498 * Filters hidden users (where the user doesn't have the right to view them)
499 * Also adds relevant block information
500 *
501 * @param bool $showBlockInfo
502 * @return void
503 */
504 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
505 $userCanViewHiddenUsers = $this->getUser()->isAllowed( 'hideuser' );
506
507 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
508 $this->addTables( 'ipblocks' );
509 $this->addJoinConds( array(
510 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
511 ) );
512
513 $this->addFields( 'ipb_deleted' );
514
515 if ( $showBlockInfo ) {
516 $this->addFields( array( 'ipb_reason', 'ipb_by_text', 'ipb_expiry' ) );
517 }
518
519 // Don't show hidden names
520 if ( !$userCanViewHiddenUsers ) {
521 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
522 }
523 }
524 }
525
526 /**
527 * @param $hash string
528 * @return bool
529 */
530 public function validateSha1Hash( $hash ) {
531 return preg_match( '/[a-fA-F0-9]{40}/', $hash );
532 }
533
534 /**
535 * @param $hash string
536 * @return bool
537 */
538 public function validateSha1Base36Hash( $hash ) {
539 return preg_match( '/[a-zA-Z0-9]{31}/', $hash );
540 }
541
542 /**
543 * @return array
544 */
545 public function getPossibleErrors() {
546 return array_merge( parent::getPossibleErrors(), array(
547 array( 'invalidtitle', 'title' ),
548 array( 'invalidtitle', 'key' ),
549 ) );
550 }
551
552 /**
553 * Get version string for use in the API help output
554 * @return string
555 */
556 public static function getBaseVersion() {
557 return __CLASS__ . ': $Id$';
558 }
559 }
560
561 /**
562 * @ingroup API
563 */
564 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
565
566 private $mIsGenerator;
567
568 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
569 parent::__construct( $query, $moduleName, $paramPrefix );
570 $this->mIsGenerator = false;
571 }
572
573 /**
574 * Switch this module to generator mode. By default, generator mode is
575 * switched off and the module acts like a normal query module.
576 */
577 public function setGeneratorMode() {
578 $this->mIsGenerator = true;
579 }
580
581 /**
582 * Overrides base class to prepend 'g' to every generator parameter
583 * @param $paramName string Parameter name
584 * @return string Prefixed parameter name
585 */
586 public function encodeParamName( $paramName ) {
587 if ( $this->mIsGenerator ) {
588 return 'g' . parent::encodeParamName( $paramName );
589 } else {
590 return parent::encodeParamName( $paramName );
591 }
592 }
593
594 /**
595 * Execute this module as a generator
596 * @param $resultPageSet ApiPageSet: All output should be appended to
597 * this object
598 */
599 public abstract function executeGenerator( $resultPageSet );
600 }