Merge "Typo fix"
[mediawiki.git] / includes / api / ApiQueryBase.php
blob8668e04ba64413c01339dbba984075bdb4151fbb
1 <?php
2 /**
5 * Created on Sep 7, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
24 * @file
27 /**
28 * This is a base class for all Query modules.
29 * It provides some common functionality such as constructing various SQL
30 * queries.
32 * @ingroup API
34 abstract class ApiQueryBase extends ApiBase {
36 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
38 /**
39 * @param $query ApiBase
40 * @param $moduleName string
41 * @param $paramPrefix string
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();
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()
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.
58 * @param $params
59 * @return string
61 public function getCacheMode( $params ) {
62 return 'private';
65 /**
66 * Blank the internal arrays with query parameters
68 protected function resetQueryParams() {
69 $this->tables = array();
70 $this->where = array();
71 $this->fields = array();
72 $this->options = array();
73 $this->join_conds = array();
76 /**
77 * Add a set of tables to the internal array
78 * @param $tables mixed Table name or array of table names
79 * @param $alias mixed Table alias, or null for no alias. Cannot be
80 * used with multiple tables
82 protected function addTables( $tables, $alias = null ) {
83 if ( is_array( $tables ) ) {
84 if ( !is_null( $alias ) ) {
85 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
87 $this->tables = array_merge( $this->tables, $tables );
88 } else {
89 if ( !is_null( $alias ) ) {
90 $this->tables[$alias] = $tables;
91 } else {
92 $this->tables[] = $tables;
97 /**
98 * Add a set of JOIN conditions to the internal array
100 * JOIN conditions are formatted as array( tablename => array(jointype,
101 * conditions) e.g. array('page' => array('LEFT JOIN',
102 * 'page_id=rev_page')) . conditions may be a string or an
103 * addWhere()-style array
104 * @param $join_conds array JOIN conditions
106 protected function addJoinConds( $join_conds ) {
107 if ( !is_array( $join_conds ) ) {
108 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
110 $this->join_conds = array_merge( $this->join_conds, $join_conds );
114 * Add a set of fields to select to the internal array
115 * @param array|string $value Field name or array of field names
117 protected function addFields( $value ) {
118 if ( is_array( $value ) ) {
119 $this->fields = array_merge( $this->fields, $value );
120 } else {
121 $this->fields[] = $value;
126 * Same as addFields(), but add the fields only if a condition is met
127 * @param array|string $value See addFields()
128 * @param bool $condition If false, do nothing
129 * @return bool $condition
131 protected function addFieldsIf( $value, $condition ) {
132 if ( $condition ) {
133 $this->addFields( $value );
134 return true;
136 return false;
140 * Add a set of WHERE clauses to the internal array.
141 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
142 * the latter only works if the value is a constant (i.e. not another field)
144 * If $value is an empty array, this function does nothing.
146 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
147 * to "foo=bar AND baz='3' AND bla='foo'"
148 * @param $value mixed String or array
150 protected function addWhere( $value ) {
151 if ( is_array( $value ) ) {
152 // Sanity check: don't insert empty arrays,
153 // Database::makeList() chokes on them
154 if ( count( $value ) ) {
155 $this->where = array_merge( $this->where, $value );
157 } else {
158 $this->where[] = $value;
163 * Same as addWhere(), but add the WHERE clauses only if a condition is met
164 * @param $value mixed See addWhere()
165 * @param bool $condition If false, do nothing
166 * @return bool $condition
168 protected function addWhereIf( $value, $condition ) {
169 if ( $condition ) {
170 $this->addWhere( $value );
171 return true;
173 return false;
177 * Equivalent to addWhere(array($field => $value))
178 * @param string $field Field name
179 * @param string $value Value; ignored if null or empty array;
181 protected function addWhereFld( $field, $value ) {
182 // Use count() to its full documented capabilities to simultaneously
183 // test for null, empty array or empty countable object
184 if ( count( $value ) ) {
185 $this->where[$field] = $value;
190 * Add a WHERE clause corresponding to a range, and an ORDER BY
191 * clause to sort in the right direction
192 * @param string $field Field name
193 * @param string $dir If 'newer', sort in ascending order, otherwise
194 * sort in descending order
195 * @param string $start Value to start the list at. If $dir == 'newer'
196 * this is the lower boundary, otherwise it's the upper boundary
197 * @param string $end Value to end the list at. If $dir == 'newer' this
198 * is the upper boundary, otherwise it's the lower boundary
199 * @param bool $sort If false, don't add an ORDER BY clause
201 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
202 $isDirNewer = ( $dir === 'newer' );
203 $after = ( $isDirNewer ? '>=' : '<=' );
204 $before = ( $isDirNewer ? '<=' : '>=' );
205 $db = $this->getDB();
207 if ( !is_null( $start ) ) {
208 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
211 if ( !is_null( $end ) ) {
212 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
215 if ( $sort ) {
216 $order = $field . ( $isDirNewer ? '' : ' DESC' );
217 // Append ORDER BY
218 $optionOrderBy = isset( $this->options['ORDER BY'] ) ? (array)$this->options['ORDER BY'] : array();
219 $optionOrderBy[] = $order;
220 $this->addOption( 'ORDER BY', $optionOrderBy );
225 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
226 * but converts $start and $end to database timestamps.
227 * @see addWhereRange
228 * @param $field
229 * @param $dir
230 * @param $start
231 * @param $end
232 * @param $sort bool
234 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
235 $db = $this->getDb();
236 $this->addWhereRange( $field, $dir,
237 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
241 * Add an option such as LIMIT or USE INDEX. If an option was set
242 * before, the old value will be overwritten
243 * @param string $name Option name
244 * @param string $value Option value
246 protected function addOption( $name, $value = null ) {
247 if ( is_null( $value ) ) {
248 $this->options[] = $name;
249 } else {
250 $this->options[$name] = $value;
255 * Execute a SELECT query based on the values in the internal arrays
256 * @param string $method Function the query should be attributed to.
257 * You should usually use __METHOD__ here
258 * @param array $extraQuery Query data to add but not store in the object
259 * Format is array( 'tables' => ..., 'fields' => ..., 'where' => ..., 'options' => ..., 'join_conds' => ... )
260 * @return ResultWrapper
262 protected function select( $method, $extraQuery = array() ) {
264 $tables = array_merge( $this->tables, isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array() );
265 $fields = array_merge( $this->fields, isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array() );
266 $where = array_merge( $this->where, isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array() );
267 $options = array_merge( $this->options, isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array() );
268 $join_conds = array_merge( $this->join_conds, isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array() );
270 // getDB has its own profileDBIn/Out calls
271 $db = $this->getDB();
273 $this->profileDBIn();
274 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
275 $this->profileDBOut();
277 return $res;
281 * Estimate the row count for the SELECT query that would be run if we
282 * called select() right now, and check if it's acceptable.
283 * @return bool true if acceptable, false otherwise
285 protected function checkRowCount() {
286 $db = $this->getDB();
287 $this->profileDBIn();
288 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
289 $this->profileDBOut();
291 global $wgAPIMaxDBRows;
292 if ( $rowcount > $wgAPIMaxDBRows ) {
293 return false;
295 return true;
299 * Add information (title and namespace) about a Title object to a
300 * result array
301 * @param array $arr Result array à la ApiResult
302 * @param $title Title
303 * @param string $prefix Module prefix
305 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
306 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
307 $arr[$prefix . 'title'] = $title->getPrefixedText();
311 * Override this method to request extra fields from the pageSet
312 * using $pageSet->requestField('fieldName')
313 * @param $pageSet ApiPageSet
315 public function requestExtraData( $pageSet ) {
319 * Get the main Query module
320 * @return ApiQuery
322 public function getQuery() {
323 return $this->mQueryModule;
327 * Add a sub-element under the page element with the given page ID
328 * @param int $pageId Page ID
329 * @param array $data Data array à la ApiResult
330 * @return bool Whether the element fit in the result
332 protected function addPageSubItems( $pageId, $data ) {
333 $result = $this->getResult();
334 $result->setIndexedTagName( $data, $this->getModulePrefix() );
335 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
336 $this->getModuleName(),
337 $data );
341 * Same as addPageSubItems(), but one element of $data at a time
342 * @param int $pageId Page ID
343 * @param array $item Data array à la ApiResult
344 * @param string $elemname XML element name. If null, getModuleName()
345 * is used
346 * @return bool Whether the element fit in the result
348 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
349 if ( is_null( $elemname ) ) {
350 $elemname = $this->getModulePrefix();
352 $result = $this->getResult();
353 $fit = $result->addValue( array( 'query', 'pages', $pageId,
354 $this->getModuleName() ), null, $item );
355 if ( !$fit ) {
356 return false;
358 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
359 $this->getModuleName() ), $elemname );
360 return true;
364 * Set a query-continue value
365 * @param string $paramName Parameter name
366 * @param string $paramValue Parameter value
368 protected function setContinueEnumParameter( $paramName, $paramValue ) {
369 $paramName = $this->encodeParamName( $paramName );
370 $msg = array( $paramName => $paramValue );
371 $result = $this->getResult();
372 $result->disableSizeCheck();
373 $result->addValue( 'query-continue', $this->getModuleName(), $msg, ApiResult::ADD_ON_TOP );
374 $result->enableSizeCheck();
378 * Get the Query database connection (read-only)
379 * @return DatabaseBase
381 protected function getDB() {
382 if ( is_null( $this->mDb ) ) {
383 $this->mDb = $this->getQuery()->getDB();
385 return $this->mDb;
389 * Selects the query database connection with the given name.
390 * See ApiQuery::getNamedDB() for more information
391 * @param string $name Name to assign to the database connection
392 * @param int $db One of the DB_* constants
393 * @param array $groups Query groups
394 * @return DatabaseBase
396 public function selectNamedDB( $name, $db, $groups ) {
397 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
401 * Get the PageSet object to work on
402 * @return ApiPageSet
404 protected function getPageSet() {
405 return $this->getQuery()->getPageSet();
409 * Convert a title to a DB key
410 * @param string $title Page title with spaces
411 * @return string Page title with underscores
413 public function titleToKey( $title ) {
414 // Don't throw an error if we got an empty string
415 if ( trim( $title ) == '' ) {
416 return '';
418 $t = Title::newFromText( $title );
419 if ( !$t ) {
420 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
422 return $t->getPrefixedDBkey();
426 * The inverse of titleToKey()
427 * @param string $key Page title with underscores
428 * @return string Page title with spaces
430 public function keyToTitle( $key ) {
431 // Don't throw an error if we got an empty string
432 if ( trim( $key ) == '' ) {
433 return '';
435 $t = Title::newFromDBkey( $key );
436 // This really shouldn't happen but we gotta check anyway
437 if ( !$t ) {
438 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
440 return $t->getPrefixedText();
444 * An alternative to titleToKey() that doesn't trim trailing spaces
445 * @param string $titlePart Title part with spaces
446 * @return string Title part with underscores
448 public function titlePartToKey( $titlePart ) {
449 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
453 * An alternative to keyToTitle() that doesn't trim trailing spaces
454 * @param string $keyPart Key part with spaces
455 * @return string Key part with underscores
457 public function keyPartToTitle( $keyPart ) {
458 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
462 * Gets the personalised direction parameter description
464 * @param string $p ModulePrefix
465 * @param string $extraDirText Any extra text to be appended on the description
466 * @return array
468 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
469 return array(
470 "In which direction to enumerate{$extraDirText}",
471 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
472 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
477 * @param $query String
478 * @param $protocol String
479 * @return null|string
481 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
482 $db = $this->getDb();
483 if ( !is_null( $query ) || $query != '' ) {
484 if ( is_null( $protocol ) ) {
485 $protocol = 'http://';
488 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
489 if ( !$likeQuery ) {
490 $this->dieUsage( 'Invalid query', 'bad_query' );
493 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
494 return 'el_index ' . $db->buildLike( $likeQuery );
495 } elseif ( !is_null( $protocol ) ) {
496 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
499 return null;
503 * Filters hidden users (where the user doesn't have the right to view them)
504 * Also adds relevant block information
506 * @param bool $showBlockInfo
507 * @return void
509 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
510 $userCanViewHiddenUsers = $this->getUser()->isAllowed( 'hideuser' );
512 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
513 $this->addTables( 'ipblocks' );
514 $this->addJoinConds( array(
515 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
516 ) );
518 $this->addFields( 'ipb_deleted' );
520 if ( $showBlockInfo ) {
521 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry' ) );
524 // Don't show hidden names
525 if ( !$userCanViewHiddenUsers ) {
526 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
532 * @param $hash string
533 * @return bool
535 public function validateSha1Hash( $hash ) {
536 return preg_match( '/^[a-f0-9]{40}$/', $hash );
540 * @param $hash string
541 * @return bool
543 public function validateSha1Base36Hash( $hash ) {
544 return preg_match( '/^[a-z0-9]{31}$/', $hash );
548 * @return array
550 public function getPossibleErrors() {
551 $errors = parent::getPossibleErrors();
552 $errors = array_merge( $errors, array(
553 array( 'invalidtitle', 'title' ),
554 array( 'invalidtitle', 'key' ),
555 ) );
556 return $errors;
561 * @ingroup API
563 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
565 private $mGeneratorPageSet = null;
568 * Switch this module to generator mode. By default, generator mode is
569 * switched off and the module acts like a normal query module.
570 * @since 1.21 requires pageset parameter
571 * @param $generatorPageSet ApiPageSet object that the module will get
572 * by calling getPageSet() when in generator mode.
574 public function setGeneratorMode( ApiPageSet $generatorPageSet ) {
575 if ( $generatorPageSet === null ) {
576 ApiBase::dieDebug( __METHOD__, 'Required parameter missing - $generatorPageSet' );
578 $this->mGeneratorPageSet = $generatorPageSet;
582 * Get the PageSet object to work on.
583 * If this module is generator, the pageSet object is different from other module's
584 * @return ApiPageSet
586 protected function getPageSet() {
587 if ( $this->mGeneratorPageSet !== null ) {
588 return $this->mGeneratorPageSet;
590 return parent::getPageSet();
594 * Overrides base class to prepend 'g' to every generator parameter
595 * @param string $paramName Parameter name
596 * @return string Prefixed parameter name
598 public function encodeParamName( $paramName ) {
599 if ( $this->mGeneratorPageSet !== null ) {
600 return 'g' . parent::encodeParamName( $paramName );
601 } else {
602 return parent::encodeParamName( $paramName );
607 * Overrides base in case of generator & smart continue to
608 * notify ApiQueryMain instead of adding them to the result right away.
609 * @param string $paramName Parameter name
610 * @param string $paramValue Parameter value
612 protected function setContinueEnumParameter( $paramName, $paramValue ) {
613 // If this is a generator and query->setGeneratorContinue() returns false, treat as before
614 if ( $this->mGeneratorPageSet === null
615 || !$this->getQuery()->setGeneratorContinue( $this, $paramName, $paramValue )
617 parent::setContinueEnumParameter( $paramName, $paramValue );
622 * Execute this module as a generator
623 * @param $resultPageSet ApiPageSet: All output should be appended to
624 * this object
626 abstract public function executeGenerator( $resultPageSet );