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
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\ResultWrapper
;
31 * This is a base class for all Query modules.
32 * It provides some common functionality such as constructing various SQL
37 abstract class ApiQueryBase
extends ApiBase
{
39 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
42 * @param ApiQuery $queryModule
43 * @param string $moduleName
44 * @param string $paramPrefix
46 public function __construct( ApiQuery
$queryModule, $moduleName, $paramPrefix = '' ) {
47 parent
::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
48 $this->mQueryModule
= $queryModule;
50 $this->resetQueryParams();
53 /************************************************************************//**
54 * @name Methods to implement
59 * Get the cache mode for the data generated by this module. Override
60 * this in the module subclass. For possible return values and other
61 * details about cache modes, see ApiMain::setCacheMode()
63 * Public caching will only be allowed if *all* the modules that supply
64 * data for a given request return a cache mode of public.
66 * @param array $params
69 public function getCacheMode( $params ) {
74 * Override this method to request extra fields from the pageSet
75 * using $pageSet->requestField('fieldName')
77 * Note this only makes sense for 'prop' modules, as 'list' and 'meta'
78 * modules should not be using the pageset.
80 * @param ApiPageSet $pageSet
82 public function requestExtraData( $pageSet ) {
87 /************************************************************************//**
93 * Get the main Query module
96 public function getQuery() {
97 return $this->mQueryModule
;
101 * @see ApiBase::getParent()
103 public function getParent() {
104 return $this->getQuery();
108 * Get the Query database connection (read-only)
111 protected function getDB() {
112 if ( is_null( $this->mDb
) ) {
113 $this->mDb
= $this->getQuery()->getDB();
120 * Selects the query database connection with the given name.
121 * See ApiQuery::getNamedDB() for more information
122 * @param string $name Name to assign to the database connection
123 * @param int $db One of the DB_* constants
124 * @param array $groups Query groups
127 public function selectNamedDB( $name, $db, $groups ) {
128 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
133 * Get the PageSet object to work on
136 protected function getPageSet() {
137 return $this->getQuery()->getPageSet();
142 /************************************************************************//**
148 * Blank the internal arrays with query parameters
150 protected function resetQueryParams() {
155 $this->join_conds
= [];
159 * Add a set of tables to the internal array
160 * @param string|string[] $tables Table name or array of table names
161 * @param string|null $alias Table alias, or null for no alias. Cannot be
162 * used with multiple tables
164 protected function addTables( $tables, $alias = null ) {
165 if ( is_array( $tables ) ) {
166 if ( !is_null( $alias ) ) {
167 ApiBase
::dieDebug( __METHOD__
, 'Multiple table aliases not supported' );
169 $this->tables
= array_merge( $this->tables
, $tables );
171 if ( !is_null( $alias ) ) {
172 $this->tables
[$alias] = $tables;
174 $this->tables
[] = $tables;
180 * Add a set of JOIN conditions to the internal array
182 * JOIN conditions are formatted as [ tablename => [ jointype, conditions ] ]
183 * e.g. [ 'page' => [ 'LEFT JOIN', 'page_id=rev_page' ] ].
184 * Conditions may be a string or an addWhere()-style array.
185 * @param array $join_conds JOIN conditions
187 protected function addJoinConds( $join_conds ) {
188 if ( !is_array( $join_conds ) ) {
189 ApiBase
::dieDebug( __METHOD__
, 'Join conditions have to be arrays' );
191 $this->join_conds
= array_merge( $this->join_conds
, $join_conds );
195 * Add a set of fields to select to the internal array
196 * @param array|string $value Field name or array of field names
198 protected function addFields( $value ) {
199 if ( is_array( $value ) ) {
200 $this->fields
= array_merge( $this->fields
, $value );
202 $this->fields
[] = $value;
207 * Same as addFields(), but add the fields only if a condition is met
208 * @param array|string $value See addFields()
209 * @param bool $condition If false, do nothing
210 * @return bool $condition
212 protected function addFieldsIf( $value, $condition ) {
214 $this->addFields( $value );
223 * Add a set of WHERE clauses to the internal array.
224 * Clauses can be formatted as 'foo=bar' or [ 'foo' => 'bar' ],
225 * the latter only works if the value is a constant (i.e. not another field)
227 * If $value is an empty array, this function does nothing.
229 * For example, [ 'foo=bar', 'baz' => 3, 'bla' => 'foo' ] translates
230 * to "foo=bar AND baz='3' AND bla='foo'"
231 * @param string|array $value
233 protected function addWhere( $value ) {
234 if ( is_array( $value ) ) {
235 // Sanity check: don't insert empty arrays,
236 // Database::makeList() chokes on them
237 if ( count( $value ) ) {
238 $this->where
= array_merge( $this->where
, $value );
241 $this->where
[] = $value;
246 * Same as addWhere(), but add the WHERE clauses only if a condition is met
247 * @param string|array $value
248 * @param bool $condition If false, do nothing
249 * @return bool $condition
251 protected function addWhereIf( $value, $condition ) {
253 $this->addWhere( $value );
262 * Equivalent to addWhere(array($field => $value))
263 * @param string $field Field name
264 * @param string|string[] $value Value; ignored if null or empty array;
266 protected function addWhereFld( $field, $value ) {
267 // Use count() to its full documented capabilities to simultaneously
268 // test for null, empty array or empty countable object
269 if ( count( $value ) ) {
270 $this->where
[$field] = $value;
275 * Add a WHERE clause corresponding to a range, and an ORDER BY
276 * clause to sort in the right direction
277 * @param string $field Field name
278 * @param string $dir If 'newer', sort in ascending order, otherwise
279 * sort in descending order
280 * @param string $start Value to start the list at. If $dir == 'newer'
281 * this is the lower boundary, otherwise it's the upper boundary
282 * @param string $end Value to end the list at. If $dir == 'newer' this
283 * is the upper boundary, otherwise it's the lower boundary
284 * @param bool $sort If false, don't add an ORDER BY clause
286 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
287 $isDirNewer = ( $dir === 'newer' );
288 $after = ( $isDirNewer ?
'>=' : '<=' );
289 $before = ( $isDirNewer ?
'<=' : '>=' );
290 $db = $this->getDB();
292 if ( !is_null( $start ) ) {
293 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
296 if ( !is_null( $end ) ) {
297 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
301 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
303 $optionOrderBy = isset( $this->options
['ORDER BY'] )
304 ?
(array)$this->options
['ORDER BY']
306 $optionOrderBy[] = $order;
307 $this->addOption( 'ORDER BY', $optionOrderBy );
312 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
313 * but converts $start and $end to database timestamps.
315 * @param string $field
317 * @param string $start
321 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
322 $db = $this->getDB();
323 $this->addWhereRange( $field, $dir,
324 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
328 * Add an option such as LIMIT or USE INDEX. If an option was set
329 * before, the old value will be overwritten
330 * @param string $name Option name
331 * @param string|string[] $value Option value
333 protected function addOption( $name, $value = null ) {
334 if ( is_null( $value ) ) {
335 $this->options
[] = $name;
337 $this->options
[$name] = $value;
342 * Execute a SELECT query based on the values in the internal arrays
343 * @param string $method Function the query should be attributed to.
344 * You should usually use __METHOD__ here
345 * @param array $extraQuery Query data to add but not store in the object
351 * 'join_conds' => ...
353 * @param array|null &$hookData If set, the ApiQueryBaseBeforeQuery and
354 * ApiQueryBaseAfterQuery hooks will be called, and the
355 * ApiQueryBaseProcessRow hook will be expected.
356 * @return ResultWrapper
358 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
359 $tables = array_merge(
361 isset( $extraQuery['tables'] ) ?
(array)$extraQuery['tables'] : []
363 $fields = array_merge(
365 isset( $extraQuery['fields'] ) ?
(array)$extraQuery['fields'] : []
367 $where = array_merge(
369 isset( $extraQuery['where'] ) ?
(array)$extraQuery['where'] : []
371 $options = array_merge(
373 isset( $extraQuery['options'] ) ?
(array)$extraQuery['options'] : []
375 $join_conds = array_merge(
377 isset( $extraQuery['join_conds'] ) ?
(array)$extraQuery['join_conds'] : []
380 if ( $hookData !== null ) {
381 Hooks
::run( 'ApiQueryBaseBeforeQuery',
382 [ $this, &$tables, &$fields, &$where, &$options, &$join_conds, &$hookData ]
386 $res = $this->getDB()->select( $tables, $fields, $where, $method, $options, $join_conds );
388 if ( $hookData !== null ) {
389 Hooks
::run( 'ApiQueryBaseAfterQuery', [ $this, $res, &$hookData ] );
396 * Call the ApiQueryBaseProcessRow hook
398 * Generally, a module that passed $hookData to self::select() will call
399 * this just before calling ApiResult::addValue(), and treat a false return
400 * here in the same way it treats a false return from addValue().
403 * @param object $row Database row
404 * @param array &$data Data to be added to the result
405 * @param array &$hookData Hook data from ApiQueryBase::select()
406 * @return bool Return false if row processing should end with continuation
408 protected function processRow( $row, array &$data, array &$hookData ) {
409 return Hooks
::run( 'ApiQueryBaseProcessRow', [ $this, $row, &$data, &$hookData ] );
413 * @param string $query
414 * @param string $protocol
415 * @return null|string
417 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
418 $db = $this->getDB();
419 if ( !is_null( $query ) ||
$query != '' ) {
420 if ( is_null( $protocol ) ) {
421 $protocol = 'http://';
424 $likeQuery = LinkFilter
::makeLikeArray( $query, $protocol );
426 $this->dieWithError( 'apierror-badquery' );
429 $likeQuery = LinkFilter
::keepOneWildcard( $likeQuery );
431 return 'el_index ' . $db->buildLike( $likeQuery );
432 } elseif ( !is_null( $protocol ) ) {
433 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
440 * Filters hidden users (where the user doesn't have the right to view them)
441 * Also adds relevant block information
443 * @param bool $showBlockInfo
446 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
447 $this->addTables( 'ipblocks' );
448 $this->addJoinConds( [
449 'ipblocks' => [ 'LEFT JOIN', 'ipb_user=user_id' ],
452 $this->addFields( 'ipb_deleted' );
454 if ( $showBlockInfo ) {
465 // Don't show hidden names
466 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
467 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
473 /************************************************************************//**
474 * @name Utility methods
479 * Add information (title and namespace) about a Title object to a
481 * @param array &$arr Result array à la ApiResult
482 * @param Title $title
483 * @param string $prefix Module prefix
485 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
486 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
487 $arr[$prefix . 'title'] = $title->getPrefixedText();
491 * Add a sub-element under the page element with the given page ID
492 * @param int $pageId Page ID
493 * @param array $data Data array à la ApiResult
494 * @return bool Whether the element fit in the result
496 protected function addPageSubItems( $pageId, $data ) {
497 $result = $this->getResult();
498 ApiResult
::setIndexedTagName( $data, $this->getModulePrefix() );
500 return $result->addValue( [ 'query', 'pages', intval( $pageId ) ],
501 $this->getModuleName(),
506 * Same as addPageSubItems(), but one element of $data at a time
507 * @param int $pageId Page ID
508 * @param array $item Data array à la ApiResult
509 * @param string $elemname XML element name. If null, getModuleName()
511 * @return bool Whether the element fit in the result
513 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
514 if ( is_null( $elemname ) ) {
515 $elemname = $this->getModulePrefix();
517 $result = $this->getResult();
518 $fit = $result->addValue( [ 'query', 'pages', $pageId,
519 $this->getModuleName() ], null, $item );
523 $result->addIndexedTagName( [ 'query', 'pages', $pageId,
524 $this->getModuleName() ], $elemname );
530 * Set a query-continue value
531 * @param string $paramName Parameter name
532 * @param string|array $paramValue Parameter value
534 protected function setContinueEnumParameter( $paramName, $paramValue ) {
535 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
539 * Convert an input title or title prefix into a dbkey.
541 * $namespace should always be specified in order to handle per-namespace
542 * capitalization settings.
544 * @param string $titlePart Title part
545 * @param int $namespace Namespace of the title
546 * @return string DBkey (no namespace prefix)
548 public function titlePartToKey( $titlePart, $namespace = NS_MAIN
) {
549 $t = Title
::makeTitleSafe( $namespace, $titlePart . 'x' );
550 if ( !$t ||
$t->hasFragment() ) {
551 // Invalid title (e.g. bad chars) or contained a '#'.
552 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
554 if ( $namespace != $t->getNamespace() ||
$t->isExternal() ) {
555 // This can happen in two cases. First, if you call titlePartToKey with a title part
556 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
557 // difficult to handle such a case. Such cases cannot exist and are therefore treated
558 // as invalid user input. The second case is when somebody specifies a title interwiki
560 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
563 return substr( $t->getDBkey(), 0, -1 );
567 * Convert an input title or title prefix into a namespace constant and dbkey.
570 * @param string $titlePart Title part
571 * @param int $defaultNamespace Default namespace if none is given
572 * @return array (int, string) Namespace number and DBkey
574 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN
) {
575 $t = Title
::newFromText( $titlePart . 'x', $defaultNamespace );
576 if ( !$t ||
$t->hasFragment() ||
$t->isExternal() ) {
577 // Invalid title (e.g. bad chars) or contained a '#'.
578 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
581 return [ $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) ];
585 * @param string $hash
588 public function validateSha1Hash( $hash ) {
589 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
593 * @param string $hash
596 public function validateSha1Base36Hash( $hash ) {
597 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
601 * Check whether the current user has permission to view revision-deleted
605 public function userCanSeeRevDel() {
606 return $this->getUser()->isAllowedAny(