Remove score display from search engine
[mediawiki.git] / includes / api / ApiQuery.php
blob606012c485c5727d9917306e4aa160a3da874859
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',
114 * @var ApiPageSet
116 private $mPageSet;
118 private $mParams;
119 private $mNamedDB = array();
120 private $mModuleMgr;
123 * @param ApiMain $main
124 * @param string $action
126 public function __construct( ApiMain $main, $action ) {
127 parent::__construct( $main, $action );
129 $this->mModuleMgr = new ApiModuleManager( $this );
131 // Allow custom modules to be added in LocalSettings.php
132 $config = $this->getConfig();
133 $this->mModuleMgr->addModules( self::$QueryPropModules, 'prop' );
134 $this->mModuleMgr->addModules( $config->get( 'APIPropModules' ), 'prop' );
135 $this->mModuleMgr->addModules( self::$QueryListModules, 'list' );
136 $this->mModuleMgr->addModules( $config->get( 'APIListModules' ), 'list' );
137 $this->mModuleMgr->addModules( self::$QueryMetaModules, 'meta' );
138 $this->mModuleMgr->addModules( $config->get( 'APIMetaModules' ), 'meta' );
140 // Create PageSet that will process titles/pageids/revids/generator
141 $this->mPageSet = new ApiPageSet( $this );
145 * Overrides to return this instance's module manager.
146 * @return ApiModuleManager
148 public function getModuleManager() {
149 return $this->mModuleMgr;
153 * Get the query database connection with the given name.
154 * If no such connection has been requested before, it will be created.
155 * Subsequent calls with the same $name will return the same connection
156 * as the first, regardless of the values of $db and $groups
157 * @param string $name Name to assign to the database connection
158 * @param int $db One of the DB_* constants
159 * @param array $groups Query groups
160 * @return DatabaseBase
162 public function getNamedDB( $name, $db, $groups ) {
163 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
164 $this->profileDBIn();
165 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
166 $this->profileDBOut();
169 return $this->mNamedDB[$name];
173 * Gets the set of pages the user has requested (or generated)
174 * @return ApiPageSet
176 public function getPageSet() {
177 return $this->mPageSet;
181 * Get the array mapping module names to class names
182 * @deprecated since 1.21, use getModuleManager()'s methods instead
183 * @return array Array(modulename => classname)
185 public function getModules() {
186 wfDeprecated( __METHOD__, '1.21' );
188 return $this->getModuleManager()->getNamesWithClasses();
192 * Get the generators array mapping module names to class names
193 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
194 * @return array Array(modulename => classname)
196 public function getGenerators() {
197 wfDeprecated( __METHOD__, '1.21' );
198 $gens = array();
199 foreach ( $this->mModuleMgr->getNamesWithClasses() as $name => $class ) {
200 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
201 $gens[$name] = $class;
205 return $gens;
209 * Get whether the specified module is a prop, list or a meta query module
210 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
211 * @param string $moduleName Name of the module to find type for
212 * @return string|null
214 function getModuleType( $moduleName ) {
215 return $this->getModuleManager()->getModuleGroup( $moduleName );
219 * @return ApiFormatRaw|null
221 public function getCustomPrinter() {
222 // If &exportnowrap is set, use the raw formatter
223 if ( $this->getParameter( 'export' ) &&
224 $this->getParameter( 'exportnowrap' )
226 return new ApiFormatRaw( $this->getMain(),
227 $this->getMain()->createPrinterByName( 'xml' ) );
228 } else {
229 return null;
234 * Query execution happens in the following steps:
235 * #1 Create a PageSet object with any pages requested by the user
236 * #2 If using a generator, execute it to get a new ApiPageSet object
237 * #3 Instantiate all requested modules.
238 * This way the PageSet object will know what shared data is required,
239 * and minimize DB calls.
240 * #4 Output all normalization and redirect resolution information
241 * #5 Execute all requested modules
243 public function execute() {
244 $this->mParams = $this->extractRequestParams();
246 // Instantiate requested modules
247 $allModules = array();
248 $this->instantiateModules( $allModules, 'prop' );
249 $propModules = array_keys( $allModules );
250 $this->instantiateModules( $allModules, 'list' );
251 $this->instantiateModules( $allModules, 'meta' );
253 // Filter modules based on continue parameter
254 list( $generatorDone, $modules ) = $this->getResult()->beginContinuation(
255 $this->mParams['continue'], $allModules, $propModules
258 if ( !$generatorDone ) {
259 // Query modules may optimize data requests through the $this->getPageSet()
260 // object by adding extra fields from the page table.
261 foreach ( $modules as $module ) {
262 $module->requestExtraData( $this->mPageSet );
264 // Populate page/revision information
265 $this->mPageSet->execute();
266 // Record page information (title, namespace, if exists, etc)
267 $this->outputGeneralPageInfo();
268 } else {
269 $this->mPageSet->executeDryRun();
272 $cacheMode = $this->mPageSet->getCacheMode();
274 // Execute all unfinished modules
275 /** @var $module ApiQueryBase */
276 foreach ( $modules as $module ) {
277 $params = $module->extractRequestParams();
278 $cacheMode = $this->mergeCacheMode(
279 $cacheMode, $module->getCacheMode( $params ) );
280 $module->profileIn();
281 $module->execute();
282 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
283 $module->profileOut();
286 // Set the cache mode
287 $this->getMain()->setCacheMode( $cacheMode );
289 // Write the continuation data into the result
290 $this->getResult()->endContinuation(
291 $this->mParams['continue'] === null ? 'raw' : 'standard'
296 * Update a cache mode string, applying the cache mode of a new module to it.
297 * The cache mode may increase in the level of privacy, but public modules
298 * added to private data do not decrease the level of privacy.
300 * @param string $cacheMode
301 * @param string $modCacheMode
302 * @return string
304 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
305 if ( $modCacheMode === 'anon-public-user-private' ) {
306 if ( $cacheMode !== 'private' ) {
307 $cacheMode = 'anon-public-user-private';
309 } elseif ( $modCacheMode === 'public' ) {
310 // do nothing, if it's public already it will stay public
311 } else { // private
312 $cacheMode = 'private';
315 return $cacheMode;
319 * Create instances of all modules requested by the client
320 * @param array $modules To append instantiated modules to
321 * @param string $param Parameter name to read modules from
323 private function instantiateModules( &$modules, $param ) {
324 $wasPosted = $this->getRequest()->wasPosted();
325 if ( isset( $this->mParams[$param] ) ) {
326 foreach ( $this->mParams[$param] as $moduleName ) {
327 $instance = $this->mModuleMgr->getModule( $moduleName, $param );
328 if ( $instance === null ) {
329 ApiBase::dieDebug( __METHOD__, 'Error instantiating module' );
331 if ( !$wasPosted && $instance->mustBePosted() ) {
332 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $moduleName ) );
334 // Ignore duplicates. TODO 2.0: die()?
335 if ( !array_key_exists( $moduleName, $modules ) ) {
336 $modules[$moduleName] = $instance;
343 * Appends an element for each page in the current pageSet with the
344 * most general information (id, title), plus any title normalizations
345 * and missing or invalid title/pageids/revids.
347 private function outputGeneralPageInfo() {
348 $pageSet = $this->getPageSet();
349 $result = $this->getResult();
351 // We can't really handle max-result-size failure here, but we need to
352 // check anyway in case someone set the limit stupidly low.
353 $fit = true;
355 $values = $pageSet->getNormalizedTitlesAsResult( $result );
356 if ( $values ) {
357 $fit = $fit && $result->addValue( 'query', 'normalized', $values );
359 $values = $pageSet->getConvertedTitlesAsResult( $result );
360 if ( $values ) {
361 $fit = $fit && $result->addValue( 'query', 'converted', $values );
363 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->mParams['iwurl'] );
364 if ( $values ) {
365 $fit = $fit && $result->addValue( 'query', 'interwiki', $values );
367 $values = $pageSet->getRedirectTitlesAsResult( $result );
368 if ( $values ) {
369 $fit = $fit && $result->addValue( 'query', 'redirects', $values );
371 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
372 if ( $values ) {
373 $fit = $fit && $result->addValue( 'query', 'badrevids', $values );
376 // Page elements
377 $pages = array();
379 // Report any missing titles
380 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
381 $vals = array();
382 ApiQueryBase::addTitleInfo( $vals, $title );
383 $vals['missing'] = '';
384 $pages[$fakeId] = $vals;
386 // Report any invalid titles
387 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
388 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
390 // Report any missing page ids
391 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
392 $pages[$pageid] = array(
393 'pageid' => $pageid,
394 'missing' => ''
397 // Report special pages
398 /** @var $title Title */
399 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
400 $vals = array();
401 ApiQueryBase::addTitleInfo( $vals, $title );
402 $vals['special'] = '';
403 if ( $title->isSpecialPage() &&
404 !SpecialPageFactory::exists( $title->getDBkey() )
406 $vals['missing'] = '';
407 } elseif ( $title->getNamespace() == NS_MEDIA &&
408 !wfFindFile( $title )
410 $vals['missing'] = '';
412 $pages[$fakeId] = $vals;
415 // Output general page information for found titles
416 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
417 $vals = array();
418 $vals['pageid'] = $pageid;
419 ApiQueryBase::addTitleInfo( $vals, $title );
420 $pages[$pageid] = $vals;
423 if ( count( $pages ) ) {
424 if ( $this->mParams['indexpageids'] ) {
425 $pageIDs = array_keys( $pages );
426 // json treats all map keys as strings - converting to match
427 $pageIDs = array_map( 'strval', $pageIDs );
428 $result->setIndexedTagName( $pageIDs, 'id' );
429 $fit = $fit && $result->addValue( 'query', 'pageids', $pageIDs );
432 $result->setIndexedTagName( $pages, 'page' );
433 $fit = $fit && $result->addValue( 'query', 'pages', $pages );
436 if ( !$fit ) {
437 $this->dieUsage(
438 'The value of $wgAPIMaxResultSize on this wiki is ' .
439 'too small to hold basic result information',
440 'badconfig'
444 if ( $this->mParams['export'] ) {
445 $this->doExport( $pageSet, $result );
450 * This method is called by the generator base when generator in the smart-continue
451 * mode tries to set 'query-continue' value. ApiQuery stores those values separately
452 * until the post-processing when it is known if the generation should continue or repeat.
453 * @deprecated since 1.24
454 * @param ApiQueryGeneratorBase $module Generator module
455 * @param string $paramName
456 * @param mixed $paramValue
457 * @return bool True if processed, false if this is a legacy continue
459 public function setGeneratorContinue( $module, $paramName, $paramValue ) {
460 wfDeprecated( __METHOD__, '1.24' );
461 $this->getResult()->setGeneratorContinueParam( $module, $paramName, $paramValue );
462 return $this->getParameter( 'continue' ) !== null;
466 * @param ApiPageSet $pageSet Pages to be exported
467 * @param ApiResult $result Result to output to
469 private function doExport( $pageSet, $result ) {
470 $exportTitles = array();
471 $titles = $pageSet->getGoodTitles();
472 if ( count( $titles ) ) {
473 $user = $this->getUser();
474 /** @var $title Title */
475 foreach ( $titles as $title ) {
476 if ( $title->userCan( 'read', $user ) ) {
477 $exportTitles[] = $title;
482 $exporter = new WikiExporter( $this->getDB() );
483 // WikiExporter writes to stdout, so catch its
484 // output with an ob
485 ob_start();
486 $exporter->openStream();
487 foreach ( $exportTitles as $title ) {
488 $exporter->pageByTitle( $title );
490 $exporter->closeStream();
491 $exportxml = ob_get_contents();
492 ob_end_clean();
494 // Don't check the size of exported stuff
495 // It's not continuable, so it would cause more
496 // problems than it'd solve
497 if ( $this->mParams['exportnowrap'] ) {
498 $result->reset();
499 // Raw formatter will handle this
500 $result->addValue( null, 'text', $exportxml, ApiResult::NO_SIZE_CHECK );
501 $result->addValue( null, 'mime', 'text/xml', ApiResult::NO_SIZE_CHECK );
502 } else {
503 $r = array();
504 ApiResult::setContent( $r, $exportxml );
505 $result->addValue( 'query', 'export', $r, ApiResult::NO_SIZE_CHECK );
509 public function getAllowedParams( $flags = 0 ) {
510 $result = array(
511 'prop' => array(
512 ApiBase::PARAM_ISMULTI => true,
513 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'prop' )
515 'list' => array(
516 ApiBase::PARAM_ISMULTI => true,
517 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'list' )
519 'meta' => array(
520 ApiBase::PARAM_ISMULTI => true,
521 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'meta' )
523 'indexpageids' => false,
524 'export' => false,
525 'exportnowrap' => false,
526 'iwurl' => false,
527 'continue' => null,
529 if ( $flags ) {
530 $result += $this->getPageSet()->getFinalParams( $flags );
533 return $result;
537 * Override the parent to generate help messages for all available query modules.
538 * @return string
540 public function makeHelpMsg() {
542 // Use parent to make default message for the query module
543 $msg = parent::makeHelpMsg();
545 $querySeparator = str_repeat( '--- ', 12 );
546 $moduleSeparator = str_repeat( '*** ', 14 );
547 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
548 $msg .= $this->makeHelpMsgHelper( 'prop' );
549 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
550 $msg .= $this->makeHelpMsgHelper( 'list' );
551 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
552 $msg .= $this->makeHelpMsgHelper( 'meta' );
553 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
555 return $msg;
559 * For all modules of a given group, generate help messages and join them together
560 * @param string $group Module group
561 * @return string
563 private function makeHelpMsgHelper( $group ) {
564 $moduleDescriptions = array();
566 $moduleNames = $this->mModuleMgr->getNames( $group );
567 sort( $moduleNames );
568 foreach ( $moduleNames as $name ) {
570 * @var $module ApiQueryBase
572 $module = $this->mModuleMgr->getModule( $name );
574 $msg = ApiMain::makeHelpMsgHeader( $module, $group );
575 $msg2 = $module->makeHelpMsg();
576 if ( $msg2 !== false ) {
577 $msg .= $msg2;
579 if ( $module instanceof ApiQueryGeneratorBase ) {
580 $msg .= "Generator:\n This module may be used as a generator\n";
582 $moduleDescriptions[] = $msg;
585 return implode( "\n", $moduleDescriptions );
588 public function shouldCheckMaxlag() {
589 return true;
592 public function getParamDescription() {
593 return $this->getPageSet()->getFinalParamDescription() + array(
594 'prop' => 'Which properties to get for the titles/revisions/pageids. ' .
595 'Module help is available below',
596 'list' => 'Which lists to get. Module help is available below',
597 'meta' => 'Which metadata to get about the site. Module help is available below',
598 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
599 'export' => 'Export the current revisions of all given or generated pages',
600 'exportnowrap' => 'Return the export XML without wrapping it in an ' .
601 'XML result (same format as Special:Export). Can only be used with export',
602 'iwurl' => 'Whether to get the full URL if the title is an interwiki link',
603 'continue' => array(
604 'When present, formats query-continue as key-value pairs that ' .
605 'should simply be merged into the original request.',
606 'This parameter must be set to an empty string in the initial query.',
607 'This parameter is recommended for all new development, and ' .
608 'will be made default in the next API version.'
613 public function getDescription() {
614 return array(
615 'Query API module allows applications to get needed pieces of data ' .
616 'from the MediaWiki databases,',
617 'and is loosely based on the old query.php interface.',
618 'All data modifications will first have to use query to acquire a ' .
619 'token to prevent abuse from malicious sites.'
623 public function getPossibleErrors() {
624 return array_merge(
625 parent::getPossibleErrors(),
626 $this->getPageSet()->getFinalPossibleErrors()
630 public function getExamples() {
631 return array(
632 'api.php?action=query&prop=revisions&meta=siteinfo&' .
633 'titles=Main%20Page&rvprop=user|comment&continue=',
634 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions&continue=',
638 public function getHelpUrls() {
639 return array(
640 'https://www.mediawiki.org/wiki/API:Query',
641 'https://www.mediawiki.org/wiki/API:Meta',
642 'https://www.mediawiki.org/wiki/API:Properties',
643 'https://www.mediawiki.org/wiki/API:Lists',