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 'duplicatefiles' => 'ApiQueryDuplicateFiles',
49 'extlinks' => 'ApiQueryExternalLinks',
50 'fileusage' => 'ApiQueryBacklinksprop',
51 'images' => 'ApiQueryImages',
52 'imageinfo' => 'ApiQueryImageInfo',
53 'info' => 'ApiQueryInfo',
54 'links' => 'ApiQueryLinks',
55 'linkshere' => 'ApiQueryBacklinksprop',
56 'iwlinks' => 'ApiQueryIWLinks',
57 'langlinks' => 'ApiQueryLangLinks',
58 'pageprops' => 'ApiQueryPageProps',
59 'redirects' => 'ApiQueryBacklinksprop',
60 'revisions' => 'ApiQueryRevisions',
61 'stashimageinfo' => 'ApiQueryStashImageInfo',
62 'templates' => 'ApiQueryLinks',
63 'transcludedin' => 'ApiQueryBacklinksprop',
67 * List of Api Query list modules
70 private static $QueryListModules = array(
71 'allcategories' => 'ApiQueryAllCategories',
72 'allfileusages' => 'ApiQueryAllLinks',
73 'allimages' => 'ApiQueryAllImages',
74 'alllinks' => 'ApiQueryAllLinks',
75 'allpages' => 'ApiQueryAllPages',
76 'allredirects' => 'ApiQueryAllLinks',
77 'alltransclusions' => 'ApiQueryAllLinks',
78 'allusers' => 'ApiQueryAllUsers',
79 'backlinks' => 'ApiQueryBacklinks',
80 'blocks' => 'ApiQueryBlocks',
81 'categorymembers' => 'ApiQueryCategoryMembers',
82 'deletedrevs' => 'ApiQueryDeletedrevs',
83 'embeddedin' => 'ApiQueryBacklinks',
84 'exturlusage' => 'ApiQueryExtLinksUsage',
85 'filearchive' => 'ApiQueryFilearchive',
86 'imageusage' => 'ApiQueryBacklinks',
87 'iwbacklinks' => 'ApiQueryIWBacklinks',
88 'langbacklinks' => 'ApiQueryLangBacklinks',
89 'logevents' => 'ApiQueryLogEvents',
90 'pageswithprop' => 'ApiQueryPagesWithProp',
91 'pagepropnames' => 'ApiQueryPagePropNames',
92 'prefixsearch' => 'ApiQueryPrefixSearch',
93 'protectedtitles' => 'ApiQueryProtectedTitles',
94 'querypage' => 'ApiQueryQueryPage',
95 'random' => 'ApiQueryRandom',
96 'recentchanges' => 'ApiQueryRecentChanges',
97 'search' => 'ApiQuerySearch',
98 'tags' => 'ApiQueryTags',
99 'usercontribs' => 'ApiQueryContributions',
100 'users' => 'ApiQueryUsers',
101 'watchlist' => 'ApiQueryWatchlist',
102 'watchlistraw' => 'ApiQueryWatchlistRaw',
106 * List of Api Query meta modules
109 private static $QueryMetaModules = array(
110 'allmessages' => 'ApiQueryAllMessages',
111 'siteinfo' => 'ApiQuerySiteinfo',
112 'userinfo' => 'ApiQueryUserInfo',
113 'filerepoinfo' => 'ApiQueryFileRepoInfo',
114 'tokens' => 'ApiQueryTokens',
123 private $mNamedDB = array();
127 * @param ApiMain $main
128 * @param string $action
130 public function __construct( ApiMain
$main, $action ) {
131 parent
::__construct( $main, $action );
133 $this->mModuleMgr
= new ApiModuleManager( $this );
135 // Allow custom modules to be added in LocalSettings.php
136 $config = $this->getConfig();
137 $this->mModuleMgr
->addModules( self
::$QueryPropModules, 'prop' );
138 $this->mModuleMgr
->addModules( $config->get( 'APIPropModules' ), 'prop' );
139 $this->mModuleMgr
->addModules( self
::$QueryListModules, 'list' );
140 $this->mModuleMgr
->addModules( $config->get( 'APIListModules' ), 'list' );
141 $this->mModuleMgr
->addModules( self
::$QueryMetaModules, 'meta' );
142 $this->mModuleMgr
->addModules( $config->get( 'APIMetaModules' ), 'meta' );
144 // Create PageSet that will process titles/pageids/revids/generator
145 $this->mPageSet
= new ApiPageSet( $this );
149 * Overrides to return this instance's module manager.
150 * @return ApiModuleManager
152 public function getModuleManager() {
153 return $this->mModuleMgr
;
157 * Get the query database connection with the given name.
158 * If no such connection has been requested before, it will be created.
159 * Subsequent calls with the same $name will return the same connection
160 * as the first, regardless of the values of $db and $groups
161 * @param string $name Name to assign to the database connection
162 * @param int $db One of the DB_* constants
163 * @param array $groups Query groups
164 * @return DatabaseBase
166 public function getNamedDB( $name, $db, $groups ) {
167 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
168 $this->profileDBIn();
169 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
170 $this->profileDBOut();
173 return $this->mNamedDB
[$name];
177 * Gets the set of pages the user has requested (or generated)
180 public function getPageSet() {
181 return $this->mPageSet
;
185 * Get the array mapping module names to class names
186 * @deprecated since 1.21, use getModuleManager()'s methods instead
187 * @return array Array(modulename => classname)
189 public function getModules() {
190 wfDeprecated( __METHOD__
, '1.21' );
192 return $this->getModuleManager()->getNamesWithClasses();
196 * Get the generators array mapping module names to class names
197 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
198 * @return array Array(modulename => classname)
200 public function getGenerators() {
201 wfDeprecated( __METHOD__
, '1.21' );
203 foreach ( $this->mModuleMgr
->getNamesWithClasses() as $name => $class ) {
204 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
205 $gens[$name] = $class;
213 * Get whether the specified module is a prop, list or a meta query module
214 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
215 * @param string $moduleName Name of the module to find type for
216 * @return string|null
218 function getModuleType( $moduleName ) {
219 return $this->getModuleManager()->getModuleGroup( $moduleName );
223 * @return ApiFormatRaw|null
225 public function getCustomPrinter() {
226 // If &exportnowrap is set, use the raw formatter
227 if ( $this->getParameter( 'export' ) &&
228 $this->getParameter( 'exportnowrap' )
230 return new ApiFormatRaw( $this->getMain(),
231 $this->getMain()->createPrinterByName( 'xml' ) );
238 * Query execution happens in the following steps:
239 * #1 Create a PageSet object with any pages requested by the user
240 * #2 If using a generator, execute it to get a new ApiPageSet object
241 * #3 Instantiate all requested modules.
242 * This way the PageSet object will know what shared data is required,
243 * and minimize DB calls.
244 * #4 Output all normalization and redirect resolution information
245 * #5 Execute all requested modules
247 public function execute() {
248 $this->mParams
= $this->extractRequestParams();
250 if ( $this->mParams
['continue'] === null && !$this->mParams
['rawcontinue'] ) {
251 $this->logFeatureUsage( 'action=query&!rawcontinue&!continue' );
253 'Formatting of continuation data will be changing soon. ' .
254 'To continue using the current formatting, use the \'rawcontinue\' parameter. ' .
255 'To begin using the new format, pass an empty string for \'continue\' ' .
256 'in the initial query.'
260 // Instantiate requested modules
261 $allModules = array();
262 $this->instantiateModules( $allModules, 'prop' );
263 $propModules = array_keys( $allModules );
264 $this->instantiateModules( $allModules, 'list' );
265 $this->instantiateModules( $allModules, 'meta' );
267 // Filter modules based on continue parameter
268 list( $generatorDone, $modules ) = $this->getResult()->beginContinuation(
269 $this->mParams
['continue'], $allModules, $propModules
272 if ( !$generatorDone ) {
273 // Query modules may optimize data requests through the $this->getPageSet()
274 // object by adding extra fields from the page table.
275 foreach ( $modules as $module ) {
276 $module->requestExtraData( $this->mPageSet
);
278 // Populate page/revision information
279 $this->mPageSet
->execute();
280 // Record page information (title, namespace, if exists, etc)
281 $this->outputGeneralPageInfo();
283 $this->mPageSet
->executeDryRun();
286 $cacheMode = $this->mPageSet
->getCacheMode();
288 // Execute all unfinished modules
289 /** @var $module ApiQueryBase */
290 foreach ( $modules as $module ) {
291 $params = $module->extractRequestParams();
292 $cacheMode = $this->mergeCacheMode(
293 $cacheMode, $module->getCacheMode( $params ) );
294 $module->profileIn();
296 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
297 $module->profileOut();
300 // Set the cache mode
301 $this->getMain()->setCacheMode( $cacheMode );
303 // Write the continuation data into the result
304 $this->getResult()->endContinuation(
305 $this->mParams
['continue'] === null ?
'raw' : 'standard'
310 * Update a cache mode string, applying the cache mode of a new module to it.
311 * The cache mode may increase in the level of privacy, but public modules
312 * added to private data do not decrease the level of privacy.
314 * @param string $cacheMode
315 * @param string $modCacheMode
318 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
319 if ( $modCacheMode === 'anon-public-user-private' ) {
320 if ( $cacheMode !== 'private' ) {
321 $cacheMode = 'anon-public-user-private';
323 } elseif ( $modCacheMode === 'public' ) {
324 // do nothing, if it's public already it will stay public
326 $cacheMode = 'private';
333 * Create instances of all modules requested by the client
334 * @param array $modules To append instantiated modules to
335 * @param string $param Parameter name to read modules from
337 private function instantiateModules( &$modules, $param ) {
338 $wasPosted = $this->getRequest()->wasPosted();
339 if ( isset( $this->mParams
[$param] ) ) {
340 foreach ( $this->mParams
[$param] as $moduleName ) {
341 $instance = $this->mModuleMgr
->getModule( $moduleName, $param );
342 if ( $instance === null ) {
343 ApiBase
::dieDebug( __METHOD__
, 'Error instantiating module' );
345 if ( !$wasPosted && $instance->mustBePosted() ) {
346 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $moduleName ) );
348 // Ignore duplicates. TODO 2.0: die()?
349 if ( !array_key_exists( $moduleName, $modules ) ) {
350 $modules[$moduleName] = $instance;
357 * Appends an element for each page in the current pageSet with the
358 * most general information (id, title), plus any title normalizations
359 * and missing or invalid title/pageids/revids.
361 private function outputGeneralPageInfo() {
362 $pageSet = $this->getPageSet();
363 $result = $this->getResult();
365 // We can't really handle max-result-size failure here, but we need to
366 // check anyway in case someone set the limit stupidly low.
369 $values = $pageSet->getNormalizedTitlesAsResult( $result );
371 $fit = $fit && $result->addValue( 'query', 'normalized', $values );
373 $values = $pageSet->getConvertedTitlesAsResult( $result );
375 $fit = $fit && $result->addValue( 'query', 'converted', $values );
377 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->mParams
['iwurl'] );
379 $fit = $fit && $result->addValue( 'query', 'interwiki', $values );
381 $values = $pageSet->getRedirectTitlesAsResult( $result );
383 $fit = $fit && $result->addValue( 'query', 'redirects', $values );
385 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
387 $fit = $fit && $result->addValue( 'query', 'badrevids', $values );
393 // Report any missing titles
394 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
396 ApiQueryBase
::addTitleInfo( $vals, $title );
397 $vals['missing'] = '';
398 $pages[$fakeId] = $vals;
400 // Report any invalid titles
401 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
402 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
404 // Report any missing page ids
405 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
406 $pages[$pageid] = array(
411 // Report special pages
412 /** @var $title Title */
413 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
415 ApiQueryBase
::addTitleInfo( $vals, $title );
416 $vals['special'] = '';
417 if ( $title->isSpecialPage() &&
418 !SpecialPageFactory
::exists( $title->getDBkey() )
420 $vals['missing'] = '';
421 } elseif ( $title->getNamespace() == NS_MEDIA
&&
422 !wfFindFile( $title )
424 $vals['missing'] = '';
426 $pages[$fakeId] = $vals;
429 // Output general page information for found titles
430 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
432 $vals['pageid'] = $pageid;
433 ApiQueryBase
::addTitleInfo( $vals, $title );
434 $pages[$pageid] = $vals;
437 if ( count( $pages ) ) {
438 if ( $this->mParams
['indexpageids'] ) {
439 $pageIDs = array_keys( $pages );
440 // json treats all map keys as strings - converting to match
441 $pageIDs = array_map( 'strval', $pageIDs );
442 $result->setIndexedTagName( $pageIDs, 'id' );
443 $fit = $fit && $result->addValue( 'query', 'pageids', $pageIDs );
446 $result->setIndexedTagName( $pages, 'page' );
447 $fit = $fit && $result->addValue( 'query', 'pages', $pages );
452 'The value of $wgAPIMaxResultSize on this wiki is ' .
453 'too small to hold basic result information',
458 if ( $this->mParams
['export'] ) {
459 $this->doExport( $pageSet, $result );
464 * This method is called by the generator base when generator in the smart-continue
465 * mode tries to set 'query-continue' value. ApiQuery stores those values separately
466 * until the post-processing when it is known if the generation should continue or repeat.
467 * @deprecated since 1.24
468 * @param ApiQueryGeneratorBase $module Generator module
469 * @param string $paramName
470 * @param mixed $paramValue
471 * @return bool True if processed, false if this is a legacy continue
473 public function setGeneratorContinue( $module, $paramName, $paramValue ) {
474 wfDeprecated( __METHOD__
, '1.24' );
475 $this->getResult()->setGeneratorContinueParam( $module, $paramName, $paramValue );
476 return $this->getParameter( 'continue' ) !== null;
480 * @param ApiPageSet $pageSet Pages to be exported
481 * @param ApiResult $result Result to output to
483 private function doExport( $pageSet, $result ) {
484 $exportTitles = array();
485 $titles = $pageSet->getGoodTitles();
486 if ( count( $titles ) ) {
487 $user = $this->getUser();
488 /** @var $title Title */
489 foreach ( $titles as $title ) {
490 if ( $title->userCan( 'read', $user ) ) {
491 $exportTitles[] = $title;
496 $exporter = new WikiExporter( $this->getDB() );
497 // WikiExporter writes to stdout, so catch its
500 $exporter->openStream();
501 foreach ( $exportTitles as $title ) {
502 $exporter->pageByTitle( $title );
504 $exporter->closeStream();
505 $exportxml = ob_get_contents();
508 // Don't check the size of exported stuff
509 // It's not continuable, so it would cause more
510 // problems than it'd solve
511 if ( $this->mParams
['exportnowrap'] ) {
513 // Raw formatter will handle this
514 $result->addValue( null, 'text', $exportxml, ApiResult
::NO_SIZE_CHECK
);
515 $result->addValue( null, 'mime', 'text/xml', ApiResult
::NO_SIZE_CHECK
);
518 ApiResult
::setContent( $r, $exportxml );
519 $result->addValue( 'query', 'export', $r, ApiResult
::NO_SIZE_CHECK
);
523 public function getAllowedParams( $flags = 0 ) {
526 ApiBase
::PARAM_ISMULTI
=> true,
527 ApiBase
::PARAM_TYPE
=> 'submodule',
530 ApiBase
::PARAM_ISMULTI
=> true,
531 ApiBase
::PARAM_TYPE
=> 'submodule',
534 ApiBase
::PARAM_ISMULTI
=> true,
535 ApiBase
::PARAM_TYPE
=> 'submodule',
537 'indexpageids' => false,
539 'exportnowrap' => false,
542 'rawcontinue' => false,
545 $result +
= $this->getPageSet()->getFinalParams( $flags );
552 * Override the parent to generate help messages for all available query modules.
553 * @deprecated since 1.25
556 public function makeHelpMsg() {
557 wfDeprecated( __METHOD__
, '1.25' );
559 // Use parent to make default message for the query module
560 $msg = parent
::makeHelpMsg();
562 $querySeparator = str_repeat( '--- ', 12 );
563 $moduleSeparator = str_repeat( '*** ', 14 );
564 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
565 $msg .= $this->makeHelpMsgHelper( 'prop' );
566 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
567 $msg .= $this->makeHelpMsgHelper( 'list' );
568 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
569 $msg .= $this->makeHelpMsgHelper( 'meta' );
570 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
576 * For all modules of a given group, generate help messages and join them together
577 * @deprecated since 1.25
578 * @param string $group Module group
581 private function makeHelpMsgHelper( $group ) {
582 $moduleDescriptions = array();
584 $moduleNames = $this->mModuleMgr
->getNames( $group );
585 sort( $moduleNames );
586 foreach ( $moduleNames as $name ) {
588 * @var $module ApiQueryBase
590 $module = $this->mModuleMgr
->getModule( $name );
592 $msg = ApiMain
::makeHelpMsgHeader( $module, $group );
593 $msg2 = $module->makeHelpMsg();
594 if ( $msg2 !== false ) {
597 if ( $module instanceof ApiQueryGeneratorBase
) {
598 $msg .= "Generator:\n This module may be used as a generator\n";
600 $moduleDescriptions[] = $msg;
603 return implode( "\n", $moduleDescriptions );
606 public function shouldCheckMaxlag() {
610 protected function getExamplesMessages() {
612 'action=query&prop=revisions&meta=siteinfo&' .
613 'titles=Main%20Page&rvprop=user|comment&continue='
614 => 'apihelp-query-example-revisions',
615 'action=query&generator=allpages&gapprefix=API/&prop=revisions&continue='
616 => 'apihelp-query-example-allpages',
620 public function getHelpUrls() {
622 'https://www.mediawiki.org/wiki/API:Query',
623 'https://www.mediawiki.org/wiki/API:Meta',
624 'https://www.mediawiki.org/wiki/API:Properties',
625 'https://www.mediawiki.org/wiki/API:Lists',