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
{
41 * List of Api Query prop modules
44 private static $QueryPropModules = array(
45 'categories' => 'ApiQueryCategories',
46 'categoryinfo' => 'ApiQueryCategoryInfo',
47 'duplicatefiles' => 'ApiQueryDuplicateFiles',
48 'extlinks' => 'ApiQueryExternalLinks',
49 'images' => 'ApiQueryImages',
50 'imageinfo' => 'ApiQueryImageInfo',
51 'info' => 'ApiQueryInfo',
52 'links' => 'ApiQueryLinks',
53 'iwlinks' => 'ApiQueryIWLinks',
54 'langlinks' => 'ApiQueryLangLinks',
55 'pageprops' => 'ApiQueryPageProps',
56 'revisions' => 'ApiQueryRevisions',
57 'stashimageinfo' => 'ApiQueryStashImageInfo',
58 'templates' => 'ApiQueryLinks',
62 * List of Api Query list modules
65 private static $QueryListModules = array(
66 'allcategories' => 'ApiQueryAllCategories',
67 'allimages' => 'ApiQueryAllImages',
68 'alllinks' => 'ApiQueryAllLinks',
69 'allpages' => 'ApiQueryAllPages',
70 'alltransclusions' => 'ApiQueryAllLinks',
71 'allusers' => 'ApiQueryAllUsers',
72 'backlinks' => 'ApiQueryBacklinks',
73 'blocks' => 'ApiQueryBlocks',
74 'categorymembers' => 'ApiQueryCategoryMembers',
75 'deletedrevs' => 'ApiQueryDeletedrevs',
76 'embeddedin' => 'ApiQueryBacklinks',
77 'exturlusage' => 'ApiQueryExtLinksUsage',
78 'filearchive' => 'ApiQueryFilearchive',
79 'imageusage' => 'ApiQueryBacklinks',
80 'iwbacklinks' => 'ApiQueryIWBacklinks',
81 'langbacklinks' => 'ApiQueryLangBacklinks',
82 'logevents' => 'ApiQueryLogEvents',
83 'protectedtitles' => 'ApiQueryProtectedTitles',
84 'querypage' => 'ApiQueryQueryPage',
85 'random' => 'ApiQueryRandom',
86 'recentchanges' => 'ApiQueryRecentChanges',
87 'search' => 'ApiQuerySearch',
88 'tags' => 'ApiQueryTags',
89 'usercontribs' => 'ApiQueryContributions',
90 'users' => 'ApiQueryUsers',
91 'watchlist' => 'ApiQueryWatchlist',
92 'watchlistraw' => 'ApiQueryWatchlistRaw',
96 * List of Api Query meta modules
99 private static $QueryMetaModules = array(
100 'allmessages' => 'ApiQueryAllMessages',
101 'siteinfo' => 'ApiQuerySiteinfo',
102 'userinfo' => 'ApiQueryUserInfo',
106 * List of Api Query generator modules
107 * Defined in code, rather than being derived at runtime,
108 * due to performance reasons
111 private $mQueryGenerators = array(
112 'allcategories' => 'ApiQueryAllCategories',
113 'allimages' => 'ApiQueryAllImages',
114 'alllinks' => 'ApiQueryAllLinks',
115 'allpages' => 'ApiQueryAllPages',
116 'alltransclusions' => 'ApiQueryAllLinks',
117 'backlinks' => 'ApiQueryBacklinks',
118 'categories' => 'ApiQueryCategories',
119 'categorymembers' => 'ApiQueryCategoryMembers',
120 'duplicatefiles' => 'ApiQueryDuplicateFiles',
121 'embeddedin' => 'ApiQueryBacklinks',
122 'exturlusage' => 'ApiQueryExtLinksUsage',
123 'images' => 'ApiQueryImages',
124 'imageusage' => 'ApiQueryBacklinks',
125 'iwbacklinks' => 'ApiQueryIWBacklinks',
126 'langbacklinks' => 'ApiQueryLangBacklinks',
127 'links' => 'ApiQueryLinks',
128 'protectedtitles' => 'ApiQueryProtectedTitles',
129 'querypage' => 'ApiQueryQueryPage',
130 'random' => 'ApiQueryRandom',
131 'recentchanges' => 'ApiQueryRecentChanges',
132 'search' => 'ApiQuerySearch',
133 'templates' => 'ApiQueryLinks',
134 'watchlist' => 'ApiQueryWatchlist',
135 'watchlistraw' => 'ApiQueryWatchlistRaw',
145 private $mNamedDB = array();
149 * @param $main ApiMain
150 * @param $action string
152 public function __construct( $main, $action ) {
153 parent
::__construct( $main, $action );
155 $this->mModuleMgr
= new ApiModuleManager( $this );
157 // Allow custom modules to be added in LocalSettings.php
158 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
159 $this->mModuleMgr
->addModules( self
::$QueryPropModules, 'prop' );
160 $this->mModuleMgr
->addModules( $wgAPIPropModules, 'prop' );
161 $this->mModuleMgr
->addModules( self
::$QueryListModules, 'list' );
162 $this->mModuleMgr
->addModules( $wgAPIListModules, 'list' );
163 $this->mModuleMgr
->addModules( self
::$QueryMetaModules, 'meta' );
164 $this->mModuleMgr
->addModules( $wgAPIMetaModules, 'meta' );
166 global $wgAPIGeneratorModules;
167 if ( is_array( $wgAPIGeneratorModules ) ) {
168 foreach ( $wgAPIGeneratorModules as $moduleName => $moduleClass ) {
169 $this->mQueryGenerators
[$moduleName] = $moduleClass;
173 // Create PageSet that will process titles/pageids/revids/generator
174 $this->mPageSet
= new ApiPageSet( $this );
178 * Overrides to return this instance's module manager.
179 * @return ApiModuleManager
181 public function getModuleManager() {
182 return $this->mModuleMgr
;
186 * Get the query database connection with the given name.
187 * If no such connection has been requested before, it will be created.
188 * Subsequent calls with the same $name will return the same connection
189 * as the first, regardless of the values of $db and $groups
190 * @param $name string Name to assign to the database connection
191 * @param $db int One of the DB_* constants
192 * @param $groups array Query groups
193 * @return DatabaseBase
195 public function getNamedDB( $name, $db, $groups ) {
196 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
197 $this->profileDBIn();
198 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
199 $this->profileDBOut();
201 return $this->mNamedDB
[$name];
205 * Gets the set of pages the user has requested (or generated)
208 public function getPageSet() {
209 return $this->mPageSet
;
213 * Get the array mapping module names to class names
214 * @deprecated since 1.21, use getModuleManager()'s methods instead
215 * @return array array(modulename => classname)
217 public function getModules() {
218 wfDeprecated( __METHOD__
, '1.21' );
219 return $this->getModuleManager()->getNamesWithClasses();
223 * Get the generators array mapping module names to class names
224 * @return array array(modulename => classname)
226 public function getGenerators() {
227 return $this->mQueryGenerators
;
231 * Get whether the specified module is a prop, list or a meta query module
232 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
233 * @param $moduleName string Name of the module to find type for
234 * @return mixed string or null
236 function getModuleType( $moduleName ) {
237 return $this->getModuleManager()->getModuleGroup( $moduleName );
241 * @return ApiFormatRaw|null
243 public function getCustomPrinter() {
244 // If &exportnowrap is set, use the raw formatter
245 if ( $this->getParameter( 'export' ) &&
246 $this->getParameter( 'exportnowrap' ) )
248 return new ApiFormatRaw( $this->getMain(),
249 $this->getMain()->createPrinterByName( 'xml' ) );
256 * Query execution happens in the following steps:
257 * #1 Create a PageSet object with any pages requested by the user
258 * #2 If using a generator, execute it to get a new ApiPageSet object
259 * #3 Instantiate all requested modules.
260 * This way the PageSet object will know what shared data is required,
261 * and minimize DB calls.
262 * #4 Output all normalization and redirect resolution information
263 * #5 Execute all requested modules
265 public function execute() {
266 $this->params
= $this->extractRequestParams();
267 $this->iwUrl
= $this->params
['iwurl'];
269 // Instantiate requested modules
271 $this->instantiateModules( $modules, 'prop' );
272 $this->instantiateModules( $modules, 'list' );
273 $this->instantiateModules( $modules, 'meta' );
275 // Query modules may optimize data requests through the $this->getPageSet()
276 // object by adding extra fields from the page table.
277 // This function will gather all the extra request fields from the modules.
278 foreach ( $modules as $module ) {
279 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
280 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $module->getModuleName() ) );
283 $module->requestExtraData( $this->mPageSet
);
286 // Populate page/revision information
287 $this->mPageSet
->execute();
288 $cacheMode = $this->mPageSet
->getCacheMode();
290 // Record page information (title, namespace, if exists, etc)
291 $this->outputGeneralPageInfo();
293 // Execute all requested modules.
295 * @var $module ApiQueryBase
297 foreach ( $modules as $module ) {
298 $params = $module->extractRequestParams();
299 $cacheMode = $this->mergeCacheMode(
300 $cacheMode, $module->getCacheMode( $params ) );
301 $module->profileIn();
303 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
304 $module->profileOut();
307 // Set the cache mode
308 $this->getMain()->setCacheMode( $cacheMode );
312 * Update a cache mode string, applying the cache mode of a new module to it.
313 * The cache mode may increase in the level of privacy, but public modules
314 * added to private data do not decrease the level of privacy.
316 * @param $cacheMode string
317 * @param $modCacheMode string
320 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
321 if ( $modCacheMode === 'anon-public-user-private' ) {
322 if ( $cacheMode !== 'private' ) {
323 $cacheMode = 'anon-public-user-private';
325 } elseif ( $modCacheMode === 'public' ) {
326 // do nothing, if it's public already it will stay public
328 $cacheMode = 'private';
334 * Create instances of all modules requested by the client
335 * @param $modules Array to append instantiated modules to
336 * @param $param string Parameter name to read modules from
338 private function instantiateModules( &$modules, $param ) {
339 if ( isset( $this->params
[$param] ) ) {
340 foreach ( $this->params
[$param] as $moduleName ) {
341 $modules[] = $this->mModuleMgr
->getModule( $moduleName );
347 * Appends an element for each page in the current pageSet with the
348 * most general information (id, title), plus any title normalizations
349 * and missing or invalid title/pageids/revids.
351 private function outputGeneralPageInfo() {
352 $pageSet = $this->getPageSet();
353 $result = $this->getResult();
355 // We don't check for a full result set here because we can't be adding
356 // more than 380K. The maximum revision size is in the megabyte range,
357 // and the maximum result size must be even higher than that.
359 $values = $pageSet->getNormalizedTitlesAsResult( $result );
361 $result->addValue( 'query', 'normalized', $values );
363 $values = $pageSet->getConvertedTitlesAsResult( $result );
365 $result->addValue( 'query', 'converted', $values );
367 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->iwUrl
);
369 $result->addValue( 'query', 'interwiki', $values );
371 $values = $pageSet->getRedirectTitlesAsResult( $result );
373 $result->addValue( 'query', 'redirects', $values );
375 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
377 $result->addValue( 'query', 'badrevids', $values );
383 // Report any missing titles
384 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
386 ApiQueryBase
::addTitleInfo( $vals, $title );
387 $vals['missing'] = '';
388 $pages[$fakeId] = $vals;
390 // Report any invalid titles
391 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
392 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
394 // Report any missing page ids
395 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
396 $pages[$pageid] = array(
401 // Report special pages
402 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
404 ApiQueryBase
::addTitleInfo( $vals, $title );
405 $vals['special'] = '';
406 if ( $title->isSpecialPage() &&
407 !SpecialPageFactory
::exists( $title->getDbKey() ) ) {
408 $vals['missing'] = '';
409 } elseif ( $title->getNamespace() == NS_MEDIA
&&
410 !wfFindFile( $title ) ) {
411 $vals['missing'] = '';
413 $pages[$fakeId] = $vals;
416 // Output general page information for found titles
417 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
419 $vals['pageid'] = $pageid;
420 ApiQueryBase
::addTitleInfo( $vals, $title );
421 $pages[$pageid] = $vals;
424 if ( count( $pages ) ) {
425 if ( $this->params
['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 $result->addValue( 'query', 'pageids', $pageIDs );
433 $result->setIndexedTagName( $pages, 'page' );
434 $result->addValue( 'query', 'pages', $pages );
436 if ( $this->params
['export'] ) {
437 $this->doExport( $pageSet, $result );
442 * @param $pageSet ApiPageSet Pages to be exported
443 * @param $result ApiResult Result to output to
445 private function doExport( $pageSet, $result ) {
446 $exportTitles = array();
447 $titles = $pageSet->getGoodTitles();
448 if ( count( $titles ) ) {
449 $user = $this->getUser();
450 foreach ( $titles as $title ) {
451 if ( $title->userCan( 'read', $user ) ) {
452 $exportTitles[] = $title;
457 $exporter = new WikiExporter( $this->getDB() );
458 // WikiExporter writes to stdout, so catch its
461 $exporter->openStream();
462 foreach ( $exportTitles as $title ) {
463 $exporter->pageByTitle( $title );
465 $exporter->closeStream();
466 $exportxml = ob_get_contents();
469 // Don't check the size of exported stuff
470 // It's not continuable, so it would cause more
471 // problems than it'd solve
472 $result->disableSizeCheck();
473 if ( $this->params
['exportnowrap'] ) {
475 // Raw formatter will handle this
476 $result->addValue( null, 'text', $exportxml );
477 $result->addValue( null, 'mime', 'text/xml' );
480 ApiResult
::setContent( $r, $exportxml );
481 $result->addValue( 'query', 'export', $r );
483 $result->enableSizeCheck();
486 public function getAllowedParams( $flags = 0 ) {
489 ApiBase
::PARAM_ISMULTI
=> true,
490 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'prop' )
493 ApiBase
::PARAM_ISMULTI
=> true,
494 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'list' )
497 ApiBase
::PARAM_ISMULTI
=> true,
498 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'meta' )
500 'indexpageids' => false,
502 'exportnowrap' => false,
506 $result +
= $this->getPageSet()->getFinalParams( $flags );
512 * Override the parent to generate help messages for all available query modules.
515 public function makeHelpMsg() {
517 // Use parent to make default message for the query module
518 $msg = parent
::makeHelpMsg();
520 $querySeparator = str_repeat( '--- ', 12 );
521 $moduleSeparator = str_repeat( '*** ', 14 );
522 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
523 $msg .= $this->makeHelpMsgHelper( 'prop' );
524 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
525 $msg .= $this->makeHelpMsgHelper( 'list' );
526 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
527 $msg .= $this->makeHelpMsgHelper( 'meta' );
528 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
534 * For all modules of a given group, generate help messages and join them together
535 * @param $group string Module group
538 private function makeHelpMsgHelper( $group ) {
539 $moduleDescriptions = array();
541 $moduleNames = $this->mModuleMgr
->getNames( $group );
542 sort( $moduleNames );
543 foreach ( $moduleNames as $name ) {
545 * @var $module ApiQueryBase
547 $module = $this->mModuleMgr
->getModule( $name );
549 $msg = ApiMain
::makeHelpMsgHeader( $module, $group );
550 $msg2 = $module->makeHelpMsg();
551 if ( $msg2 !== false ) {
554 if ( $module instanceof ApiQueryGeneratorBase
) {
555 $msg .= "Generator:\n This module may be used as a generator\n";
557 $moduleDescriptions[] = $msg;
560 return implode( "\n", $moduleDescriptions );
563 public function shouldCheckMaxlag() {
567 public function getParamDescription() {
568 return $this->getPageSet()->getParamDescription() +
array(
569 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
570 'list' => 'Which lists to get. Module help is available below',
571 'meta' => 'Which metadata to get about the site. Module help is available below',
572 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
573 'export' => 'Export the current revisions of all given or generated pages',
574 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
575 'iwurl' => 'Whether to get the full URL if the title is an interwiki link',
579 public function getDescription() {
581 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
582 'and is loosely based on the old query.php interface.',
583 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
587 public function getPossibleErrors() {
589 parent
::getPossibleErrors(),
590 $this->getPageSet()->getPossibleErrors()
594 public function getExamples() {
596 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
597 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
601 public function getHelpUrls() {
603 'https://www.mediawiki.org/wiki/API:Meta',
604 'https://www.mediawiki.org/wiki/API:Properties',
605 'https://www.mediawiki.org/wiki/API:Lists',