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',
112 private $mNamedDB = array();
116 * @param $main ApiMain
117 * @param $action string
119 public function __construct( $main, $action ) {
120 parent
::__construct( $main, $action );
122 $this->mModuleMgr
= new ApiModuleManager( $this );
124 // Allow custom modules to be added in LocalSettings.php
125 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
126 $this->mModuleMgr
->addModules( self
::$QueryPropModules, 'prop' );
127 $this->mModuleMgr
->addModules( $wgAPIPropModules, 'prop' );
128 $this->mModuleMgr
->addModules( self
::$QueryListModules, 'list' );
129 $this->mModuleMgr
->addModules( $wgAPIListModules, 'list' );
130 $this->mModuleMgr
->addModules( self
::$QueryMetaModules, 'meta' );
131 $this->mModuleMgr
->addModules( $wgAPIMetaModules, 'meta' );
133 // Create PageSet that will process titles/pageids/revids/generator
134 $this->mPageSet
= new ApiPageSet( $this );
138 * Overrides to return this instance's module manager.
139 * @return ApiModuleManager
141 public function getModuleManager() {
142 return $this->mModuleMgr
;
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 DatabaseBase
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)
168 public function getPageSet() {
169 return $this->mPageSet
;
173 * Get the array mapping module names to class names
174 * @deprecated since 1.21, use getModuleManager()'s methods instead
175 * @return array array(modulename => classname)
177 public function getModules() {
178 wfDeprecated( __METHOD__
, '1.21' );
179 return $this->getModuleManager()->getNamesWithClasses();
183 * Get the generators array mapping module names to class names
184 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
185 * @return array array(modulename => classname)
187 public function getGenerators() {
188 wfDeprecated( __METHOD__
, '1.21' );
190 foreach ( $this->mModuleMgr
->getNamesWithClasses() as $name => $class ) {
191 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
192 $gens[$name] = $class;
199 * Get whether the specified module is a prop, list or a meta query module
200 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
201 * @param $moduleName string Name of the module to find type for
202 * @return mixed string or null
204 function getModuleType( $moduleName ) {
205 return $this->getModuleManager()->getModuleGroup( $moduleName );
209 * @return ApiFormatRaw|null
211 public function getCustomPrinter() {
212 // If &exportnowrap is set, use the raw formatter
213 if ( $this->getParameter( 'export' ) &&
214 $this->getParameter( 'exportnowrap' ) )
216 return new ApiFormatRaw( $this->getMain(),
217 $this->getMain()->createPrinterByName( 'xml' ) );
224 * Query execution happens in the following steps:
225 * #1 Create a PageSet object with any pages requested by the user
226 * #2 If using a generator, execute it to get a new ApiPageSet object
227 * #3 Instantiate all requested modules.
228 * This way the PageSet object will know what shared data is required,
229 * and minimize DB calls.
230 * #4 Output all normalization and redirect resolution information
231 * #5 Execute all requested modules
233 public function execute() {
234 $this->params
= $this->extractRequestParams();
235 $this->iwUrl
= $this->params
['iwurl'];
237 // Instantiate requested modules
239 $this->instantiateModules( $modules, 'prop' );
240 $this->instantiateModules( $modules, 'list' );
241 $this->instantiateModules( $modules, 'meta' );
243 // Query modules may optimize data requests through the $this->getPageSet()
244 // object by adding extra fields from the page table.
245 // This function will gather all the extra request fields from the modules.
246 foreach ( $modules as $module ) {
247 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
248 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $module->getModuleName() ) );
251 $module->requestExtraData( $this->mPageSet
);
254 // Populate page/revision information
255 $this->mPageSet
->execute();
256 $cacheMode = $this->mPageSet
->getCacheMode();
258 // Record page information (title, namespace, if exists, etc)
259 $this->outputGeneralPageInfo();
261 // Execute all requested modules.
263 * @var $module ApiQueryBase
265 foreach ( $modules as $module ) {
266 $params = $module->extractRequestParams();
267 $cacheMode = $this->mergeCacheMode(
268 $cacheMode, $module->getCacheMode( $params ) );
269 $module->profileIn();
271 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
272 $module->profileOut();
275 // Set the cache mode
276 $this->getMain()->setCacheMode( $cacheMode );
280 * Update a cache mode string, applying the cache mode of a new module to it.
281 * The cache mode may increase in the level of privacy, but public modules
282 * added to private data do not decrease the level of privacy.
284 * @param $cacheMode string
285 * @param $modCacheMode string
288 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
289 if ( $modCacheMode === 'anon-public-user-private' ) {
290 if ( $cacheMode !== 'private' ) {
291 $cacheMode = 'anon-public-user-private';
293 } elseif ( $modCacheMode === 'public' ) {
294 // do nothing, if it's public already it will stay public
296 $cacheMode = 'private';
302 * Create instances of all modules requested by the client
303 * @param $modules Array to append instantiated modules to
304 * @param $param string Parameter name to read modules from
306 private function instantiateModules( &$modules, $param ) {
307 if ( isset( $this->params
[$param] ) ) {
308 foreach ( $this->params
[$param] as $moduleName ) {
309 $modules[] = $this->mModuleMgr
->getModule( $moduleName );
315 * Appends an element for each page in the current pageSet with the
316 * most general information (id, title), plus any title normalizations
317 * and missing or invalid title/pageids/revids.
319 private function outputGeneralPageInfo() {
320 $pageSet = $this->getPageSet();
321 $result = $this->getResult();
323 // We don't check for a full result set here because we can't be adding
324 // more than 380K. The maximum revision size is in the megabyte range,
325 // and the maximum result size must be even higher than that.
327 $values = $pageSet->getNormalizedTitlesAsResult( $result );
329 $result->addValue( 'query', 'normalized', $values );
331 $values = $pageSet->getConvertedTitlesAsResult( $result );
333 $result->addValue( 'query', 'converted', $values );
335 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->iwUrl
);
337 $result->addValue( 'query', 'interwiki', $values );
339 $values = $pageSet->getRedirectTitlesAsResult( $result );
341 $result->addValue( 'query', 'redirects', $values );
343 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
345 $result->addValue( 'query', 'badrevids', $values );
351 // Report any missing titles
352 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
354 ApiQueryBase
::addTitleInfo( $vals, $title );
355 $vals['missing'] = '';
356 $pages[$fakeId] = $vals;
358 // Report any invalid titles
359 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
360 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
362 // Report any missing page ids
363 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
364 $pages[$pageid] = array(
369 // Report special pages
370 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
372 ApiQueryBase
::addTitleInfo( $vals, $title );
373 $vals['special'] = '';
374 if ( $title->isSpecialPage() &&
375 !SpecialPageFactory
::exists( $title->getDbKey() ) ) {
376 $vals['missing'] = '';
377 } elseif ( $title->getNamespace() == NS_MEDIA
&&
378 !wfFindFile( $title ) ) {
379 $vals['missing'] = '';
381 $pages[$fakeId] = $vals;
384 // Output general page information for found titles
385 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
387 $vals['pageid'] = $pageid;
388 ApiQueryBase
::addTitleInfo( $vals, $title );
389 $pages[$pageid] = $vals;
392 if ( count( $pages ) ) {
393 if ( $this->params
['indexpageids'] ) {
394 $pageIDs = array_keys( $pages );
395 // json treats all map keys as strings - converting to match
396 $pageIDs = array_map( 'strval', $pageIDs );
397 $result->setIndexedTagName( $pageIDs, 'id' );
398 $result->addValue( 'query', 'pageids', $pageIDs );
401 $result->setIndexedTagName( $pages, 'page' );
402 $result->addValue( 'query', 'pages', $pages );
404 if ( $this->params
['export'] ) {
405 $this->doExport( $pageSet, $result );
410 * @param $pageSet ApiPageSet Pages to be exported
411 * @param $result ApiResult Result to output to
413 private function doExport( $pageSet, $result ) {
414 $exportTitles = array();
415 $titles = $pageSet->getGoodTitles();
416 if ( count( $titles ) ) {
417 $user = $this->getUser();
418 foreach ( $titles as $title ) {
419 if ( $title->userCan( 'read', $user ) ) {
420 $exportTitles[] = $title;
425 $exporter = new WikiExporter( $this->getDB() );
426 // WikiExporter writes to stdout, so catch its
429 $exporter->openStream();
430 foreach ( $exportTitles as $title ) {
431 $exporter->pageByTitle( $title );
433 $exporter->closeStream();
434 $exportxml = ob_get_contents();
437 // Don't check the size of exported stuff
438 // It's not continuable, so it would cause more
439 // problems than it'd solve
440 $result->disableSizeCheck();
441 if ( $this->params
['exportnowrap'] ) {
443 // Raw formatter will handle this
444 $result->addValue( null, 'text', $exportxml );
445 $result->addValue( null, 'mime', 'text/xml' );
448 ApiResult
::setContent( $r, $exportxml );
449 $result->addValue( 'query', 'export', $r );
451 $result->enableSizeCheck();
454 public function getAllowedParams( $flags = 0 ) {
457 ApiBase
::PARAM_ISMULTI
=> true,
458 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'prop' )
461 ApiBase
::PARAM_ISMULTI
=> true,
462 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'list' )
465 ApiBase
::PARAM_ISMULTI
=> true,
466 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'meta' )
468 'indexpageids' => false,
470 'exportnowrap' => false,
474 $result +
= $this->getPageSet()->getFinalParams( $flags );
480 * Override the parent to generate help messages for all available query modules.
483 public function makeHelpMsg() {
485 // Use parent to make default message for the query module
486 $msg = parent
::makeHelpMsg();
488 $querySeparator = str_repeat( '--- ', 12 );
489 $moduleSeparator = str_repeat( '*** ', 14 );
490 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
491 $msg .= $this->makeHelpMsgHelper( 'prop' );
492 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
493 $msg .= $this->makeHelpMsgHelper( 'list' );
494 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
495 $msg .= $this->makeHelpMsgHelper( 'meta' );
496 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
502 * For all modules of a given group, generate help messages and join them together
503 * @param $group string Module group
506 private function makeHelpMsgHelper( $group ) {
507 $moduleDescriptions = array();
509 $moduleNames = $this->mModuleMgr
->getNames( $group );
510 sort( $moduleNames );
511 foreach ( $moduleNames as $name ) {
513 * @var $module ApiQueryBase
515 $module = $this->mModuleMgr
->getModule( $name );
517 $msg = ApiMain
::makeHelpMsgHeader( $module, $group );
518 $msg2 = $module->makeHelpMsg();
519 if ( $msg2 !== false ) {
522 if ( $module instanceof ApiQueryGeneratorBase
) {
523 $msg .= "Generator:\n This module may be used as a generator\n";
525 $moduleDescriptions[] = $msg;
528 return implode( "\n", $moduleDescriptions );
531 public function shouldCheckMaxlag() {
535 public function getParamDescription() {
536 return $this->getPageSet()->getParamDescription() +
array(
537 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
538 'list' => 'Which lists to get. Module help is available below',
539 'meta' => 'Which metadata to get about the site. Module help is available below',
540 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
541 'export' => 'Export the current revisions of all given or generated pages',
542 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
543 'iwurl' => 'Whether to get the full URL if the title is an interwiki link',
547 public function getDescription() {
549 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
550 'and is loosely based on the old query.php interface.',
551 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
555 public function getPossibleErrors() {
557 parent
::getPossibleErrors(),
558 $this->getPageSet()->getPossibleErrors()
562 public function getExamples() {
564 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
565 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
569 public function getHelpUrls() {
571 'https://www.mediawiki.org/wiki/API:Meta',
572 'https://www.mediawiki.org/wiki/API:Properties',
573 'https://www.mediawiki.org/wiki/API:Lists',