3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\IDatabase
;
24 use Wikimedia\Rdbms\ResultWrapper
;
27 * This is a base class for all Query modules.
28 * It provides some common functionality such as constructing various SQL
33 abstract class ApiQueryBase
extends ApiBase
{
35 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
38 * @param ApiQuery $queryModule
39 * @param string $moduleName
40 * @param string $paramPrefix
42 public function __construct( ApiQuery
$queryModule, $moduleName, $paramPrefix = '' ) {
43 parent
::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
44 $this->mQueryModule
= $queryModule;
46 $this->resetQueryParams();
49 /************************************************************************//**
50 * @name Methods to implement
55 * Get the cache mode for the data generated by this module. Override
56 * this in the module subclass. For possible return values and other
57 * details about cache modes, see ApiMain::setCacheMode()
59 * Public caching will only be allowed if *all* the modules that supply
60 * data for a given request return a cache mode of public.
62 * @param array $params
65 public function getCacheMode( $params ) {
70 * Override this method to request extra fields from the pageSet
71 * using $pageSet->requestField('fieldName')
73 * Note this only makes sense for 'prop' modules, as 'list' and 'meta'
74 * modules should not be using the pageset.
76 * @param ApiPageSet $pageSet
78 public function requestExtraData( $pageSet ) {
83 /************************************************************************//**
89 * Get the main Query module
92 public function getQuery() {
93 return $this->mQueryModule
;
97 public function getParent() {
98 return $this->getQuery();
102 * Get the Query database connection (read-only)
105 protected function getDB() {
106 if ( is_null( $this->mDb
) ) {
107 $this->mDb
= $this->getQuery()->getDB();
114 * Selects the query database connection with the given name.
115 * See ApiQuery::getNamedDB() for more information
116 * @param string $name Name to assign to the database connection
117 * @param int $db One of the DB_* constants
118 * @param string|string[] $groups Query groups
121 public function selectNamedDB( $name, $db, $groups ) {
122 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
127 * Get the PageSet object to work on
130 protected function getPageSet() {
131 return $this->getQuery()->getPageSet();
136 /************************************************************************//**
142 * Blank the internal arrays with query parameters
144 protected function resetQueryParams() {
149 $this->join_conds
= [];
153 * Add a set of tables to the internal array
154 * @param string|string[] $tables Table name or array of table names
155 * @param string|null $alias Table alias, or null for no alias. Cannot be
156 * used with multiple tables
158 protected function addTables( $tables, $alias = null ) {
159 if ( is_array( $tables ) ) {
160 if ( !is_null( $alias ) ) {
161 ApiBase
::dieDebug( __METHOD__
, 'Multiple table aliases not supported' );
163 $this->tables
= array_merge( $this->tables
, $tables );
165 if ( !is_null( $alias ) ) {
166 $this->tables
[$alias] = $tables;
168 $this->tables
[] = $tables;
174 * Add a set of JOIN conditions to the internal array
176 * JOIN conditions are formatted as [ tablename => [ jointype, conditions ] ]
177 * e.g. [ 'page' => [ 'LEFT JOIN', 'page_id=rev_page' ] ].
178 * Conditions may be a string or an addWhere()-style array.
179 * @param array $join_conds JOIN conditions
181 protected function addJoinConds( $join_conds ) {
182 if ( !is_array( $join_conds ) ) {
183 ApiBase
::dieDebug( __METHOD__
, 'Join conditions have to be arrays' );
185 $this->join_conds
= array_merge( $this->join_conds
, $join_conds );
189 * Add a set of fields to select to the internal array
190 * @param array|string $value Field name or array of field names
192 protected function addFields( $value ) {
193 if ( is_array( $value ) ) {
194 $this->fields
= array_merge( $this->fields
, $value );
196 $this->fields
[] = $value;
201 * Same as addFields(), but add the fields only if a condition is met
202 * @param array|string $value See addFields()
203 * @param bool $condition If false, do nothing
204 * @return bool $condition
206 protected function addFieldsIf( $value, $condition ) {
208 $this->addFields( $value );
217 * Add a set of WHERE clauses to the internal array.
218 * Clauses can be formatted as 'foo=bar' or [ 'foo' => 'bar' ],
219 * the latter only works if the value is a constant (i.e. not another field)
221 * If $value is an empty array, this function does nothing.
223 * For example, [ 'foo=bar', 'baz' => 3, 'bla' => 'foo' ] translates
224 * to "foo=bar AND baz='3' AND bla='foo'"
225 * @param string|array $value
227 protected function addWhere( $value ) {
228 if ( is_array( $value ) ) {
229 // Sanity check: don't insert empty arrays,
230 // Database::makeList() chokes on them
231 if ( count( $value ) ) {
232 $this->where
= array_merge( $this->where
, $value );
235 $this->where
[] = $value;
240 * Same as addWhere(), but add the WHERE clauses only if a condition is met
241 * @param string|array $value
242 * @param bool $condition If false, do nothing
243 * @return bool $condition
245 protected function addWhereIf( $value, $condition ) {
247 $this->addWhere( $value );
256 * Equivalent to addWhere(array($field => $value))
257 * @param string $field Field name
258 * @param string|string[] $value Value; ignored if null or empty array
260 protected function addWhereFld( $field, $value ) {
261 if ( $value !== null && !( is_array( $value ) && !$value ) ) {
262 $this->where
[$field] = $value;
267 * Like addWhereFld for an integer list of IDs
269 * @param string $table Table name
270 * @param string $field Field name
271 * @param int[] $ids IDs
272 * @return int Count of IDs actually included
274 protected function addWhereIDsFld( $table, $field, $ids ) {
275 // Use count() to its full documented capabilities to simultaneously
276 // test for null, empty array or empty countable object
277 if ( count( $ids ) ) {
278 $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
281 // Return nothing, no IDs are valid
282 $this->where
[] = '0 = 1';
284 $this->where
[$field] = $ids;
287 return count( $ids );
291 * Add a WHERE clause corresponding to a range, and an ORDER BY
292 * clause to sort in the right direction
293 * @param string $field Field name
294 * @param string $dir If 'newer', sort in ascending order, otherwise
295 * sort in descending order
296 * @param string $start Value to start the list at. If $dir == 'newer'
297 * this is the lower boundary, otherwise it's the upper boundary
298 * @param string $end Value to end the list at. If $dir == 'newer' this
299 * is the upper boundary, otherwise it's the lower boundary
300 * @param bool $sort If false, don't add an ORDER BY clause
302 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
303 $isDirNewer = ( $dir === 'newer' );
304 $after = ( $isDirNewer ?
'>=' : '<=' );
305 $before = ( $isDirNewer ?
'<=' : '>=' );
306 $db = $this->getDB();
308 if ( !is_null( $start ) ) {
309 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
312 if ( !is_null( $end ) ) {
313 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
317 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
319 $optionOrderBy = isset( $this->options
['ORDER BY'] )
320 ?
(array)$this->options
['ORDER BY']
322 $optionOrderBy[] = $order;
323 $this->addOption( 'ORDER BY', $optionOrderBy );
328 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
329 * but converts $start and $end to database timestamps.
331 * @param string $field
333 * @param string $start
337 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
338 $db = $this->getDB();
339 $this->addWhereRange( $field, $dir,
340 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
344 * Add an option such as LIMIT or USE INDEX. If an option was set
345 * before, the old value will be overwritten
346 * @param string $name Option name
347 * @param string|string[]|null $value Option value
349 protected function addOption( $name, $value = null ) {
350 if ( is_null( $value ) ) {
351 $this->options
[] = $name;
353 $this->options
[$name] = $value;
358 * Execute a SELECT query based on the values in the internal arrays
359 * @param string $method Function the query should be attributed to.
360 * You should usually use __METHOD__ here
361 * @param array $extraQuery Query data to add but not store in the object
367 * 'join_conds' => ...
369 * @param array|null &$hookData If set, the ApiQueryBaseBeforeQuery and
370 * ApiQueryBaseAfterQuery hooks will be called, and the
371 * ApiQueryBaseProcessRow hook will be expected.
372 * @return ResultWrapper
374 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
375 $tables = array_merge(
377 isset( $extraQuery['tables'] ) ?
(array)$extraQuery['tables'] : []
379 $fields = array_merge(
381 isset( $extraQuery['fields'] ) ?
(array)$extraQuery['fields'] : []
383 $where = array_merge(
385 isset( $extraQuery['where'] ) ?
(array)$extraQuery['where'] : []
387 $options = array_merge(
389 isset( $extraQuery['options'] ) ?
(array)$extraQuery['options'] : []
391 $join_conds = array_merge(
393 isset( $extraQuery['join_conds'] ) ?
(array)$extraQuery['join_conds'] : []
396 if ( $hookData !== null ) {
397 Hooks
::run( 'ApiQueryBaseBeforeQuery',
398 [ $this, &$tables, &$fields, &$where, &$options, &$join_conds, &$hookData ]
402 $res = $this->getDB()->select( $tables, $fields, $where, $method, $options, $join_conds );
404 if ( $hookData !== null ) {
405 Hooks
::run( 'ApiQueryBaseAfterQuery', [ $this, $res, &$hookData ] );
412 * Call the ApiQueryBaseProcessRow hook
414 * Generally, a module that passed $hookData to self::select() will call
415 * this just before calling ApiResult::addValue(), and treat a false return
416 * here in the same way it treats a false return from addValue().
419 * @param object $row Database row
420 * @param array &$data Data to be added to the result
421 * @param array &$hookData Hook data from ApiQueryBase::select()
422 * @return bool Return false if row processing should end with continuation
424 protected function processRow( $row, array &$data, array &$hookData ) {
425 return Hooks
::run( 'ApiQueryBaseProcessRow', [ $this, $row, &$data, &$hookData ] );
429 * @deprecated since 1.33, use LinkFilter::getQueryConditions() instead
430 * @param string|null $query
431 * @param string|null $protocol
432 * @return null|string
434 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
435 wfDeprecated( __METHOD__
, '1.33' );
436 $db = $this->getDB();
437 if ( $query !== null && $query !== '' ) {
438 if ( is_null( $protocol ) ) {
439 $protocol = 'http://';
442 $likeQuery = LinkFilter
::makeLikeArray( $query, $protocol );
444 $this->dieWithError( 'apierror-badquery' );
447 $likeQuery = LinkFilter
::keepOneWildcard( $likeQuery );
449 return 'el_index ' . $db->buildLike( $likeQuery );
450 } elseif ( !is_null( $protocol ) ) {
451 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
458 * Filters hidden users (where the user doesn't have the right to view them)
459 * Also adds relevant block information
461 * @param bool $showBlockInfo
464 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
465 $db = $this->getDB();
467 $tables = [ 'ipblocks' ];
468 $fields = [ 'ipb_deleted' ];
470 'blk' => [ 'LEFT JOIN', [
472 'ipb_expiry > ' . $db->addQuotes( $db->timestamp() ),
476 if ( $showBlockInfo ) {
477 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
478 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
479 $tables +
= $actorQuery['tables'] +
$commentQuery['tables'];
480 $joinConds +
= $actorQuery['joins'] +
$commentQuery['joins'];
481 $fields = array_merge( $fields, [
485 ], $actorQuery['fields'], $commentQuery['fields'] );
488 $this->addTables( [ 'blk' => $tables ] );
489 $this->addFields( $fields );
490 $this->addJoinConds( $joinConds );
492 // Don't show hidden names
493 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
494 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
500 /************************************************************************//**
501 * @name Utility methods
506 * Add information (title and namespace) about a Title object to a
508 * @param array &$arr Result array à la ApiResult
509 * @param Title $title
510 * @param string $prefix Module prefix
512 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
513 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
514 $arr[$prefix . 'title'] = $title->getPrefixedText();
518 * Add a sub-element under the page element with the given page ID
519 * @param int $pageId Page ID
520 * @param array $data Data array à la ApiResult
521 * @return bool Whether the element fit in the result
523 protected function addPageSubItems( $pageId, $data ) {
524 $result = $this->getResult();
525 ApiResult
::setIndexedTagName( $data, $this->getModulePrefix() );
527 return $result->addValue( [ 'query', 'pages', intval( $pageId ) ],
528 $this->getModuleName(),
533 * Same as addPageSubItems(), but one element of $data at a time
534 * @param int $pageId Page ID
535 * @param array $item Data array à la ApiResult
536 * @param string|null $elemname XML element name. If null, getModuleName()
538 * @return bool Whether the element fit in the result
540 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
541 if ( is_null( $elemname ) ) {
542 $elemname = $this->getModulePrefix();
544 $result = $this->getResult();
545 $fit = $result->addValue( [ 'query', 'pages', $pageId,
546 $this->getModuleName() ], null, $item );
550 $result->addIndexedTagName( [ 'query', 'pages', $pageId,
551 $this->getModuleName() ], $elemname );
557 * Set a query-continue value
558 * @param string $paramName Parameter name
559 * @param string|array $paramValue Parameter value
561 protected function setContinueEnumParameter( $paramName, $paramValue ) {
562 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
566 * Convert an input title or title prefix into a dbkey.
568 * $namespace should always be specified in order to handle per-namespace
569 * capitalization settings.
571 * @param string $titlePart Title part
572 * @param int $namespace Namespace of the title
573 * @return string DBkey (no namespace prefix)
575 public function titlePartToKey( $titlePart, $namespace = NS_MAIN
) {
576 $t = Title
::makeTitleSafe( $namespace, $titlePart . 'x' );
577 if ( !$t ||
$t->hasFragment() ) {
578 // Invalid title (e.g. bad chars) or contained a '#'.
579 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
581 if ( $namespace != $t->getNamespace() ||
$t->isExternal() ) {
582 // This can happen in two cases. First, if you call titlePartToKey with a title part
583 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
584 // difficult to handle such a case. Such cases cannot exist and are therefore treated
585 // as invalid user input. The second case is when somebody specifies a title interwiki
587 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
590 return substr( $t->getDBkey(), 0, -1 );
594 * Convert an input title or title prefix into a namespace constant and dbkey.
597 * @param string $titlePart Title part
598 * @param int $defaultNamespace Default namespace if none is given
599 * @return array (int, string) Namespace number and DBkey
601 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN
) {
602 $t = Title
::newFromText( $titlePart . 'x', $defaultNamespace );
603 if ( !$t ||
$t->hasFragment() ||
$t->isExternal() ) {
604 // Invalid title (e.g. bad chars) or contained a '#'.
605 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
608 return [ $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) ];
612 * @param string $hash
615 public function validateSha1Hash( $hash ) {
616 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
620 * @param string $hash
623 public function validateSha1Base36Hash( $hash ) {
624 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
628 * Check whether the current user has permission to view revision-deleted
632 public function userCanSeeRevDel() {
633 return $this->getUser()->isAllowedAny(