MediaWiki REL1_37
ApiQueryBase.php
Go to the documentation of this file.
1<?php
27
37abstract class ApiQueryBase extends ApiBase {
39
41
46
53 public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
54 parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
55 $this->mQueryModule = $queryModule;
56 $this->mDb = null;
57 $this->resetQueryParams();
58 }
59
60 /***************************************************************************/
61 // region Methods to implement
76 public function getCacheMode( $params ) {
77 return 'private';
78 }
79
90 public function requestExtraData( $pageSet ) {
91 }
92
93 // endregion -- end of methods to implement
94
95 /***************************************************************************/
96 // region Data access
103 public function getQuery() {
104 return $this->mQueryModule;
105 }
106
108 public function getParent() {
109 return $this->getQuery();
110 }
111
117 protected function getDB() {
118 if ( $this->mDb === null ) {
119 $this->mDb = $this->getQuery()->getDB();
120 }
121
122 return $this->mDb;
123 }
124
133 public function selectNamedDB( $name, $db, $groups ) {
134 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
135 return $this->mDb;
136 }
137
143 protected function getPageSet() {
144 return $this->getQuery()->getPageSet();
145 }
146
147 // endregion -- end of data access
148
149 /***************************************************************************/
150 // region Querying
156 protected function resetQueryParams() {
157 $this->queryBuilder = null;
158 }
159
168 protected function getQueryBuilder() {
169 if ( $this->queryBuilder === null ) {
170 $this->queryBuilder = $this->getDB()->newSelectQueryBuilder();
171 }
172 return $this->queryBuilder;
173 }
174
182 protected function addTables( $tables, $alias = null ) {
183 if ( is_array( $tables ) ) {
184 if ( $alias !== null ) {
185 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
186 }
187 $this->getQueryBuilder()->rawTables( $tables );
188 } else {
189 $this->getQueryBuilder()->table( $tables, $alias );
190 }
191 }
192
201 protected function addJoinConds( $join_conds ) {
202 if ( !is_array( $join_conds ) ) {
203 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
204 }
205 $this->getQueryBuilder()->joinConds( $join_conds );
206 }
207
212 protected function addFields( $value ) {
213 $this->getQueryBuilder()->fields( $value );
214 }
215
222 protected function addFieldsIf( $value, $condition ) {
223 if ( $condition ) {
224 $this->addFields( $value );
225
226 return true;
227 }
228
229 return false;
230 }
231
245 protected function addWhere( $value ) {
246 if ( is_array( $value ) ) {
247 // Sanity check: don't insert empty arrays,
248 // Database::makeList() chokes on them
249 if ( count( $value ) ) {
250 $this->getQueryBuilder()->where( $value );
251 }
252 } else {
253 $this->getQueryBuilder()->where( $value );
254 }
255 }
256
263 protected function addWhereIf( $value, $condition ) {
264 if ( $condition ) {
265 $this->addWhere( $value );
266
267 return true;
268 }
269
270 return false;
271 }
272
282 protected function addWhereFld( $field, $value ) {
283 if ( $value !== null && !( is_array( $value ) && !$value ) ) {
284 $this->getQueryBuilder()->where( [ $field => $value ] );
285 }
286 }
287
309 protected function addWhereIDsFld( $table, $field, $ids ) {
310 // Use count() to its full documented capabilities to simultaneously
311 // test for null, empty array or empty countable object
312 if ( count( $ids ) ) {
313 $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
314
315 if ( $ids === [] ) {
316 // Return nothing, no IDs are valid
317 $this->getQueryBuilder()->where( '0 = 1' );
318 } else {
319 $this->getQueryBuilder()->where( [ $field => $ids ] );
320 }
321 }
322 return count( $ids );
323 }
324
337 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
338 $isDirNewer = ( $dir === 'newer' );
339 $after = ( $isDirNewer ? '>=' : '<=' );
340 $before = ( $isDirNewer ? '<=' : '>=' );
341 $db = $this->getDB();
342
343 if ( $start !== null ) {
344 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
345 }
346
347 if ( $end !== null ) {
348 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
349 }
350
351 if ( $sort ) {
352 $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
353 }
354 }
355
366 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
367 $db = $this->getDB();
368 $this->addWhereRange( $field, $dir,
369 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
370 }
371
378 protected function addOption( $name, $value = null ) {
379 $this->getQueryBuilder()->option( $name, $value );
380 }
381
399 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
400 $queryBuilder = clone $this->getQueryBuilder();
401 if ( isset( $extraQuery['tables'] ) ) {
402 $queryBuilder->rawTables( (array)$extraQuery['tables'] );
403 }
404 if ( isset( $extraQuery['fields'] ) ) {
405 $queryBuilder->fields( (array)$extraQuery['fields'] );
406 }
407 if ( isset( $extraQuery['where'] ) ) {
408 $queryBuilder->where( (array)$extraQuery['where'] );
409 }
410 if ( isset( $extraQuery['options'] ) ) {
411 $queryBuilder->options( (array)$extraQuery['options'] );
412 }
413 if ( isset( $extraQuery['join_conds'] ) ) {
414 $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
415 }
416
417 if ( $hookData !== null && $this->getHookContainer()->isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
418 $info = $queryBuilder->getQueryInfo();
419 $this->getHookRunner()->onApiQueryBaseBeforeQuery(
420 $this, $info['tables'], $info['fields'], $info['conds'],
421 $info['options'], $info['join_conds'], $hookData
422 );
423 $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
424 }
425
426 $queryBuilder->caller( $method );
428
429 if ( $hookData !== null ) {
430 $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
431 }
432
433 return $res;
434 }
435
449 protected function processRow( $row, array &$data, array &$hookData ) {
450 return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
451 }
452
453 // endregion -- end of querying
454
455 /***************************************************************************/
456 // region Utility methods
466 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
467 $arr[$prefix . 'ns'] = $title->getNamespace();
468 $arr[$prefix . 'title'] = $title->getPrefixedText();
469 }
470
477 protected function addPageSubItems( $pageId, $data ) {
478 $result = $this->getResult();
479 ApiResult::setIndexedTagName( $data, $this->getModulePrefix() );
480
481 return $result->addValue( [ 'query', 'pages', (int)$pageId ],
482 $this->getModuleName(),
483 $data );
484 }
485
494 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
495 if ( $elemname === null ) {
496 $elemname = $this->getModulePrefix();
497 }
498 $result = $this->getResult();
499 $fit = $result->addValue( [ 'query', 'pages', $pageId,
500 $this->getModuleName() ], null, $item );
501 if ( !$fit ) {
502 return false;
503 }
504 $result->addIndexedTagName( [ 'query', 'pages', $pageId,
505 $this->getModuleName() ], $elemname );
506
507 return true;
508 }
509
515 protected function setContinueEnumParameter( $paramName, $paramValue ) {
516 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
517 }
518
529 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
530 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
531 if ( !$t || $t->hasFragment() ) {
532 // Invalid title (e.g. bad chars) or contained a '#'.
533 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
534 }
535 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
536 // This can happen in two cases. First, if you call titlePartToKey with a title part
537 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
538 // difficult to handle such a case. Such cases cannot exist and are therefore treated
539 // as invalid user input. The second case is when somebody specifies a title interwiki
540 // prefix.
541 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
542 }
543
544 return substr( $t->getDBkey(), 0, -1 );
545 }
546
555 protected function parsePrefixedTitlePart( $titlePart, $defaultNamespace = NS_MAIN ) {
556 try {
557 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
558 $t = $titleParser->parseTitle( $titlePart . 'X', $defaultNamespace );
559 } catch ( MalformedTitleException $e ) {
560 $t = null;
561 }
562
563 if ( !$t || $t->hasFragment() || $t->isExternal() || $t->getDBkey() === 'X' ) {
564 // Invalid title (e.g. bad chars) or contained a '#'.
565 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
566 }
567
568 return new TitleValue( $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) );
569 }
570
580 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
581 wfDeprecated( __METHOD__, '1.35' );
582 $t = $this->parsePrefixedTitlePart( $titlePart, $defaultNamespace );
583 return [ $t->getNamespace(), $t->getDBkey() ];
584 }
585
590 public function validateSha1Hash( $hash ) {
591 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
592 }
593
598 public function validateSha1Base36Hash( $hash ) {
599 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
600 }
601
607 public function userCanSeeRevDel() {
608 return $this->getAuthority()->isAllowedAny(
609 'deletedhistory',
610 'deletedtext',
611 'deleterevision',
612 'suppressrevision',
613 'viewsuppressed'
614 );
615 }
616
627 IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
628 ) {
629 if ( !$res->numRows() ) {
630 return;
631 }
632
633 $services = MediaWikiServices::getInstance();
634 if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
635 return;
636 }
637
638 $nsInfo = $services->getNamespaceInfo();
639 $namespaceField = $fieldPrefix . '_namespace';
640 $titleField = $fieldPrefix . '_title';
641
642 $usernames = [];
643 foreach ( $res as $row ) {
644 if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
645 $usernames[] = $row->$titleField;
646 }
647 }
648
649 if ( $usernames === [] ) {
650 return;
651 }
652
653 $genderCache = $services->getGenderCache();
654 $genderCache->doQuery( $usernames, $fname );
655 }
656
657 // endregion -- end of utility methods
658
659 /***************************************************************************/
660 // region Deprecated methods
670 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
671 wfDeprecated( __METHOD__, '1.34' );
672 $this->addBlockInfoToQuery( $showBlockInfo );
673 }
674
675 // endregion -- end of deprecated methods
676}
getAuthority()
getDB()
addBlockInfoToQuery( $showBlockInfo)
Filters hidden users (where the user doesn't have the right to view them) Also adds relevant block in...
addWhere( $conds)
addFields( $fields)
const NS_MAIN
Definition Defines.php:64
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:55
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1436
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:505
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition ApiBase.php:1307
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1633
getMain()
Get the main module.
Definition ApiBase.php:513
getResult()
Get the result object.
Definition ApiBase.php:628
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:497
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:710
getContinuationManager()
Definition ApiBase.php:662
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition ApiBase.php:695
This is a base class for all Query modules.
selectNamedDB( $name, $db, $groups)
Selects the query database connection with the given name.
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.
SelectQueryBuilder $queryBuilder
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='')
prefixedTitlePartToKey( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a namespace constant and dbkey.
showHiddenUsersAddBlockInfo( $showBlockInfo)
Filters hidden users (where the user doesn't have the right to view them) Also adds relevant block in...
userCanSeeRevDel()
Check whether the current user has permission to view revision-deleted fields.
This is the main query class.
Definition ApiQuery.php:37
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Represents a page (or page fragment) title within MediaWiki.
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 IDatabase::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 IDatabase::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:38
Result wrapper for grabbing data queried from an IDatabase object.