MediaWiki  master
ApiQueryBase.php
Go to the documentation of this file.
1 <?php
27 
37 abstract class ApiQueryBase extends ApiBase {
39 
40  private $mQueryModule, $mDb;
41 
45  private $queryBuilder;
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  $this->mDb ??= $this->getQuery()->getDB();
119 
120  return $this->mDb;
121  }
122 
135  public function selectNamedDB( $name, $db, $groups ) {
136  wfDeprecated( __METHOD__, '1.39' );
137  $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
138  return $this->mDb;
139  }
140 
146  protected function getPageSet() {
147  return $this->getQuery()->getPageSet();
148  }
149 
150  // endregion -- end of data access
151 
152  /***************************************************************************/
153  // region Querying
159  protected function resetQueryParams() {
160  $this->queryBuilder = null;
161  }
162 
171  protected function getQueryBuilder() {
172  $this->queryBuilder ??= $this->getDB()->newSelectQueryBuilder();
173  return $this->queryBuilder;
174  }
175 
183  protected function addTables( $tables, $alias = null ) {
184  if ( is_array( $tables ) ) {
185  if ( $alias !== null ) {
186  ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
187  }
188  $this->getQueryBuilder()->rawTables( $tables );
189  } else {
190  $this->getQueryBuilder()->table( $tables, $alias );
191  }
192  }
193 
202  protected function addJoinConds( $join_conds ) {
203  if ( !is_array( $join_conds ) ) {
204  ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
205  }
206  $this->getQueryBuilder()->joinConds( $join_conds );
207  }
208 
213  protected function addFields( $value ) {
214  $this->getQueryBuilder()->fields( $value );
215  }
216 
223  protected function addFieldsIf( $value, $condition ) {
224  if ( $condition ) {
225  $this->addFields( $value );
226 
227  return true;
228  }
229 
230  return false;
231  }
232 
246  protected function addWhere( $value ) {
247  if ( is_array( $value ) ) {
248  // Double check: don't insert empty arrays,
249  // Database::makeList() chokes on them
250  if ( count( $value ) ) {
251  $this->getQueryBuilder()->where( $value );
252  }
253  } else {
254  $this->getQueryBuilder()->where( $value );
255  }
256  }
257 
264  protected function addWhereIf( $value, $condition ) {
265  if ( $condition ) {
266  $this->addWhere( $value );
267 
268  return true;
269  }
270 
271  return false;
272  }
273 
283  protected function addWhereFld( $field, $value ) {
284  if ( $value !== null && !( is_array( $value ) && !$value ) ) {
285  $this->getQueryBuilder()->where( [ $field => $value ] );
286  }
287  }
288 
310  protected function addWhereIDsFld( $table, $field, $ids ) {
311  // Use count() to its full documented capabilities to simultaneously
312  // test for null, empty array or empty countable object
313  if ( count( $ids ) ) {
314  $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
315 
316  if ( $ids === [] ) {
317  // Return nothing, no IDs are valid
318  $this->getQueryBuilder()->where( '0 = 1' );
319  } else {
320  $this->getQueryBuilder()->where( [ $field => $ids ] );
321  }
322  }
323  return count( $ids );
324  }
325 
338  protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
339  $isDirNewer = ( $dir === 'newer' );
340  $after = ( $isDirNewer ? '>=' : '<=' );
341  $before = ( $isDirNewer ? '<=' : '>=' );
342  $db = $this->getDB();
343 
344  if ( $start !== null ) {
345  $this->addWhere( $field . $after . $db->addQuotes( $start ) );
346  }
347 
348  if ( $end !== null ) {
349  $this->addWhere( $field . $before . $db->addQuotes( $end ) );
350  }
351 
352  if ( $sort ) {
353  $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
354  }
355  }
356 
367  protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
368  $db = $this->getDB();
369  $this->addWhereRange( $field, $dir,
370  $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
371  }
372 
379  protected function addOption( $name, $value = null ) {
380  $this->getQueryBuilder()->option( $name, $value );
381  }
382 
400  protected function select( $method, $extraQuery = [], array &$hookData = null ) {
401  $queryBuilder = clone $this->getQueryBuilder();
402  if ( isset( $extraQuery['tables'] ) ) {
403  $queryBuilder->rawTables( (array)$extraQuery['tables'] );
404  }
405  if ( isset( $extraQuery['fields'] ) ) {
406  $queryBuilder->fields( (array)$extraQuery['fields'] );
407  }
408  if ( isset( $extraQuery['where'] ) ) {
409  $queryBuilder->where( (array)$extraQuery['where'] );
410  }
411  if ( isset( $extraQuery['options'] ) ) {
412  $queryBuilder->options( (array)$extraQuery['options'] );
413  }
414  if ( isset( $extraQuery['join_conds'] ) ) {
415  $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
416  }
417 
418  if ( $hookData !== null && $this->getHookContainer()->isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
419  $info = $queryBuilder->getQueryInfo();
420  $this->getHookRunner()->onApiQueryBaseBeforeQuery(
421  $this, $info['tables'], $info['fields'], $info['conds'],
422  $info['options'], $info['join_conds'], $hookData
423  );
424  $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
425  }
426 
427  $queryBuilder->caller( $method );
428  $res = $queryBuilder->fetchResultSet();
429 
430  if ( $hookData !== null ) {
431  $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
432  }
433 
434  return $res;
435  }
436 
450  protected function processRow( $row, array &$data, array &$hookData ) {
451  return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
452  }
453 
454  // endregion -- end of querying
455 
456  /***************************************************************************/
457  // region Utility methods
467  public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
468  $arr[$prefix . 'ns'] = $title->getNamespace();
469  $arr[$prefix . 'title'] = $title->getPrefixedText();
470  }
471 
478  protected function addPageSubItems( $pageId, $data ) {
479  $result = $this->getResult();
481 
482  return $result->addValue( [ 'query', 'pages', (int)$pageId ],
483  $this->getModuleName(),
484  $data );
485  }
486 
495  protected function addPageSubItem( $pageId, $item, $elemname = null ) {
496  $result = $this->getResult();
497  $fit = $result->addValue( [ 'query', 'pages', $pageId,
498  $this->getModuleName() ], null, $item );
499  if ( !$fit ) {
500  return false;
501  }
502  $result->addIndexedTagName(
503  [ 'query', 'pages', $pageId, $this->getModuleName() ],
504  $elemname ?? $this->getModulePrefix()
505  );
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 
575  public function validateSha1Hash( $hash ) {
576  return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
577  }
578 
583  public function validateSha1Base36Hash( $hash ) {
584  return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
585  }
586 
592  public function userCanSeeRevDel() {
593  return $this->getAuthority()->isAllowedAny(
594  'deletedhistory',
595  'deletedtext',
596  'deleterevision',
597  'suppressrevision',
598  'viewsuppressed'
599  );
600  }
601 
612  IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
613  ) {
614  if ( !$res->numRows() ) {
615  return;
616  }
617 
618  $services = MediaWikiServices::getInstance();
619  if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
620  return;
621  }
622 
623  $nsInfo = $services->getNamespaceInfo();
624  $namespaceField = $fieldPrefix . '_namespace';
625  $titleField = $fieldPrefix . '_title';
626 
627  $usernames = [];
628  foreach ( $res as $row ) {
629  if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
630  $usernames[] = $row->$titleField;
631  }
632  }
633 
634  if ( $usernames === [] ) {
635  return;
636  }
637 
638  $genderCache = $services->getGenderCache();
639  $genderCache->doQuery( $usernames, $fname );
640  }
641 
642  // endregion -- end of utility methods
643 }
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:1459
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:1330
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1700
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:718
getContinuationManager()
Definition: ApiBase.php:670
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: ApiBase.php:703
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:41
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 page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:40
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:667
A query builder for 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:40
Result wrapper for grabbing data queried from an IDatabase object.