MediaWiki  master
ApiQueryBase.php
Go to the documentation of this file.
1 <?php
27 
35 abstract class ApiQueryBase extends ApiBase {
37 
38  private $mQueryModule, $mDb;
39 
43  private $queryBuilder;
44 
50  public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
51  parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
52  $this->mQueryModule = $queryModule;
53  $this->mDb = null;
54  $this->resetQueryParams();
55  }
56 
57  /************************************************************************/
73  public function getCacheMode( $params ) {
74  return 'private';
75  }
76 
86  public function requestExtraData( $pageSet ) {
87  }
88 
91  /************************************************************************/
100  public function getQuery() {
101  return $this->mQueryModule;
102  }
103 
105  public function getParent() {
106  return $this->getQuery();
107  }
108 
113  protected function getDB() {
114  if ( $this->mDb === null ) {
115  $this->mDb = $this->getQuery()->getDB();
116  }
117 
118  return $this->mDb;
119  }
120 
129  public function selectNamedDB( $name, $db, $groups ) {
130  $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
131  return $this->mDb;
132  }
133 
138  protected function getPageSet() {
139  return $this->getQuery()->getPageSet();
140  }
141 
144  /************************************************************************/
152  protected function resetQueryParams() {
153  $this->queryBuilder = null;
154  }
155 
164  protected function getQueryBuilder() {
165  if ( $this->queryBuilder === null ) {
166  $this->queryBuilder = $this->getDB()->newSelectQueryBuilder();
167  }
168  return $this->queryBuilder;
169  }
170 
178  protected function addTables( $tables, $alias = null ) {
179  if ( is_array( $tables ) ) {
180  if ( $alias !== null ) {
181  ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
182  }
183  $this->getQueryBuilder()->rawTables( $tables );
184  } else {
185  $this->getQueryBuilder()->table( $tables, $alias );
186  }
187  }
188 
197  protected function addJoinConds( $join_conds ) {
198  if ( !is_array( $join_conds ) ) {
199  ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
200  }
201  $this->getQueryBuilder()->joinConds( $join_conds );
202  }
203 
208  protected function addFields( $value ) {
209  $this->getQueryBuilder()->fields( $value );
210  }
211 
218  protected function addFieldsIf( $value, $condition ) {
219  if ( $condition ) {
220  $this->addFields( $value );
221 
222  return true;
223  }
224 
225  return false;
226  }
227 
241  protected function addWhere( $value ) {
242  if ( is_array( $value ) ) {
243  // Sanity check: don't insert empty arrays,
244  // Database::makeList() chokes on them
245  if ( count( $value ) ) {
246  $this->getQueryBuilder()->where( $value );
247  }
248  } else {
249  $this->getQueryBuilder()->where( $value );
250  }
251  }
252 
259  protected function addWhereIf( $value, $condition ) {
260  if ( $condition ) {
261  $this->addWhere( $value );
262 
263  return true;
264  }
265 
266  return false;
267  }
268 
278  protected function addWhereFld( $field, $value ) {
279  if ( $value !== null && !( is_array( $value ) && !$value ) ) {
280  $this->getQueryBuilder()->where( [ $field => $value ] );
281  }
282  }
283 
305  protected function addWhereIDsFld( $table, $field, $ids ) {
306  // Use count() to its full documented capabilities to simultaneously
307  // test for null, empty array or empty countable object
308  if ( count( $ids ) ) {
309  $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
310 
311  if ( $ids === [] ) {
312  // Return nothing, no IDs are valid
313  $this->getQueryBuilder()->where( '0 = 1' );
314  } else {
315  $this->getQueryBuilder()->where( [ $field => $ids ] );
316  }
317  }
318  return count( $ids );
319  }
320 
333  protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
334  $isDirNewer = ( $dir === 'newer' );
335  $after = ( $isDirNewer ? '>=' : '<=' );
336  $before = ( $isDirNewer ? '<=' : '>=' );
337  $db = $this->getDB();
338 
339  if ( $start !== null ) {
340  $this->addWhere( $field . $after . $db->addQuotes( $start ) );
341  }
342 
343  if ( $end !== null ) {
344  $this->addWhere( $field . $before . $db->addQuotes( $end ) );
345  }
346 
347  if ( $sort ) {
348  $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
349  }
350  }
351 
362  protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
363  $db = $this->getDB();
364  $this->addWhereRange( $field, $dir,
365  $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
366  }
367 
374  protected function addOption( $name, $value = null ) {
375  $this->getQueryBuilder()->option( $name, $value );
376  }
377 
395  protected function select( $method, $extraQuery = [], array &$hookData = null ) {
396  $queryBuilder = clone $this->getQueryBuilder();
397  if ( isset( $extraQuery['tables'] ) ) {
398  $queryBuilder->rawTables( (array)$extraQuery['tables'] );
399  }
400  if ( isset( $extraQuery['fields'] ) ) {
401  $queryBuilder->fields( (array)$extraQuery['fields'] );
402  }
403  if ( isset( $extraQuery['where'] ) ) {
404  $queryBuilder->where( (array)$extraQuery['where'] );
405  }
406  if ( isset( $extraQuery['options'] ) ) {
407  $queryBuilder->options( (array)$extraQuery['options'] );
408  }
409  if ( isset( $extraQuery['join_conds'] ) ) {
410  $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
411  }
412 
413  if ( $hookData !== null && Hooks::isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
414  $info = $queryBuilder->getQueryInfo();
415  $this->getHookRunner()->onApiQueryBaseBeforeQuery(
416  $this, $info['tables'], $info['fields'], $info['conds'],
417  $info['options'], $info['join_conds'], $hookData
418  );
419  $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
420  }
421 
422  $queryBuilder->caller( $method );
424 
425  if ( $hookData !== null ) {
426  $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
427  }
428 
429  return $res;
430  }
431 
445  protected function processRow( $row, array &$data, array &$hookData ) {
446  return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
447  }
448 
451  /************************************************************************/
463  public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
464  $arr[$prefix . 'ns'] = (int)$title->getNamespace();
465  $arr[$prefix . 'title'] = $title->getPrefixedText();
466  }
467 
474  protected function addPageSubItems( $pageId, $data ) {
475  $result = $this->getResult();
477 
478  return $result->addValue( [ 'query', 'pages', (int)$pageId ],
479  $this->getModuleName(),
480  $data );
481  }
482 
491  protected function addPageSubItem( $pageId, $item, $elemname = null ) {
492  if ( $elemname === null ) {
493  $elemname = $this->getModulePrefix();
494  }
495  $result = $this->getResult();
496  $fit = $result->addValue( [ 'query', 'pages', $pageId,
497  $this->getModuleName() ], null, $item );
498  if ( !$fit ) {
499  return false;
500  }
501  $result->addIndexedTagName( [ 'query', 'pages', $pageId,
502  $this->getModuleName() ], $elemname );
503 
504  return true;
505  }
506 
512  protected function setContinueEnumParameter( $paramName, $paramValue ) {
513  $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
514  }
515 
526  public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
527  $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
528  if ( !$t || $t->hasFragment() ) {
529  // Invalid title (e.g. bad chars) or contained a '#'.
530  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
531  }
532  if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
533  // This can happen in two cases. First, if you call titlePartToKey with a title part
534  // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
535  // difficult to handle such a case. Such cases cannot exist and are therefore treated
536  // as invalid user input. The second case is when somebody specifies a title interwiki
537  // prefix.
538  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
539  }
540 
541  return substr( $t->getDBkey(), 0, -1 );
542  }
543 
552  protected function parsePrefixedTitlePart( $titlePart, $defaultNamespace = NS_MAIN ) {
553  try {
554  $titleParser = MediaWikiServices::getInstance()->getTitleParser();
555  $t = $titleParser->parseTitle( $titlePart . 'X', $defaultNamespace );
556  } catch ( MalformedTitleException $e ) {
557  $t = null;
558  }
559 
560  if ( !$t || $t->hasFragment() || $t->isExternal() || $t->getDBkey() === 'X' ) {
561  // Invalid title (e.g. bad chars) or contained a '#'.
562  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
563  }
564 
565  return new TitleValue( $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) );
566  }
567 
577  public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
578  wfDeprecated( __METHOD__, '1.35' );
579  $t = $this->parsePrefixedTitlePart( $titlePart, $defaultNamespace );
580  return [ $t->getNamespace(), $t->getDBkey() ];
581  }
582 
587  public function validateSha1Hash( $hash ) {
588  return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
589  }
590 
595  public function validateSha1Base36Hash( $hash ) {
596  return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
597  }
598 
604  public function userCanSeeRevDel() {
605  return $this->getPermissionManager()->userHasAnyRight(
606  $this->getUser(),
607  'deletedhistory',
608  'deletedtext',
609  'suppressrevision',
610  'viewsuppressed'
611  );
612  }
613 
624  IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
625  ) {
626  if ( !$res->numRows() ) {
627  return;
628  }
629 
630  $services = MediaWikiServices::getInstance();
631  if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
632  return;
633  }
634 
635  $nsInfo = $services->getNamespaceInfo();
636  $namespaceField = $fieldPrefix . '_namespace';
637  $titleField = $fieldPrefix . '_title';
638 
639  $usernames = [];
640  foreach ( $res as $row ) {
641  if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
642  $usernames[] = $row->$titleField;
643  }
644  }
645 
646  if ( $usernames === [] ) {
647  return;
648  }
649 
650  $genderCache = $services->getGenderCache();
651  $genderCache->doQuery( $usernames, $fname );
652  }
653 
656  /************************************************************************/
668  public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
669  wfDeprecated( __METHOD__, '1.34' );
670  $this->addBlockInfoToQuery( $showBlockInfo );
671  }
672 
674 }
ApiQueryBase\validateSha1Base36Hash
validateSha1Base36Hash( $hash)
Definition: ApiQueryBase.php:595
ApiQueryBase\addWhereIDsFld
addWhereIDsFld( $table, $field, $ids)
Like addWhereFld for an integer list of IDs.
Definition: ApiQueryBase.php:305
ApiQueryBase\showHiddenUsersAddBlockInfo
showHiddenUsersAddBlockInfo( $showBlockInfo)
Filters hidden users (where the user doesn't have the right to view them) Also adds relevant block in...
Definition: ApiQueryBase.php:668
ApiQueryBase\addPageSubItems
addPageSubItems( $pageId, $data)
Add a sub-element under the page element with the given page ID.
Definition: ApiQueryBase.php:474
ApiQueryBase\processRow
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
Definition: ApiQueryBase.php:445
ApiQueryBase\addFields
addFields( $value)
Add a set of fields to select to the internal array.
Definition: ApiQueryBase.php:208
Wikimedia\Rdbms\SelectQueryBuilder\joinConds
joinConds(array $joinConds)
Manually append to the $join_conds array which will be passed to IDatabase::select().
Definition: SelectQueryBuilder.php:275
ApiQuery
This is the main query class.
Definition: ApiQuery.php:37
ApiQueryBase\resetQueryParams
resetQueryParams()
Blank the internal arrays with query parameters.
Definition: ApiQueryBase.php:152
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:152
Wikimedia\Rdbms\SelectQueryBuilder\options
options(array $options)
Manually set multiple options in the $options array to be passed to IDatabase::select().
Definition: SelectQueryBuilder.php:578
ApiQueryBase\getParent
getParent()
Get the parent of this module.1.25 ApiBase|null
Definition: ApiQueryBase.php:105
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1415
ApiQueryBase\addTimestampWhereRange
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
Definition: ApiQueryBase.php:362
Wikimedia\Rdbms\SelectQueryBuilder\rawTables
rawTables( $tables)
Given a table or table array as might be passed to Database::select(), append it to the existing tabl...
Definition: SelectQueryBuilder.php:107
Wikimedia\Rdbms\SelectQueryBuilder\fetchResultSet
fetchResultSet()
Run the constructed SELECT query and return all results.
Definition: SelectQueryBuilder.php:599
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:546
ApiQueryBase\getQuery
getQuery()
Get the main Query module.
Definition: ApiQueryBase.php:100
ApiQueryBase\addOption
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
Definition: ApiQueryBase.php:374
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Definition: ContextSource.php:120
ApiQueryBase\addFieldsIf
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
Definition: ApiQueryBase.php:218
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:50
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
NS_MAIN
const NS_MAIN
Definition: Defines.php:69
ApiQueryBlockInfoTrait
trait ApiQueryBlockInfoTrait
Definition: ApiQueryBlockInfoTrait.php:28
ApiQueryBase\executeGenderCacheFromResultWrapper
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
Definition: ApiQueryBase.php:623
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1029
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
ApiQueryBase
This is a base class for all Query modules.
Definition: ApiQueryBase.php:35
Wikimedia\Rdbms\SelectQueryBuilder\caller
caller( $fname)
Set the method name to be included in an SQL comment.
Definition: SelectQueryBuilder.php:589
ApiQueryBase\getDB
getDB()
Get the Query database connection (read-only)
Definition: ApiQueryBase.php:113
Wikimedia\Rdbms\SelectQueryBuilder
Definition: SelectQueryBuilder.php:5
ApiQueryBase\addTables
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
Definition: ApiQueryBase.php:178
ApiQueryBase\select
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
Definition: ApiQueryBase.php:395
$title
$title
Definition: testCompression.php:38
ApiQueryBase\$mDb
$mDb
Definition: ApiQueryBase.php:38
ApiQueryBase\$queryBuilder
SelectQueryBuilder $queryBuilder
Definition: ApiQueryBase.php:43
Wikimedia\Rdbms\SelectQueryBuilder\fields
fields( $fields)
Add a field or an array of fields to the query.
Definition: SelectQueryBuilder.php:166
ApiBase\getModulePrefix
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:434
ApiQueryBase\addWhereRange
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.
Definition: ApiQueryBase.php:333
ApiBase\getContinuationManager
getContinuationManager()
Get the continuation manager.
Definition: ApiBase.php:586
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:618
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
ApiQueryBase\getQueryBuilder
getQueryBuilder()
Get the SelectQueryBuilder.
Definition: ApiQueryBase.php:164
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:616
ApiQueryBase\requestExtraData
requestExtraData( $pageSet)
Override this method to request extra fields from the pageSet using $pageSet->requestField('fieldName...
Definition: ApiQueryBase.php:86
ApiQueryBase\addJoinConds
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
Definition: ApiQueryBase.php:197
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1490
ApiQueryBase\addWhereFld
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
Definition: ApiQueryBase.php:278
ApiQueryBase\getCacheMode
getCacheMode( $params)
Get the cache mode for the data generated by this module.
Definition: ApiQueryBase.php:73
ApiQueryBase\prefixedTitlePartToKey
prefixedTitlePartToKey( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a namespace constant and dbkey.
Definition: ApiQueryBase.php:577
ApiQueryBase\getPageSet
getPageSet()
Get the PageSet object to work on.
Definition: ApiQueryBase.php:138
Hooks\isRegistered
static isRegistered( $name)
Returns true if a hook has a function registered to it.
Definition: Hooks.php:88
Wikimedia\Rdbms\SelectQueryBuilder\getQueryInfo
getQueryInfo()
Get an associative array describing the query in terms of its raw parameters to Database::select().
Definition: SelectQueryBuilder.php:745
ApiBase\filterIDs
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition: ApiBase.php:1286
ApiQueryBase\selectNamedDB
selectNamedDB( $name, $db, $groups)
Selects the query database connection with the given name.
Definition: ApiQueryBase.php:129
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:25
ApiQueryBase\__construct
__construct(ApiQuery $queryModule, $moduleName, $paramPrefix='')
Definition: ApiQueryBase.php:50
ApiQueryBase\parsePrefixedTitlePart
parsePrefixedTitlePart( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a TitleValue.
Definition: ApiQueryBase.php:552
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:426
ApiQueryBase\$mQueryModule
$mQueryModule
Definition: ApiQueryBase.php:38
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:442
ApiQueryBase\addWhere
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Definition: ApiQueryBase.php:241
$t
$t
Definition: testCompression.php:74
ApiQueryBase\setContinueEnumParameter
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
Definition: ApiQueryBase.php:512
ApiQueryBase\titlePartToKey
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
Definition: ApiQueryBase.php:526
ApiBase\getHookRunner
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:641
Wikimedia\Rdbms\SelectQueryBuilder\where
where( $conds)
Add conditions to the query.
Definition: SelectQueryBuilder.php:238
ApiQueryBase\userCanSeeRevDel
userCanSeeRevDel()
Check whether the current user has permission to view revision-deleted fields.
Definition: ApiQueryBase.php:604
ApiQueryBase\addPageSubItem
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
Definition: ApiQueryBase.php:491
ApiBase\dieDebug
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1607
ApiQueryBase\addWhereIf
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
Definition: ApiQueryBase.php:259
ApiQueryBase\addTitleInfo
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
Definition: ApiQueryBase.php:463
addBlockInfoToQuery
addBlockInfoToQuery( $showBlockInfo)
Filters hidden users (where the user doesn't have the right to view them) Also adds relevant block in...
Definition: ApiQueryBlockInfoTrait.php:38
TitleValue
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:37
ApiQueryBase\validateSha1Hash
validateSha1Hash( $hash)
Definition: ApiQueryBase.php:587