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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
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.
43 class ApiQuery extends ApiBase {
45 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
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 'stashimageinfo' => 'ApiQueryStashImageInfo',
58 'templates' => 'ApiQueryLinks',
59 'categories' => 'ApiQueryCategories',
60 'extlinks' => 'ApiQueryExternalLinks',
61 'categoryinfo' => 'ApiQueryCategoryInfo',
62 'duplicatefiles' => 'ApiQueryDuplicateFiles',
63 'pageprops' => 'ApiQueryPageProps',
66 private $mQueryListModules = array(
67 'allimages' => 'ApiQueryAllimages',
68 'allpages' => 'ApiQueryAllpages',
69 'alllinks' => 'ApiQueryAllLinks',
70 'allcategories' => 'ApiQueryAllCategories',
71 'allusers' => 'ApiQueryAllUsers',
72 'backlinks' => 'ApiQueryBacklinks',
73 'blocks' => 'ApiQueryBlocks',
74 'categorymembers' => 'ApiQueryCategoryMembers',
75 'deletedrevs' => 'ApiQueryDeletedrevs',
76 'embeddedin' => 'ApiQueryBacklinks',
77 'filearchive' => 'ApiQueryFilearchive',
78 'imageusage' => 'ApiQueryBacklinks',
79 'iwbacklinks' => 'ApiQueryIWBacklinks',
80 'logevents' => 'ApiQueryLogEvents',
81 'recentchanges' => 'ApiQueryRecentChanges',
82 'search' => 'ApiQuerySearch',
83 'tags' => 'ApiQueryTags',
84 'usercontribs' => 'ApiQueryContributions',
85 'watchlist' => 'ApiQueryWatchlist',
86 'watchlistraw' => 'ApiQueryWatchlistRaw',
87 'exturlusage' => 'ApiQueryExtLinksUsage',
88 'users' => 'ApiQueryUsers',
89 'random' => 'ApiQueryRandom',
90 'protectedtitles' => 'ApiQueryProtectedTitles',
93 private $mQueryMetaModules = array(
94 'siteinfo' => 'ApiQuerySiteinfo',
95 'userinfo' => 'ApiQueryUserInfo',
96 'allmessages' => 'ApiQueryAllmessages',
99 private $mSlaveDB = null;
100 private $mNamedDB = array();
102 public function __construct( $main, $action ) {
103 parent::__construct( $main, $action );
105 // Allow custom modules to be added in LocalSettings.php
106 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
107 self::appendUserModules( $this->mQueryPropModules, $wgAPIPropModules );
108 self::appendUserModules( $this->mQueryListModules, $wgAPIListModules );
109 self::appendUserModules( $this->mQueryMetaModules, $wgAPIMetaModules );
111 $this->mPropModuleNames = array_keys( $this->mQueryPropModules );
112 $this->mListModuleNames = array_keys( $this->mQueryListModules );
113 $this->mMetaModuleNames = array_keys( $this->mQueryMetaModules );
115 // Allow the entire list of modules at first,
116 // but during module instantiation check if it can be used as a generator.
117 $this->mAllowedGenerators = array_merge( $this->mListModuleNames, $this->mPropModuleNames );
121 * Helper function to append any add-in modules to the list
122 * @param $modules array Module array
123 * @param $newModules array Module array to add to $modules
125 private static function appendUserModules( &$modules, $newModules ) {
126 if ( is_array( $newModules ) ) {
127 foreach ( $newModules as $moduleName => $moduleClass ) {
128 $modules[$moduleName] = $moduleClass;
134 * Gets a default slave database connection object
137 public function getDB() {
138 if ( !isset( $this->mSlaveDB ) ) {
139 $this->profileDBIn();
140 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
141 $this->profileDBOut();
143 return $this->mSlaveDB;
147 * Get the query database connection with the given name.
148 * If no such connection has been requested before, it will be created.
149 * Subsequent calls with the same $name will return the same connection
150 * as the first, regardless of the values of $db and $groups
151 * @param $name string Name to assign to the database connection
152 * @param $db int One of the DB_* constants
153 * @param $groups array Query groups
156 public function getNamedDB( $name, $db, $groups ) {
157 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
158 $this->profileDBIn();
159 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
160 $this->profileDBOut();
162 return $this->mNamedDB[$name];
166 * Gets the set of pages the user has requested (or generated)
169 public function getPageSet() {
170 return $this->mPageSet;
174 * Get the array mapping module names to class names
175 * @return array(modulename => classname)
177 function getModules() {
178 return array_merge( $this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules );
182 * Get whether the specified module is a prop, list or a meta query module
183 * @param $moduleName string Name of the module to find type for
184 * @return mixed string or null
186 function getModuleType( $moduleName ) {
187 if ( array_key_exists ( $moduleName, $this->mQueryPropModules ) ) {
191 if ( array_key_exists ( $moduleName, $this->mQueryListModules ) ) {
195 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules ) ) {
202 public function getCustomPrinter() {
203 // If &exportnowrap is set, use the raw formatter
204 if ( $this->getParameter( 'export' ) &&
205 $this->getParameter( 'exportnowrap' ) )
207 return new ApiFormatRaw( $this->getMain(),
208 $this->getMain()->createPrinterByName( 'xml' ) );
215 * Query execution happens in the following steps:
216 * #1 Create a PageSet object with any pages requested by the user
217 * #2 If using a generator, execute it to get a new ApiPageSet object
218 * #3 Instantiate all requested modules.
219 * This way the PageSet object will know what shared data is required,
220 * and minimize DB calls.
221 * #4 Output all normalization and redirect resolution information
222 * #5 Execute all requested modules
224 public function execute() {
225 $this->params = $this->extractRequestParams();
226 $this->redirects = $this->params['redirects'];
227 $this->convertTitles = $this->params['converttitles'];
230 $this->mPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
232 // Instantiate requested modules
234 $this->instantiateModules( $modules, 'prop', $this->mQueryPropModules );
235 $this->instantiateModules( $modules, 'list', $this->mQueryListModules );
236 $this->instantiateModules( $modules, 'meta', $this->mQueryMetaModules );
238 $cacheMode = 'public';
240 // If given, execute generator to substitute user supplied data with generated data.
241 if ( isset( $this->params['generator'] ) ) {
242 $generator = $this->newGenerator( $this->params['generator'] );
243 $params = $generator->extractRequestParams();
244 $cacheMode = $this->mergeCacheMode( $cacheMode,
245 $generator->getCacheMode( $params ) );
246 $this->executeGeneratorModule( $generator, $modules );
248 // Append custom fields and populate page/revision information
249 $this->addCustomFldsToPageSet( $modules, $this->mPageSet );
250 $this->mPageSet->execute();
253 // Record page information (title, namespace, if exists, etc)
254 $this->outputGeneralPageInfo();
256 // Execute all requested modules.
257 foreach ( $modules as $module ) {
258 $params = $module->extractRequestParams();
259 $cacheMode = $this->mergeCacheMode(
260 $cacheMode, $module->getCacheMode( $params ) );
261 $module->profileIn();
263 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
264 $module->profileOut();
267 // Set the cache mode
268 $this->getMain()->setCacheMode( $cacheMode );
272 * Update a cache mode string, applying the cache mode of a new module to it.
273 * The cache mode may increase in the level of privacy, but public modules
274 * added to private data do not decrease the level of privacy.
276 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
277 if ( $modCacheMode === 'anon-public-user-private' ) {
278 if ( $cacheMode !== 'private' ) {
279 $cacheMode = 'anon-public-user-private';
281 } elseif ( $modCacheMode === 'public' ) {
282 // do nothing, if it's public already it will stay public
284 $cacheMode = 'private';
290 * Query modules may optimize data requests through the $this->getPageSet() object
291 * by adding extra fields from the page table.
292 * This function will gather all the extra request fields from the modules.
293 * @param $modules array of module objects
294 * @param $pageSet ApiPageSet
296 private function addCustomFldsToPageSet( $modules, $pageSet ) {
297 // Query all requested modules.
298 foreach ( $modules as $module ) {
299 $module->requestExtraData( $pageSet );
304 * Create instances of all modules requested by the client
305 * @param $modules Array to append instantiated modules to
306 * @param $param string Parameter name to read modules from
307 * @param $moduleList Array array(modulename => classname)
309 private function instantiateModules( &$modules, $param, $moduleList ) {
310 $list = @$this->params[$param];
311 if ( !is_null ( $list ) ) {
312 foreach ( $list as $moduleName ) {
313 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
319 * Appends an element for each page in the current pageSet with the
320 * most general information (id, title), plus any title normalizations
321 * and missing or invalid title/pageids/revids.
323 private function outputGeneralPageInfo() {
324 $pageSet = $this->getPageSet();
325 $result = $this->getResult();
327 // We don't check for a full result set here because we can't be adding
328 // more than 380K. The maximum revision size is in the megabyte range,
329 // and the maximum result size must be even higher than that.
331 // Title normalizations
332 $normValues = array();
333 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
334 $normValues[] = array(
335 'from' => $rawTitleStr,
340 if ( count( $normValues ) ) {
341 $result->setIndexedTagName( $normValues, 'n' );
342 $result->addValue( 'query', 'normalized', $normValues );
346 $convValues = array();
347 foreach ( $pageSet->getConvertedTitles() as $rawTitleStr => $titleStr ) {
348 $convValues[] = array(
349 'from' => $rawTitleStr,
354 if ( count( $convValues ) ) {
355 $result->setIndexedTagName( $convValues, 'c' );
356 $result->addValue( 'query', 'converted', $convValues );
360 $intrwValues = array();
361 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
362 $intrwValues[] = array(
363 'title' => $rawTitleStr,
364 'iw' => $interwikiStr
368 if ( count( $intrwValues ) ) {
369 $result->setIndexedTagName( $intrwValues, 'i' );
370 $result->addValue( 'query', 'interwiki', $intrwValues );
373 // Show redirect information
374 $redirValues = array();
375 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
376 $redirValues[] = array(
377 'from' => strval( $titleStrFrom ),
382 if ( count( $redirValues ) ) {
383 $result->setIndexedTagName( $redirValues, 'r' );
384 $result->addValue( 'query', 'redirects', $redirValues );
387 // Missing revision elements
388 $missingRevIDs = $pageSet->getMissingRevisionIDs();
389 if ( count( $missingRevIDs ) ) {
391 foreach ( $missingRevIDs as $revid ) {
392 $revids[$revid] = array(
396 $result->setIndexedTagName( $revids, 'rev' );
397 $result->addValue( 'query', 'badrevids', $revids );
403 // Report any missing titles
404 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
406 ApiQueryBase::addTitleInfo( $vals, $title );
407 $vals['missing'] = '';
408 $pages[$fakeId] = $vals;
410 // Report any invalid titles
411 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
412 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
414 // Report any missing page ids
415 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
416 $pages[$pageid] = array(
421 // Report special pages
422 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
424 ApiQueryBase::addTitleInfo( $vals, $title );
425 $vals['special'] = '';
426 if ( $title->getNamespace() == NS_SPECIAL &&
427 !SpecialPage::exists( $title->getDbKey() ) ) {
428 $vals['missing'] = '';
429 } elseif ( $title->getNamespace() == NS_MEDIA &&
430 !wfFindFile( $title ) ) {
431 $vals['missing'] = '';
433 $pages[$fakeId] = $vals;
436 // Output general page information for found titles
437 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
439 $vals['pageid'] = $pageid;
440 ApiQueryBase::addTitleInfo( $vals, $title );
441 $pages[$pageid] = $vals;
444 if ( count( $pages ) ) {
445 if ( $this->params['indexpageids'] ) {
446 $pageIDs = array_keys( $pages );
447 // json treats all map keys as strings - converting to match
448 $pageIDs = array_map( 'strval', $pageIDs );
449 $result->setIndexedTagName( $pageIDs, 'id' );
450 $result->addValue( 'query', 'pageids', $pageIDs );
453 $result->setIndexedTagName( $pages, 'page' );
454 $result->addValue( 'query', 'pages', $pages );
456 if ( $this->params['export'] ) {
457 $this->doExport( $pageSet, $result );
462 * @param $pageSet ApiPageSet Pages to be exported
463 * @param $result ApiResult Result to output to
465 private function doExport( $pageSet, $result ) {
466 $exportTitles = array();
467 $titles = $pageSet->getGoodTitles();
468 if( count( $titles ) ) {
469 foreach ( $titles as $title ) {
470 if ( $title->userCanRead() ) {
471 $exportTitles[] = $title;
475 // only export when there are titles
476 if ( !count( $exportTitles ) ) {
480 $exporter = new WikiExporter( $this->getDB() );
481 // WikiExporter writes to stdout, so catch its
484 $exporter->openStream();
485 foreach ( $exportTitles as $title ) {
486 $exporter->pageByTitle( $title );
488 $exporter->closeStream();
489 $exportxml = ob_get_contents();
492 // Don't check the size of exported stuff
493 // It's not continuable, so it would cause more
494 // problems than it'd solve
495 $result->disableSizeCheck();
496 if ( $this->params['exportnowrap'] ) {
498 // Raw formatter will handle this
499 $result->addValue( null, 'text', $exportxml );
500 $result->addValue( null, 'mime', 'text/xml' );
503 ApiResult::setContent( $r, $exportxml );
504 $result->addValue( 'query', 'export', $r );
506 $result->enableSizeCheck();
510 * Create a generator object of the given type and return it
511 * @param $generatorName string Module name
512 * @return ApiQueryGeneratorBase
514 public function newGenerator( $generatorName ) {
515 // Find class that implements requested generator
516 if ( isset( $this->mQueryListModules[$generatorName] ) ) {
517 $className = $this->mQueryListModules[$generatorName];
518 } elseif ( isset( $this->mQueryPropModules[$generatorName] ) ) {
519 $className = $this->mQueryPropModules[$generatorName];
521 ApiBase::dieDebug( __METHOD__, "Unknown generator=$generatorName" );
523 $generator = new $className ( $this, $generatorName );
524 if ( !$generator instanceof ApiQueryGeneratorBase ) {
525 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
527 $generator->setGeneratorMode();
532 * For generator mode, execute generator, and use its output as new
534 * @param $generator ApiQueryGeneratorBase Generator Module
535 * @param $modules array of module objects
537 protected function executeGeneratorModule( $generator, $modules ) {
539 $resultPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
541 // Add any additional fields modules may need
542 $generator->requestExtraData( $this->mPageSet );
543 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
545 // Populate page information with the original user input
546 $this->mPageSet->execute();
548 // populate resultPageSet with the generator output
549 $generator->profileIn();
550 $generator->executeGenerator( $resultPageSet );
551 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
552 $resultPageSet->finishPageSetGeneration();
553 $generator->profileOut();
555 // Swap the resulting pageset back in
556 $this->mPageSet = $resultPageSet;
559 public function getAllowedParams() {
562 ApiBase::PARAM_ISMULTI => true,
563 ApiBase::PARAM_TYPE => $this->mPropModuleNames
566 ApiBase::PARAM_ISMULTI => true,
567 ApiBase::PARAM_TYPE => $this->mListModuleNames
570 ApiBase::PARAM_ISMULTI => true,
571 ApiBase::PARAM_TYPE => $this->mMetaModuleNames
573 'generator' => array(
574 ApiBase::PARAM_TYPE => $this->mAllowedGenerators
576 'redirects' => false,
577 'converttitles' => false,
578 'indexpageids' => false,
580 'exportnowrap' => false,
585 * Override the parent to generate help messages for all available query modules.
588 public function makeHelpMsg() {
591 // Make sure the internal object is empty
592 // (just in case a sub-module decides to optimize during instantiation)
593 $this->mPageSet = null;
594 $this->mAllowedGenerators = array(); // Will be repopulated
596 $querySeparator = str_repeat( '--- ', 8 );
597 $moduleSeparator = str_repeat( '*** ', 10 );
598 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
599 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules, 'prop' );
600 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
601 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules, 'list' );
602 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
603 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules, 'meta' );
604 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
606 // Perform the base call last because the $this->mAllowedGenerators
607 // will be updated inside makeHelpMsgHelper()
608 // Use parent to make default message for the query module
609 $msg = parent::makeHelpMsg() . $msg;
615 * For all modules in $moduleList, generate help messages and join them together
616 * @param $moduleList Array array(modulename => classname)
617 * @param $paramName string Parameter name
620 private function makeHelpMsgHelper( $moduleList, $paramName ) {
621 $moduleDescriptions = array();
623 foreach ( $moduleList as $moduleName => $moduleClass ) {
624 $module = new $moduleClass ( $this, $moduleName, null );
626 $msg = ApiMain::makeHelpMsgHeader( $module, $paramName );
627 $msg2 = $module->makeHelpMsg();
628 if ( $msg2 !== false ) {
631 if ( $module instanceof ApiQueryGeneratorBase ) {
632 $this->mAllowedGenerators[] = $moduleName;
633 $msg .= "Generator:\n This module may be used as a generator\n";
635 $moduleDescriptions[] = $msg;
638 return implode( "\n", $moduleDescriptions );
642 * Override to add extra parameters from PageSet
645 public function makeHelpMsgParameters() {
646 $psModule = new ApiPageSet( $this );
647 return $psModule->makeHelpMsgParameters() . parent::makeHelpMsgParameters();
650 public function shouldCheckMaxlag() {
654 public function getParamDescription() {
656 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
657 'list' => 'Which lists to get. Module help is available below',
658 'meta' => 'Which metadata to get about the site. Module help is available below',
659 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
660 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
661 'redirects' => 'Automatically resolve redirects',
662 'converttitles' => array( "Convert titles to other variants if necessary. Only works if the wiki's content language supports variant conversion.",
663 'Languages that support variant conversion include kk, ku, gan, tg, sr, zh' ),
664 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
665 'export' => 'Export the current revisions of all given or generated pages',
666 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
670 public function getDescription() {
672 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
673 'and is loosely based on the old query.php interface.',
674 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
678 public function getPossibleErrors() {
679 return array_merge( parent::getPossibleErrors(), array(
680 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
684 protected function getExamples() {
686 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
687 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
691 public function getVersion() {
692 $psModule = new ApiPageSet( $this );
694 $vers[] = __CLASS__ . ': $Id$';
695 $vers[] = $psModule->getVersion();