Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / api / ApiQueryBase.php
blob998cc91c639d9b8a8218b5a96bc0dbe5386e1a66
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 ApiQuery $queryModule
40 * @param string $moduleName
41 * @param string $paramPrefix
43 public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
44 parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule = $queryModule;
46 $this->mDb = null;
47 $this->resetQueryParams();
50 /************************************************************************//**
51 * @name Methods to implement
52 * @{
55 /**
56 * Get the cache mode for the data generated by this module. Override
57 * this in the module subclass. For possible return values and other
58 * details about cache modes, see ApiMain::setCacheMode()
60 * Public caching will only be allowed if *all* the modules that supply
61 * data for a given request return a cache mode of public.
63 * @param array $params
64 * @return string
66 public function getCacheMode( $params ) {
67 return 'private';
70 /**
71 * Override this method to request extra fields from the pageSet
72 * using $pageSet->requestField('fieldName')
74 * Note this only makes sense for 'prop' modules, as 'list' and 'meta'
75 * modules should not be using the pageset.
77 * @param ApiPageSet $pageSet
79 public function requestExtraData( $pageSet ) {
82 /**@}*/
84 /************************************************************************//**
85 * @name Data access
86 * @{
89 /**
90 * Get the main Query module
91 * @return ApiQuery
93 public function getQuery() {
94 return $this->mQueryModule;
97 /**
98 * @see ApiBase::getParent()
100 public function getParent() {
101 return $this->getQuery();
105 * Get the Query database connection (read-only)
106 * @return DatabaseBase
108 protected function getDB() {
109 if ( is_null( $this->mDb ) ) {
110 $this->mDb = $this->getQuery()->getDB();
113 return $this->mDb;
117 * Selects the query database connection with the given name.
118 * See ApiQuery::getNamedDB() for more information
119 * @param string $name Name to assign to the database connection
120 * @param int $db One of the DB_* constants
121 * @param array $groups Query groups
122 * @return DatabaseBase
124 public function selectNamedDB( $name, $db, $groups ) {
125 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
129 * Get the PageSet object to work on
130 * @return ApiPageSet
132 protected function getPageSet() {
133 return $this->getQuery()->getPageSet();
136 /**@}*/
138 /************************************************************************//**
139 * @name Querying
140 * @{
144 * Blank the internal arrays with query parameters
146 protected function resetQueryParams() {
147 $this->tables = array();
148 $this->where = array();
149 $this->fields = array();
150 $this->options = array();
151 $this->join_conds = array();
155 * Add a set of tables to the internal array
156 * @param string|string[] $tables Table name or array of table names
157 * @param string|null $alias Table alias, or null for no alias. Cannot be
158 * used with multiple tables
160 protected function addTables( $tables, $alias = null ) {
161 if ( is_array( $tables ) ) {
162 if ( !is_null( $alias ) ) {
163 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
165 $this->tables = array_merge( $this->tables, $tables );
166 } else {
167 if ( !is_null( $alias ) ) {
168 $this->tables[$alias] = $tables;
169 } else {
170 $this->tables[] = $tables;
176 * Add a set of JOIN conditions to the internal array
178 * JOIN conditions are formatted as array( tablename => array(jointype,
179 * conditions) e.g. array('page' => array('LEFT JOIN',
180 * 'page_id=rev_page')) . conditions may be a string or an
181 * addWhere()-style array
182 * @param array $join_conds JOIN conditions
184 protected function addJoinConds( $join_conds ) {
185 if ( !is_array( $join_conds ) ) {
186 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
188 $this->join_conds = array_merge( $this->join_conds, $join_conds );
192 * Add a set of fields to select to the internal array
193 * @param array|string $value Field name or array of field names
195 protected function addFields( $value ) {
196 if ( is_array( $value ) ) {
197 $this->fields = array_merge( $this->fields, $value );
198 } else {
199 $this->fields[] = $value;
204 * Same as addFields(), but add the fields only if a condition is met
205 * @param array|string $value See addFields()
206 * @param bool $condition If false, do nothing
207 * @return bool $condition
209 protected function addFieldsIf( $value, $condition ) {
210 if ( $condition ) {
211 $this->addFields( $value );
213 return true;
216 return false;
220 * Add a set of WHERE clauses to the internal array.
221 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
222 * the latter only works if the value is a constant (i.e. not another field)
224 * If $value is an empty array, this function does nothing.
226 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
227 * to "foo=bar AND baz='3' AND bla='foo'"
228 * @param string|array $value
230 protected function addWhere( $value ) {
231 if ( is_array( $value ) ) {
232 // Sanity check: don't insert empty arrays,
233 // Database::makeList() chokes on them
234 if ( count( $value ) ) {
235 $this->where = array_merge( $this->where, $value );
237 } else {
238 $this->where[] = $value;
243 * Same as addWhere(), but add the WHERE clauses only if a condition is met
244 * @param string|array $value
245 * @param bool $condition If false, do nothing
246 * @return bool $condition
248 protected function addWhereIf( $value, $condition ) {
249 if ( $condition ) {
250 $this->addWhere( $value );
252 return true;
255 return false;
259 * Equivalent to addWhere(array($field => $value))
260 * @param string $field Field name
261 * @param string $value Value; ignored if null or empty array;
263 protected function addWhereFld( $field, $value ) {
264 // Use count() to its full documented capabilities to simultaneously
265 // test for null, empty array or empty countable object
266 if ( count( $value ) ) {
267 $this->where[$field] = $value;
272 * Add a WHERE clause corresponding to a range, and an ORDER BY
273 * clause to sort in the right direction
274 * @param string $field Field name
275 * @param string $dir If 'newer', sort in ascending order, otherwise
276 * sort in descending order
277 * @param string $start Value to start the list at. If $dir == 'newer'
278 * this is the lower boundary, otherwise it's the upper boundary
279 * @param string $end Value to end the list at. If $dir == 'newer' this
280 * is the upper boundary, otherwise it's the lower boundary
281 * @param bool $sort If false, don't add an ORDER BY clause
283 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
284 $isDirNewer = ( $dir === 'newer' );
285 $after = ( $isDirNewer ? '>=' : '<=' );
286 $before = ( $isDirNewer ? '<=' : '>=' );
287 $db = $this->getDB();
289 if ( !is_null( $start ) ) {
290 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
293 if ( !is_null( $end ) ) {
294 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
297 if ( $sort ) {
298 $order = $field . ( $isDirNewer ? '' : ' DESC' );
299 // Append ORDER BY
300 $optionOrderBy = isset( $this->options['ORDER BY'] )
301 ? (array)$this->options['ORDER BY']
302 : array();
303 $optionOrderBy[] = $order;
304 $this->addOption( 'ORDER BY', $optionOrderBy );
309 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
310 * but converts $start and $end to database timestamps.
311 * @see addWhereRange
312 * @param string $field
313 * @param string $dir
314 * @param string $start
315 * @param string $end
316 * @param bool $sort
318 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
319 $db = $this->getDb();
320 $this->addWhereRange( $field, $dir,
321 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
325 * Add an option such as LIMIT or USE INDEX. If an option was set
326 * before, the old value will be overwritten
327 * @param string $name Option name
328 * @param string $value Option value
330 protected function addOption( $name, $value = null ) {
331 if ( is_null( $value ) ) {
332 $this->options[] = $name;
333 } else {
334 $this->options[$name] = $value;
339 * Execute a SELECT query based on the values in the internal arrays
340 * @param string $method Function the query should be attributed to.
341 * You should usually use __METHOD__ here
342 * @param array $extraQuery Query data to add but not store in the object
343 * Format is array(
344 * 'tables' => ...,
345 * 'fields' => ...,
346 * 'where' => ...,
347 * 'options' => ...,
348 * 'join_conds' => ...
350 * @return ResultWrapper
352 protected function select( $method, $extraQuery = array() ) {
354 $tables = array_merge(
355 $this->tables,
356 isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array()
358 $fields = array_merge(
359 $this->fields,
360 isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array()
362 $where = array_merge(
363 $this->where,
364 isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array()
366 $options = array_merge(
367 $this->options,
368 isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array()
370 $join_conds = array_merge(
371 $this->join_conds,
372 isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array()
375 // getDB has its own profileDBIn/Out calls
376 $db = $this->getDB();
378 $this->profileDBIn();
379 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
380 $this->profileDBOut();
382 return $res;
386 * @param string $query
387 * @param string $protocol
388 * @return null|string
390 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
391 $db = $this->getDb();
392 if ( !is_null( $query ) || $query != '' ) {
393 if ( is_null( $protocol ) ) {
394 $protocol = 'http://';
397 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
398 if ( !$likeQuery ) {
399 $this->dieUsage( 'Invalid query', 'bad_query' );
402 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
404 return 'el_index ' . $db->buildLike( $likeQuery );
405 } elseif ( !is_null( $protocol ) ) {
406 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
409 return null;
413 * Filters hidden users (where the user doesn't have the right to view them)
414 * Also adds relevant block information
416 * @param bool $showBlockInfo
417 * @return void
419 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
420 $this->addTables( 'ipblocks' );
421 $this->addJoinConds( array(
422 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
423 ) );
425 $this->addFields( 'ipb_deleted' );
427 if ( $showBlockInfo ) {
428 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry', 'ipb_timestamp' ) );
431 // Don't show hidden names
432 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
433 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
437 /**@}*/
439 /************************************************************************//**
440 * @name Utility methods
441 * @{
445 * Add information (title and namespace) about a Title object to a
446 * result array
447 * @param array $arr Result array à la ApiResult
448 * @param Title $title
449 * @param string $prefix Module prefix
451 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
452 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
453 $arr[$prefix . 'title'] = $title->getPrefixedText();
457 * Add a sub-element under the page element with the given page ID
458 * @param int $pageId Page ID
459 * @param array $data Data array à la ApiResult
460 * @return bool Whether the element fit in the result
462 protected function addPageSubItems( $pageId, $data ) {
463 $result = $this->getResult();
464 $result->setIndexedTagName( $data, $this->getModulePrefix() );
466 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
467 $this->getModuleName(),
468 $data );
472 * Same as addPageSubItems(), but one element of $data at a time
473 * @param int $pageId Page ID
474 * @param array $item Data array à la ApiResult
475 * @param string $elemname XML element name. If null, getModuleName()
476 * is used
477 * @return bool Whether the element fit in the result
479 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
480 if ( is_null( $elemname ) ) {
481 $elemname = $this->getModulePrefix();
483 $result = $this->getResult();
484 $fit = $result->addValue( array( 'query', 'pages', $pageId,
485 $this->getModuleName() ), null, $item );
486 if ( !$fit ) {
487 return false;
489 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
490 $this->getModuleName() ), $elemname );
492 return true;
496 * Set a query-continue value
497 * @param string $paramName Parameter name
498 * @param string|array $paramValue Parameter value
500 protected function setContinueEnumParameter( $paramName, $paramValue ) {
501 $this->getResult()->setContinueParam( $this, $paramName, $paramValue );
505 * Convert an input title or title prefix into a dbkey.
507 * $namespace should always be specified in order to handle per-namespace
508 * capitalization settings.
510 * @param string $titlePart Title part
511 * @param int $defaultNamespace Namespace of the title
512 * @return string DBkey (no namespace prefix)
514 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
515 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
516 if ( !$t ) {
517 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
519 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
520 // This can happen in two cases. First, if you call titlePartToKey with a title part
521 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
522 // difficult to handle such a case. Such cases cannot exist and are therefore treated
523 // as invalid user input. The second case is when somebody specifies a title interwiki
524 // prefix.
525 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
528 return substr( $t->getDbKey(), 0, -1 );
532 * Gets the personalised direction parameter description
534 * @param string $p ModulePrefix
535 * @param string $extraDirText Any extra text to be appended on the description
536 * @return array
538 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
539 return array(
540 "In which direction to enumerate{$extraDirText}",
541 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
542 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
547 * @param string $hash
548 * @return bool
550 public function validateSha1Hash( $hash ) {
551 return preg_match( '/^[a-f0-9]{40}$/', $hash );
555 * @param string $hash
556 * @return bool
558 public function validateSha1Base36Hash( $hash ) {
559 return preg_match( '/^[a-z0-9]{31}$/', $hash );
563 * Check whether the current user has permission to view revision-deleted
564 * fields.
565 * @return bool
567 public function userCanSeeRevDel() {
568 return $this->getUser()->isAllowedAny(
569 'deletedhistory',
570 'deletedtext',
571 'suppressrevision',
572 'viewsuppressed'
576 /**@}*/
578 /************************************************************************//**
579 * @name Deprecated
580 * @{
584 * Estimate the row count for the SELECT query that would be run if we
585 * called select() right now, and check if it's acceptable.
586 * @deprecated since 1.24
587 * @return bool True if acceptable, false otherwise
589 protected function checkRowCount() {
590 wfDeprecated( __METHOD__, '1.24' );
591 $db = $this->getDB();
592 $this->profileDBIn();
593 $rowcount = $db->estimateRowCount(
594 $this->tables,
595 $this->fields,
596 $this->where,
597 __METHOD__,
598 $this->options
600 $this->profileDBOut();
602 if ( $rowcount > $this->getConfig()->get( 'APIMaxDBRows' ) ) {
603 return false;
606 return true;
610 * Convert a title to a DB key
611 * @deprecated since 1.24, past uses of this were always incorrect and should
612 * have used self::titlePartToKey() instead
613 * @param string $title Page title with spaces
614 * @return string Page title with underscores
616 public function titleToKey( $title ) {
617 wfDeprecated( __METHOD__, '1.24' );
618 // Don't throw an error if we got an empty string
619 if ( trim( $title ) == '' ) {
620 return '';
622 $t = Title::newFromText( $title );
623 if ( !$t ) {
624 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
627 return $t->getPrefixedDBkey();
631 * The inverse of titleToKey()
632 * @deprecated since 1.24, unused and probably never needed
633 * @param string $key Page title with underscores
634 * @return string Page title with spaces
636 public function keyToTitle( $key ) {
637 wfDeprecated( __METHOD__, '1.24' );
638 // Don't throw an error if we got an empty string
639 if ( trim( $key ) == '' ) {
640 return '';
642 $t = Title::newFromDBkey( $key );
643 // This really shouldn't happen but we gotta check anyway
644 if ( !$t ) {
645 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
648 return $t->getPrefixedText();
652 * Inverse of titlePartToKey()
653 * @deprecated since 1.24, unused and probably never needed
654 * @param string $keyPart DBkey, with prefix
655 * @return string Key part with underscores
657 public function keyPartToTitle( $keyPart ) {
658 wfDeprecated( __METHOD__, '1.24' );
659 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 );
662 /**@}*/
666 * @ingroup API
668 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
670 private $mGeneratorPageSet = null;
673 * Switch this module to generator mode. By default, generator mode is
674 * switched off and the module acts like a normal query module.
675 * @since 1.21 requires pageset parameter
676 * @param ApiPageSet $generatorPageSet ApiPageSet object that the module will get
677 * by calling getPageSet() when in generator mode.
679 public function setGeneratorMode( ApiPageSet $generatorPageSet ) {
680 if ( $generatorPageSet === null ) {
681 ApiBase::dieDebug( __METHOD__, 'Required parameter missing - $generatorPageSet' );
683 $this->mGeneratorPageSet = $generatorPageSet;
687 * Get the PageSet object to work on.
688 * If this module is generator, the pageSet object is different from other module's
689 * @return ApiPageSet
691 protected function getPageSet() {
692 if ( $this->mGeneratorPageSet !== null ) {
693 return $this->mGeneratorPageSet;
696 return parent::getPageSet();
700 * Overrides ApiBase to prepend 'g' to every generator parameter
701 * @param string $paramName Parameter name
702 * @return string Prefixed parameter name
704 public function encodeParamName( $paramName ) {
705 if ( $this->mGeneratorPageSet !== null ) {
706 return 'g' . parent::encodeParamName( $paramName );
707 } else {
708 return parent::encodeParamName( $paramName );
713 * Overridden to set the generator param if in generator mode
714 * @param string $paramName Parameter name
715 * @param string|array $paramValue Parameter value
717 protected function setContinueEnumParameter( $paramName, $paramValue ) {
718 if ( $this->mGeneratorPageSet !== null ) {
719 $this->getResult()->setGeneratorContinueParam( $this, $paramName, $paramValue );
720 } else {
721 parent::setContinueEnumParameter( $paramName, $paramValue );
726 * @see ApiBase::getHelpFlags()
728 * Corresponding messages: api-help-flag-generator
730 protected function getHelpFlags() {
731 $flags = parent::getHelpFlags();
732 $flags[] = 'generator';
733 return $flags;
737 * Execute this module as a generator
738 * @param ApiPageSet $resultPageSet All output should be appended to this object
740 abstract public function executeGenerator( $resultPageSet );