Localisation updates for core and extension messages from translatewiki.net (2010...
[mediawiki.git] / includes / api / ApiQuery.php
blobe4b453950c7acd7755370471a0415804177e67e0
1 <?php
2 /**
3 * API for MediaWiki 1.8+
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 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
32 /**
33 * This is the main query class. It behaves similar to ApiMain: based on the
34 * parameters given, it will create a list of titles to work on (an ApiPageSet
35 * object), instantiate and execute various property/list/meta modules, and
36 * assemble all resulting data into a single ApiResult object.
38 * In generator mode, a generator will be executed first to populate a second
39 * ApiPageSet object, and that object will be used for all subsequent modules.
41 * @ingroup API
43 class ApiQuery extends ApiBase {
45 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
46 private $mPageSet;
47 private $params, $redirects, $convertTitles;
49 private $mQueryPropModules = array(
50 'info' => 'ApiQueryInfo',
51 'revisions' => 'ApiQueryRevisions',
52 'links' => 'ApiQueryLinks',
53 'iwlinks' => 'ApiQueryIWLinks',
54 'langlinks' => 'ApiQueryLangLinks',
55 'images' => 'ApiQueryImages',
56 'imageinfo' => 'ApiQueryImageInfo',
57 'templates' => 'ApiQueryLinks',
58 'categories' => 'ApiQueryCategories',
59 'extlinks' => 'ApiQueryExternalLinks',
60 'categoryinfo' => 'ApiQueryCategoryInfo',
61 'duplicatefiles' => 'ApiQueryDuplicateFiles',
62 'pageprops' => 'ApiQueryPageProps',
65 private $mQueryListModules = array(
66 'allimages' => 'ApiQueryAllimages',
67 'allpages' => 'ApiQueryAllpages',
68 'alllinks' => 'ApiQueryAllLinks',
69 'allcategories' => 'ApiQueryAllCategories',
70 'allusers' => 'ApiQueryAllUsers',
71 'backlinks' => 'ApiQueryBacklinks',
72 'blocks' => 'ApiQueryBlocks',
73 'categorymembers' => 'ApiQueryCategoryMembers',
74 'deletedrevs' => 'ApiQueryDeletedrevs',
75 'embeddedin' => 'ApiQueryBacklinks',
76 'filearchive' => 'ApiQueryFilearchive',
77 'imageusage' => 'ApiQueryBacklinks',
78 'iwbacklinks' => 'ApiQueryIWBacklinks',
79 'logevents' => 'ApiQueryLogEvents',
80 'recentchanges' => 'ApiQueryRecentChanges',
81 'search' => 'ApiQuerySearch',
82 'tags' => 'ApiQueryTags',
83 'usercontribs' => 'ApiQueryContributions',
84 'watchlist' => 'ApiQueryWatchlist',
85 'watchlistraw' => 'ApiQueryWatchlistRaw',
86 'exturlusage' => 'ApiQueryExtLinksUsage',
87 'users' => 'ApiQueryUsers',
88 'random' => 'ApiQueryRandom',
89 'protectedtitles' => 'ApiQueryProtectedTitles',
92 private $mQueryMetaModules = array(
93 'siteinfo' => 'ApiQuerySiteinfo',
94 'userinfo' => 'ApiQueryUserInfo',
95 'allmessages' => 'ApiQueryAllmessages',
98 private $mSlaveDB = null;
99 private $mNamedDB = array();
101 public function __construct( $main, $action ) {
102 parent::__construct( $main, $action );
104 // Allow custom modules to be added in LocalSettings.php
105 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
106 self::appendUserModules( $this->mQueryPropModules, $wgAPIPropModules );
107 self::appendUserModules( $this->mQueryListModules, $wgAPIListModules );
108 self::appendUserModules( $this->mQueryMetaModules, $wgAPIMetaModules );
110 $this->mPropModuleNames = array_keys( $this->mQueryPropModules );
111 $this->mListModuleNames = array_keys( $this->mQueryListModules );
112 $this->mMetaModuleNames = array_keys( $this->mQueryMetaModules );
114 // Allow the entire list of modules at first,
115 // but during module instantiation check if it can be used as a generator.
116 $this->mAllowedGenerators = array_merge( $this->mListModuleNames, $this->mPropModuleNames );
120 * Helper function to append any add-in modules to the list
121 * @param $modules array Module array
122 * @param $newModules array Module array to add to $modules
124 private static function appendUserModules( &$modules, $newModules ) {
125 if ( is_array( $newModules ) ) {
126 foreach ( $newModules as $moduleName => $moduleClass ) {
127 $modules[$moduleName] = $moduleClass;
133 * Gets a default slave database connection object
134 * @return Database
136 public function getDB() {
137 if ( !isset( $this->mSlaveDB ) ) {
138 $this->profileDBIn();
139 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
140 $this->profileDBOut();
142 return $this->mSlaveDB;
146 * Get the query database connection with the given name.
147 * If no such connection has been requested before, it will be created.
148 * Subsequent calls with the same $name will return the same connection
149 * as the first, regardless of the values of $db and $groups
150 * @param $name string Name to assign to the database connection
151 * @param $db int One of the DB_* constants
152 * @param $groups array Query groups
153 * @return Database
155 public function getNamedDB( $name, $db, $groups ) {
156 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
157 $this->profileDBIn();
158 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
159 $this->profileDBOut();
161 return $this->mNamedDB[$name];
165 * Gets the set of pages the user has requested (or generated)
166 * @return ApiPageSet
168 public function getPageSet() {
169 return $this->mPageSet;
173 * Get the array mapping module names to class names
174 * @return array(modulename => classname)
176 function getModules() {
177 return array_merge( $this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules );
181 * Get whether the specified module is a prop, list or a meta query module
182 * @param $moduleName string Name of the module to find type for
183 * @return mixed string or null
185 function getModuleType( $moduleName ) {
186 if ( array_key_exists ( $moduleName, $this->mQueryPropModules ) ) {
187 return 'prop';
190 if ( array_key_exists ( $moduleName, $this->mQueryListModules ) ) {
191 return 'list';
194 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules ) ) {
195 return 'meta';
198 return null;
201 public function getCustomPrinter() {
202 // If &exportnowrap is set, use the raw formatter
203 if ( $this->getParameter( 'export' ) &&
204 $this->getParameter( 'exportnowrap' ) )
206 return new ApiFormatRaw( $this->getMain(),
207 $this->getMain()->createPrinterByName( 'xml' ) );
208 } else {
209 return null;
214 * Query execution happens in the following steps:
215 * #1 Create a PageSet object with any pages requested by the user
216 * #2 If using a generator, execute it to get a new ApiPageSet object
217 * #3 Instantiate all requested modules.
218 * This way the PageSet object will know what shared data is required,
219 * and minimize DB calls.
220 * #4 Output all normalization and redirect resolution information
221 * #5 Execute all requested modules
223 public function execute() {
224 $this->params = $this->extractRequestParams();
225 $this->redirects = $this->params['redirects'];
226 $this->convertTitles = $this->params['converttitles'];
228 // Create PageSet
229 $this->mPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
231 // Instantiate requested modules
232 $modules = array();
233 $this->instantiateModules( $modules, 'prop', $this->mQueryPropModules );
234 $this->instantiateModules( $modules, 'list', $this->mQueryListModules );
235 $this->instantiateModules( $modules, 'meta', $this->mQueryMetaModules );
237 $cacheMode = 'public';
239 // If given, execute generator to substitute user supplied data with generated data.
240 if ( isset( $this->params['generator'] ) ) {
241 $generator = $this->newGenerator( $this->params['generator'] );
242 $params = $generator->extractRequestParams();
243 $cacheMode = $this->mergeCacheMode( $cacheMode,
244 $generator->getCacheMode( $params ) );
245 $this->executeGeneratorModule( $generator, $modules );
246 } else {
247 // Append custom fields and populate page/revision information
248 $this->addCustomFldsToPageSet( $modules, $this->mPageSet );
249 $this->mPageSet->execute();
252 // Record page information (title, namespace, if exists, etc)
253 $this->outputGeneralPageInfo();
255 // Execute all requested modules.
256 foreach ( $modules as $module ) {
257 $params = $module->extractRequestParams();
258 $cacheMode = $this->mergeCacheMode(
259 $cacheMode, $module->getCacheMode( $params ) );
260 $module->profileIn();
261 $module->execute();
262 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
263 $module->profileOut();
266 // Set the cache mode
267 $this->getMain()->setCacheMode( $cacheMode );
271 * Update a cache mode string, applying the cache mode of a new module to it.
272 * The cache mode may increase in the level of privacy, but public modules
273 * added to private data do not decrease the level of privacy.
275 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
276 if ( $modCacheMode === 'anon-public-user-private' ) {
277 if ( $cacheMode !== 'private' ) {
278 $cacheMode = 'anon-public-user-private';
280 } elseif ( $modCacheMode === 'public' ) {
281 // do nothing, if it's public already it will stay public
282 } else { // private
283 $cacheMode = 'private';
285 return $cacheMode;
289 * Query modules may optimize data requests through the $this->getPageSet() object
290 * by adding extra fields from the page table.
291 * This function will gather all the extra request fields from the modules.
292 * @param $modules array of module objects
293 * @param $pageSet ApiPageSet
295 private function addCustomFldsToPageSet( $modules, $pageSet ) {
296 // Query all requested modules.
297 foreach ( $modules as $module ) {
298 $module->requestExtraData( $pageSet );
303 * Create instances of all modules requested by the client
304 * @param $modules Array to append instantiated modules to
305 * @param $param string Parameter name to read modules from
306 * @param $moduleList Array array(modulename => classname)
308 private function instantiateModules( &$modules, $param, $moduleList ) {
309 $list = @$this->params[$param];
310 if ( !is_null ( $list ) ) {
311 foreach ( $list as $moduleName ) {
312 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
318 * Appends an element for each page in the current pageSet with the
319 * most general information (id, title), plus any title normalizations
320 * and missing or invalid title/pageids/revids.
322 private function outputGeneralPageInfo() {
323 $pageSet = $this->getPageSet();
324 $result = $this->getResult();
326 // We don't check for a full result set here because we can't be adding
327 // more than 380K. The maximum revision size is in the megabyte range,
328 // and the maximum result size must be even higher than that.
330 // Title normalizations
331 $normValues = array();
332 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
333 $normValues[] = array(
334 'from' => $rawTitleStr,
335 'to' => $titleStr
339 if ( count( $normValues ) ) {
340 $result->setIndexedTagName( $normValues, 'n' );
341 $result->addValue( 'query', 'normalized', $normValues );
344 // Title conversions
345 $convValues = array();
346 foreach ( $pageSet->getConvertedTitles() as $rawTitleStr => $titleStr ) {
347 $convValues[] = array(
348 'from' => $rawTitleStr,
349 'to' => $titleStr
353 if ( count( $convValues ) ) {
354 $result->setIndexedTagName( $convValues, 'c' );
355 $result->addValue( 'query', 'converted', $convValues );
358 // Interwiki titles
359 $intrwValues = array();
360 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
361 $intrwValues[] = array(
362 'title' => $rawTitleStr,
363 'iw' => $interwikiStr
367 if ( count( $intrwValues ) ) {
368 $result->setIndexedTagName( $intrwValues, 'i' );
369 $result->addValue( 'query', 'interwiki', $intrwValues );
372 // Show redirect information
373 $redirValues = array();
374 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
375 $redirValues[] = array(
376 'from' => strval( $titleStrFrom ),
377 'to' => $titleStrTo
381 if ( count( $redirValues ) ) {
382 $result->setIndexedTagName( $redirValues, 'r' );
383 $result->addValue( 'query', 'redirects', $redirValues );
386 // Missing revision elements
387 $missingRevIDs = $pageSet->getMissingRevisionIDs();
388 if ( count( $missingRevIDs ) ) {
389 $revids = array();
390 foreach ( $missingRevIDs as $revid ) {
391 $revids[$revid] = array(
392 'revid' => $revid
395 $result->setIndexedTagName( $revids, 'rev' );
396 $result->addValue( 'query', 'badrevids', $revids );
399 // Page elements
400 $pages = array();
402 // Report any missing titles
403 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
404 $vals = array();
405 ApiQueryBase::addTitleInfo( $vals, $title );
406 $vals['missing'] = '';
407 $pages[$fakeId] = $vals;
409 // Report any invalid titles
410 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
411 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
413 // Report any missing page ids
414 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
415 $pages[$pageid] = array(
416 'pageid' => $pageid,
417 'missing' => ''
420 // Report special pages
421 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
422 $vals = array();
423 ApiQueryBase::addTitleInfo( $vals, $title );
424 $vals['special'] = '';
425 if ( $title->getNamespace() == NS_SPECIAL &&
426 !SpecialPage::exists( $title->getText() ) ) {
427 $vals['missing'] = '';
428 } elseif ( $title->getNamespace() == NS_MEDIA &&
429 !wfFindFile( $title ) ) {
430 $vals['missing'] = '';
432 $pages[$fakeId] = $vals;
435 // Output general page information for found titles
436 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
437 $vals = array();
438 $vals['pageid'] = $pageid;
439 ApiQueryBase::addTitleInfo( $vals, $title );
440 $pages[$pageid] = $vals;
443 if ( count( $pages ) ) {
444 if ( $this->params['indexpageids'] ) {
445 $pageIDs = array_keys( $pages );
446 // json treats all map keys as strings - converting to match
447 $pageIDs = array_map( 'strval', $pageIDs );
448 $result->setIndexedTagName( $pageIDs, 'id' );
449 $result->addValue( 'query', 'pageids', $pageIDs );
452 $result->setIndexedTagName( $pages, 'page' );
453 $result->addValue( 'query', 'pages', $pages );
455 if ( $this->params['export'] ) {
456 $this->doExport( $pageSet, $result );
461 * @param $pageSet ApiPageSet Pages to be exported
462 * @param $result ApiResult Result to output to
464 private function doExport( $pageSet, $result ) {
465 $exportTitles = array();
466 $titles = $pageSet->getGoodTitles();
467 if( count( $titles ) ) {
468 foreach ( $titles as $title ) {
469 if ( $title->userCanRead() ) {
470 $exportTitles[] = $title;
474 // only export when there are titles
475 if ( !count( $exportTitles ) ) {
476 return;
479 $exporter = new WikiExporter( $this->getDB() );
480 // WikiExporter writes to stdout, so catch its
481 // output with an ob
482 ob_start();
483 $exporter->openStream();
484 foreach ( $exportTitles as $title ) {
485 $exporter->pageByTitle( $title );
487 $exporter->closeStream();
488 $exportxml = ob_get_contents();
489 ob_end_clean();
491 // Don't check the size of exported stuff
492 // It's not continuable, so it would cause more
493 // problems than it'd solve
494 $result->disableSizeCheck();
495 if ( $this->params['exportnowrap'] ) {
496 $result->reset();
497 // Raw formatter will handle this
498 $result->addValue( null, 'text', $exportxml );
499 $result->addValue( null, 'mime', 'text/xml' );
500 } else {
501 $r = array();
502 ApiResult::setContent( $r, $exportxml );
503 $result->addValue( 'query', 'export', $r );
505 $result->enableSizeCheck();
509 * Create a generator object of the given type and return it
510 * @param $generatorName string Module name
511 * @return ApiQueryGeneratorBase
513 public function newGenerator( $generatorName ) {
514 // Find class that implements requested generator
515 if ( isset( $this->mQueryListModules[$generatorName] ) ) {
516 $className = $this->mQueryListModules[$generatorName];
517 } elseif ( isset( $this->mQueryPropModules[$generatorName] ) ) {
518 $className = $this->mQueryPropModules[$generatorName];
519 } else {
520 ApiBase::dieDebug( __METHOD__, "Unknown generator=$generatorName" );
522 $generator = new $className ( $this, $generatorName );
523 if ( !$generator instanceof ApiQueryGeneratorBase ) {
524 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
526 $generator->setGeneratorMode();
527 return $generator;
531 * For generator mode, execute generator, and use its output as new
532 * ApiPageSet
533 * @param $generator ApiQueryGeneratorBase Generator Module
534 * @param $modules array of module objects
536 protected function executeGeneratorModule( $generator, $modules ) {
537 // Generator results
538 $resultPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
540 // Add any additional fields modules may need
541 $generator->requestExtraData( $this->mPageSet );
542 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
544 // Populate page information with the original user input
545 $this->mPageSet->execute();
547 // populate resultPageSet with the generator output
548 $generator->profileIn();
549 $generator->executeGenerator( $resultPageSet );
550 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
551 $resultPageSet->finishPageSetGeneration();
552 $generator->profileOut();
554 // Swap the resulting pageset back in
555 $this->mPageSet = $resultPageSet;
558 public function getAllowedParams() {
559 return array(
560 'prop' => array(
561 ApiBase::PARAM_ISMULTI => true,
562 ApiBase::PARAM_TYPE => $this->mPropModuleNames
564 'list' => array(
565 ApiBase::PARAM_ISMULTI => true,
566 ApiBase::PARAM_TYPE => $this->mListModuleNames
568 'meta' => array(
569 ApiBase::PARAM_ISMULTI => true,
570 ApiBase::PARAM_TYPE => $this->mMetaModuleNames
572 'generator' => array(
573 ApiBase::PARAM_TYPE => $this->mAllowedGenerators
575 'redirects' => false,
576 'converttitles' => false,
577 'indexpageids' => false,
578 'export' => false,
579 'exportnowrap' => false,
584 * Override the parent to generate help messages for all available query modules.
585 * @return string
587 public function makeHelpMsg() {
588 $msg = '';
590 // Make sure the internal object is empty
591 // (just in case a sub-module decides to optimize during instantiation)
592 $this->mPageSet = null;
593 $this->mAllowedGenerators = array(); // Will be repopulated
595 $querySeparator = str_repeat( '--- ', 8 );
596 $moduleSeparator = str_repeat( '*** ', 10 );
597 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
598 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules, 'prop' );
599 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
600 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules, 'list' );
601 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
602 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules, 'meta' );
603 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
605 // Perform the base call last because the $this->mAllowedGenerators
606 // will be updated inside makeHelpMsgHelper()
607 // Use parent to make default message for the query module
608 $msg = parent::makeHelpMsg() . $msg;
610 return $msg;
614 * For all modules in $moduleList, generate help messages and join them together
615 * @param $moduleList Array array(modulename => classname)
616 * @param $paramName string Parameter name
617 * @return string
619 private function makeHelpMsgHelper( $moduleList, $paramName ) {
620 $moduleDescriptions = array();
622 foreach ( $moduleList as $moduleName => $moduleClass ) {
623 $module = new $moduleClass ( $this, $moduleName, null );
625 $msg = ApiMain::makeHelpMsgHeader( $module, $paramName );
626 $msg2 = $module->makeHelpMsg();
627 if ( $msg2 !== false ) {
628 $msg .= $msg2;
630 if ( $module instanceof ApiQueryGeneratorBase ) {
631 $this->mAllowedGenerators[] = $moduleName;
632 $msg .= "Generator:\n This module may be used as a generator\n";
634 $moduleDescriptions[] = $msg;
637 return implode( "\n", $moduleDescriptions );
641 * Override to add extra parameters from PageSet
642 * @return string
644 public function makeHelpMsgParameters() {
645 $psModule = new ApiPageSet( $this );
646 return $psModule->makeHelpMsgParameters() . parent::makeHelpMsgParameters();
649 public function shouldCheckMaxlag() {
650 return true;
653 public function getParamDescription() {
654 return array(
655 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
656 'list' => 'Which lists to get. Module help is available below',
657 'meta' => 'Which metadata to get about the site. Module help is available below',
658 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
659 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
660 'redirects' => 'Automatically resolve redirects',
661 'converttitles' => array( "Convert titles to other variants if necessary. Only works if the wiki's content language supports variant conversion.",
662 'Languages that support variant conversion include kk, ku, gan, tg, sr, zh' ),
663 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
664 'export' => 'Export the current revisions of all given or generated pages',
665 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
669 public function getDescription() {
670 return array(
671 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
672 'and is loosely based on the old query.php interface.',
673 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
677 public function getPossibleErrors() {
678 return array_merge( parent::getPossibleErrors(), array(
679 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
680 ) );
683 protected function getExamples() {
684 return array(
685 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
686 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
690 public function getVersion() {
691 $psModule = new ApiPageSet( $this );
692 $vers = array();
693 $vers[] = __CLASS__ . ': $Id$';
694 $vers[] = $psModule->getVersion();
695 return $vers;