MediaWiki fundraising/REL1_35
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 /************************************************************************/
77 public function getCacheMode( $params ) {
78 return 'private';
79 }
80
91 public function requestExtraData( $pageSet ) {
92 }
93
96 /************************************************************************/
105 public function getQuery() {
106 return $this->mQueryModule;
107 }
108
110 public function getParent() {
111 return $this->getQuery();
112 }
113
119 protected function getDB() {
120 if ( $this->mDb === null ) {
121 $this->mDb = $this->getQuery()->getDB();
122 }
123
124 return $this->mDb;
125 }
126
135 public function selectNamedDB( $name, $db, $groups ) {
136 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
137 return $this->mDb;
138 }
139
145 protected function getPageSet() {
146 return $this->getQuery()->getPageSet();
147 }
148
151 /************************************************************************/
159 protected function resetQueryParams() {
160 $this->queryBuilder = null;
161 }
162
171 protected function getQueryBuilder() {
172 if ( $this->queryBuilder === null ) {
173 $this->queryBuilder = $this->getDB()->newSelectQueryBuilder();
174 }
175 return $this->queryBuilder;
176 }
177
185 protected function addTables( $tables, $alias = null ) {
186 if ( is_array( $tables ) ) {
187 if ( $alias !== null ) {
188 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
189 }
190 $this->getQueryBuilder()->rawTables( $tables );
191 } else {
192 $this->getQueryBuilder()->table( $tables, $alias );
193 }
194 }
195
204 protected function addJoinConds( $join_conds ) {
205 if ( !is_array( $join_conds ) ) {
206 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
207 }
208 $this->getQueryBuilder()->joinConds( $join_conds );
209 }
210
215 protected function addFields( $value ) {
216 $this->getQueryBuilder()->fields( $value );
217 }
218
225 protected function addFieldsIf( $value, $condition ) {
226 if ( $condition ) {
227 $this->addFields( $value );
228
229 return true;
230 }
231
232 return false;
233 }
234
248 protected function addWhere( $value ) {
249 if ( is_array( $value ) ) {
250 // Sanity check: don't insert empty arrays,
251 // Database::makeList() chokes on them
252 if ( count( $value ) ) {
253 $this->getQueryBuilder()->where( $value );
254 }
255 } else {
256 $this->getQueryBuilder()->where( $value );
257 }
258 }
259
266 protected function addWhereIf( $value, $condition ) {
267 if ( $condition ) {
268 $this->addWhere( $value );
269
270 return true;
271 }
272
273 return false;
274 }
275
285 protected function addWhereFld( $field, $value ) {
286 if ( $value !== null && !( is_array( $value ) && !$value ) ) {
287 $this->getQueryBuilder()->where( [ $field => $value ] );
288 }
289 }
290
312 protected function addWhereIDsFld( $table, $field, $ids ) {
313 // Use count() to its full documented capabilities to simultaneously
314 // test for null, empty array or empty countable object
315 if ( count( $ids ) ) {
316 $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
317
318 if ( $ids === [] ) {
319 // Return nothing, no IDs are valid
320 $this->getQueryBuilder()->where( '0 = 1' );
321 } else {
322 $this->getQueryBuilder()->where( [ $field => $ids ] );
323 }
324 }
325 return count( $ids );
326 }
327
340 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
341 $isDirNewer = ( $dir === 'newer' );
342 $after = ( $isDirNewer ? '>=' : '<=' );
343 $before = ( $isDirNewer ? '<=' : '>=' );
344 $db = $this->getDB();
345
346 if ( $start !== null ) {
347 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
348 }
349
350 if ( $end !== null ) {
351 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
352 }
353
354 if ( $sort ) {
355 $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
356 }
357 }
358
369 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
370 $db = $this->getDB();
371 $this->addWhereRange( $field, $dir,
372 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
373 }
374
381 protected function addOption( $name, $value = null ) {
382 $this->getQueryBuilder()->option( $name, $value );
383 }
384
402 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
403 $queryBuilder = clone $this->getQueryBuilder();
404 if ( isset( $extraQuery['tables'] ) ) {
405 $queryBuilder->rawTables( (array)$extraQuery['tables'] );
406 }
407 if ( isset( $extraQuery['fields'] ) ) {
408 $queryBuilder->fields( (array)$extraQuery['fields'] );
409 }
410 if ( isset( $extraQuery['where'] ) ) {
411 $queryBuilder->where( (array)$extraQuery['where'] );
412 }
413 if ( isset( $extraQuery['options'] ) ) {
414 $queryBuilder->options( (array)$extraQuery['options'] );
415 }
416 if ( isset( $extraQuery['join_conds'] ) ) {
417 $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
418 }
419
420 if ( $hookData !== null && Hooks::isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
421 $info = $queryBuilder->getQueryInfo();
422 $this->getHookRunner()->onApiQueryBaseBeforeQuery(
423 $this, $info['tables'], $info['fields'], $info['conds'],
424 $info['options'], $info['join_conds'], $hookData
425 );
426 $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
427 }
428
429 $queryBuilder->caller( $method );
431
432 if ( $hookData !== null ) {
433 $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
434 }
435
436 return $res;
437 }
438
452 protected function processRow( $row, array &$data, array &$hookData ) {
453 return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
454 }
455
458 /************************************************************************/
470 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
471 $arr[$prefix . 'ns'] = (int)$title->getNamespace();
472 $arr[$prefix . 'title'] = $title->getPrefixedText();
473 }
474
481 protected function addPageSubItems( $pageId, $data ) {
482 $result = $this->getResult();
483 ApiResult::setIndexedTagName( $data, $this->getModulePrefix() );
484
485 return $result->addValue( [ 'query', 'pages', (int)$pageId ],
486 $this->getModuleName(),
487 $data );
488 }
489
498 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
499 if ( $elemname === null ) {
500 $elemname = $this->getModulePrefix();
501 }
502 $result = $this->getResult();
503 $fit = $result->addValue( [ 'query', 'pages', $pageId,
504 $this->getModuleName() ], null, $item );
505 if ( !$fit ) {
506 return false;
507 }
508 $result->addIndexedTagName( [ 'query', 'pages', $pageId,
509 $this->getModuleName() ], $elemname );
510
511 return true;
512 }
513
519 protected function setContinueEnumParameter( $paramName, $paramValue ) {
520 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
521 }
522
533 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
534 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
535 if ( !$t || $t->hasFragment() ) {
536 // Invalid title (e.g. bad chars) or contained a '#'.
537 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
538 }
539 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
540 // This can happen in two cases. First, if you call titlePartToKey with a title part
541 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
542 // difficult to handle such a case. Such cases cannot exist and are therefore treated
543 // as invalid user input. The second case is when somebody specifies a title interwiki
544 // prefix.
545 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
546 }
547
548 return substr( $t->getDBkey(), 0, -1 );
549 }
550
559 protected function parsePrefixedTitlePart( $titlePart, $defaultNamespace = NS_MAIN ) {
560 try {
561 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
562 $t = $titleParser->parseTitle( $titlePart . 'X', $defaultNamespace );
563 } catch ( MalformedTitleException $e ) {
564 $t = null;
565 }
566
567 if ( !$t || $t->hasFragment() || $t->isExternal() || $t->getDBkey() === 'X' ) {
568 // Invalid title (e.g. bad chars) or contained a '#'.
569 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
570 }
571
572 return new TitleValue( $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) );
573 }
574
584 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
585 wfDeprecated( __METHOD__, '1.35' );
586 $t = $this->parsePrefixedTitlePart( $titlePart, $defaultNamespace );
587 return [ $t->getNamespace(), $t->getDBkey() ];
588 }
589
594 public function validateSha1Hash( $hash ) {
595 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
596 }
597
602 public function validateSha1Base36Hash( $hash ) {
603 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
604 }
605
611 public function userCanSeeRevDel() {
612 return $this->getPermissionManager()->userHasAnyRight(
613 $this->getUser(),
614 'deletedhistory',
615 'deletedtext',
616 'suppressrevision',
617 'viewsuppressed'
618 );
619 }
620
631 IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
632 ) {
633 if ( !$res->numRows() ) {
634 return;
635 }
636
637 $services = MediaWikiServices::getInstance();
638 if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
639 return;
640 }
641
642 $nsInfo = $services->getNamespaceInfo();
643 $namespaceField = $fieldPrefix . '_namespace';
644 $titleField = $fieldPrefix . '_title';
645
646 $usernames = [];
647 foreach ( $res as $row ) {
648 if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
649 $usernames[] = $row->$titleField;
650 }
651 }
652
653 if ( $usernames === [] ) {
654 return;
655 }
656
657 $genderCache = $services->getGenderCache();
658 $genderCache->doQuery( $usernames, $fname );
659 }
660
663 /************************************************************************/
675 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
676 wfDeprecated( __METHOD__, '1.34' );
677 $this->addBlockInfoToQuery( $showBlockInfo );
678 }
679
681}
getPermissionManager()
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)
getUser()
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 $function is deprecated.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:52
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1437
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:507
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition ApiBase.php:1308
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1629
getMain()
Get the main module.
Definition ApiBase.php:515
getResult()
Get the result object.
Definition ApiBase.php:620
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:499
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:717
getContinuationManager()
Get the continuation manager.
Definition ApiBase.php:662
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 Stable 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) Stable to override.
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 Stable to override.
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='')
Stable to call.
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.
rawTables( $tables)
Given a table or table array as might be passed to Database::select(), append it to the existing tabl...
getQueryInfo()
Get an associative array describing the query in terms of its raw parameters to Database::select().
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
const NS_MAIN
Definition Defines.php:70
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.