MediaWiki master
ApiQueryBase.php
Go to the documentation of this file.
1<?php
32
42abstract class ApiQueryBase extends ApiBase {
44
45 private ApiQuery $mQueryModule;
46 private ?IReadableDatabase $mDb;
47
51 private $queryBuilder;
52
59 public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
60 parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
61 $this->mQueryModule = $queryModule;
62 $this->mDb = null;
63 $this->resetQueryParams();
64 }
65
66 /***************************************************************************/
67 // region Methods to implement
82 public function getCacheMode( $params ) {
83 return 'private';
84 }
85
96 public function requestExtraData( $pageSet ) {
97 }
98
99 // endregion -- end of methods to implement
100
101 /***************************************************************************/
102 // region Data access
109 public function getQuery() {
110 return $this->mQueryModule;
111 }
112
114 public function getParent() {
115 return $this->getQuery();
116 }
117
123 protected function getDB() {
124 $this->mDb ??= $this->getQuery()->getDB();
125
126 return $this->mDb;
127 }
128
134 protected function getPageSet() {
135 return $this->getQuery()->getPageSet();
136 }
137
138 // endregion -- end of data access
139
140 /***************************************************************************/
141 // region Querying
147 protected function resetQueryParams() {
148 $this->queryBuilder = null;
149 }
150
159 protected function getQueryBuilder() {
160 $this->queryBuilder ??= $this->getDB()->newSelectQueryBuilder();
161 return $this->queryBuilder;
162 }
163
171 protected function addTables( $tables, $alias = null ) {
172 if ( is_array( $tables ) ) {
173 if ( $alias !== null ) {
174 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
175 }
176 $this->getQueryBuilder()->rawTables( $tables );
177 } else {
178 $this->getQueryBuilder()->table( $tables, $alias );
179 }
180 }
181
190 protected function addJoinConds( $join_conds ) {
191 if ( !is_array( $join_conds ) ) {
192 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
193 }
194 $this->getQueryBuilder()->joinConds( $join_conds );
195 }
196
201 protected function addFields( $value ) {
202 $this->getQueryBuilder()->fields( $value );
203 }
204
211 protected function addFieldsIf( $value, $condition ) {
212 if ( $condition ) {
213 $this->addFields( $value );
214
215 return true;
216 }
217
218 return false;
219 }
220
234 protected function addWhere( $value ) {
235 if ( is_array( $value ) ) {
236 // Double check: don't insert empty arrays,
237 // Database::makeList() chokes on them
238 if ( count( $value ) ) {
239 $this->getQueryBuilder()->where( $value );
240 }
241 } else {
242 $this->getQueryBuilder()->where( $value );
243 }
244 }
245
252 protected function addWhereIf( $value, $condition ) {
253 if ( $condition ) {
254 $this->addWhere( $value );
255
256 return true;
257 }
258
259 return false;
260 }
261
271 protected function addWhereFld( $field, $value ) {
272 if ( $value !== null && !( is_array( $value ) && !$value ) ) {
273 $this->getQueryBuilder()->where( [ $field => $value ] );
274 }
275 }
276
298 protected function addWhereIDsFld( $table, $field, $ids ) {
299 // Use count() to its full documented capabilities to simultaneously
300 // test for null, empty array or empty countable object
301 if ( count( $ids ) ) {
302 $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
303
304 if ( $ids === [] ) {
305 // Return nothing, no IDs are valid
306 $this->getQueryBuilder()->where( '0 = 1' );
307 } else {
308 $this->getQueryBuilder()->where( [ $field => $ids ] );
309 }
310 }
311 return count( $ids );
312 }
313
326 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
327 $isDirNewer = ( $dir === 'newer' );
328 $after = ( $isDirNewer ? '>=' : '<=' );
329 $before = ( $isDirNewer ? '<=' : '>=' );
330 $db = $this->getDB();
331
332 if ( $start !== null ) {
333 $this->addWhere( $db->expr( $field, $after, $start ) );
334 }
335
336 if ( $end !== null ) {
337 $this->addWhere( $db->expr( $field, $before, $end ) );
338 }
339
340 if ( $sort ) {
341 $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
342 }
343 }
344
355 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
356 $db = $this->getDB();
357 $this->addWhereRange( $field, $dir,
358 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
359 }
360
367 protected function addOption( $name, $value = null ) {
368 $this->getQueryBuilder()->option( $name, $value );
369 }
370
388 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
389 $queryBuilder = clone $this->getQueryBuilder();
390 if ( isset( $extraQuery['tables'] ) ) {
391 $queryBuilder->rawTables( (array)$extraQuery['tables'] );
392 }
393 if ( isset( $extraQuery['fields'] ) ) {
394 $queryBuilder->fields( (array)$extraQuery['fields'] );
395 }
396 if ( isset( $extraQuery['where'] ) ) {
397 $queryBuilder->where( (array)$extraQuery['where'] );
398 }
399 if ( isset( $extraQuery['options'] ) ) {
400 $queryBuilder->options( (array)$extraQuery['options'] );
401 }
402 if ( isset( $extraQuery['join_conds'] ) ) {
403 $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
404 }
405
406 if ( $hookData !== null && $this->getHookContainer()->isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
407 $info = $queryBuilder->getQueryInfo();
408 $this->getHookRunner()->onApiQueryBaseBeforeQuery(
409 $this, $info['tables'], $info['fields'], $info['conds'],
410 $info['options'], $info['join_conds'], $hookData
411 );
412 $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
413 }
414
415 $queryBuilder->caller( $method );
416 $res = $queryBuilder->fetchResultSet();
417
418 if ( $hookData !== null ) {
419 $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
420 }
421
422 return $res;
423 }
424
438 protected function processRow( $row, array &$data, array &$hookData ) {
439 return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
440 }
441
442 // endregion -- end of querying
443
444 /***************************************************************************/
445 // region Utility methods
455 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
456 $arr[$prefix . 'ns'] = $title->getNamespace();
457 $arr[$prefix . 'title'] = $title->getPrefixedText();
458 }
459
466 protected function addPageSubItems( $pageId, $data ) {
467 $result = $this->getResult();
468 ApiResult::setIndexedTagName( $data, $this->getModulePrefix() );
469
470 return $result->addValue( [ 'query', 'pages', (int)$pageId ],
471 $this->getModuleName(),
472 $data );
473 }
474
483 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
484 $result = $this->getResult();
485 $fit = $result->addValue( [ 'query', 'pages', $pageId,
486 $this->getModuleName() ], null, $item );
487 if ( !$fit ) {
488 return false;
489 }
490 $result->addIndexedTagName(
491 [ 'query', 'pages', $pageId, $this->getModuleName() ],
492 $elemname ?? $this->getModulePrefix()
493 );
494
495 return true;
496 }
497
503 protected function setContinueEnumParameter( $paramName, $paramValue ) {
504 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
505 }
506
517 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
518 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
519 if ( !$t || $t->hasFragment() ) {
520 // Invalid title (e.g. bad chars) or contained a '#'.
521 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
522 }
523 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
524 // This can happen in two cases. First, if you call titlePartToKey with a title part
525 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
526 // difficult to handle such a case. Such cases cannot exist and are therefore treated
527 // as invalid user input. The second case is when somebody specifies a title interwiki
528 // prefix.
529 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
530 }
531
532 return substr( $t->getDBkey(), 0, -1 );
533 }
534
543 protected function parsePrefixedTitlePart( $titlePart, $defaultNamespace = NS_MAIN ) {
544 try {
545 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
546 $t = $titleParser->parseTitle( $titlePart . 'X', $defaultNamespace );
547 } catch ( MalformedTitleException $e ) {
548 $t = null;
549 }
550
551 if ( !$t || $t->hasFragment() || $t->isExternal() || $t->getDBkey() === 'X' ) {
552 // Invalid title (e.g. bad chars) or contained a '#'.
553 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
554 }
555
556 return new TitleValue( $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) );
557 }
558
563 public function validateSha1Hash( $hash ) {
564 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
565 }
566
571 public function validateSha1Base36Hash( $hash ) {
572 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
573 }
574
580 public function userCanSeeRevDel() {
581 return $this->getAuthority()->isAllowedAny(
582 'deletedhistory',
583 'deletedtext',
584 'deleterevision',
585 'suppressrevision',
586 'viewsuppressed'
587 );
588 }
589
600 IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
601 ) {
602 if ( !$res->numRows() ) {
603 return;
604 }
605
606 $services = MediaWikiServices::getInstance();
607 if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
608 return;
609 }
610
611 $nsInfo = $services->getNamespaceInfo();
612 $namespaceField = $fieldPrefix . '_namespace';
613 $titleField = $fieldPrefix . '_title';
614
615 $usernames = [];
616 foreach ( $res as $row ) {
617 if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
618 $usernames[] = $row->$titleField;
619 }
620 }
621
622 if ( $usernames === [] ) {
623 return;
624 }
625
626 $genderCache = $services->getGenderCache();
627 $genderCache->doQuery( $usernames, $fname );
628 }
629
630 // endregion -- end of utility methods
631}
getAuthority()
getDB()
addWhere( $conds)
addFields( $fields)
getQueryBuilder()
const NS_MAIN
Definition Defines.php:65
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
array $params
The job parameters.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:64
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1542
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:550
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition ApiBase.php:1417
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1786
getMain()
Get the main module.
Definition ApiBase.php:559
getResult()
Get the result object.
Definition ApiBase.php:680
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:541
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:765
getContinuationManager()
Definition ApiBase.php:717
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition ApiBase.php:750
This is a base class for all Query modules.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
parsePrefixedTitlePart( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a TitleValue.
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
validateSha1Base36Hash( $hash)
resetQueryParams()
Blank the internal arrays with query parameters.
getCacheMode( $params)
Get the cache mode for the data generated by this module.
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction.
getQueryBuilder()
Get the SelectQueryBuilder.
addPageSubItems( $pageId, $data)
Add a sub-element under the page element with the given page ID.
validateSha1Hash( $hash)
addFields( $value)
Add a set of fields to select to the internal array.
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
getParent()
Get the parent of this module.to override 1.25 ApiBase|null
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
getDB()
Get the Query database connection (read-only)
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
addWhereIDsFld( $table, $field, $ids)
Like addWhereFld for an integer list of IDs.
requestExtraData( $pageSet)
Override this method to request extra fields from the pageSet using $pageSet->requestField('fieldName...
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
getQuery()
Get the main Query module.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
getPageSet()
Get the PageSet object to work on.
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
__construct(ApiQuery $queryModule, $moduleName, $paramPrefix='')
userCanSeeRevDel()
Check whether the current user has permission to view revision-deleted fields.
This is the main query class.
Definition ApiQuery.php:43
Service locator for MediaWiki core services.
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Represents the target of a wiki link.
Represents a title within MediaWiki.
Definition Title.php:78
Build SELECT queries with a fluent interface.
getQueryInfo( $joinsName='join_conds')
Get an associative array describing the query in terms of its raw parameters to Database::select().
rawTables( $tables)
Given a table or table array as might be passed to Database::select(), append it to the existing tabl...
fetchResultSet()
Run the constructed SELECT query and return all results.
queryInfo( $info)
Set the query parameters to the given values, appending to the values which were already set.
options(array $options)
Manually set multiple options in the $options array to be passed to IReadableDatabase::select().
caller( $fname)
Set the method name to be included in an SQL comment.
joinConds(array $joinConds)
Manually append to the $join_conds array which will be passed to IReadableDatabase::select().
fields( $fields)
Add a field or an array of fields to the query.
where( $conds)
Add conditions to the query.
trait ApiQueryBlockInfoTrait
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:36
A database connection without write operations.
Result wrapper for grabbing data queried from an IDatabase object.
numRows()
Get the number of rows in a result object.