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  /************************************************************************/
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();
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 }
ApiQueryBase\validateSha1Base36Hash
validateSha1Base36Hash( $hash)
Definition: ApiQueryBase.php:602
ApiQueryBase\addWhereIDsFld
addWhereIDsFld( $table, $field, $ids)
Like addWhereFld for an integer list of IDs.
Definition: ApiQueryBase.php:312
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:675
ApiQueryBase\addPageSubItems
addPageSubItems( $pageId, $data)
Add a sub-element under the page element with the given page ID.
Definition: ApiQueryBase.php:481
ApiQueryBase\processRow
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
Definition: ApiQueryBase.php:452
ApiQueryBase\addFields
addFields( $value)
Add a set of fields to select to the internal array.
Definition: ApiQueryBase.php:215
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:159
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:160
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 Stable to override.1.25 ApiBase|null
Definition: ApiQueryBase.php:110
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1381
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:369
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:564
ApiQueryBase\getQuery
getQuery()
Get the main Query module.
Definition: ApiQueryBase.php:105
ApiQueryBase\addOption
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
Definition: ApiQueryBase.php:381
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Stable to override.
Definition: ContextSource.php:134
ApiQueryBase\addFieldsIf
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
Definition: ApiQueryBase.php:225
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:52
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:630
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
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:37
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) Stable to override.
Definition: ApiQueryBase.php:119
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:185
ApiQueryBase\select
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
Definition: ApiQueryBase.php:402
$title
$title
Definition: testCompression.php:38
ApiQueryBase\$mDb
$mDb
Definition: ApiQueryBase.php:40
ApiQueryBase\$queryBuilder
SelectQueryBuilder $queryBuilder
Definition: ApiQueryBase.php:45
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:451
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:340
ApiBase\getContinuationManager
getContinuationManager()
Get the continuation manager.
Definition: ApiBase.php:606
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
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:171
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:636
ApiQueryBase\requestExtraData
requestExtraData( $pageSet)
Override this method to request extra fields from the pageSet using $pageSet->requestField('fieldName...
Definition: ApiQueryBase.php:91
ApiQueryBase\addJoinConds
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
Definition: ApiQueryBase.php:204
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1494
ApiQueryBase\addWhereFld
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
Definition: ApiQueryBase.php:285
ApiQueryBase\getCacheMode
getCacheMode( $params)
Get the cache mode for the data generated by this module.
Definition: ApiQueryBase.php:77
ApiQueryBase\prefixedTitlePartToKey
prefixedTitlePartToKey( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a namespace constant and dbkey.
Definition: ApiQueryBase.php:584
ApiQueryBase\getPageSet
getPageSet()
Get the PageSet object to work on Stable to override.
Definition: ApiQueryBase.php:145
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:1252
ApiQueryBase\selectNamedDB
selectNamedDB( $name, $db, $groups)
Selects the query database connection with the given name.
Definition: ApiQueryBase.php:135
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:26
ApiQueryBase\__construct
__construct(ApiQuery $queryModule, $moduleName, $paramPrefix='')
Stable to call.
Definition: ApiQueryBase.php:53
ApiQueryBase\parsePrefixedTitlePart
parsePrefixedTitlePart( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a TitleValue.
Definition: ApiQueryBase.php:559
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:443
ApiQueryBase\$mQueryModule
$mQueryModule
Definition: ApiQueryBase.php:40
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:459
ApiQueryBase\addWhere
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Definition: ApiQueryBase.php:248
$t
$t
Definition: testCompression.php:74
ApiQueryBase\setContinueEnumParameter
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
Definition: ApiQueryBase.php:519
ApiQueryBase\titlePartToKey
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
Definition: ApiQueryBase.php:533
ApiBase\getHookRunner
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:661
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:611
ApiQueryBase\addPageSubItem
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
Definition: ApiQueryBase.php:498
ApiBase\dieDebug
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1573
ApiQueryBase\addWhereIf
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
Definition: ApiQueryBase.php:266
ApiQueryBase\addTitleInfo
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
Definition: ApiQueryBase.php:470
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:39
ApiQueryBase\validateSha1Hash
validateSha1Hash( $hash)
Definition: ApiQueryBase.php:594