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 public function getParent() {
102 return $this->getQuery();
106 * Get the Query database connection (read-only)
109 protected function getDB() {
110 if ( is_null( $this->mDb
) ) {
111 $this->mDb
= $this->getQuery()->getDB();
118 * Selects the query database connection with the given name.
119 * See ApiQuery::getNamedDB() for more information
120 * @param string $name Name to assign to the database connection
121 * @param int $db One of the DB_* constants
122 * @param string|string[] $groups Query groups
125 public function selectNamedDB( $name, $db, $groups ) {
126 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
131 * Get the PageSet object to work on
134 protected function getPageSet() {
135 return $this->getQuery()->getPageSet();
140 /************************************************************************//**
146 * Blank the internal arrays with query parameters
148 protected function resetQueryParams() {
153 $this->join_conds
= [];
157 * Add a set of tables to the internal array
158 * @param string|string[] $tables Table name or array of table names
159 * @param string|null $alias Table alias, or null for no alias. Cannot be
160 * used with multiple tables
162 protected function addTables( $tables, $alias = null ) {
163 if ( is_array( $tables ) ) {
164 if ( !is_null( $alias ) ) {
165 ApiBase
::dieDebug( __METHOD__
, 'Multiple table aliases not supported' );
167 $this->tables
= array_merge( $this->tables
, $tables );
169 if ( !is_null( $alias ) ) {
170 $this->tables
[$alias] = $tables;
172 $this->tables
[] = $tables;
178 * Add a set of JOIN conditions to the internal array
180 * JOIN conditions are formatted as [ tablename => [ jointype, conditions ] ]
181 * e.g. [ 'page' => [ 'LEFT JOIN', 'page_id=rev_page' ] ].
182 * Conditions may be a string or an addWhere()-style array.
183 * @param array $join_conds JOIN conditions
185 protected function addJoinConds( $join_conds ) {
186 if ( !is_array( $join_conds ) ) {
187 ApiBase
::dieDebug( __METHOD__
, 'Join conditions have to be arrays' );
189 $this->join_conds
= array_merge( $this->join_conds
, $join_conds );
193 * Add a set of fields to select to the internal array
194 * @param array|string $value Field name or array of field names
196 protected function addFields( $value ) {
197 if ( is_array( $value ) ) {
198 $this->fields
= array_merge( $this->fields
, $value );
200 $this->fields
[] = $value;
205 * Same as addFields(), but add the fields only if a condition is met
206 * @param array|string $value See addFields()
207 * @param bool $condition If false, do nothing
208 * @return bool $condition
210 protected function addFieldsIf( $value, $condition ) {
212 $this->addFields( $value );
221 * Add a set of WHERE clauses to the internal array.
222 * Clauses can be formatted as 'foo=bar' or [ 'foo' => 'bar' ],
223 * the latter only works if the value is a constant (i.e. not another field)
225 * If $value is an empty array, this function does nothing.
227 * For example, [ 'foo=bar', 'baz' => 3, 'bla' => 'foo' ] translates
228 * to "foo=bar AND baz='3' AND bla='foo'"
229 * @param string|array $value
231 protected function addWhere( $value ) {
232 if ( is_array( $value ) ) {
233 // Sanity check: don't insert empty arrays,
234 // Database::makeList() chokes on them
235 if ( count( $value ) ) {
236 $this->where
= array_merge( $this->where
, $value );
239 $this->where
[] = $value;
244 * Same as addWhere(), but add the WHERE clauses only if a condition is met
245 * @param string|array $value
246 * @param bool $condition If false, do nothing
247 * @return bool $condition
249 protected function addWhereIf( $value, $condition ) {
251 $this->addWhere( $value );
260 * Equivalent to addWhere(array($field => $value))
261 * @param string $field Field name
262 * @param string|string[] $value Value; ignored if null or empty array;
264 protected function addWhereFld( $field, $value ) {
265 if ( $value !== null && count( $value ) ) {
266 $this->where
[$field] = $value;
271 * Add a WHERE clause corresponding to a range, and an ORDER BY
272 * clause to sort in the right direction
273 * @param string $field Field name
274 * @param string $dir If 'newer', sort in ascending order, otherwise
275 * sort in descending order
276 * @param string $start Value to start the list at. If $dir == 'newer'
277 * this is the lower boundary, otherwise it's the upper boundary
278 * @param string $end Value to end the list at. If $dir == 'newer' this
279 * is the upper boundary, otherwise it's the lower boundary
280 * @param bool $sort If false, don't add an ORDER BY clause
282 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
283 $isDirNewer = ( $dir === 'newer' );
284 $after = ( $isDirNewer ?
'>=' : '<=' );
285 $before = ( $isDirNewer ?
'<=' : '>=' );
286 $db = $this->getDB();
288 if ( !is_null( $start ) ) {
289 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
292 if ( !is_null( $end ) ) {
293 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
297 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
299 $optionOrderBy = isset( $this->options
['ORDER BY'] )
300 ?
(array)$this->options
['ORDER BY']
302 $optionOrderBy[] = $order;
303 $this->addOption( 'ORDER BY', $optionOrderBy );
308 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
309 * but converts $start and $end to database timestamps.
311 * @param string $field
313 * @param string $start
317 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
318 $db = $this->getDB();
319 $this->addWhereRange( $field, $dir,
320 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
324 * Add an option such as LIMIT or USE INDEX. If an option was set
325 * before, the old value will be overwritten
326 * @param string $name Option name
327 * @param string|string[] $value Option value
329 protected function addOption( $name, $value = null ) {
330 if ( is_null( $value ) ) {
331 $this->options
[] = $name;
333 $this->options
[$name] = $value;
338 * Execute a SELECT query based on the values in the internal arrays
339 * @param string $method Function the query should be attributed to.
340 * You should usually use __METHOD__ here
341 * @param array $extraQuery Query data to add but not store in the object
347 * 'join_conds' => ...
349 * @param array|null &$hookData If set, the ApiQueryBaseBeforeQuery and
350 * ApiQueryBaseAfterQuery hooks will be called, and the
351 * ApiQueryBaseProcessRow hook will be expected.
352 * @return ResultWrapper
354 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
355 $tables = array_merge(
357 isset( $extraQuery['tables'] ) ?
(array)$extraQuery['tables'] : []
359 $fields = array_merge(
361 isset( $extraQuery['fields'] ) ?
(array)$extraQuery['fields'] : []
363 $where = array_merge(
365 isset( $extraQuery['where'] ) ?
(array)$extraQuery['where'] : []
367 $options = array_merge(
369 isset( $extraQuery['options'] ) ?
(array)$extraQuery['options'] : []
371 $join_conds = array_merge(
373 isset( $extraQuery['join_conds'] ) ?
(array)$extraQuery['join_conds'] : []
376 if ( $hookData !== null ) {
377 Hooks
::run( 'ApiQueryBaseBeforeQuery',
378 [ $this, &$tables, &$fields, &$where, &$options, &$join_conds, &$hookData ]
382 $res = $this->getDB()->select( $tables, $fields, $where, $method, $options, $join_conds );
384 if ( $hookData !== null ) {
385 Hooks
::run( 'ApiQueryBaseAfterQuery', [ $this, $res, &$hookData ] );
392 * Call the ApiQueryBaseProcessRow hook
394 * Generally, a module that passed $hookData to self::select() will call
395 * this just before calling ApiResult::addValue(), and treat a false return
396 * here in the same way it treats a false return from addValue().
399 * @param object $row Database row
400 * @param array &$data Data to be added to the result
401 * @param array &$hookData Hook data from ApiQueryBase::select()
402 * @return bool Return false if row processing should end with continuation
404 protected function processRow( $row, array &$data, array &$hookData ) {
405 return Hooks
::run( 'ApiQueryBaseProcessRow', [ $this, $row, &$data, &$hookData ] );
409 * @param string $query
410 * @param string $protocol
411 * @return null|string
413 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
414 $db = $this->getDB();
415 if ( !is_null( $query ) ||
$query != '' ) {
416 if ( is_null( $protocol ) ) {
417 $protocol = 'http://';
420 $likeQuery = LinkFilter
::makeLikeArray( $query, $protocol );
422 $this->dieWithError( 'apierror-badquery' );
425 $likeQuery = LinkFilter
::keepOneWildcard( $likeQuery );
427 return 'el_index ' . $db->buildLike( $likeQuery );
428 } elseif ( !is_null( $protocol ) ) {
429 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
436 * Filters hidden users (where the user doesn't have the right to view them)
437 * Also adds relevant block information
439 * @param bool $showBlockInfo
442 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
443 $this->addTables( 'ipblocks' );
444 $this->addJoinConds( [
445 'ipblocks' => [ 'LEFT JOIN', 'ipb_user=user_id' ],
448 $this->addFields( 'ipb_deleted' );
450 if ( $showBlockInfo ) {
458 $commentQuery = CommentStore
::newKey( 'ipb_reason' )->getJoin();
459 $this->addTables( $commentQuery['tables'] );
460 $this->addFields( $commentQuery['fields'] );
461 $this->addJoinConds( $commentQuery['joins'] );
464 // Don't show hidden names
465 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
466 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
472 /************************************************************************//**
473 * @name Utility methods
478 * Add information (title and namespace) about a Title object to a
480 * @param array &$arr Result array à la ApiResult
481 * @param Title $title
482 * @param string $prefix Module prefix
484 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
485 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
486 $arr[$prefix . 'title'] = $title->getPrefixedText();
490 * Add a sub-element under the page element with the given page ID
491 * @param int $pageId Page ID
492 * @param array $data Data array à la ApiResult
493 * @return bool Whether the element fit in the result
495 protected function addPageSubItems( $pageId, $data ) {
496 $result = $this->getResult();
497 ApiResult
::setIndexedTagName( $data, $this->getModulePrefix() );
499 return $result->addValue( [ 'query', 'pages', intval( $pageId ) ],
500 $this->getModuleName(),
505 * Same as addPageSubItems(), but one element of $data at a time
506 * @param int $pageId Page ID
507 * @param array $item Data array à la ApiResult
508 * @param string $elemname XML element name. If null, getModuleName()
510 * @return bool Whether the element fit in the result
512 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
513 if ( is_null( $elemname ) ) {
514 $elemname = $this->getModulePrefix();
516 $result = $this->getResult();
517 $fit = $result->addValue( [ 'query', 'pages', $pageId,
518 $this->getModuleName() ], null, $item );
522 $result->addIndexedTagName( [ 'query', 'pages', $pageId,
523 $this->getModuleName() ], $elemname );
529 * Set a query-continue value
530 * @param string $paramName Parameter name
531 * @param string|array $paramValue Parameter value
533 protected function setContinueEnumParameter( $paramName, $paramValue ) {
534 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
538 * Convert an input title or title prefix into a dbkey.
540 * $namespace should always be specified in order to handle per-namespace
541 * capitalization settings.
543 * @param string $titlePart Title part
544 * @param int $namespace Namespace of the title
545 * @return string DBkey (no namespace prefix)
547 public function titlePartToKey( $titlePart, $namespace = NS_MAIN
) {
548 $t = Title
::makeTitleSafe( $namespace, $titlePart . 'x' );
549 if ( !$t ||
$t->hasFragment() ) {
550 // Invalid title (e.g. bad chars) or contained a '#'.
551 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
553 if ( $namespace != $t->getNamespace() ||
$t->isExternal() ) {
554 // This can happen in two cases. First, if you call titlePartToKey with a title part
555 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
556 // difficult to handle such a case. Such cases cannot exist and are therefore treated
557 // as invalid user input. The second case is when somebody specifies a title interwiki
559 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
562 return substr( $t->getDBkey(), 0, -1 );
566 * Convert an input title or title prefix into a namespace constant and dbkey.
569 * @param string $titlePart Title part
570 * @param int $defaultNamespace Default namespace if none is given
571 * @return array (int, string) Namespace number and DBkey
573 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN
) {
574 $t = Title
::newFromText( $titlePart . 'x', $defaultNamespace );
575 if ( !$t ||
$t->hasFragment() ||
$t->isExternal() ) {
576 // Invalid title (e.g. bad chars) or contained a '#'.
577 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
580 return [ $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) ];
584 * @param string $hash
587 public function validateSha1Hash( $hash ) {
588 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
592 * @param string $hash
595 public function validateSha1Base36Hash( $hash ) {
596 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
600 * Check whether the current user has permission to view revision-deleted
604 public function userCanSeeRevDel() {
605 return $this->getUser()->isAllowedAny(