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  if ( $this->mDb === null ) {
119  $this->mDb = $this->getQuery()->getDB();
120  }
121 
122  return $this->mDb;
123  }
124 
137  public function selectNamedDB( $name, $db, $groups ) {
138  wfDeprecated( __METHOD__, '1.39' );
139  $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
140  return $this->mDb;
141  }
142 
148  protected function getPageSet() {
149  return $this->getQuery()->getPageSet();
150  }
151 
152  // endregion -- end of data access
153 
154  /***************************************************************************/
155  // region Querying
161  protected function resetQueryParams() {
162  $this->queryBuilder = null;
163  }
164 
173  protected function getQueryBuilder() {
174  if ( $this->queryBuilder === null ) {
175  $this->queryBuilder = $this->getDB()->newSelectQueryBuilder();
176  }
177  return $this->queryBuilder;
178  }
179 
187  protected function addTables( $tables, $alias = null ) {
188  if ( is_array( $tables ) ) {
189  if ( $alias !== null ) {
190  ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
191  }
192  $this->getQueryBuilder()->rawTables( $tables );
193  } else {
194  $this->getQueryBuilder()->table( $tables, $alias );
195  }
196  }
197 
206  protected function addJoinConds( $join_conds ) {
207  if ( !is_array( $join_conds ) ) {
208  ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
209  }
210  $this->getQueryBuilder()->joinConds( $join_conds );
211  }
212 
217  protected function addFields( $value ) {
218  $this->getQueryBuilder()->fields( $value );
219  }
220 
227  protected function addFieldsIf( $value, $condition ) {
228  if ( $condition ) {
229  $this->addFields( $value );
230 
231  return true;
232  }
233 
234  return false;
235  }
236 
250  protected function addWhere( $value ) {
251  if ( is_array( $value ) ) {
252  // Double check: don't insert empty arrays,
253  // Database::makeList() chokes on them
254  if ( count( $value ) ) {
255  $this->getQueryBuilder()->where( $value );
256  }
257  } else {
258  $this->getQueryBuilder()->where( $value );
259  }
260  }
261 
268  protected function addWhereIf( $value, $condition ) {
269  if ( $condition ) {
270  $this->addWhere( $value );
271 
272  return true;
273  }
274 
275  return false;
276  }
277 
287  protected function addWhereFld( $field, $value ) {
288  if ( $value !== null && !( is_array( $value ) && !$value ) ) {
289  $this->getQueryBuilder()->where( [ $field => $value ] );
290  }
291  }
292 
314  protected function addWhereIDsFld( $table, $field, $ids ) {
315  // Use count() to its full documented capabilities to simultaneously
316  // test for null, empty array or empty countable object
317  if ( count( $ids ) ) {
318  $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
319 
320  if ( $ids === [] ) {
321  // Return nothing, no IDs are valid
322  $this->getQueryBuilder()->where( '0 = 1' );
323  } else {
324  $this->getQueryBuilder()->where( [ $field => $ids ] );
325  }
326  }
327  return count( $ids );
328  }
329 
342  protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
343  $isDirNewer = ( $dir === 'newer' );
344  $after = ( $isDirNewer ? '>=' : '<=' );
345  $before = ( $isDirNewer ? '<=' : '>=' );
346  $db = $this->getDB();
347 
348  if ( $start !== null ) {
349  $this->addWhere( $field . $after . $db->addQuotes( $start ) );
350  }
351 
352  if ( $end !== null ) {
353  $this->addWhere( $field . $before . $db->addQuotes( $end ) );
354  }
355 
356  if ( $sort ) {
357  $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
358  }
359  }
360 
371  protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
372  $db = $this->getDB();
373  $this->addWhereRange( $field, $dir,
374  $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
375  }
376 
383  protected function addOption( $name, $value = null ) {
384  $this->getQueryBuilder()->option( $name, $value );
385  }
386 
404  protected function select( $method, $extraQuery = [], array &$hookData = null ) {
405  $queryBuilder = clone $this->getQueryBuilder();
406  if ( isset( $extraQuery['tables'] ) ) {
407  $queryBuilder->rawTables( (array)$extraQuery['tables'] );
408  }
409  if ( isset( $extraQuery['fields'] ) ) {
410  $queryBuilder->fields( (array)$extraQuery['fields'] );
411  }
412  if ( isset( $extraQuery['where'] ) ) {
413  $queryBuilder->where( (array)$extraQuery['where'] );
414  }
415  if ( isset( $extraQuery['options'] ) ) {
416  $queryBuilder->options( (array)$extraQuery['options'] );
417  }
418  if ( isset( $extraQuery['join_conds'] ) ) {
419  $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
420  }
421 
422  if ( $hookData !== null && $this->getHookContainer()->isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
423  $info = $queryBuilder->getQueryInfo();
424  $this->getHookRunner()->onApiQueryBaseBeforeQuery(
425  $this, $info['tables'], $info['fields'], $info['conds'],
426  $info['options'], $info['join_conds'], $hookData
427  );
428  $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
429  }
430 
431  $queryBuilder->caller( $method );
432  $res = $queryBuilder->fetchResultSet();
433 
434  if ( $hookData !== null ) {
435  $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
436  }
437 
438  return $res;
439  }
440 
454  protected function processRow( $row, array &$data, array &$hookData ) {
455  return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
456  }
457 
458  // endregion -- end of querying
459 
460  /***************************************************************************/
461  // region Utility methods
471  public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
472  $arr[$prefix . 'ns'] = $title->getNamespace();
473  $arr[$prefix . 'title'] = $title->getPrefixedText();
474  }
475 
482  protected function addPageSubItems( $pageId, $data ) {
483  $result = $this->getResult();
485 
486  return $result->addValue( [ 'query', 'pages', (int)$pageId ],
487  $this->getModuleName(),
488  $data );
489  }
490 
499  protected function addPageSubItem( $pageId, $item, $elemname = null ) {
500  if ( $elemname === null ) {
501  $elemname = $this->getModulePrefix();
502  }
503  $result = $this->getResult();
504  $fit = $result->addValue( [ 'query', 'pages', $pageId,
505  $this->getModuleName() ], null, $item );
506  if ( !$fit ) {
507  return false;
508  }
509  $result->addIndexedTagName( [ 'query', 'pages', $pageId,
510  $this->getModuleName() ], $elemname );
511 
512  return true;
513  }
514 
520  protected function setContinueEnumParameter( $paramName, $paramValue ) {
521  $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
522  }
523 
534  public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
535  $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
536  if ( !$t || $t->hasFragment() ) {
537  // Invalid title (e.g. bad chars) or contained a '#'.
538  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
539  }
540  if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
541  // This can happen in two cases. First, if you call titlePartToKey with a title part
542  // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
543  // difficult to handle such a case. Such cases cannot exist and are therefore treated
544  // as invalid user input. The second case is when somebody specifies a title interwiki
545  // prefix.
546  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
547  }
548 
549  return substr( $t->getDBkey(), 0, -1 );
550  }
551 
560  protected function parsePrefixedTitlePart( $titlePart, $defaultNamespace = NS_MAIN ) {
561  try {
562  $titleParser = MediaWikiServices::getInstance()->getTitleParser();
563  $t = $titleParser->parseTitle( $titlePart . 'X', $defaultNamespace );
564  } catch ( MalformedTitleException $e ) {
565  $t = null;
566  }
567 
568  if ( !$t || $t->hasFragment() || $t->isExternal() || $t->getDBkey() === 'X' ) {
569  // Invalid title (e.g. bad chars) or contained a '#'.
570  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
571  }
572 
573  return new TitleValue( $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) );
574  }
575 
580  public function validateSha1Hash( $hash ) {
581  return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
582  }
583 
588  public function validateSha1Base36Hash( $hash ) {
589  return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
590  }
591 
597  public function userCanSeeRevDel() {
598  return $this->getAuthority()->isAllowedAny(
599  'deletedhistory',
600  'deletedtext',
601  'deleterevision',
602  'suppressrevision',
603  'viewsuppressed'
604  );
605  }
606 
617  IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
618  ) {
619  if ( !$res->numRows() ) {
620  return;
621  }
622 
623  $services = MediaWikiServices::getInstance();
624  if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
625  return;
626  }
627 
628  $nsInfo = $services->getNamespaceInfo();
629  $namespaceField = $fieldPrefix . '_namespace';
630  $titleField = $fieldPrefix . '_title';
631 
632  $usernames = [];
633  foreach ( $res as $row ) {
634  if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
635  $usernames[] = $row->$titleField;
636  }
637  }
638 
639  if ( $usernames === [] ) {
640  return;
641  }
642 
643  $genderCache = $services->getGenderCache();
644  $genderCache->doQuery( $usernames, $fname );
645  }
646 
647  // endregion -- end of utility methods
648 }
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:56
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1453
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:506
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition: ApiBase.php:1324
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1658
getMain()
Get the main module.
Definition: ApiBase.php:514
getResult()
Get the result object.
Definition: ApiBase.php:629
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:498
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:711
getContinuationManager()
Definition: ApiBase.php:663
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: ApiBase.php:696
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:664
Note that none of the methods in this class are stable to override.
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:39
Result wrapper for grabbing data queried from an IDatabase object.