MediaWiki  master
ApiQueryBase.php
Go to the documentation of this file.
1 <?php
28 
38 abstract class ApiQueryBase extends ApiBase {
40 
41  private $mQueryModule, $mDb;
42 
46  private $queryBuilder;
47 
54  public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
55  parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
56  $this->mQueryModule = $queryModule;
57  $this->mDb = null;
58  $this->resetQueryParams();
59  }
60 
61  /***************************************************************************/
62  // region Methods to implement
77  public function getCacheMode( $params ) {
78  return 'private';
79  }
80 
91  public function requestExtraData( $pageSet ) {
92  }
93 
94  // endregion -- end of methods to implement
95 
96  /***************************************************************************/
97  // region Data access
104  public function getQuery() {
105  return $this->mQueryModule;
106  }
107 
109  public function getParent() {
110  return $this->getQuery();
111  }
112 
118  protected function getDB() {
119  $this->mDb ??= $this->getQuery()->getDB();
120 
121  return $this->mDb;
122  }
123 
136  public function selectNamedDB( $name, $db, $groups ) {
137  wfDeprecated( __METHOD__, '1.39' );
138  $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
139  return $this->mDb;
140  }
141 
147  protected function getPageSet() {
148  return $this->getQuery()->getPageSet();
149  }
150 
151  // endregion -- end of data access
152 
153  /***************************************************************************/
154  // region Querying
160  protected function resetQueryParams() {
161  $this->queryBuilder = null;
162  }
163 
172  protected function getQueryBuilder() {
173  $this->queryBuilder ??= $this->getDB()->newSelectQueryBuilder();
174  return $this->queryBuilder;
175  }
176 
184  protected function addTables( $tables, $alias = null ) {
185  if ( is_array( $tables ) ) {
186  if ( $alias !== null ) {
187  ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
188  }
189  $this->getQueryBuilder()->rawTables( $tables );
190  } else {
191  $this->getQueryBuilder()->table( $tables, $alias );
192  }
193  }
194 
203  protected function addJoinConds( $join_conds ) {
204  if ( !is_array( $join_conds ) ) {
205  ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
206  }
207  $this->getQueryBuilder()->joinConds( $join_conds );
208  }
209 
214  protected function addFields( $value ) {
215  $this->getQueryBuilder()->fields( $value );
216  }
217 
224  protected function addFieldsIf( $value, $condition ) {
225  if ( $condition ) {
226  $this->addFields( $value );
227 
228  return true;
229  }
230 
231  return false;
232  }
233 
247  protected function addWhere( $value ) {
248  if ( is_array( $value ) ) {
249  // Double check: don't insert empty arrays,
250  // Database::makeList() chokes on them
251  if ( count( $value ) ) {
252  $this->getQueryBuilder()->where( $value );
253  }
254  } else {
255  $this->getQueryBuilder()->where( $value );
256  }
257  }
258 
265  protected function addWhereIf( $value, $condition ) {
266  if ( $condition ) {
267  $this->addWhere( $value );
268 
269  return true;
270  }
271 
272  return false;
273  }
274 
284  protected function addWhereFld( $field, $value ) {
285  if ( $value !== null && !( is_array( $value ) && !$value ) ) {
286  $this->getQueryBuilder()->where( [ $field => $value ] );
287  }
288  }
289 
311  protected function addWhereIDsFld( $table, $field, $ids ) {
312  // Use count() to its full documented capabilities to simultaneously
313  // test for null, empty array or empty countable object
314  if ( count( $ids ) ) {
315  $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
316 
317  if ( $ids === [] ) {
318  // Return nothing, no IDs are valid
319  $this->getQueryBuilder()->where( '0 = 1' );
320  } else {
321  $this->getQueryBuilder()->where( [ $field => $ids ] );
322  }
323  }
324  return count( $ids );
325  }
326 
339  protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
340  $isDirNewer = ( $dir === 'newer' );
341  $after = ( $isDirNewer ? '>=' : '<=' );
342  $before = ( $isDirNewer ? '<=' : '>=' );
343  $db = $this->getDB();
344 
345  if ( $start !== null ) {
346  $this->addWhere( $field . $after . $db->addQuotes( $start ) );
347  }
348 
349  if ( $end !== null ) {
350  $this->addWhere( $field . $before . $db->addQuotes( $end ) );
351  }
352 
353  if ( $sort ) {
354  $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
355  }
356  }
357 
368  protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
369  $db = $this->getDB();
370  $this->addWhereRange( $field, $dir,
371  $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
372  }
373 
380  protected function addOption( $name, $value = null ) {
381  $this->getQueryBuilder()->option( $name, $value );
382  }
383 
401  protected function select( $method, $extraQuery = [], array &$hookData = null ) {
402  $queryBuilder = clone $this->getQueryBuilder();
403  if ( isset( $extraQuery['tables'] ) ) {
404  $queryBuilder->rawTables( (array)$extraQuery['tables'] );
405  }
406  if ( isset( $extraQuery['fields'] ) ) {
407  $queryBuilder->fields( (array)$extraQuery['fields'] );
408  }
409  if ( isset( $extraQuery['where'] ) ) {
410  $queryBuilder->where( (array)$extraQuery['where'] );
411  }
412  if ( isset( $extraQuery['options'] ) ) {
413  $queryBuilder->options( (array)$extraQuery['options'] );
414  }
415  if ( isset( $extraQuery['join_conds'] ) ) {
416  $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
417  }
418 
419  if ( $hookData !== null && $this->getHookContainer()->isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
420  $info = $queryBuilder->getQueryInfo();
421  $this->getHookRunner()->onApiQueryBaseBeforeQuery(
422  $this, $info['tables'], $info['fields'], $info['conds'],
423  $info['options'], $info['join_conds'], $hookData
424  );
425  $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
426  }
427 
428  $queryBuilder->caller( $method );
429  $res = $queryBuilder->fetchResultSet();
430 
431  if ( $hookData !== null ) {
432  $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
433  }
434 
435  return $res;
436  }
437 
451  protected function processRow( $row, array &$data, array &$hookData ) {
452  return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
453  }
454 
455  // endregion -- end of querying
456 
457  /***************************************************************************/
458  // region Utility methods
468  public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
469  $arr[$prefix . 'ns'] = $title->getNamespace();
470  $arr[$prefix . 'title'] = $title->getPrefixedText();
471  }
472 
479  protected function addPageSubItems( $pageId, $data ) {
480  $result = $this->getResult();
482 
483  return $result->addValue( [ 'query', 'pages', (int)$pageId ],
484  $this->getModuleName(),
485  $data );
486  }
487 
496  protected function addPageSubItem( $pageId, $item, $elemname = null ) {
497  $result = $this->getResult();
498  $fit = $result->addValue( [ 'query', 'pages', $pageId,
499  $this->getModuleName() ], null, $item );
500  if ( !$fit ) {
501  return false;
502  }
503  $result->addIndexedTagName(
504  [ 'query', 'pages', $pageId, $this->getModuleName() ],
505  $elemname ?? $this->getModulePrefix()
506  );
507 
508  return true;
509  }
510 
516  protected function setContinueEnumParameter( $paramName, $paramValue ) {
517  $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
518  }
519 
530  public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
531  $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
532  if ( !$t || $t->hasFragment() ) {
533  // Invalid title (e.g. bad chars) or contained a '#'.
534  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
535  }
536  if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
537  // This can happen in two cases. First, if you call titlePartToKey with a title part
538  // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
539  // difficult to handle such a case. Such cases cannot exist and are therefore treated
540  // as invalid user input. The second case is when somebody specifies a title interwiki
541  // prefix.
542  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
543  }
544 
545  return substr( $t->getDBkey(), 0, -1 );
546  }
547 
556  protected function parsePrefixedTitlePart( $titlePart, $defaultNamespace = NS_MAIN ) {
557  try {
558  $titleParser = MediaWikiServices::getInstance()->getTitleParser();
559  $t = $titleParser->parseTitle( $titlePart . 'X', $defaultNamespace );
560  } catch ( MalformedTitleException $e ) {
561  $t = null;
562  }
563 
564  if ( !$t || $t->hasFragment() || $t->isExternal() || $t->getDBkey() === 'X' ) {
565  // Invalid title (e.g. bad chars) or contained a '#'.
566  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
567  }
568 
569  return new TitleValue( $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) );
570  }
571 
576  public function validateSha1Hash( $hash ) {
577  return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
578  }
579 
584  public function validateSha1Base36Hash( $hash ) {
585  return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
586  }
587 
593  public function userCanSeeRevDel() {
594  return $this->getAuthority()->isAllowedAny(
595  'deletedhistory',
596  'deletedtext',
597  'deleterevision',
598  'suppressrevision',
599  'viewsuppressed'
600  );
601  }
602 
613  IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
614  ) {
615  if ( !$res->numRows() ) {
616  return;
617  }
618 
619  $services = MediaWikiServices::getInstance();
620  if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
621  return;
622  }
623 
624  $nsInfo = $services->getNamespaceInfo();
625  $namespaceField = $fieldPrefix . '_namespace';
626  $titleField = $fieldPrefix . '_title';
627 
628  $usernames = [];
629  foreach ( $res as $row ) {
630  if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
631  $usernames[] = $row->$titleField;
632  }
633  }
634 
635  if ( $usernames === [] ) {
636  return;
637  }
638 
639  $genderCache = $services->getGenderCache();
640  $genderCache->doQuery( $usernames, $fname );
641  }
642 
643  // endregion -- end of utility methods
644 }
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:58
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1469
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:513
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition: ApiBase.php:1340
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1702
getMain()
Get the main module.
Definition: ApiBase.php:521
getResult()
Get the result object.
Definition: ApiBase.php:636
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:505
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:720
getContinuationManager()
Definition: ApiBase.php:672
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: ApiBase.php:705
This is a base class for all Query modules.
selectNamedDB( $name, $db, $groups)
Change the database connection for subsequent calls to getDB().
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.Stability: stableto 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:42
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Service locator for MediaWiki core services.
Represents a title within MediaWiki.
Definition: Title.php:82
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:40
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.
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:36
Result wrapper for grabbing data queried from an IDatabase object.