Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / api / ApiQuery.php
blob514d559430bdef13efc2bcaf4c513082f4148db6
1 <?php
2 /**
5 * Created on Sep 7, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
24 * @file
27 /**
28 * This is the main query class. It behaves similar to ApiMain: based on the
29 * parameters given, it will create a list of titles to work on (an ApiPageSet
30 * object), instantiate and execute various property/list/meta modules, and
31 * assemble all resulting data into a single ApiResult object.
33 * In generator mode, a generator will be executed first to populate a second
34 * ApiPageSet object, and that object will be used for all subsequent modules.
36 * @ingroup API
38 class ApiQuery extends ApiBase {
40 /**
41 * List of Api Query prop modules
42 * @var array
44 private static $QueryPropModules = array(
45 'categories' => 'ApiQueryCategories',
46 'categoryinfo' => 'ApiQueryCategoryInfo',
47 'contributors' => 'ApiQueryContributors',
48 'deletedrevisions' => 'ApiQueryDeletedRevisions',
49 'duplicatefiles' => 'ApiQueryDuplicateFiles',
50 'extlinks' => 'ApiQueryExternalLinks',
51 'fileusage' => 'ApiQueryBacklinksprop',
52 'images' => 'ApiQueryImages',
53 'imageinfo' => 'ApiQueryImageInfo',
54 'info' => 'ApiQueryInfo',
55 'links' => 'ApiQueryLinks',
56 'linkshere' => 'ApiQueryBacklinksprop',
57 'iwlinks' => 'ApiQueryIWLinks',
58 'langlinks' => 'ApiQueryLangLinks',
59 'pageprops' => 'ApiQueryPageProps',
60 'redirects' => 'ApiQueryBacklinksprop',
61 'revisions' => 'ApiQueryRevisions',
62 'stashimageinfo' => 'ApiQueryStashImageInfo',
63 'templates' => 'ApiQueryLinks',
64 'transcludedin' => 'ApiQueryBacklinksprop',
67 /**
68 * List of Api Query list modules
69 * @var array
71 private static $QueryListModules = array(
72 'allcategories' => 'ApiQueryAllCategories',
73 'alldeletedrevisions' => 'ApiQueryAllDeletedRevisions',
74 'allfileusages' => 'ApiQueryAllLinks',
75 'allimages' => 'ApiQueryAllImages',
76 'alllinks' => 'ApiQueryAllLinks',
77 'allpages' => 'ApiQueryAllPages',
78 'allredirects' => 'ApiQueryAllLinks',
79 'alltransclusions' => 'ApiQueryAllLinks',
80 'allusers' => 'ApiQueryAllUsers',
81 'backlinks' => 'ApiQueryBacklinks',
82 'blocks' => 'ApiQueryBlocks',
83 'categorymembers' => 'ApiQueryCategoryMembers',
84 'deletedrevs' => 'ApiQueryDeletedrevs',
85 'embeddedin' => 'ApiQueryBacklinks',
86 'exturlusage' => 'ApiQueryExtLinksUsage',
87 'filearchive' => 'ApiQueryFilearchive',
88 'imageusage' => 'ApiQueryBacklinks',
89 'iwbacklinks' => 'ApiQueryIWBacklinks',
90 'langbacklinks' => 'ApiQueryLangBacklinks',
91 'logevents' => 'ApiQueryLogEvents',
92 'pageswithprop' => 'ApiQueryPagesWithProp',
93 'pagepropnames' => 'ApiQueryPagePropNames',
94 'prefixsearch' => 'ApiQueryPrefixSearch',
95 'protectedtitles' => 'ApiQueryProtectedTitles',
96 'querypage' => 'ApiQueryQueryPage',
97 'random' => 'ApiQueryRandom',
98 'recentchanges' => 'ApiQueryRecentChanges',
99 'search' => 'ApiQuerySearch',
100 'tags' => 'ApiQueryTags',
101 'usercontribs' => 'ApiQueryContributions',
102 'users' => 'ApiQueryUsers',
103 'watchlist' => 'ApiQueryWatchlist',
104 'watchlistraw' => 'ApiQueryWatchlistRaw',
108 * List of Api Query meta modules
109 * @var array
111 private static $QueryMetaModules = array(
112 'allmessages' => 'ApiQueryAllMessages',
113 'siteinfo' => 'ApiQuerySiteinfo',
114 'userinfo' => 'ApiQueryUserInfo',
115 'filerepoinfo' => 'ApiQueryFileRepoInfo',
116 'tokens' => 'ApiQueryTokens',
120 * @var ApiPageSet
122 private $mPageSet;
124 private $mParams;
125 private $mNamedDB = array();
126 private $mModuleMgr;
129 * @param ApiMain $main
130 * @param string $action
132 public function __construct( ApiMain $main, $action ) {
133 parent::__construct( $main, $action );
135 $this->mModuleMgr = new ApiModuleManager( $this );
137 // Allow custom modules to be added in LocalSettings.php
138 $config = $this->getConfig();
139 $this->mModuleMgr->addModules( self::$QueryPropModules, 'prop' );
140 $this->mModuleMgr->addModules( $config->get( 'APIPropModules' ), 'prop' );
141 $this->mModuleMgr->addModules( self::$QueryListModules, 'list' );
142 $this->mModuleMgr->addModules( $config->get( 'APIListModules' ), 'list' );
143 $this->mModuleMgr->addModules( self::$QueryMetaModules, 'meta' );
144 $this->mModuleMgr->addModules( $config->get( 'APIMetaModules' ), 'meta' );
146 // Create PageSet that will process titles/pageids/revids/generator
147 $this->mPageSet = new ApiPageSet( $this );
151 * Overrides to return this instance's module manager.
152 * @return ApiModuleManager
154 public function getModuleManager() {
155 return $this->mModuleMgr;
159 * Get the query database connection with the given name.
160 * If no such connection has been requested before, it will be created.
161 * Subsequent calls with the same $name will return the same connection
162 * as the first, regardless of the values of $db and $groups
163 * @param string $name Name to assign to the database connection
164 * @param int $db One of the DB_* constants
165 * @param array $groups Query groups
166 * @return DatabaseBase
168 public function getNamedDB( $name, $db, $groups ) {
169 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
170 $this->profileDBIn();
171 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
172 $this->profileDBOut();
175 return $this->mNamedDB[$name];
179 * Gets the set of pages the user has requested (or generated)
180 * @return ApiPageSet
182 public function getPageSet() {
183 return $this->mPageSet;
187 * Get the array mapping module names to class names
188 * @deprecated since 1.21, use getModuleManager()'s methods instead
189 * @return array Array(modulename => classname)
191 public function getModules() {
192 wfDeprecated( __METHOD__, '1.21' );
194 return $this->getModuleManager()->getNamesWithClasses();
198 * Get the generators array mapping module names to class names
199 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
200 * @return array Array(modulename => classname)
202 public function getGenerators() {
203 wfDeprecated( __METHOD__, '1.21' );
204 $gens = array();
205 foreach ( $this->mModuleMgr->getNamesWithClasses() as $name => $class ) {
206 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
207 $gens[$name] = $class;
211 return $gens;
215 * Get whether the specified module is a prop, list or a meta query module
216 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
217 * @param string $moduleName Name of the module to find type for
218 * @return string|null
220 function getModuleType( $moduleName ) {
221 return $this->getModuleManager()->getModuleGroup( $moduleName );
225 * @return ApiFormatRaw|null
227 public function getCustomPrinter() {
228 // If &exportnowrap is set, use the raw formatter
229 if ( $this->getParameter( 'export' ) &&
230 $this->getParameter( 'exportnowrap' )
232 return new ApiFormatRaw( $this->getMain(),
233 $this->getMain()->createPrinterByName( 'xml' ) );
234 } else {
235 return null;
240 * Query execution happens in the following steps:
241 * #1 Create a PageSet object with any pages requested by the user
242 * #2 If using a generator, execute it to get a new ApiPageSet object
243 * #3 Instantiate all requested modules.
244 * This way the PageSet object will know what shared data is required,
245 * and minimize DB calls.
246 * #4 Output all normalization and redirect resolution information
247 * #5 Execute all requested modules
249 public function execute() {
250 $this->mParams = $this->extractRequestParams();
252 if ( $this->mParams['continue'] === null && !$this->mParams['rawcontinue'] ) {
253 $this->logFeatureUsage( 'action=query&!rawcontinue&!continue' );
254 $this->setWarning(
255 'Formatting of continuation data will be changing soon. ' .
256 'To continue using the current formatting, use the \'rawcontinue\' parameter. ' .
257 'To begin using the new format, pass an empty string for \'continue\' ' .
258 'in the initial query.'
262 // Instantiate requested modules
263 $allModules = array();
264 $this->instantiateModules( $allModules, 'prop' );
265 $propModules = array_keys( $allModules );
266 $this->instantiateModules( $allModules, 'list' );
267 $this->instantiateModules( $allModules, 'meta' );
269 // Filter modules based on continue parameter
270 list( $generatorDone, $modules ) = $this->getResult()->beginContinuation(
271 $this->mParams['continue'], $allModules, $propModules
274 if ( !$generatorDone ) {
275 // Query modules may optimize data requests through the $this->getPageSet()
276 // object by adding extra fields from the page table.
277 foreach ( $modules as $module ) {
278 $module->requestExtraData( $this->mPageSet );
280 // Populate page/revision information
281 $this->mPageSet->execute();
282 // Record page information (title, namespace, if exists, etc)
283 $this->outputGeneralPageInfo();
284 } else {
285 $this->mPageSet->executeDryRun();
288 $cacheMode = $this->mPageSet->getCacheMode();
290 // Execute all unfinished modules
291 /** @var $module ApiQueryBase */
292 foreach ( $modules as $module ) {
293 $params = $module->extractRequestParams();
294 $cacheMode = $this->mergeCacheMode(
295 $cacheMode, $module->getCacheMode( $params ) );
296 $module->profileIn();
297 $module->execute();
298 Hooks::run( 'APIQueryAfterExecute', array( &$module ) );
299 $module->profileOut();
302 // Set the cache mode
303 $this->getMain()->setCacheMode( $cacheMode );
305 // Write the continuation data into the result
306 $this->getResult()->endContinuation(
307 $this->mParams['continue'] === null ? 'raw' : 'standard'
312 * Update a cache mode string, applying the cache mode of a new module to it.
313 * The cache mode may increase in the level of privacy, but public modules
314 * added to private data do not decrease the level of privacy.
316 * @param string $cacheMode
317 * @param string $modCacheMode
318 * @return string
320 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
321 if ( $modCacheMode === 'anon-public-user-private' ) {
322 if ( $cacheMode !== 'private' ) {
323 $cacheMode = 'anon-public-user-private';
325 } elseif ( $modCacheMode === 'public' ) {
326 // do nothing, if it's public already it will stay public
327 } else { // private
328 $cacheMode = 'private';
331 return $cacheMode;
335 * Create instances of all modules requested by the client
336 * @param array $modules To append instantiated modules to
337 * @param string $param Parameter name to read modules from
339 private function instantiateModules( &$modules, $param ) {
340 $wasPosted = $this->getRequest()->wasPosted();
341 if ( isset( $this->mParams[$param] ) ) {
342 foreach ( $this->mParams[$param] as $moduleName ) {
343 $instance = $this->mModuleMgr->getModule( $moduleName, $param );
344 if ( $instance === null ) {
345 ApiBase::dieDebug( __METHOD__, 'Error instantiating module' );
347 if ( !$wasPosted && $instance->mustBePosted() ) {
348 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $moduleName ) );
350 // Ignore duplicates. TODO 2.0: die()?
351 if ( !array_key_exists( $moduleName, $modules ) ) {
352 $modules[$moduleName] = $instance;
359 * Appends an element for each page in the current pageSet with the
360 * most general information (id, title), plus any title normalizations
361 * and missing or invalid title/pageids/revids.
363 private function outputGeneralPageInfo() {
364 $pageSet = $this->getPageSet();
365 $result = $this->getResult();
367 // We can't really handle max-result-size failure here, but we need to
368 // check anyway in case someone set the limit stupidly low.
369 $fit = true;
371 $values = $pageSet->getNormalizedTitlesAsResult( $result );
372 if ( $values ) {
373 $fit = $fit && $result->addValue( 'query', 'normalized', $values );
375 $values = $pageSet->getConvertedTitlesAsResult( $result );
376 if ( $values ) {
377 $fit = $fit && $result->addValue( 'query', 'converted', $values );
379 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->mParams['iwurl'] );
380 if ( $values ) {
381 $fit = $fit && $result->addValue( 'query', 'interwiki', $values );
383 $values = $pageSet->getRedirectTitlesAsResult( $result );
384 if ( $values ) {
385 $fit = $fit && $result->addValue( 'query', 'redirects', $values );
387 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
388 if ( $values ) {
389 $fit = $fit && $result->addValue( 'query', 'badrevids', $values );
392 // Page elements
393 $pages = array();
395 // Report any missing titles
396 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
397 $vals = array();
398 ApiQueryBase::addTitleInfo( $vals, $title );
399 $vals['missing'] = '';
400 $pages[$fakeId] = $vals;
402 // Report any invalid titles
403 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
404 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
406 // Report any missing page ids
407 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
408 $pages[$pageid] = array(
409 'pageid' => $pageid,
410 'missing' => ''
413 // Report special pages
414 /** @var $title Title */
415 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
416 $vals = array();
417 ApiQueryBase::addTitleInfo( $vals, $title );
418 $vals['special'] = '';
419 if ( $title->isSpecialPage() &&
420 !SpecialPageFactory::exists( $title->getDBkey() )
422 $vals['missing'] = '';
423 } elseif ( $title->getNamespace() == NS_MEDIA &&
424 !wfFindFile( $title )
426 $vals['missing'] = '';
428 $pages[$fakeId] = $vals;
431 // Output general page information for found titles
432 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
433 $vals = array();
434 $vals['pageid'] = $pageid;
435 ApiQueryBase::addTitleInfo( $vals, $title );
436 $pages[$pageid] = $vals;
439 if ( count( $pages ) ) {
440 $pageSet->populateGeneratorData( $pages );
442 if ( $this->mParams['indexpageids'] ) {
443 $pageIDs = array_keys( $pages );
444 // json treats all map keys as strings - converting to match
445 $pageIDs = array_map( 'strval', $pageIDs );
446 $result->setIndexedTagName( $pageIDs, 'id' );
447 $fit = $fit && $result->addValue( 'query', 'pageids', $pageIDs );
450 $result->setIndexedTagName( $pages, 'page' );
451 $fit = $fit && $result->addValue( 'query', 'pages', $pages );
454 if ( !$fit ) {
455 $this->dieUsage(
456 'The value of $wgAPIMaxResultSize on this wiki is ' .
457 'too small to hold basic result information',
458 'badconfig'
462 if ( $this->mParams['export'] ) {
463 $this->doExport( $pageSet, $result );
468 * This method is called by the generator base when generator in the smart-continue
469 * mode tries to set 'query-continue' value. ApiQuery stores those values separately
470 * until the post-processing when it is known if the generation should continue or repeat.
471 * @deprecated since 1.24
472 * @param ApiQueryGeneratorBase $module Generator module
473 * @param string $paramName
474 * @param mixed $paramValue
475 * @return bool True if processed, false if this is a legacy continue
477 public function setGeneratorContinue( $module, $paramName, $paramValue ) {
478 wfDeprecated( __METHOD__, '1.24' );
479 $this->getResult()->setGeneratorContinueParam( $module, $paramName, $paramValue );
480 return $this->getParameter( 'continue' ) !== null;
484 * @param ApiPageSet $pageSet Pages to be exported
485 * @param ApiResult $result Result to output to
487 private function doExport( $pageSet, $result ) {
488 $exportTitles = array();
489 $titles = $pageSet->getGoodTitles();
490 if ( count( $titles ) ) {
491 $user = $this->getUser();
492 /** @var $title Title */
493 foreach ( $titles as $title ) {
494 if ( $title->userCan( 'read', $user ) ) {
495 $exportTitles[] = $title;
500 $exporter = new WikiExporter( $this->getDB() );
501 // WikiExporter writes to stdout, so catch its
502 // output with an ob
503 ob_start();
504 $exporter->openStream();
505 foreach ( $exportTitles as $title ) {
506 $exporter->pageByTitle( $title );
508 $exporter->closeStream();
509 $exportxml = ob_get_contents();
510 ob_end_clean();
512 // Don't check the size of exported stuff
513 // It's not continuable, so it would cause more
514 // problems than it'd solve
515 if ( $this->mParams['exportnowrap'] ) {
516 $result->reset();
517 // Raw formatter will handle this
518 $result->addValue( null, 'text', $exportxml, ApiResult::NO_SIZE_CHECK );
519 $result->addValue( null, 'mime', 'text/xml', ApiResult::NO_SIZE_CHECK );
520 } else {
521 $r = array();
522 ApiResult::setContent( $r, $exportxml );
523 $result->addValue( 'query', 'export', $r, ApiResult::NO_SIZE_CHECK );
527 public function getAllowedParams( $flags = 0 ) {
528 $result = array(
529 'prop' => array(
530 ApiBase::PARAM_ISMULTI => true,
531 ApiBase::PARAM_TYPE => 'submodule',
533 'list' => array(
534 ApiBase::PARAM_ISMULTI => true,
535 ApiBase::PARAM_TYPE => 'submodule',
537 'meta' => array(
538 ApiBase::PARAM_ISMULTI => true,
539 ApiBase::PARAM_TYPE => 'submodule',
541 'indexpageids' => false,
542 'export' => false,
543 'exportnowrap' => false,
544 'iwurl' => false,
545 'continue' => null,
546 'rawcontinue' => false,
548 if ( $flags ) {
549 $result += $this->getPageSet()->getFinalParams( $flags );
552 return $result;
556 * Override the parent to generate help messages for all available query modules.
557 * @deprecated since 1.25
558 * @return string
560 public function makeHelpMsg() {
561 wfDeprecated( __METHOD__, '1.25' );
563 // Use parent to make default message for the query module
564 $msg = parent::makeHelpMsg();
566 $querySeparator = str_repeat( '--- ', 12 );
567 $moduleSeparator = str_repeat( '*** ', 14 );
568 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
569 $msg .= $this->makeHelpMsgHelper( 'prop' );
570 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
571 $msg .= $this->makeHelpMsgHelper( 'list' );
572 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
573 $msg .= $this->makeHelpMsgHelper( 'meta' );
574 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
576 return $msg;
580 * For all modules of a given group, generate help messages and join them together
581 * @deprecated since 1.25
582 * @param string $group Module group
583 * @return string
585 private function makeHelpMsgHelper( $group ) {
586 $moduleDescriptions = array();
588 $moduleNames = $this->mModuleMgr->getNames( $group );
589 sort( $moduleNames );
590 foreach ( $moduleNames as $name ) {
592 * @var $module ApiQueryBase
594 $module = $this->mModuleMgr->getModule( $name );
596 $msg = ApiMain::makeHelpMsgHeader( $module, $group );
597 $msg2 = $module->makeHelpMsg();
598 if ( $msg2 !== false ) {
599 $msg .= $msg2;
601 if ( $module instanceof ApiQueryGeneratorBase ) {
602 $msg .= "Generator:\n This module may be used as a generator\n";
604 $moduleDescriptions[] = $msg;
607 return implode( "\n", $moduleDescriptions );
610 public function shouldCheckMaxlag() {
611 return true;
614 protected function getExamplesMessages() {
615 return array(
616 'action=query&prop=revisions&meta=siteinfo&' .
617 'titles=Main%20Page&rvprop=user|comment&continue='
618 => 'apihelp-query-example-revisions',
619 'action=query&generator=allpages&gapprefix=API/&prop=revisions&continue='
620 => 'apihelp-query-example-allpages',
624 public function getHelpUrls() {
625 return array(
626 'https://www.mediawiki.org/wiki/API:Query',
627 'https://www.mediawiki.org/wiki/API:Meta',
628 'https://www.mediawiki.org/wiki/API:Properties',
629 'https://www.mediawiki.org/wiki/API:Lists',