Merge "SpecialChangeEmail: Remove cancel button"
[mediawiki.git] / includes / api / ApiQuery.php
blob8407fad7943fac882f618da3994daf29fe2c4ea1
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 'duplicatefiles' => 'ApiQueryDuplicateFiles',
49 'extlinks' => 'ApiQueryExternalLinks',
50 'images' => 'ApiQueryImages',
51 'imageinfo' => 'ApiQueryImageInfo',
52 'info' => 'ApiQueryInfo',
53 'links' => 'ApiQueryLinks',
54 'iwlinks' => 'ApiQueryIWLinks',
55 'langlinks' => 'ApiQueryLangLinks',
56 'pageprops' => 'ApiQueryPageProps',
57 'redirects' => 'ApiQueryRedirects',
58 'revisions' => 'ApiQueryRevisions',
59 'stashimageinfo' => 'ApiQueryStashImageInfo',
60 'templates' => 'ApiQueryLinks',
63 /**
64 * List of Api Query list modules
65 * @var array
67 private static $QueryListModules = array(
68 'allcategories' => 'ApiQueryAllCategories',
69 'allfileusages' => 'ApiQueryAllLinks',
70 'allimages' => 'ApiQueryAllImages',
71 'alllinks' => 'ApiQueryAllLinks',
72 'allpages' => 'ApiQueryAllPages',
73 'allredirects' => 'ApiQueryAllLinks',
74 'alltransclusions' => 'ApiQueryAllLinks',
75 'allusers' => 'ApiQueryAllUsers',
76 'backlinks' => 'ApiQueryBacklinks',
77 'blocks' => 'ApiQueryBlocks',
78 'categorymembers' => 'ApiQueryCategoryMembers',
79 'deletedrevs' => 'ApiQueryDeletedrevs',
80 'embeddedin' => 'ApiQueryBacklinks',
81 'exturlusage' => 'ApiQueryExtLinksUsage',
82 'filearchive' => 'ApiQueryFilearchive',
83 'imageusage' => 'ApiQueryBacklinks',
84 'iwbacklinks' => 'ApiQueryIWBacklinks',
85 'langbacklinks' => 'ApiQueryLangBacklinks',
86 'logevents' => 'ApiQueryLogEvents',
87 'pageswithprop' => 'ApiQueryPagesWithProp',
88 'pagepropnames' => 'ApiQueryPagePropNames',
89 'prefixsearch' => 'ApiQueryPrefixSearch',
90 'protectedtitles' => 'ApiQueryProtectedTitles',
91 'querypage' => 'ApiQueryQueryPage',
92 'random' => 'ApiQueryRandom',
93 'recentchanges' => 'ApiQueryRecentChanges',
94 'search' => 'ApiQuerySearch',
95 'tags' => 'ApiQueryTags',
96 'usercontribs' => 'ApiQueryContributions',
97 'users' => 'ApiQueryUsers',
98 'watchlist' => 'ApiQueryWatchlist',
99 'watchlistraw' => 'ApiQueryWatchlistRaw',
103 * List of Api Query meta modules
104 * @var array
106 private static $QueryMetaModules = array(
107 'allmessages' => 'ApiQueryAllMessages',
108 'siteinfo' => 'ApiQuerySiteinfo',
109 'userinfo' => 'ApiQueryUserInfo',
110 'filerepoinfo' => 'ApiQueryFileRepoInfo',
111 'tokens' => 'ApiQueryTokens',
115 * @var ApiPageSet
117 private $mPageSet;
119 private $mParams;
120 private $mNamedDB = array();
121 private $mModuleMgr;
124 * @param ApiMain $main
125 * @param string $action
127 public function __construct( ApiMain $main, $action ) {
128 parent::__construct( $main, $action );
130 $this->mModuleMgr = new ApiModuleManager( $this );
132 // Allow custom modules to be added in LocalSettings.php
133 $config = $this->getConfig();
134 $this->mModuleMgr->addModules( self::$QueryPropModules, 'prop' );
135 $this->mModuleMgr->addModules( $config->get( 'APIPropModules' ), 'prop' );
136 $this->mModuleMgr->addModules( self::$QueryListModules, 'list' );
137 $this->mModuleMgr->addModules( $config->get( 'APIListModules' ), 'list' );
138 $this->mModuleMgr->addModules( self::$QueryMetaModules, 'meta' );
139 $this->mModuleMgr->addModules( $config->get( 'APIMetaModules' ), 'meta' );
141 // Create PageSet that will process titles/pageids/revids/generator
142 $this->mPageSet = new ApiPageSet( $this );
146 * Overrides to return this instance's module manager.
147 * @return ApiModuleManager
149 public function getModuleManager() {
150 return $this->mModuleMgr;
154 * Get the query database connection with the given name.
155 * If no such connection has been requested before, it will be created.
156 * Subsequent calls with the same $name will return the same connection
157 * as the first, regardless of the values of $db and $groups
158 * @param string $name Name to assign to the database connection
159 * @param int $db One of the DB_* constants
160 * @param array $groups Query groups
161 * @return DatabaseBase
163 public function getNamedDB( $name, $db, $groups ) {
164 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
165 $this->profileDBIn();
166 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
167 $this->profileDBOut();
170 return $this->mNamedDB[$name];
174 * Gets the set of pages the user has requested (or generated)
175 * @return ApiPageSet
177 public function getPageSet() {
178 return $this->mPageSet;
182 * Get the array mapping module names to class names
183 * @deprecated since 1.21, use getModuleManager()'s methods instead
184 * @return array Array(modulename => classname)
186 public function getModules() {
187 wfDeprecated( __METHOD__, '1.21' );
189 return $this->getModuleManager()->getNamesWithClasses();
193 * Get the generators array mapping module names to class names
194 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
195 * @return array Array(modulename => classname)
197 public function getGenerators() {
198 wfDeprecated( __METHOD__, '1.21' );
199 $gens = array();
200 foreach ( $this->mModuleMgr->getNamesWithClasses() as $name => $class ) {
201 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
202 $gens[$name] = $class;
206 return $gens;
210 * Get whether the specified module is a prop, list or a meta query module
211 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
212 * @param string $moduleName Name of the module to find type for
213 * @return string|null
215 function getModuleType( $moduleName ) {
216 return $this->getModuleManager()->getModuleGroup( $moduleName );
220 * @return ApiFormatRaw|null
222 public function getCustomPrinter() {
223 // If &exportnowrap is set, use the raw formatter
224 if ( $this->getParameter( 'export' ) &&
225 $this->getParameter( 'exportnowrap' )
227 return new ApiFormatRaw( $this->getMain(),
228 $this->getMain()->createPrinterByName( 'xml' ) );
229 } else {
230 return null;
235 * Query execution happens in the following steps:
236 * #1 Create a PageSet object with any pages requested by the user
237 * #2 If using a generator, execute it to get a new ApiPageSet object
238 * #3 Instantiate all requested modules.
239 * This way the PageSet object will know what shared data is required,
240 * and minimize DB calls.
241 * #4 Output all normalization and redirect resolution information
242 * #5 Execute all requested modules
244 public function execute() {
245 $this->mParams = $this->extractRequestParams();
247 // Instantiate requested modules
248 $allModules = array();
249 $this->instantiateModules( $allModules, 'prop' );
250 $propModules = array_keys( $allModules );
251 $this->instantiateModules( $allModules, 'list' );
252 $this->instantiateModules( $allModules, 'meta' );
254 // Filter modules based on continue parameter
255 list( $generatorDone, $modules ) = $this->getResult()->beginContinuation(
256 $this->mParams['continue'], $allModules, $propModules
259 if ( !$generatorDone ) {
260 // Query modules may optimize data requests through the $this->getPageSet()
261 // object by adding extra fields from the page table.
262 foreach ( $modules as $module ) {
263 $module->requestExtraData( $this->mPageSet );
265 // Populate page/revision information
266 $this->mPageSet->execute();
267 // Record page information (title, namespace, if exists, etc)
268 $this->outputGeneralPageInfo();
269 } else {
270 $this->mPageSet->executeDryRun();
273 $cacheMode = $this->mPageSet->getCacheMode();
275 // Execute all unfinished modules
276 /** @var $module ApiQueryBase */
277 foreach ( $modules as $module ) {
278 $params = $module->extractRequestParams();
279 $cacheMode = $this->mergeCacheMode(
280 $cacheMode, $module->getCacheMode( $params ) );
281 $module->profileIn();
282 $module->execute();
283 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
284 $module->profileOut();
287 // Set the cache mode
288 $this->getMain()->setCacheMode( $cacheMode );
290 // Write the continuation data into the result
291 $this->getResult()->endContinuation(
292 $this->mParams['continue'] === null ? 'raw' : 'standard'
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
303 * @return string
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
312 } else { // private
313 $cacheMode = 'private';
316 return $cacheMode;
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.
354 $fit = true;
356 $values = $pageSet->getNormalizedTitlesAsResult( $result );
357 if ( $values ) {
358 $fit = $fit && $result->addValue( 'query', 'normalized', $values );
360 $values = $pageSet->getConvertedTitlesAsResult( $result );
361 if ( $values ) {
362 $fit = $fit && $result->addValue( 'query', 'converted', $values );
364 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->mParams['iwurl'] );
365 if ( $values ) {
366 $fit = $fit && $result->addValue( 'query', 'interwiki', $values );
368 $values = $pageSet->getRedirectTitlesAsResult( $result );
369 if ( $values ) {
370 $fit = $fit && $result->addValue( 'query', 'redirects', $values );
372 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
373 if ( $values ) {
374 $fit = $fit && $result->addValue( 'query', 'badrevids', $values );
377 // Page elements
378 $pages = array();
380 // Report any missing titles
381 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
382 $vals = array();
383 ApiQueryBase::addTitleInfo( $vals, $title );
384 $vals['missing'] = '';
385 $pages[$fakeId] = $vals;
387 // Report any invalid titles
388 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
389 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
391 // Report any missing page ids
392 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
393 $pages[$pageid] = array(
394 'pageid' => $pageid,
395 'missing' => ''
398 // Report special pages
399 /** @var $title Title */
400 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
401 $vals = array();
402 ApiQueryBase::addTitleInfo( $vals, $title );
403 $vals['special'] = '';
404 if ( $title->isSpecialPage() &&
405 !SpecialPageFactory::exists( $title->getDBkey() )
407 $vals['missing'] = '';
408 } elseif ( $title->getNamespace() == NS_MEDIA &&
409 !wfFindFile( $title )
411 $vals['missing'] = '';
413 $pages[$fakeId] = $vals;
416 // Output general page information for found titles
417 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
418 $vals = array();
419 $vals['pageid'] = $pageid;
420 ApiQueryBase::addTitleInfo( $vals, $title );
421 $pages[$pageid] = $vals;
424 if ( count( $pages ) ) {
425 if ( $this->mParams['indexpageids'] ) {
426 $pageIDs = array_keys( $pages );
427 // json treats all map keys as strings - converting to match
428 $pageIDs = array_map( 'strval', $pageIDs );
429 $result->setIndexedTagName( $pageIDs, 'id' );
430 $fit = $fit && $result->addValue( 'query', 'pageids', $pageIDs );
433 $result->setIndexedTagName( $pages, 'page' );
434 $fit = $fit && $result->addValue( 'query', 'pages', $pages );
437 if ( !$fit ) {
438 $this->dieUsage(
439 'The value of $wgAPIMaxResultSize on this wiki is ' .
440 'too small to hold basic result information',
441 'badconfig'
445 if ( $this->mParams['export'] ) {
446 $this->doExport( $pageSet, $result );
451 * This method is called by the generator base when generator in the smart-continue
452 * mode tries to set 'query-continue' value. ApiQuery stores those values separately
453 * until the post-processing when it is known if the generation should continue or repeat.
454 * @deprecated since 1.24
455 * @param ApiQueryGeneratorBase $module Generator module
456 * @param string $paramName
457 * @param mixed $paramValue
458 * @return bool True if processed, false if this is a legacy continue
460 public function setGeneratorContinue( $module, $paramName, $paramValue ) {
461 wfDeprecated( __METHOD__, '1.24' );
462 $this->getResult()->setGeneratorContinueParam( $module, $paramName, $paramValue );
463 return $this->getParameter( 'continue' ) !== null;
467 * @param ApiPageSet $pageSet Pages to be exported
468 * @param ApiResult $result Result to output to
470 private function doExport( $pageSet, $result ) {
471 $exportTitles = array();
472 $titles = $pageSet->getGoodTitles();
473 if ( count( $titles ) ) {
474 $user = $this->getUser();
475 /** @var $title Title */
476 foreach ( $titles as $title ) {
477 if ( $title->userCan( 'read', $user ) ) {
478 $exportTitles[] = $title;
483 $exporter = new WikiExporter( $this->getDB() );
484 // WikiExporter writes to stdout, so catch its
485 // output with an ob
486 ob_start();
487 $exporter->openStream();
488 foreach ( $exportTitles as $title ) {
489 $exporter->pageByTitle( $title );
491 $exporter->closeStream();
492 $exportxml = ob_get_contents();
493 ob_end_clean();
495 // Don't check the size of exported stuff
496 // It's not continuable, so it would cause more
497 // problems than it'd solve
498 if ( $this->mParams['exportnowrap'] ) {
499 $result->reset();
500 // Raw formatter will handle this
501 $result->addValue( null, 'text', $exportxml, ApiResult::NO_SIZE_CHECK );
502 $result->addValue( null, 'mime', 'text/xml', ApiResult::NO_SIZE_CHECK );
503 } else {
504 $r = array();
505 ApiResult::setContent( $r, $exportxml );
506 $result->addValue( 'query', 'export', $r, ApiResult::NO_SIZE_CHECK );
510 public function getAllowedParams( $flags = 0 ) {
511 $result = array(
512 'prop' => array(
513 ApiBase::PARAM_ISMULTI => true,
514 ApiBase::PARAM_TYPE => 'submodule',
516 'list' => array(
517 ApiBase::PARAM_ISMULTI => true,
518 ApiBase::PARAM_TYPE => 'submodule',
520 'meta' => array(
521 ApiBase::PARAM_ISMULTI => true,
522 ApiBase::PARAM_TYPE => 'submodule',
524 'indexpageids' => false,
525 'export' => false,
526 'exportnowrap' => false,
527 'iwurl' => false,
528 'continue' => null,
529 'rawcontinue' => false,
531 if ( $flags ) {
532 $result += $this->getPageSet()->getFinalParams( $flags );
535 return $result;
539 * Override the parent to generate help messages for all available query modules.
540 * @return string
542 public function makeHelpMsg() {
544 // Use parent to make default message for the query module
545 $msg = parent::makeHelpMsg();
547 $querySeparator = str_repeat( '--- ', 12 );
548 $moduleSeparator = str_repeat( '*** ', 14 );
549 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
550 $msg .= $this->makeHelpMsgHelper( 'prop' );
551 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
552 $msg .= $this->makeHelpMsgHelper( 'list' );
553 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
554 $msg .= $this->makeHelpMsgHelper( 'meta' );
555 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
557 return $msg;
561 * For all modules of a given group, generate help messages and join them together
562 * @param string $group Module group
563 * @return string
565 private function makeHelpMsgHelper( $group ) {
566 $moduleDescriptions = array();
568 $moduleNames = $this->mModuleMgr->getNames( $group );
569 sort( $moduleNames );
570 foreach ( $moduleNames as $name ) {
572 * @var $module ApiQueryBase
574 $module = $this->mModuleMgr->getModule( $name );
576 $msg = ApiMain::makeHelpMsgHeader( $module, $group );
577 $msg2 = $module->makeHelpMsg();
578 if ( $msg2 !== false ) {
579 $msg .= $msg2;
581 if ( $module instanceof ApiQueryGeneratorBase ) {
582 $msg .= "Generator:\n This module may be used as a generator\n";
584 $moduleDescriptions[] = $msg;
587 return implode( "\n", $moduleDescriptions );
590 public function shouldCheckMaxlag() {
591 return true;
594 public function getParamDescription() {
595 return $this->getPageSet()->getFinalParamDescription() + array(
596 'prop' => 'Which properties to get for the titles/revisions/pageids. ' .
597 'Module help is available below',
598 'list' => 'Which lists to get. Module help is available below',
599 'meta' => 'Which metadata to get about the site. Module help is available below',
600 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
601 'export' => 'Export the current revisions of all given or generated pages',
602 'exportnowrap' => 'Return the export XML without wrapping it in an ' .
603 'XML result (same format as Special:Export). Can only be used with export',
604 'iwurl' => 'Whether to get the full URL if the title is an interwiki link',
605 'continue' => array(
606 'When present, formats query-continue as key-value pairs that ' .
607 'should simply be merged into the original request.',
608 'This parameter must be set to an empty string in the initial query.',
609 'This parameter is recommended for all new development, and ' .
610 'will be made default in the next API version.'
612 'rawcontinue' => 'Currently ignored. In the future, \'continue=\' will become the ' .
613 'default and this will be needed to receive the raw query-continue data.',
617 public function getDescription() {
618 return array(
619 'Query API module allows applications to get needed pieces of data ' .
620 'from the MediaWiki databases,',
621 'and is loosely based on the old query.php interface.',
622 'All data modifications will first have to use query to acquire a ' .
623 'token to prevent abuse from malicious sites.'
627 public function getExamples() {
628 return array(
629 'api.php?action=query&prop=revisions&meta=siteinfo&' .
630 'titles=Main%20Page&rvprop=user|comment&continue=',
631 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions&continue=',
635 public function getHelpUrls() {
636 return array(
637 'https://www.mediawiki.org/wiki/API:Query',
638 'https://www.mediawiki.org/wiki/API:Meta',
639 'https://www.mediawiki.org/wiki/API:Properties',
640 'https://www.mediawiki.org/wiki/API:Lists',