MediaWiki master
ApiQueryBase.php
Go to the documentation of this file.
1<?php
8
9namespace MediaWiki\Api;
10
15use stdClass;
16use Wikimedia\Rdbms\IDatabase;
17use Wikimedia\Rdbms\IExpression;
18use Wikimedia\Rdbms\IReadableDatabase;
19use Wikimedia\Rdbms\IResultWrapper;
20use Wikimedia\Rdbms\SelectQueryBuilder;
21
31abstract class ApiQueryBase extends ApiBase {
33
34 private ?IReadableDatabase $mDb;
36 private array $virtualDBs;
37 private string|false $currentDomain;
38
42 private $queryBuilder;
43
50 public function __construct(
51 private readonly ApiQuery $mQueryModule,
52 string $moduleName,
53 $paramPrefix = '',
54 ) {
55 parent::__construct( $mQueryModule->getMain(), $moduleName, $paramPrefix );
56 $this->mDb = null;
57 $this->virtualDBs = [];
58 $this->currentDomain = false;
59 $this->resetQueryParams();
60 }
61
62 /***************************************************************************/
63 // region Methods to implement
65
78 public function getCacheMode( $params ) {
79 return 'private';
80 }
81
92 public function requestExtraData( $pageSet ) {
93 }
94
95 // endregion -- end of methods to implement
96
97 /***************************************************************************/
98 // region Data access
100
105 public function getQuery() {
106 return $this->mQueryModule;
107 }
108
110 public function getParent() {
111 return $this->getQuery();
112 }
113
121 protected function getDB() {
122 if ( $this->currentDomain ) {
123 if ( !isset( $this->virtualDBs[$this->currentDomain] ) ) {
125 ->getConnectionProvider()
126 ->getReplicaDatabase( $this->currentDomain );
127 $this->virtualDBs[$this->currentDomain] = $db;
128 }
129 return $this->virtualDBs[$this->currentDomain];
130 }
131
132 $this->mDb ??= $this->getQuery()->getDB();
133
134 return $this->mDb;
135 }
136
143 protected function setVirtualDomain( string|false $virtualDomain ) {
144 $this->currentDomain = $virtualDomain;
145 $this->updateQueryBuilderConnection();
146 }
147
153 protected function resetVirtualDomain() {
154 $this->currentDomain = false;
155 $this->updateQueryBuilderConnection();
156 }
157
158 private function updateQueryBuilderConnection() {
159 if ( $this->queryBuilder ) {
160 $this->queryBuilder->connection( $this->getDB() );
161 }
162 }
163
169 protected function getPageSet() {
170 return $this->getQuery()->getPageSet();
171 }
172
173 // endregion -- end of data access
174
175 /***************************************************************************/
176 // region Querying
178
182 protected function resetQueryParams() {
183 $this->queryBuilder = null;
184 }
185
194 protected function getQueryBuilder() {
195 $this->queryBuilder ??= $this->getDB()->newSelectQueryBuilder();
196 return $this->queryBuilder;
197 }
198
206 protected function addTables( $tables, $alias = null ) {
207 if ( is_array( $tables ) ) {
208 if ( $alias !== null ) {
209 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
210 }
211 $this->getQueryBuilder()->rawTables( $tables );
212 } else {
213 $this->getQueryBuilder()->table( $tables, $alias );
214 }
215 }
216
225 protected function addJoinConds( $join_conds ) {
226 if ( !is_array( $join_conds ) ) {
227 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
228 }
229 $this->getQueryBuilder()->joinConds( $join_conds );
230 }
231
236 protected function addFields( $value ) {
237 $this->getQueryBuilder()->fields( $value );
238 }
239
246 protected function addFieldsIf( $value, $condition ) {
247 if ( $condition ) {
248 $this->addFields( $value );
249
250 return true;
251 }
252
253 return false;
254 }
255
269 protected function addWhere( $value ) {
270 if ( is_array( $value ) ) {
271 // Double check: don't insert empty arrays,
272 // Database::makeList() chokes on them
273 if ( count( $value ) ) {
274 $this->getQueryBuilder()->where( $value );
275 }
276 } else {
277 $this->getQueryBuilder()->where( $value );
278 }
279 }
280
287 protected function addWhereIf( $value, $condition ) {
288 if ( $condition ) {
289 $this->addWhere( $value );
290
291 return true;
292 }
293
294 return false;
295 }
296
306 protected function addWhereFld( $field, $value ) {
307 if ( $value !== null && !( is_array( $value ) && !$value ) ) {
308 $this->getQueryBuilder()->where( [ $field => $value ] );
309 }
310 }
311
333 protected function addWhereIDsFld( $table, $field, $ids ) {
334 // Use count() to its full documented capabilities to simultaneously
335 // test for null, empty array or empty countable object
336 if ( count( $ids ) ) {
337 $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
338
339 if ( $ids === [] ) {
340 // Return nothing, no IDs are valid
341 $this->getQueryBuilder()->where( '0 = 1' );
342 } else {
343 $this->getQueryBuilder()->where( [ $field => $ids ] );
344 }
345 }
346 return count( $ids );
347 }
348
361 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
362 $isDirNewer = ( $dir === 'newer' );
363 $after = ( $isDirNewer ? '>=' : '<=' );
364 $before = ( $isDirNewer ? '<=' : '>=' );
365 $db = $this->getDB();
366
367 if ( $start !== null ) {
368 $this->addWhere( $db->expr( $field, $after, $start ) );
369 }
370
371 if ( $end !== null ) {
372 $this->addWhere( $db->expr( $field, $before, $end ) );
373 }
374
375 if ( $sort ) {
376 $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
377 }
378
379 if ( // Warn if the range is impossible due to reversed boundaries
380 ( is_numeric( $start ) && is_numeric( $end ) ) && (
381 ( $isDirNewer && $start > $end ) ||
382 ( !$isDirNewer && $start < $end )
383 ) ) {
384 // If $isDirNewer: $field >= $start AND $field <= $end
385 // If !$isDirNewer: $field <= $start AND $field >= $end
386 $op = $isDirNewer ? '<' : '>';
387 $this->addWarning( [ 'apiwarn-invalidrange', "$start $op $end" ] );
388 }
389 }
390
401 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
402 $db = $this->getDB();
403 $this->addWhereRange( $field, $dir,
404 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
405 }
406
413 protected function addOption( $name, $value = null ) {
414 $this->getQueryBuilder()->option( $name, $value );
415 }
416
434 protected function select( $method, $extraQuery = [], ?array &$hookData = null ) {
435 $queryBuilder = clone $this->getQueryBuilder();
436 if ( isset( $extraQuery['tables'] ) ) {
437 $queryBuilder->rawTables( (array)$extraQuery['tables'] );
438 }
439 if ( isset( $extraQuery['fields'] ) ) {
440 $queryBuilder->fields( (array)$extraQuery['fields'] );
441 }
442 if ( isset( $extraQuery['where'] ) ) {
443 $queryBuilder->where( (array)$extraQuery['where'] );
444 }
445 if ( isset( $extraQuery['options'] ) ) {
446 $queryBuilder->options( (array)$extraQuery['options'] );
447 }
448 if ( isset( $extraQuery['join_conds'] ) ) {
449 $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
450 }
451
452 if ( $hookData !== null && $this->getHookContainer()->isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
453 $info = $queryBuilder->getQueryInfo();
454 $this->getHookRunner()->onApiQueryBaseBeforeQuery(
455 $this, $info['tables'], $info['fields'], $info['conds'],
456 $info['options'], $info['join_conds'], $hookData
457 );
458 $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
459 }
460
461 $queryBuilder->caller( $method );
462 $res = $queryBuilder->fetchResultSet();
463
464 if ( $hookData !== null ) {
465 $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
466 }
467
468 return $res;
469 }
470
484 protected function processRow( $row, array &$data, array &$hookData ) {
485 return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
486 }
487
488 // endregion -- end of querying
489
490 /***************************************************************************/
491 // region Utility methods
493
501 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
502 $arr[$prefix . 'ns'] = $title->getNamespace();
503 $arr[$prefix . 'title'] = $title->getPrefixedText();
504 }
505
512 protected function addPageSubItems( $pageId, $data ) {
513 $result = $this->getResult();
515
516 return $result->addValue( [ 'query', 'pages', (int)$pageId ],
517 $this->getModuleName(),
518 $data );
519 }
520
529 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
530 $result = $this->getResult();
531 $fit = $result->addValue( [ 'query', 'pages', $pageId,
532 $this->getModuleName() ], null, $item );
533 if ( !$fit ) {
534 return false;
535 }
536 $result->addIndexedTagName(
537 [ 'query', 'pages', $pageId, $this->getModuleName() ],
538 $elemname ?? $this->getModulePrefix()
539 );
540
541 return true;
542 }
543
549 protected function setContinueEnumParameter( $paramName, $paramValue ) {
550 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
551 }
552
563 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
564 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
565 if ( !$t || $t->hasFragment() ) {
566 // Invalid title (e.g. bad chars) or contained a '#'.
567 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
568 }
569 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
570 // This can happen in two cases. First, if you call titlePartToKey with a title part
571 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
572 // difficult to handle such a case. Such cases cannot exist and are therefore treated
573 // as invalid user input. The second case is when somebody specifies a title interwiki
574 // prefix.
575 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
576 }
577
578 return substr( $t->getDBkey(), 0, -1 );
579 }
580
589 protected function parsePrefixedTitlePart( $titlePart, $defaultNamespace = NS_MAIN ) {
590 try {
591 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
592 $t = $titleParser->parseTitle( $titlePart . 'X', $defaultNamespace );
593 } catch ( MalformedTitleException ) {
594 $t = null;
595 }
596
597 if ( !$t || $t->hasFragment() || $t->isExternal() || $t->getDBkey() === 'X' ) {
598 // Invalid title (e.g. bad chars) or contained a '#'.
599 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
600 }
601
602 return new TitleValue( $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) );
603 }
604
609 public function validateSha1Hash( $hash ) {
610 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
611 }
612
617 public function validateSha1Base36Hash( $hash ) {
618 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
619 }
620
626 public function userCanSeeRevDel() {
627 return $this->getAuthority()->isAllowedAny(
628 'deletedhistory',
629 'deletedtext',
630 'deleterevision',
631 'suppressrevision',
632 'viewsuppressed'
633 );
634 }
635
646 IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
647 ) {
648 if ( !$res->numRows() ) {
649 return;
650 }
651
652 $services = MediaWikiServices::getInstance();
653 if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
654 return;
655 }
656
657 $nsInfo = $services->getNamespaceInfo();
658 $namespaceField = $fieldPrefix . '_namespace';
659 $titleField = $fieldPrefix . '_title';
660
661 $usernames = [];
662 foreach ( $res as $row ) {
663 if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
664 $usernames[] = $row->$titleField;
665 }
666 }
667
668 if ( $usernames === [] ) {
669 return;
670 }
671
672 $genderCache = $services->getGenderCache();
673 $genderCache->doQuery( $usernames, $fname );
674 }
675
676 // endregion -- end of utility methods
677}
678
680class_alias( ApiQueryBase::class, 'ApiQueryBase' );
const NS_MAIN
Definition Defines.php:51
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:59
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1482
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:565
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:556
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:776
getResult()
Get the result object.
Definition ApiBase.php:695
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1399
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition ApiBase.php:1356
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1719
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition ApiBase.php:764
This is a base class for all Query modules.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
getParent()
Get the parent of this module.to override 1.25 ApiBase|null
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
addPageSubItems( $pageId, $data)
Add a sub-element under the page element with the given page ID.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereIDsFld( $table, $field, $ids)
Like addWhereFld for an integer list of IDs.
resetVirtualDomain()
Reset the virtual domain to the main database.
setVirtualDomain(string|false $virtualDomain)
Set the Query database connection (read-only).
getDB()
Get the Query database connection (read-only).
requestExtraData( $pageSet)
Override this method to request extra fields from the pageSet using $pageSet->requestField('fieldName...
select( $method, $extraQuery=[], ?array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
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.
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self\ad...
parsePrefixedTitlePart( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a TitleValue.
getPageSet()
Get the PageSet object to work on.
__construct(private readonly ApiQuery $mQueryModule, string $moduleName, $paramPrefix='',)
getCacheMode( $params)
Get the cache mode for the data generated by this module.
getQuery()
Get the main Query module.
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
getQueryBuilder()
Get the SelectQueryBuilder.
userCanSeeRevDel()
Check whether the current user has permission to view revision-deleted fields.
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
resetQueryParams()
Blank the internal arrays with query parameters.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] ).
addFields( $value)
Add a set of fields to select to the internal array.
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.
This is the main query class.
Definition ApiQuery.php:36
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
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:69
Build SELECT queries with a fluent interface.
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.