4 * Created on Sep 7, 2006
6 * API for MediaWiki 1.8+
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
32 * This is the main query class. It behaves similar to ApiMain: based on the
33 * parameters given, it will create a list of titles to work on (an ApiPageSet
34 * object), instantiate and execute various property/list/meta modules, and
35 * assemble all resulting data into a single ApiResult object.
37 * In generator mode, a generator will be executed first to populate a second
38 * ApiPageSet object, and that object will be used for all subsequent modules.
42 class ApiQuery
extends ApiBase
{
44 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
48 private $mQueryPropModules = array(
49 'info' => 'ApiQueryInfo',
50 'revisions' => 'ApiQueryRevisions',
51 'links' => 'ApiQueryLinks',
52 'iwlinks' => 'ApiQueryIWLinks',
53 'langlinks' => 'ApiQueryLangLinks',
54 'images' => 'ApiQueryImages',
55 'imageinfo' => 'ApiQueryImageInfo',
56 'templates' => 'ApiQueryLinks',
57 'categories' => 'ApiQueryCategories',
58 'extlinks' => 'ApiQueryExternalLinks',
59 'categoryinfo' => 'ApiQueryCategoryInfo',
60 'duplicatefiles' => 'ApiQueryDuplicateFiles',
61 'pageprops' => 'ApiQueryPageProps',
64 private $mQueryListModules = array(
65 'allimages' => 'ApiQueryAllimages',
66 'allpages' => 'ApiQueryAllpages',
67 'alllinks' => 'ApiQueryAllLinks',
68 'allcategories' => 'ApiQueryAllCategories',
69 'allusers' => 'ApiQueryAllUsers',
70 'backlinks' => 'ApiQueryBacklinks',
71 'blocks' => 'ApiQueryBlocks',
72 'categorymembers' => 'ApiQueryCategoryMembers',
73 'deletedrevs' => 'ApiQueryDeletedrevs',
74 'embeddedin' => 'ApiQueryBacklinks',
75 'filearchive' => 'ApiQueryFilearchive',
76 'imageusage' => 'ApiQueryBacklinks',
77 'iwbacklinks' => 'ApiQueryIWBacklinks',
78 'logevents' => 'ApiQueryLogEvents',
79 'recentchanges' => 'ApiQueryRecentChanges',
80 'search' => 'ApiQuerySearch',
81 'tags' => 'ApiQueryTags',
82 'usercontribs' => 'ApiQueryContributions',
83 'watchlist' => 'ApiQueryWatchlist',
84 'watchlistraw' => 'ApiQueryWatchlistRaw',
85 'exturlusage' => 'ApiQueryExtLinksUsage',
86 'users' => 'ApiQueryUsers',
87 'random' => 'ApiQueryRandom',
88 'protectedtitles' => 'ApiQueryProtectedTitles',
91 private $mQueryMetaModules = array(
92 'siteinfo' => 'ApiQuerySiteinfo',
93 'userinfo' => 'ApiQueryUserInfo',
94 'allmessages' => 'ApiQueryAllmessages',
97 private $mSlaveDB = null;
98 private $mNamedDB = array();
100 public function __construct( $main, $action ) {
101 parent
::__construct( $main, $action );
103 // Allow custom modules to be added in LocalSettings.php
104 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
105 self
::appendUserModules( $this->mQueryPropModules
, $wgAPIPropModules );
106 self
::appendUserModules( $this->mQueryListModules
, $wgAPIListModules );
107 self
::appendUserModules( $this->mQueryMetaModules
, $wgAPIMetaModules );
109 $this->mPropModuleNames
= array_keys( $this->mQueryPropModules
);
110 $this->mListModuleNames
= array_keys( $this->mQueryListModules
);
111 $this->mMetaModuleNames
= array_keys( $this->mQueryMetaModules
);
113 // Allow the entire list of modules at first,
114 // but during module instantiation check if it can be used as a generator.
115 $this->mAllowedGenerators
= array_merge( $this->mListModuleNames
, $this->mPropModuleNames
);
119 * Helper function to append any add-in modules to the list
120 * @param $modules array Module array
121 * @param $newModules array Module array to add to $modules
123 private static function appendUserModules( &$modules, $newModules ) {
124 if ( is_array( $newModules ) ) {
125 foreach ( $newModules as $moduleName => $moduleClass ) {
126 $modules[$moduleName] = $moduleClass;
132 * Gets a default slave database connection object
135 public function getDB() {
136 if ( !isset( $this->mSlaveDB
) ) {
137 $this->profileDBIn();
138 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
139 $this->profileDBOut();
141 return $this->mSlaveDB
;
145 * Get the query database connection with the given name.
146 * If no such connection has been requested before, it will be created.
147 * Subsequent calls with the same $name will return the same connection
148 * as the first, regardless of the values of $db and $groups
149 * @param $name string Name to assign to the database connection
150 * @param $db int One of the DB_* constants
151 * @param $groups array Query groups
154 public function getNamedDB( $name, $db, $groups ) {
155 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
156 $this->profileDBIn();
157 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
158 $this->profileDBOut();
160 return $this->mNamedDB
[$name];
164 * Gets the set of pages the user has requested (or generated)
167 public function getPageSet() {
168 return $this->mPageSet
;
172 * Get the array mapping module names to class names
173 * @return array(modulename => classname)
175 function getModules() {
176 return array_merge( $this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
180 * Get whether the specified module is a prop, list or a meta query module
181 * @param $moduleName string Name of the module to find type for
182 * @return mixed string or null
184 function getModuleType( $moduleName ) {
185 if ( array_key_exists ( $moduleName, $this->mQueryPropModules
) ) {
189 if ( array_key_exists ( $moduleName, $this->mQueryListModules
) ) {
193 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules
) ) {
200 public function getCustomPrinter() {
201 // If &exportnowrap is set, use the raw formatter
202 if ( $this->getParameter( 'export' ) &&
203 $this->getParameter( 'exportnowrap' ) )
205 return new ApiFormatRaw( $this->getMain(),
206 $this->getMain()->createPrinterByName( 'xml' ) );
213 * Query execution happens in the following steps:
214 * #1 Create a PageSet object with any pages requested by the user
215 * #2 If using a generator, execute it to get a new ApiPageSet object
216 * #3 Instantiate all requested modules.
217 * This way the PageSet object will know what shared data is required,
218 * and minimize DB calls.
219 * #4 Output all normalization and redirect resolution information
220 * #5 Execute all requested modules
222 public function execute() {
223 $this->params
= $this->extractRequestParams();
224 $this->redirects
= $this->params
['redirects'];
225 $this->convertTitles
= $this->params
['converttitles'];
228 $this->mPageSet
= new ApiPageSet( $this, $this->redirects
, $this->convertTitles
);
230 // Instantiate requested modules
232 $this->instantiateModules( $modules, 'prop', $this->mQueryPropModules
);
233 $this->instantiateModules( $modules, 'list', $this->mQueryListModules
);
234 $this->instantiateModules( $modules, 'meta', $this->mQueryMetaModules
);
236 $cacheMode = 'public';
238 // If given, execute generator to substitute user supplied data with generated data.
239 if ( isset( $this->params
['generator'] ) ) {
240 $generator = $this->newGenerator( $this->params
['generator'] );
241 $params = $generator->extractRequestParams();
242 $cacheMode = $this->mergeCacheMode( $cacheMode,
243 $generator->getCacheMode( $params ) );
244 $this->executeGeneratorModule( $generator, $modules );
246 // Append custom fields and populate page/revision information
247 $this->addCustomFldsToPageSet( $modules, $this->mPageSet
);
248 $this->mPageSet
->execute();
251 // Record page information (title, namespace, if exists, etc)
252 $this->outputGeneralPageInfo();
254 // Execute all requested modules.
255 foreach ( $modules as $module ) {
256 $params = $module->extractRequestParams();
257 $cacheMode = $this->mergeCacheMode(
258 $cacheMode, $module->getCacheMode( $params ) );
259 $module->profileIn();
261 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
262 $module->profileOut();
265 // Set the cache mode
266 $this->getMain()->setCacheMode( $cacheMode );
270 * Update a cache mode string, applying the cache mode of a new module to it.
271 * The cache mode may increase in the level of privacy, but public modules
272 * added to private data do not decrease the level of privacy.
274 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
275 if ( $modCacheMode === 'anon-public-user-private' ) {
276 if ( $cacheMode !== 'private' ) {
277 $cacheMode = 'anon-public-user-private';
279 } elseif ( $modCacheMode === 'public' ) {
280 // do nothing, if it's public already it will stay public
282 $cacheMode = 'private';
288 * Query modules may optimize data requests through the $this->getPageSet() object
289 * by adding extra fields from the page table.
290 * This function will gather all the extra request fields from the modules.
291 * @param $modules array of module objects
292 * @param $pageSet ApiPageSet
294 private function addCustomFldsToPageSet( $modules, $pageSet ) {
295 // Query all requested modules.
296 foreach ( $modules as $module ) {
297 $module->requestExtraData( $pageSet );
302 * Create instances of all modules requested by the client
303 * @param $modules array to append instatiated modules to
304 * @param $param string Parameter name to read modules from
305 * @param $moduleList array(modulename => classname)
307 private function instantiateModules( &$modules, $param, $moduleList ) {
308 $list = @$this->params
[$param];
309 if ( !is_null ( $list ) ) {
310 foreach ( $list as $moduleName ) {
311 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
317 * Appends an element for each page in the current pageSet with the
318 * most general information (id, title), plus any title normalizations
319 * and missing or invalid title/pageids/revids.
321 private function outputGeneralPageInfo() {
322 $pageSet = $this->getPageSet();
323 $result = $this->getResult();
325 // We don't check for a full result set here because we can't be adding
326 // more than 380K. The maximum revision size is in the megabyte range,
327 // and the maximum result size must be even higher than that.
329 // Title normalizations
330 $normValues = array();
331 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
332 $normValues[] = array(
333 'from' => $rawTitleStr,
338 if ( count( $normValues ) ) {
339 $result->setIndexedTagName( $normValues, 'n' );
340 $result->addValue( 'query', 'normalized', $normValues );
344 $convValues = array();
345 foreach ( $pageSet->getConvertedTitles() as $rawTitleStr => $titleStr ) {
346 $convValues[] = array(
347 'from' => $rawTitleStr,
352 if ( count( $convValues ) ) {
353 $result->setIndexedTagName( $convValues, 'c' );
354 $result->addValue( 'query', 'converted', $convValues );
358 $intrwValues = array();
359 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
360 $intrwValues[] = array(
361 'title' => $rawTitleStr,
362 'iw' => $interwikiStr
366 if ( count( $intrwValues ) ) {
367 $result->setIndexedTagName( $intrwValues, 'i' );
368 $result->addValue( 'query', 'interwiki', $intrwValues );
371 // Show redirect information
372 $redirValues = array();
373 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
374 $redirValues[] = array(
375 'from' => strval( $titleStrFrom ),
380 if ( count( $redirValues ) ) {
381 $result->setIndexedTagName( $redirValues, 'r' );
382 $result->addValue( 'query', 'redirects', $redirValues );
386 // 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 );
405 // Report any missing titles
406 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
408 ApiQueryBase
::addTitleInfo( $vals, $title );
409 $vals['missing'] = '';
410 $pages[$fakeId] = $vals;
412 // Report any invalid titles
413 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
414 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
416 // Report any missing page ids
417 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
418 $pages[$pageid] = array(
423 // Report special pages
424 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
426 ApiQueryBase
::addTitleInfo( $vals, $title );
427 $vals['special'] = '';
428 if ( $title->getNamespace() == NS_SPECIAL
&&
429 !SpecialPage
::exists( $title->getText() ) ) {
430 $vals['missing'] = '';
431 } elseif ( $title->getNamespace() == NS_MEDIA
&&
432 !wfFindFile( $title ) ) {
433 $vals['missing'] = '';
435 $pages[$fakeId] = $vals;
438 // Output general page information for found titles
439 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
441 $vals['pageid'] = $pageid;
442 ApiQueryBase
::addTitleInfo( $vals, $title );
443 $pages[$pageid] = $vals;
446 if ( count( $pages ) ) {
447 if ( $this->params
['indexpageids'] ) {
448 $pageIDs = array_keys( $pages );
449 // json treats all map keys as strings - converting to match
450 $pageIDs = array_map( 'strval', $pageIDs );
451 $result->setIndexedTagName( $pageIDs, 'id' );
452 $result->addValue( 'query', 'pageids', $pageIDs );
455 $result->setIndexedTagName( $pages, 'page' );
456 $result->addValue( 'query', 'pages', $pages );
458 if ( $this->params
['export'] ) {
459 $exporter = new WikiExporter( $this->getDB() );
460 // WikiExporter writes to stdout, so catch its
463 $exporter->openStream();
464 foreach ( @$pageSet->getGoodTitles() as $title ) {
465 if ( $title->userCanRead() ) {
466 $exporter->pageByTitle( $title );
469 $exporter->closeStream();
470 $exportxml = ob_get_contents();
473 // Don't check the size of exported stuff
474 // It's not continuable, so it would cause more
475 // problems than it'd solve
476 $result->disableSizeCheck();
477 if ( $this->params
['exportnowrap'] ) {
479 // Raw formatter will handle this
480 $result->addValue( null, 'text', $exportxml );
481 $result->addValue( null, 'mime', 'text/xml' );
484 ApiResult
::setContent( $r, $exportxml );
485 $result->addValue( 'query', 'export', $r );
487 $result->enableSizeCheck();
492 * Create a generator object of the given type and return it
493 * @param $generatorName string Module name
495 public function newGenerator( $generatorName ) {
496 // Find class that implements requested generator
497 if ( isset( $this->mQueryListModules
[$generatorName] ) ) {
498 $className = $this->mQueryListModules
[$generatorName];
499 } elseif ( isset( $this->mQueryPropModules
[$generatorName] ) ) {
500 $className = $this->mQueryPropModules
[$generatorName];
502 ApiBase
::dieDebug( __METHOD__
, "Unknown generator=$generatorName" );
504 $generator = new $className ( $this, $generatorName );
505 if ( !$generator instanceof ApiQueryGeneratorBase
) {
506 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
508 $generator->setGeneratorMode();
513 * For generator mode, execute generator, and use its output as new
515 * @param $generatorName string Module name
516 * @param $modules array of module objects
518 protected function executeGeneratorModule( $generator, $modules ) {
520 $resultPageSet = new ApiPageSet( $this, $this->redirects
, $this->convertTitles
);
522 // Add any additional fields modules may need
523 $generator->requestExtraData( $this->mPageSet
);
524 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
526 // Populate page information with the original user input
527 $this->mPageSet
->execute();
529 // populate resultPageSet with the generator output
530 $generator->profileIn();
531 $generator->executeGenerator( $resultPageSet );
532 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
533 $resultPageSet->finishPageSetGeneration();
534 $generator->profileOut();
536 // Swap the resulting pageset back in
537 $this->mPageSet
= $resultPageSet;
540 public function getAllowedParams() {
543 ApiBase
::PARAM_ISMULTI
=> true,
544 ApiBase
::PARAM_TYPE
=> $this->mPropModuleNames
547 ApiBase
::PARAM_ISMULTI
=> true,
548 ApiBase
::PARAM_TYPE
=> $this->mListModuleNames
551 ApiBase
::PARAM_ISMULTI
=> true,
552 ApiBase
::PARAM_TYPE
=> $this->mMetaModuleNames
554 'generator' => array(
555 ApiBase
::PARAM_TYPE
=> $this->mAllowedGenerators
557 'redirects' => false,
558 'converttitles' => false,
559 'indexpageids' => false,
561 'exportnowrap' => false,
566 * Override the parent to generate help messages for all available query modules.
569 public function makeHelpMsg() {
572 // Make sure the internal object is empty
573 // (just in case a sub-module decides to optimize during instantiation)
574 $this->mPageSet
= null;
575 $this->mAllowedGenerators
= array(); // Will be repopulated
577 $astriks = str_repeat( '--- ', 8 );
578 $astriks2 = str_repeat( '*** ', 10 );
579 $msg .= "\n$astriks Query: Prop $astriks\n\n";
580 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules
, 'prop' );
581 $msg .= "\n$astriks Query: List $astriks\n\n";
582 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules
, 'list' );
583 $msg .= "\n$astriks Query: Meta $astriks\n\n";
584 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules
, 'meta' );
585 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
587 // Perform the base call last because the $this->mAllowedGenerators
588 // will be updated inside makeHelpMsgHelper()
589 // Use parent to make default message for the query module
590 $msg = parent
::makeHelpMsg() . $msg;
596 * For all modules in $moduleList, generate help messages and join them together
597 * @param $moduleList array(modulename => classname)
598 * @param $paramName string Parameter name
601 private function makeHelpMsgHelper( $moduleList, $paramName ) {
602 $moduleDescriptions = array();
604 foreach ( $moduleList as $moduleName => $moduleClass ) {
605 $module = new $moduleClass ( $this, $moduleName, null );
607 $msg = ApiMain
::makeHelpMsgHeader( $module, $paramName );
608 $msg2 = $module->makeHelpMsg();
609 if ( $msg2 !== false ) {
612 if ( $module instanceof ApiQueryGeneratorBase
) {
613 $this->mAllowedGenerators
[] = $moduleName;
614 $msg .= "Generator:\n This module may be used as a generator\n";
616 $moduleDescriptions[] = $msg;
619 return implode( "\n", $moduleDescriptions );
623 * Override to add extra parameters from PageSet
626 public function makeHelpMsgParameters() {
627 $psModule = new ApiPageSet( $this );
628 return $psModule->makeHelpMsgParameters() . parent
::makeHelpMsgParameters();
631 public function shouldCheckMaxlag() {
635 public function getParamDescription() {
637 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
638 'list' => 'Which lists to get. Module help is available below',
639 'meta' => 'Which metadata to get about the site. Module help is available below',
640 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
641 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
642 'redirects' => 'Automatically resolve redirects',
643 'converttitles' => "Convert titles to other variants if necessary. Only works if the wiki's content language supports variant conversion.",
644 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
645 'export' => 'Export the current revisions of all given or generated pages',
646 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
650 public function getDescription() {
652 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
653 'and is loosely based on the old query.php interface.',
654 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
658 public function getPossibleErrors() {
659 return array_merge( parent
::getPossibleErrors(), array(
660 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
664 protected function getExamples() {
666 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
667 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
671 public function getVersion() {
672 $psModule = new ApiPageSet( $this );
674 $vers[] = __CLASS__
. ': $Id$';
675 $vers[] = $psModule->getVersion();