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 
133  public function selectNamedDB( $name, $db, $groups ) {
134  $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
135  return $this->mDb;
136  }
137 
143  protected function getPageSet() {
144  return $this->getQuery()->getPageSet();
145  }
146 
147  // endregion -- end of data access
148 
149  /***************************************************************************/
150  // region Querying
156  protected function resetQueryParams() {
157  $this->queryBuilder = null;
158  }
159 
168  protected function getQueryBuilder() {
169  if ( $this->queryBuilder === null ) {
170  $this->queryBuilder = $this->getDB()->newSelectQueryBuilder();
171  }
172  return $this->queryBuilder;
173  }
174 
182  protected function addTables( $tables, $alias = null ) {
183  if ( is_array( $tables ) ) {
184  if ( $alias !== null ) {
185  ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
186  }
187  $this->getQueryBuilder()->rawTables( $tables );
188  } else {
189  $this->getQueryBuilder()->table( $tables, $alias );
190  }
191  }
192 
201  protected function addJoinConds( $join_conds ) {
202  if ( !is_array( $join_conds ) ) {
203  ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
204  }
205  $this->getQueryBuilder()->joinConds( $join_conds );
206  }
207 
212  protected function addFields( $value ) {
213  $this->getQueryBuilder()->fields( $value );
214  }
215 
222  protected function addFieldsIf( $value, $condition ) {
223  if ( $condition ) {
224  $this->addFields( $value );
225 
226  return true;
227  }
228 
229  return false;
230  }
231 
245  protected function addWhere( $value ) {
246  if ( is_array( $value ) ) {
247  // Sanity check: don't insert empty arrays,
248  // Database::makeList() chokes on them
249  if ( count( $value ) ) {
250  $this->getQueryBuilder()->where( $value );
251  }
252  } else {
253  $this->getQueryBuilder()->where( $value );
254  }
255  }
256 
263  protected function addWhereIf( $value, $condition ) {
264  if ( $condition ) {
265  $this->addWhere( $value );
266 
267  return true;
268  }
269 
270  return false;
271  }
272 
282  protected function addWhereFld( $field, $value ) {
283  if ( $value !== null && !( is_array( $value ) && !$value ) ) {
284  $this->getQueryBuilder()->where( [ $field => $value ] );
285  }
286  }
287 
309  protected function addWhereIDsFld( $table, $field, $ids ) {
310  // Use count() to its full documented capabilities to simultaneously
311  // test for null, empty array or empty countable object
312  if ( count( $ids ) ) {
313  $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
314 
315  if ( $ids === [] ) {
316  // Return nothing, no IDs are valid
317  $this->getQueryBuilder()->where( '0 = 1' );
318  } else {
319  $this->getQueryBuilder()->where( [ $field => $ids ] );
320  }
321  }
322  return count( $ids );
323  }
324 
337  protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
338  $isDirNewer = ( $dir === 'newer' );
339  $after = ( $isDirNewer ? '>=' : '<=' );
340  $before = ( $isDirNewer ? '<=' : '>=' );
341  $db = $this->getDB();
342 
343  if ( $start !== null ) {
344  $this->addWhere( $field . $after . $db->addQuotes( $start ) );
345  }
346 
347  if ( $end !== null ) {
348  $this->addWhere( $field . $before . $db->addQuotes( $end ) );
349  }
350 
351  if ( $sort ) {
352  $this->getQueryBuilder()->orderBy( $field, $isDirNewer ? null : 'DESC' );
353  }
354  }
355 
366  protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
367  $db = $this->getDB();
368  $this->addWhereRange( $field, $dir,
369  $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
370  }
371 
378  protected function addOption( $name, $value = null ) {
379  $this->getQueryBuilder()->option( $name, $value );
380  }
381 
399  protected function select( $method, $extraQuery = [], array &$hookData = null ) {
400  $queryBuilder = clone $this->getQueryBuilder();
401  if ( isset( $extraQuery['tables'] ) ) {
402  $queryBuilder->rawTables( (array)$extraQuery['tables'] );
403  }
404  if ( isset( $extraQuery['fields'] ) ) {
405  $queryBuilder->fields( (array)$extraQuery['fields'] );
406  }
407  if ( isset( $extraQuery['where'] ) ) {
408  $queryBuilder->where( (array)$extraQuery['where'] );
409  }
410  if ( isset( $extraQuery['options'] ) ) {
411  $queryBuilder->options( (array)$extraQuery['options'] );
412  }
413  if ( isset( $extraQuery['join_conds'] ) ) {
414  $queryBuilder->joinConds( (array)$extraQuery['join_conds'] );
415  }
416 
417  if ( $hookData !== null && $this->getHookContainer()->isRegistered( 'ApiQueryBaseBeforeQuery' ) ) {
418  $info = $queryBuilder->getQueryInfo();
419  $this->getHookRunner()->onApiQueryBaseBeforeQuery(
420  $this, $info['tables'], $info['fields'], $info['conds'],
421  $info['options'], $info['join_conds'], $hookData
422  );
423  $queryBuilder = $this->getDB()->newSelectQueryBuilder()->queryInfo( $info );
424  }
425 
426  $queryBuilder->caller( $method );
428 
429  if ( $hookData !== null ) {
430  $this->getHookRunner()->onApiQueryBaseAfterQuery( $this, $res, $hookData );
431  }
432 
433  return $res;
434  }
435 
449  protected function processRow( $row, array &$data, array &$hookData ) {
450  return $this->getHookRunner()->onApiQueryBaseProcessRow( $this, $row, $data, $hookData );
451  }
452 
453  // endregion -- end of querying
454 
455  /***************************************************************************/
456  // region Utility methods
466  public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
467  $arr[$prefix . 'ns'] = $title->getNamespace();
468  $arr[$prefix . 'title'] = $title->getPrefixedText();
469  }
470 
477  protected function addPageSubItems( $pageId, $data ) {
478  $result = $this->getResult();
480 
481  return $result->addValue( [ 'query', 'pages', (int)$pageId ],
482  $this->getModuleName(),
483  $data );
484  }
485 
494  protected function addPageSubItem( $pageId, $item, $elemname = null ) {
495  if ( $elemname === null ) {
496  $elemname = $this->getModulePrefix();
497  }
498  $result = $this->getResult();
499  $fit = $result->addValue( [ 'query', 'pages', $pageId,
500  $this->getModuleName() ], null, $item );
501  if ( !$fit ) {
502  return false;
503  }
504  $result->addIndexedTagName( [ 'query', 'pages', $pageId,
505  $this->getModuleName() ], $elemname );
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 
580  public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
581  wfDeprecated( __METHOD__, '1.35' );
582  $t = $this->parsePrefixedTitlePart( $titlePart, $defaultNamespace );
583  return [ $t->getNamespace(), $t->getDBkey() ];
584  }
585 
590  public function validateSha1Hash( $hash ) {
591  return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
592  }
593 
598  public function validateSha1Base36Hash( $hash ) {
599  return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
600  }
601 
607  public function userCanSeeRevDel() {
608  return $this->getAuthority()->isAllowedAny(
609  'deletedhistory',
610  'deletedtext',
611  'deleterevision',
612  'suppressrevision',
613  'viewsuppressed'
614  );
615  }
616 
627  IResultWrapper $res, $fname = __METHOD__, $fieldPrefix = 'page'
628  ) {
629  if ( !$res->numRows() ) {
630  return;
631  }
632 
633  $services = MediaWikiServices::getInstance();
634  if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
635  return;
636  }
637 
638  $nsInfo = $services->getNamespaceInfo();
639  $namespaceField = $fieldPrefix . '_namespace';
640  $titleField = $fieldPrefix . '_title';
641 
642  $usernames = [];
643  foreach ( $res as $row ) {
644  if ( $nsInfo->hasGenderDistinction( $row->$namespaceField ) ) {
645  $usernames[] = $row->$titleField;
646  }
647  }
648 
649  if ( $usernames === [] ) {
650  return;
651  }
652 
653  $genderCache = $services->getGenderCache();
654  $genderCache->doQuery( $usernames, $fname );
655  }
656 
657  // endregion -- end of utility methods
658 
659  /***************************************************************************/
660  // region Deprecated methods
670  public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
671  wfDeprecated( __METHOD__, '1.34' );
672  $this->addBlockInfoToQuery( $showBlockInfo );
673  }
674 
675  // endregion -- end of deprecated methods
676 }
ApiQueryBase\validateSha1Base36Hash
validateSha1Base36Hash( $hash)
Definition: ApiQueryBase.php:598
ApiQueryBase\addWhereIDsFld
addWhereIDsFld( $table, $field, $ids)
Like addWhereFld for an integer list of IDs.
Definition: ApiQueryBase.php:309
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:670
ApiQueryBase\addPageSubItems
addPageSubItems( $pageId, $data)
Add a sub-element under the page element with the given page ID.
Definition: ApiQueryBase.php:477
ApiQueryBase\processRow
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
Definition: ApiQueryBase.php:449
ApiQueryBase\addFields
addFields( $value)
Add a set of fields to select to the internal array.
Definition: ApiQueryBase.php:212
Wikimedia\Rdbms\SelectQueryBuilder\joinConds
joinConds(array $joinConds)
Manually append to the $join_conds array which will be passed to IDatabase::select().
Definition: SelectQueryBuilder.php:303
ApiQuery
This is the main query class.
Definition: ApiQuery.php:37
ApiQueryBase\resetQueryParams
resetQueryParams()
Blank the internal arrays with query parameters.
Definition: ApiQueryBase.php:156
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:193
Wikimedia\Rdbms\SelectQueryBuilder\options
options(array $options)
Manually set multiple options in the $options array to be passed to IDatabase::select().
Definition: SelectQueryBuilder.php:607
ApiQueryBase\getParent
getParent()
Get the parent of this module.Stability: stableto override 1.25 ApiBase|null
Definition: ApiQueryBase.php:108
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1379
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:366
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:125
Wikimedia\Rdbms\SelectQueryBuilder\fetchResultSet
fetchResultSet()
Run the constructed SELECT query and return all results.
Definition: SelectQueryBuilder.php:628
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:571
ApiQueryBase\getQuery
getQuery()
Get the main Query module.
Definition: ApiQueryBase.php:103
ApiBase\getHookContainer
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: ApiBase.php:638
ApiQueryBase\addOption
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
Definition: ApiQueryBase.php:378
$res
$res
Definition: testCompression.php:57
ApiQueryBase\addFieldsIf
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
Definition: ApiQueryBase.php:222
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:55
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:64
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:626
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Definition: GlobalFunctions.php:997
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:26
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:618
ApiQueryBase\getDB
getDB()
Get the Query database connection (read-only)
Definition: ApiQueryBase.php:117
Wikimedia\Rdbms\SelectQueryBuilder
Definition: SelectQueryBuilder.php:11
ApiQueryBase\addTables
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
Definition: ApiQueryBase.php:182
ApiQueryBase\select
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
Definition: ApiQueryBase.php:399
$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:184
Wikimedia\Rdbms\SelectQueryBuilder\getQueryInfo
getQueryInfo( $joinsName='join_conds')
Get an associative array describing the query in terms of its raw parameters to Database::select().
Definition: SelectQueryBuilder.php:777
ApiBase\getModulePrefix
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:448
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:337
ApiBase\getContinuationManager
getContinuationManager()
Definition: ApiBase.php:605
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:677
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:603
ApiQueryBase\getQueryBuilder
getQueryBuilder()
Get the SelectQueryBuilder.
Definition: ApiQueryBase.php:168
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:144
ApiQueryBase\requestExtraData
requestExtraData( $pageSet)
Override this method to request extra fields from the pageSet using $pageSet->requestField('fieldName...
Definition: ApiQueryBase.php:90
ApiQueryBase\addJoinConds
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
Definition: ApiQueryBase.php:201
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1455
ApiQueryBase\addWhereFld
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
Definition: ApiQueryBase.php:282
ApiQueryBase\getCacheMode
getCacheMode( $params)
Get the cache mode for the data generated by this module.
Definition: ApiQueryBase.php:76
ApiQueryBase\prefixedTitlePartToKey
prefixedTitlePartToKey( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a namespace constant and dbkey.
Definition: ApiQueryBase.php:580
ApiQueryBase\getPageSet
getPageSet()
Get the PageSet object to work on.
Definition: ApiQueryBase.php:143
ApiBase\filterIDs
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition: ApiBase.php:1250
ApiQueryBase\selectNamedDB
selectNamedDB( $name, $db, $groups)
Selects the query database connection with the given name.
Definition: ApiQueryBase.php:133
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='')
Definition: ApiQueryBase.php:53
ApiQueryBase\parsePrefixedTitlePart
parsePrefixedTitlePart( $titlePart, $defaultNamespace=NS_MAIN)
Convert an input title or title prefix into a TitleValue.
Definition: ApiQueryBase.php:555
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:440
ApiQueryBase\$mQueryModule
$mQueryModule
Definition: ApiQueryBase.php:40
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:456
ApiQueryBase\addWhere
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Definition: ApiQueryBase.php:245
$t
$t
Definition: testCompression.php:74
ApiQueryBase\setContinueEnumParameter
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
Definition: ApiQueryBase.php:515
ApiQueryBase\titlePartToKey
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
Definition: ApiQueryBase.php:529
ApiBase\getHookRunner
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:653
Wikimedia\Rdbms\SelectQueryBuilder\where
where( $conds)
Add conditions to the query.
Definition: SelectQueryBuilder.php:256
ApiQueryBase\userCanSeeRevDel
userCanSeeRevDel()
Check whether the current user has permission to view revision-deleted fields.
Definition: ApiQueryBase.php:607
ApiQueryBase\addPageSubItem
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
Definition: ApiQueryBase.php:494
ApiBase\dieDebug
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1582
ApiQueryBase\addWhereIf
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
Definition: ApiQueryBase.php:263
ApiQueryBase\addTitleInfo
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
Definition: ApiQueryBase.php:466
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:40
ApiQueryBase\validateSha1Hash
validateSha1Hash( $hash)
Definition: ApiQueryBase.php:590