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
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.
38 class ApiQuery
extends ApiBase
{
41 * List of Api Query prop modules
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',
68 * List of Api Query list modules
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 'allrevisions' => 'ApiQueryAllRevisions',
80 'alltransclusions' => 'ApiQueryAllLinks',
81 'allusers' => 'ApiQueryAllUsers',
82 'backlinks' => 'ApiQueryBacklinks',
83 'blocks' => 'ApiQueryBlocks',
84 'categorymembers' => 'ApiQueryCategoryMembers',
85 'deletedrevs' => 'ApiQueryDeletedrevs',
86 'embeddedin' => 'ApiQueryBacklinks',
87 'exturlusage' => 'ApiQueryExtLinksUsage',
88 'filearchive' => 'ApiQueryFilearchive',
89 'imageusage' => 'ApiQueryBacklinks',
90 'iwbacklinks' => 'ApiQueryIWBacklinks',
91 'langbacklinks' => 'ApiQueryLangBacklinks',
92 'logevents' => 'ApiQueryLogEvents',
93 'pageswithprop' => 'ApiQueryPagesWithProp',
94 'pagepropnames' => 'ApiQueryPagePropNames',
95 'prefixsearch' => 'ApiQueryPrefixSearch',
96 'protectedtitles' => 'ApiQueryProtectedTitles',
97 'querypage' => 'ApiQueryQueryPage',
98 'random' => 'ApiQueryRandom',
99 'recentchanges' => 'ApiQueryRecentChanges',
100 'search' => 'ApiQuerySearch',
101 'tags' => 'ApiQueryTags',
102 'usercontribs' => 'ApiQueryContributions',
103 'users' => 'ApiQueryUsers',
104 'watchlist' => 'ApiQueryWatchlist',
105 'watchlistraw' => 'ApiQueryWatchlistRaw',
109 * List of Api Query meta modules
112 private static $QueryMetaModules = array(
113 'allmessages' => 'ApiQueryAllMessages',
114 'siteinfo' => 'ApiQuerySiteinfo',
115 'userinfo' => 'ApiQueryUserInfo',
116 'filerepoinfo' => 'ApiQueryFileRepoInfo',
117 'tokens' => 'ApiQueryTokens',
126 private $mNamedDB = array();
130 * @param ApiMain $main
131 * @param string $action
133 public function __construct( ApiMain
$main, $action ) {
134 parent
::__construct( $main, $action );
136 $this->mModuleMgr
= new ApiModuleManager( $this );
138 // Allow custom modules to be added in LocalSettings.php
139 $config = $this->getConfig();
140 $this->mModuleMgr
->addModules( self
::$QueryPropModules, 'prop' );
141 $this->mModuleMgr
->addModules( $config->get( 'APIPropModules' ), 'prop' );
142 $this->mModuleMgr
->addModules( self
::$QueryListModules, 'list' );
143 $this->mModuleMgr
->addModules( $config->get( 'APIListModules' ), 'list' );
144 $this->mModuleMgr
->addModules( self
::$QueryMetaModules, 'meta' );
145 $this->mModuleMgr
->addModules( $config->get( 'APIMetaModules' ), 'meta' );
147 Hooks
::run( 'ApiQuery::moduleManager', array( $this->mModuleMgr
) );
149 // Create PageSet that will process titles/pageids/revids/generator
150 $this->mPageSet
= new ApiPageSet( $this );
154 * Overrides to return this instance's module manager.
155 * @return ApiModuleManager
157 public function getModuleManager() {
158 return $this->mModuleMgr
;
162 * Get the query database connection with the given name.
163 * If no such connection has been requested before, it will be created.
164 * Subsequent calls with the same $name will return the same connection
165 * as the first, regardless of the values of $db and $groups
166 * @param string $name Name to assign to the database connection
167 * @param int $db One of the DB_* constants
168 * @param array $groups Query groups
169 * @return DatabaseBase
171 public function getNamedDB( $name, $db, $groups ) {
172 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
173 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
176 return $this->mNamedDB
[$name];
180 * Gets the set of pages the user has requested (or generated)
183 public function getPageSet() {
184 return $this->mPageSet
;
188 * Get the generators array mapping module names to class names
189 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
190 * @return array Array(modulename => classname)
192 public function getGenerators() {
193 wfDeprecated( __METHOD__
, '1.21' );
195 foreach ( $this->mModuleMgr
->getNamesWithClasses() as $name => $class ) {
196 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
197 $gens[$name] = $class;
205 * Get whether the specified module is a prop, list or a meta query module
206 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
207 * @param string $moduleName Name of the module to find type for
208 * @return string|null
210 function getModuleType( $moduleName ) {
211 return $this->getModuleManager()->getModuleGroup( $moduleName );
215 * @return ApiFormatRaw|null
217 public function getCustomPrinter() {
218 // If &exportnowrap is set, use the raw formatter
219 if ( $this->getParameter( 'export' ) &&
220 $this->getParameter( 'exportnowrap' )
222 return new ApiFormatRaw( $this->getMain(),
223 $this->getMain()->createPrinterByName( 'xml' ) );
230 * Query execution happens in the following steps:
231 * #1 Create a PageSet object with any pages requested by the user
232 * #2 If using a generator, execute it to get a new ApiPageSet object
233 * #3 Instantiate all requested modules.
234 * This way the PageSet object will know what shared data is required,
235 * and minimize DB calls.
236 * #4 Output all normalization and redirect resolution information
237 * #5 Execute all requested modules
239 public function execute() {
240 $this->mParams
= $this->extractRequestParams();
242 // Instantiate requested modules
243 $allModules = array();
244 $this->instantiateModules( $allModules, 'prop' );
245 $propModules = array_keys( $allModules );
246 $this->instantiateModules( $allModules, 'list' );
247 $this->instantiateModules( $allModules, 'meta' );
249 // Filter modules based on continue parameter
250 $continuationManager = new ApiContinuationManager( $this, $allModules, $propModules );
251 $this->setContinuationManager( $continuationManager );
252 $modules = $continuationManager->getRunModules();
254 if ( !$continuationManager->isGeneratorDone() ) {
255 // Query modules may optimize data requests through the $this->getPageSet()
256 // object by adding extra fields from the page table.
257 foreach ( $modules as $module ) {
258 $module->requestExtraData( $this->mPageSet
);
260 // Populate page/revision information
261 $this->mPageSet
->execute();
262 // Record page information (title, namespace, if exists, etc)
263 $this->outputGeneralPageInfo();
265 $this->mPageSet
->executeDryRun();
268 $cacheMode = $this->mPageSet
->getCacheMode();
270 // Execute all unfinished modules
271 /** @var $module ApiQueryBase */
272 foreach ( $modules as $module ) {
273 $params = $module->extractRequestParams();
274 $cacheMode = $this->mergeCacheMode(
275 $cacheMode, $module->getCacheMode( $params ) );
277 Hooks
::run( 'APIQueryAfterExecute', array( &$module ) );
280 // Set the cache mode
281 $this->getMain()->setCacheMode( $cacheMode );
283 // Write the continuation data into the result
284 $this->setContinuationManager( null );
285 if ( $this->mParams
['rawcontinue'] ) {
286 $data = $continuationManager->getRawContinuation();
288 $this->getResult()->addValue( null, 'query-continue', $data,
289 ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
292 $continuationManager->setContinuationIntoResult( $this->getResult() );
297 * Update a cache mode string, applying the cache mode of a new module to it.
298 * The cache mode may increase in the level of privacy, but public modules
299 * added to private data do not decrease the level of privacy.
301 * @param string $cacheMode
302 * @param string $modCacheMode
305 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
306 if ( $modCacheMode === 'anon-public-user-private' ) {
307 if ( $cacheMode !== 'private' ) {
308 $cacheMode = 'anon-public-user-private';
310 } elseif ( $modCacheMode === 'public' ) {
311 // do nothing, if it's public already it will stay public
313 $cacheMode = 'private';
320 * Create instances of all modules requested by the client
321 * @param array $modules To append instantiated modules to
322 * @param string $param Parameter name to read modules from
324 private function instantiateModules( &$modules, $param ) {
325 $wasPosted = $this->getRequest()->wasPosted();
326 if ( isset( $this->mParams
[$param] ) ) {
327 foreach ( $this->mParams
[$param] as $moduleName ) {
328 $instance = $this->mModuleMgr
->getModule( $moduleName, $param );
329 if ( $instance === null ) {
330 ApiBase
::dieDebug( __METHOD__
, 'Error instantiating module' );
332 if ( !$wasPosted && $instance->mustBePosted() ) {
333 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $moduleName ) );
335 // Ignore duplicates. TODO 2.0: die()?
336 if ( !array_key_exists( $moduleName, $modules ) ) {
337 $modules[$moduleName] = $instance;
344 * Appends an element for each page in the current pageSet with the
345 * most general information (id, title), plus any title normalizations
346 * and missing or invalid title/pageids/revids.
348 private function outputGeneralPageInfo() {
349 $pageSet = $this->getPageSet();
350 $result = $this->getResult();
352 // We can't really handle max-result-size failure here, but we need to
353 // check anyway in case someone set the limit stupidly low.
356 $values = $pageSet->getNormalizedTitlesAsResult( $result );
358 $fit = $fit && $result->addValue( 'query', 'normalized', $values );
360 $values = $pageSet->getConvertedTitlesAsResult( $result );
362 $fit = $fit && $result->addValue( 'query', 'converted', $values );
364 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->mParams
['iwurl'] );
366 $fit = $fit && $result->addValue( 'query', 'interwiki', $values );
368 $values = $pageSet->getRedirectTitlesAsResult( $result );
370 $fit = $fit && $result->addValue( 'query', 'redirects', $values );
372 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
374 $fit = $fit && $result->addValue( 'query', 'badrevids', $values );
380 // Report any missing titles
381 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
383 ApiQueryBase
::addTitleInfo( $vals, $title );
384 $vals['missing'] = true;
385 $pages[$fakeId] = $vals;
387 // Report any invalid titles
388 foreach ( $pageSet->getInvalidTitlesAndReasons() as $fakeId => $data ) {
389 $pages[$fakeId] = $data +
array( 'invalid' => true );
391 // Report any missing page ids
392 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
393 $pages[$pageid] = array(
398 // Report special pages
399 /** @var $title Title */
400 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
402 ApiQueryBase
::addTitleInfo( $vals, $title );
403 $vals['special'] = true;
404 if ( $title->isSpecialPage() &&
405 !SpecialPageFactory
::exists( $title->getDBkey() )
407 $vals['missing'] = true;
408 } elseif ( $title->getNamespace() == NS_MEDIA
&&
409 !wfFindFile( $title )
411 $vals['missing'] = true;
413 $pages[$fakeId] = $vals;
416 // Output general page information for found titles
417 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
419 $vals['pageid'] = $pageid;
420 ApiQueryBase
::addTitleInfo( $vals, $title );
421 $pages[$pageid] = $vals;
424 if ( count( $pages ) ) {
425 $pageSet->populateGeneratorData( $pages );
426 ApiResult
::setArrayType( $pages, 'BCarray' );
428 if ( $this->mParams
['indexpageids'] ) {
429 $pageIDs = array_keys( ApiResult
::stripMetadataNonRecursive( $pages ) );
430 // json treats all map keys as strings - converting to match
431 $pageIDs = array_map( 'strval', $pageIDs );
432 ApiResult
::setIndexedTagName( $pageIDs, 'id' );
433 $fit = $fit && $result->addValue( 'query', 'pageids', $pageIDs );
436 ApiResult
::setIndexedTagName( $pages, 'page' );
437 $fit = $fit && $result->addValue( 'query', 'pages', $pages );
442 'The value of $wgAPIMaxResultSize on this wiki is ' .
443 'too small to hold basic result information',
448 if ( $this->mParams
['export'] ) {
449 $this->doExport( $pageSet, $result );
454 * This method is called by the generator base when generator in the smart-continue
455 * mode tries to set 'query-continue' value. ApiQuery stores those values separately
456 * until the post-processing when it is known if the generation should continue or repeat.
457 * @deprecated since 1.24
458 * @param ApiQueryGeneratorBase $module Generator module
459 * @param string $paramName
460 * @param mixed $paramValue
461 * @return bool True if processed, false if this is a legacy continue
463 public function setGeneratorContinue( $module, $paramName, $paramValue ) {
464 wfDeprecated( __METHOD__
, '1.24' );
465 $this->getContinuationManager()->addGeneratorContinueParam( $module, $paramName, $paramValue );
466 return !$this->getParameter( 'rawcontinue' );
470 * @param ApiPageSet $pageSet Pages to be exported
471 * @param ApiResult $result Result to output to
473 private function doExport( $pageSet, $result ) {
474 $exportTitles = array();
475 $titles = $pageSet->getGoodTitles();
476 if ( count( $titles ) ) {
477 $user = $this->getUser();
478 /** @var $title Title */
479 foreach ( $titles as $title ) {
480 if ( $title->userCan( 'read', $user ) ) {
481 $exportTitles[] = $title;
486 $exporter = new WikiExporter( $this->getDB() );
487 // WikiExporter writes to stdout, so catch its
490 $exporter->openStream();
491 foreach ( $exportTitles as $title ) {
492 $exporter->pageByTitle( $title );
494 $exporter->closeStream();
495 $exportxml = ob_get_contents();
498 // Don't check the size of exported stuff
499 // It's not continuable, so it would cause more
500 // problems than it'd solve
501 if ( $this->mParams
['exportnowrap'] ) {
503 // Raw formatter will handle this
504 $result->addValue( null, 'text', $exportxml, ApiResult
::NO_SIZE_CHECK
);
505 $result->addValue( null, 'mime', 'text/xml', ApiResult
::NO_SIZE_CHECK
);
507 $result->addValue( 'query', 'export', $exportxml, ApiResult
::NO_SIZE_CHECK
);
508 $result->addValue( 'query', ApiResult
::META_BC_SUBELEMENTS
, array( 'export' ) );
512 public function getAllowedParams( $flags = 0 ) {
515 ApiBase
::PARAM_ISMULTI
=> true,
516 ApiBase
::PARAM_TYPE
=> 'submodule',
519 ApiBase
::PARAM_ISMULTI
=> true,
520 ApiBase
::PARAM_TYPE
=> 'submodule',
523 ApiBase
::PARAM_ISMULTI
=> true,
524 ApiBase
::PARAM_TYPE
=> 'submodule',
526 'indexpageids' => false,
528 'exportnowrap' => false,
531 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
533 'rawcontinue' => false,
536 $result +
= $this->getPageSet()->getFinalParams( $flags );
543 * Override the parent to generate help messages for all available query modules.
544 * @deprecated since 1.25
547 public function makeHelpMsg() {
548 wfDeprecated( __METHOD__
, '1.25' );
550 // Use parent to make default message for the query module
551 $msg = parent
::makeHelpMsg();
553 $querySeparator = str_repeat( '--- ', 12 );
554 $moduleSeparator = str_repeat( '*** ', 14 );
555 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
556 $msg .= $this->makeHelpMsgHelper( 'prop' );
557 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
558 $msg .= $this->makeHelpMsgHelper( 'list' );
559 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
560 $msg .= $this->makeHelpMsgHelper( 'meta' );
561 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
567 * For all modules of a given group, generate help messages and join them together
568 * @deprecated since 1.25
569 * @param string $group Module group
572 private function makeHelpMsgHelper( $group ) {
573 $moduleDescriptions = array();
575 $moduleNames = $this->mModuleMgr
->getNames( $group );
576 sort( $moduleNames );
577 foreach ( $moduleNames as $name ) {
579 * @var $module ApiQueryBase
581 $module = $this->mModuleMgr
->getModule( $name );
583 $msg = ApiMain
::makeHelpMsgHeader( $module, $group );
584 $msg2 = $module->makeHelpMsg();
585 if ( $msg2 !== false ) {
588 if ( $module instanceof ApiQueryGeneratorBase
) {
589 $msg .= "Generator:\n This module may be used as a generator\n";
591 $moduleDescriptions[] = $msg;
594 return implode( "\n", $moduleDescriptions );
597 protected function getExamplesMessages() {
599 'action=query&prop=revisions&meta=siteinfo&' .
600 'titles=Main%20Page&rvprop=user|comment&continue='
601 => 'apihelp-query-example-revisions',
602 'action=query&generator=allpages&gapprefix=API/&prop=revisions&continue='
603 => 'apihelp-query-example-allpages',
607 public function getHelpUrls() {
609 'https://www.mediawiki.org/wiki/API:Query',
610 'https://www.mediawiki.org/wiki/API:Meta',
611 'https://www.mediawiki.org/wiki/API:Properties',
612 'https://www.mediawiki.org/wiki/API:Lists',