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
{
40 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
47 private $params, $redirects, $convertTitles, $iwUrl;
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 'langbacklinks' => 'ApiQueryLangBacklinks',
81 'logevents' => 'ApiQueryLogEvents',
82 'recentchanges' => 'ApiQueryRecentChanges',
83 'search' => 'ApiQuerySearch',
84 'tags' => 'ApiQueryTags',
85 'usercontribs' => 'ApiQueryContributions',
86 'watchlist' => 'ApiQueryWatchlist',
87 'watchlistraw' => 'ApiQueryWatchlistRaw',
88 'exturlusage' => 'ApiQueryExtLinksUsage',
89 'users' => 'ApiQueryUsers',
90 'random' => 'ApiQueryRandom',
91 'protectedtitles' => 'ApiQueryProtectedTitles',
92 'querypage' => 'ApiQueryQueryPage',
95 private $mQueryMetaModules = array(
96 'siteinfo' => 'ApiQuerySiteinfo',
97 'userinfo' => 'ApiQueryUserInfo',
98 'allmessages' => 'ApiQueryAllMessages',
101 private $mSlaveDB = null;
102 private $mNamedDB = array();
104 protected $mAllowedGenerators = array();
107 * @param $main ApiMain
108 * @param $action string
110 public function __construct( $main, $action ) {
111 parent
::__construct( $main, $action );
113 // Allow custom modules to be added in LocalSettings.php
114 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
115 self
::appendUserModules( $this->mQueryPropModules
, $wgAPIPropModules );
116 self
::appendUserModules( $this->mQueryListModules
, $wgAPIListModules );
117 self
::appendUserModules( $this->mQueryMetaModules
, $wgAPIMetaModules );
119 $this->mPropModuleNames
= array_keys( $this->mQueryPropModules
);
120 $this->mListModuleNames
= array_keys( $this->mQueryListModules
);
121 $this->mMetaModuleNames
= array_keys( $this->mQueryMetaModules
);
125 * Helper function to append any add-in modules to the list
126 * @param $modules array Module array
127 * @param $newModules array Module array to add to $modules
129 private static function appendUserModules( &$modules, $newModules ) {
130 if ( is_array( $newModules ) ) {
131 foreach ( $newModules as $moduleName => $moduleClass ) {
132 $modules[$moduleName] = $moduleClass;
138 * Gets a default slave database connection object
139 * @return DatabaseBase
141 public function getDB() {
142 if ( !isset( $this->mSlaveDB
) ) {
143 $this->profileDBIn();
144 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
145 $this->profileDBOut();
147 return $this->mSlaveDB
;
151 * Get the query database connection with the given name.
152 * If no such connection has been requested before, it will be created.
153 * Subsequent calls with the same $name will return the same connection
154 * as the first, regardless of the values of $db and $groups
155 * @param $name string Name to assign to the database connection
156 * @param $db int One of the DB_* constants
157 * @param $groups array Query groups
158 * @return DatabaseBase
160 public function getNamedDB( $name, $db, $groups ) {
161 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
162 $this->profileDBIn();
163 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
164 $this->profileDBOut();
166 return $this->mNamedDB
[$name];
170 * Gets the set of pages the user has requested (or generated)
173 public function getPageSet() {
174 return $this->mPageSet
;
178 * Get the array mapping module names to class names
179 * @return array array(modulename => classname)
181 function getModules() {
182 return array_merge( $this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
186 * Get whether the specified module is a prop, list or a meta query module
187 * @param $moduleName string Name of the module to find type for
188 * @return mixed string or null
190 function getModuleType( $moduleName ) {
191 if ( isset( $this->mQueryPropModules
[$moduleName] ) ) {
195 if ( isset( $this->mQueryListModules
[$moduleName] ) ) {
199 if ( isset( $this->mQueryMetaModules
[$moduleName] ) ) {
207 * @return ApiFormatRaw|null
209 public function getCustomPrinter() {
210 // If &exportnowrap is set, use the raw formatter
211 if ( $this->getParameter( 'export' ) &&
212 $this->getParameter( 'exportnowrap' ) )
214 return new ApiFormatRaw( $this->getMain(),
215 $this->getMain()->createPrinterByName( 'xml' ) );
222 * Query execution happens in the following steps:
223 * #1 Create a PageSet object with any pages requested by the user
224 * #2 If using a generator, execute it to get a new ApiPageSet object
225 * #3 Instantiate all requested modules.
226 * This way the PageSet object will know what shared data is required,
227 * and minimize DB calls.
228 * #4 Output all normalization and redirect resolution information
229 * #5 Execute all requested modules
231 public function execute() {
232 $this->params
= $this->extractRequestParams();
233 $this->redirects
= $this->params
['redirects'];
234 $this->convertTitles
= $this->params
['converttitles'];
235 $this->iwUrl
= $this->params
['iwurl'];
238 $this->mPageSet
= new ApiPageSet( $this, $this->redirects
, $this->convertTitles
);
240 // Instantiate requested modules
242 $this->instantiateModules( $modules, 'prop', $this->mQueryPropModules
);
243 $this->instantiateModules( $modules, 'list', $this->mQueryListModules
);
244 $this->instantiateModules( $modules, 'meta', $this->mQueryMetaModules
);
246 $cacheMode = 'public';
248 // If given, execute generator to substitute user supplied data with generated data.
249 if ( isset( $this->params
['generator'] ) ) {
250 $generator = $this->newGenerator( $this->params
['generator'] );
251 $params = $generator->extractRequestParams();
252 $cacheMode = $this->mergeCacheMode( $cacheMode,
253 $generator->getCacheMode( $params ) );
254 $this->executeGeneratorModule( $generator, $modules );
256 // Append custom fields and populate page/revision information
257 $this->addCustomFldsToPageSet( $modules, $this->mPageSet
);
258 $this->mPageSet
->execute();
261 // Record page information (title, namespace, if exists, etc)
262 $this->outputGeneralPageInfo();
264 // Execute all requested modules.
266 * @var $module ApiQueryBase
268 foreach ( $modules as $module ) {
269 $params = $module->extractRequestParams();
270 $cacheMode = $this->mergeCacheMode(
271 $cacheMode, $module->getCacheMode( $params ) );
272 $module->profileIn();
274 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
275 $module->profileOut();
278 // Set the cache mode
279 $this->getMain()->setCacheMode( $cacheMode );
283 * Update a cache mode string, applying the cache mode of a new module to it.
284 * The cache mode may increase in the level of privacy, but public modules
285 * added to private data do not decrease the level of privacy.
287 * @param $cacheMode string
288 * @param $modCacheMode string
291 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
292 if ( $modCacheMode === 'anon-public-user-private' ) {
293 if ( $cacheMode !== 'private' ) {
294 $cacheMode = 'anon-public-user-private';
296 } elseif ( $modCacheMode === 'public' ) {
297 // do nothing, if it's public already it will stay public
299 $cacheMode = 'private';
305 * Query modules may optimize data requests through the $this->getPageSet() object
306 * by adding extra fields from the page table.
307 * This function will gather all the extra request fields from the modules.
308 * @param $modules array of module objects
309 * @param $pageSet ApiPageSet
311 private function addCustomFldsToPageSet( $modules, $pageSet ) {
312 // Query all requested modules.
314 * @var $module ApiQueryBase
316 foreach ( $modules as $module ) {
317 $module->requestExtraData( $pageSet );
322 * Create instances of all modules requested by the client
323 * @param $modules Array to append instantiated modules to
324 * @param $param string Parameter name to read modules from
325 * @param $moduleList Array array(modulename => classname)
327 private function instantiateModules( &$modules, $param, $moduleList ) {
328 if ( isset( $this->params
[$param] ) ) {
329 foreach ( $this->params
[$param] as $moduleName ) {
330 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
336 * Appends an element for each page in the current pageSet with the
337 * most general information (id, title), plus any title normalizations
338 * and missing or invalid title/pageids/revids.
340 private function outputGeneralPageInfo() {
341 $pageSet = $this->getPageSet();
342 $result = $this->getResult();
344 // We don't check for a full result set here because we can't be adding
345 // more than 380K. The maximum revision size is in the megabyte range,
346 // and the maximum result size must be even higher than that.
348 // Title normalizations
349 $normValues = array();
350 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
351 $normValues[] = array(
352 'from' => $rawTitleStr,
357 if ( count( $normValues ) ) {
358 $result->setIndexedTagName( $normValues, 'n' );
359 $result->addValue( 'query', 'normalized', $normValues );
363 $convValues = array();
364 foreach ( $pageSet->getConvertedTitles() as $rawTitleStr => $titleStr ) {
365 $convValues[] = array(
366 'from' => $rawTitleStr,
371 if ( count( $convValues ) ) {
372 $result->setIndexedTagName( $convValues, 'c' );
373 $result->addValue( 'query', 'converted', $convValues );
377 $intrwValues = array();
378 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
380 'title' => $rawTitleStr,
381 'iw' => $interwikiStr,
383 if ( $this->iwUrl
) {
384 $title = Title
::newFromText( $rawTitleStr );
385 $item['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
387 $intrwValues[] = $item;
390 if ( count( $intrwValues ) ) {
391 $result->setIndexedTagName( $intrwValues, 'i' );
392 $result->addValue( 'query', 'interwiki', $intrwValues );
395 // Show redirect information
396 $redirValues = array();
398 * @var $titleTo Title
400 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleTo ) {
402 'from' => strval( $titleStrFrom ),
403 'to' => $titleTo->getPrefixedText(),
405 if ( $titleTo->getFragment() !== '' ) {
406 $r['tofragment'] = $titleTo->getFragment();
411 if ( count( $redirValues ) ) {
412 $result->setIndexedTagName( $redirValues, 'r' );
413 $result->addValue( 'query', 'redirects', $redirValues );
416 // Missing revision elements
417 $missingRevIDs = $pageSet->getMissingRevisionIDs();
418 if ( count( $missingRevIDs ) ) {
420 foreach ( $missingRevIDs as $revid ) {
421 $revids[$revid] = array(
425 $result->setIndexedTagName( $revids, 'rev' );
426 $result->addValue( 'query', 'badrevids', $revids );
432 // Report any missing titles
433 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
435 ApiQueryBase
::addTitleInfo( $vals, $title );
436 $vals['missing'] = '';
437 $pages[$fakeId] = $vals;
439 // Report any invalid titles
440 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
441 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
443 // Report any missing page ids
444 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
445 $pages[$pageid] = array(
450 // Report special pages
451 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
453 ApiQueryBase
::addTitleInfo( $vals, $title );
454 $vals['special'] = '';
455 if ( $title->isSpecialPage() &&
456 !SpecialPageFactory
::exists( $title->getDbKey() ) ) {
457 $vals['missing'] = '';
458 } elseif ( $title->getNamespace() == NS_MEDIA
&&
459 !wfFindFile( $title ) ) {
460 $vals['missing'] = '';
462 $pages[$fakeId] = $vals;
465 // Output general page information for found titles
466 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
468 $vals['pageid'] = $pageid;
469 ApiQueryBase
::addTitleInfo( $vals, $title );
470 $pages[$pageid] = $vals;
473 if ( count( $pages ) ) {
474 if ( $this->params
['indexpageids'] ) {
475 $pageIDs = array_keys( $pages );
476 // json treats all map keys as strings - converting to match
477 $pageIDs = array_map( 'strval', $pageIDs );
478 $result->setIndexedTagName( $pageIDs, 'id' );
479 $result->addValue( 'query', 'pageids', $pageIDs );
482 $result->setIndexedTagName( $pages, 'page' );
483 $result->addValue( 'query', 'pages', $pages );
485 if ( $this->params
['export'] ) {
486 $this->doExport( $pageSet, $result );
491 * @param $pageSet ApiPageSet Pages to be exported
492 * @param $result ApiResult Result to output to
494 private function doExport( $pageSet, $result ) {
495 $exportTitles = array();
496 $titles = $pageSet->getGoodTitles();
497 if ( count( $titles ) ) {
498 foreach ( $titles as $title ) {
499 if ( $title->userCan( 'read' ) ) {
500 $exportTitles[] = $title;
505 $exporter = new WikiExporter( $this->getDB() );
506 // WikiExporter writes to stdout, so catch its
509 $exporter->openStream();
510 foreach ( $exportTitles as $title ) {
511 $exporter->pageByTitle( $title );
513 $exporter->closeStream();
514 $exportxml = ob_get_contents();
517 // Don't check the size of exported stuff
518 // It's not continuable, so it would cause more
519 // problems than it'd solve
520 $result->disableSizeCheck();
521 if ( $this->params
['exportnowrap'] ) {
523 // Raw formatter will handle this
524 $result->addValue( null, 'text', $exportxml );
525 $result->addValue( null, 'mime', 'text/xml' );
528 ApiResult
::setContent( $r, $exportxml );
529 $result->addValue( 'query', 'export', $r );
531 $result->enableSizeCheck();
535 * Create a generator object of the given type and return it
536 * @param $generatorName string Module name
537 * @return ApiQueryGeneratorBase
539 public function newGenerator( $generatorName ) {
540 // Find class that implements requested generator
541 if ( isset( $this->mQueryListModules
[$generatorName] ) ) {
542 $className = $this->mQueryListModules
[$generatorName];
543 } elseif ( isset( $this->mQueryPropModules
[$generatorName] ) ) {
544 $className = $this->mQueryPropModules
[$generatorName];
546 ApiBase
::dieDebug( __METHOD__
, "Unknown generator=$generatorName" );
548 $generator = new $className ( $this, $generatorName );
549 if ( !$generator instanceof ApiQueryGeneratorBase
) {
550 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
552 $generator->setGeneratorMode();
557 * For generator mode, execute generator, and use its output as new
559 * @param $generator ApiQueryGeneratorBase Generator Module
560 * @param $modules array of module objects
562 protected function executeGeneratorModule( $generator, $modules ) {
564 $resultPageSet = new ApiPageSet( $this, $this->redirects
, $this->convertTitles
);
566 // Add any additional fields modules may need
567 $generator->requestExtraData( $this->mPageSet
);
568 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
570 // Populate page information with the original user input
571 $this->mPageSet
->execute();
573 // populate resultPageSet with the generator output
574 $generator->profileIn();
575 $generator->executeGenerator( $resultPageSet );
576 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
577 $resultPageSet->finishPageSetGeneration();
578 $generator->profileOut();
580 // Swap the resulting pageset back in
581 $this->mPageSet
= $resultPageSet;
584 public function getAllowedParams() {
587 ApiBase
::PARAM_ISMULTI
=> true,
588 ApiBase
::PARAM_TYPE
=> $this->mPropModuleNames
591 ApiBase
::PARAM_ISMULTI
=> true,
592 ApiBase
::PARAM_TYPE
=> $this->mListModuleNames
595 ApiBase
::PARAM_ISMULTI
=> true,
596 ApiBase
::PARAM_TYPE
=> $this->mMetaModuleNames
598 'generator' => array(
599 ApiBase
::PARAM_TYPE
=> $this->mAllowedGenerators
601 'redirects' => false,
602 'converttitles' => false,
603 'indexpageids' => false,
605 'exportnowrap' => false,
611 * Override the parent to generate help messages for all available query modules.
614 public function makeHelpMsg() {
615 // Make sure the internal object is empty
616 // (just in case a sub-module decides to optimize during instantiation)
617 $this->mPageSet
= null;
618 $this->mAllowedGenerators
= array(); // Will be repopulated
620 $querySeparator = str_repeat( '--- ', 12 );
621 $moduleSeparator = str_repeat( '*** ', 14 );
622 $msg = "\n$querySeparator Query: Prop $querySeparator\n\n";
623 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules
, 'prop' );
624 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
625 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules
, 'list' );
626 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
627 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules
, 'meta' );
628 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
630 // Perform the base call last because the $this->mAllowedGenerators
631 // will be updated inside makeHelpMsgHelper()
632 // Use parent to make default message for the query module
633 $msg = parent
::makeHelpMsg() . $msg;
639 * For all modules in $moduleList, generate help messages and join them together
640 * @param $moduleList Array array(modulename => classname)
641 * @param $paramName string Parameter name
644 private function makeHelpMsgHelper( $moduleList, $paramName ) {
645 $moduleDescriptions = array();
647 foreach ( $moduleList as $moduleName => $moduleClass ) {
649 * @var $module ApiQueryBase
651 $module = new $moduleClass( $this, $moduleName, null );
653 $msg = ApiMain
::makeHelpMsgHeader( $module, $paramName );
654 $msg2 = $module->makeHelpMsg();
655 if ( $msg2 !== false ) {
658 if ( $module instanceof ApiQueryGeneratorBase
) {
659 $this->mAllowedGenerators
[] = $moduleName;
660 $msg .= "Generator:\n This module may be used as a generator\n";
662 $moduleDescriptions[] = $msg;
665 return implode( "\n", $moduleDescriptions );
669 * Override to add extra parameters from PageSet
672 public function makeHelpMsgParameters() {
673 $psModule = new ApiPageSet( $this );
674 return $psModule->makeHelpMsgParameters() . parent
::makeHelpMsgParameters();
677 public function shouldCheckMaxlag() {
681 public function getParamDescription() {
683 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
684 'list' => 'Which lists to get. Module help is available below',
685 'meta' => 'Which metadata to get about the site. Module help is available below',
686 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
687 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
688 'redirects' => 'Automatically resolve redirects',
689 'converttitles' => array( "Convert titles to other variants if necessary. Only works if the wiki's content language supports variant conversion.",
690 'Languages that support variant conversion include ' . implode( ', ', LanguageConverter
::$languagesWithVariants ) ),
691 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
692 'export' => 'Export the current revisions of all given or generated pages',
693 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
694 'iwurl' => 'Whether to get the full URL if the title is an interwiki link',
698 public function getDescription() {
700 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
701 'and is loosely based on the old query.php interface.',
702 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
706 public function getPossibleErrors() {
707 return array_merge( parent
::getPossibleErrors(), array(
708 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
712 public function getExamples() {
714 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
715 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
719 public function getHelpUrls() {
721 'https://www.mediawiki.org/wiki/API:Meta',
722 'https://www.mediawiki.org/wiki/API:Properties',
723 'https://www.mediawiki.org/wiki/API:Lists',
727 public function getVersion() {
728 $psModule = new ApiPageSet( $this );
730 $vers[] = __CLASS__
. ': $Id$';
731 $vers[] = $psModule->getVersion();