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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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;
46 private $params, $redirect;
48 private $mQueryPropModules = array(
49 'info' => 'ApiQueryInfo',
50 'revisions' => 'ApiQueryRevisions',
51 'links' => 'ApiQueryLinks',
52 'langlinks' => 'ApiQueryLangLinks',
53 'images' => 'ApiQueryImages',
54 'imageinfo' => 'ApiQueryImageInfo',
55 'templates' => 'ApiQueryLinks',
56 'categories' => 'ApiQueryCategories',
57 'extlinks' => 'ApiQueryExternalLinks',
58 'categoryinfo' => 'ApiQueryCategoryInfo',
59 'duplicatefiles' => 'ApiQueryDuplicateFiles',
62 private $mQueryListModules = array(
63 'allimages' => 'ApiQueryAllimages',
64 'allpages' => 'ApiQueryAllpages',
65 'alllinks' => 'ApiQueryAllLinks',
66 'allcategories' => 'ApiQueryAllCategories',
67 'allusers' => 'ApiQueryAllUsers',
68 'backlinks' => 'ApiQueryBacklinks',
69 'blocks' => 'ApiQueryBlocks',
70 'categorymembers' => 'ApiQueryCategoryMembers',
71 'deletedrevs' => 'ApiQueryDeletedrevs',
72 'embeddedin' => 'ApiQueryBacklinks',
73 'filearchive' => 'ApiQueryFilearchive',
74 'imageusage' => 'ApiQueryBacklinks',
75 'logevents' => 'ApiQueryLogEvents',
76 'recentchanges' => 'ApiQueryRecentChanges',
77 'search' => 'ApiQuerySearch',
78 'tags' => 'ApiQueryTags',
79 'usercontribs' => 'ApiQueryContributions',
80 'watchlist' => 'ApiQueryWatchlist',
81 'watchlistraw' => 'ApiQueryWatchlistRaw',
82 'exturlusage' => 'ApiQueryExtLinksUsage',
83 'users' => 'ApiQueryUsers',
84 'random' => 'ApiQueryRandom',
85 'protectedtitles' => 'ApiQueryProtectedTitles',
88 private $mQueryMetaModules = array(
89 'siteinfo' => 'ApiQuerySiteinfo',
90 'userinfo' => 'ApiQueryUserInfo',
91 'allmessages' => 'ApiQueryAllmessages',
94 private $mSlaveDB = null;
95 private $mNamedDB = array();
97 public function __construct( $main, $action ) {
98 parent
::__construct( $main, $action );
100 // Allow custom modules to be added in LocalSettings.php
101 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
102 self
::appendUserModules( $this->mQueryPropModules
, $wgAPIPropModules );
103 self
::appendUserModules( $this->mQueryListModules
, $wgAPIListModules );
104 self
::appendUserModules( $this->mQueryMetaModules
, $wgAPIMetaModules );
106 $this->mPropModuleNames
= array_keys( $this->mQueryPropModules
);
107 $this->mListModuleNames
= array_keys( $this->mQueryListModules
);
108 $this->mMetaModuleNames
= array_keys( $this->mQueryMetaModules
);
110 // Allow the entire list of modules at first,
111 // but during module instantiation check if it can be used as a generator.
112 $this->mAllowedGenerators
= array_merge( $this->mListModuleNames
, $this->mPropModuleNames
);
116 * Helper function to append any add-in modules to the list
117 * @param $modules array Module array
118 * @param $newModules array Module array to add to $modules
120 private static function appendUserModules( &$modules, $newModules ) {
121 if ( is_array( $newModules ) ) {
122 foreach ( $newModules as $moduleName => $moduleClass ) {
123 $modules[$moduleName] = $moduleClass;
129 * Gets a default slave database connection object
132 public function getDB() {
133 if ( !isset( $this->mSlaveDB
) ) {
134 $this->profileDBIn();
135 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
136 $this->profileDBOut();
138 return $this->mSlaveDB
;
142 * Get the query database connection with the given name.
143 * If no such connection has been requested before, it will be created.
144 * Subsequent calls with the same $name will return the same connection
145 * as the first, regardless of the values of $db and $groups
146 * @param $name string Name to assign to the database connection
147 * @param $db int One of the DB_* constants
148 * @param $groups array Query groups
151 public function getNamedDB( $name, $db, $groups ) {
152 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
153 $this->profileDBIn();
154 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
155 $this->profileDBOut();
157 return $this->mNamedDB
[$name];
161 * Gets the set of pages the user has requested (or generated)
164 public function getPageSet() {
165 return $this->mPageSet
;
169 * Get the array mapping module names to class names
170 * @return array(modulename => classname)
172 function getModules() {
173 return array_merge( $this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
177 * Get whether the specified module is a prop, list or a meta query module
178 * @param $moduleName string Name of the module to find type for
179 * @return mixed string or null
181 function getModuleType( $moduleName ) {
182 if ( array_key_exists ( $moduleName, $this->mQueryPropModules
) ) {
186 if ( array_key_exists ( $moduleName, $this->mQueryListModules
) ) {
190 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules
) ) {
197 public function getCustomPrinter() {
198 // If &exportnowrap is set, use the raw formatter
199 if ( $this->getParameter( 'export' ) &&
200 $this->getParameter( 'exportnowrap' ) )
202 return new ApiFormatRaw( $this->getMain(),
203 $this->getMain()->createPrinterByName( 'xml' ) );
210 * Query execution happens in the following steps:
211 * #1 Create a PageSet object with any pages requested by the user
212 * #2 If using a generator, execute it to get a new ApiPageSet object
213 * #3 Instantiate all requested modules.
214 * This way the PageSet object will know what shared data is required,
215 * and minimize DB calls.
216 * #4 Output all normalization and redirect resolution information
217 * #5 Execute all requested modules
219 public function execute() {
220 $this->params
= $this->extractRequestParams();
221 $this->redirects
= $this->params
['redirects'];
224 $this->mPageSet
= new ApiPageSet( $this, $this->redirects
);
226 // Instantiate requested modules
228 $this->InstantiateModules( $modules, 'prop', $this->mQueryPropModules
);
229 $this->InstantiateModules( $modules, 'list', $this->mQueryListModules
);
230 $this->InstantiateModules( $modules, 'meta', $this->mQueryMetaModules
);
232 // If given, execute generator to substitute user supplied data with generated data.
233 if ( isset( $this->params
['generator'] ) ) {
234 $this->executeGeneratorModule( $this->params
['generator'], $modules );
236 // Append custom fields and populate page/revision information
237 $this->addCustomFldsToPageSet( $modules, $this->mPageSet
);
238 $this->mPageSet
->execute();
241 // Record page information (title, namespace, if exists, etc)
242 $this->outputGeneralPageInfo();
244 // Execute all requested modules.
245 foreach ( $modules as $module ) {
246 $module->profileIn();
248 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
249 $module->profileOut();
254 * Query modules may optimize data requests through the $this->getPageSet() object
255 * by adding extra fields from the page table.
256 * This function will gather all the extra request fields from the modules.
257 * @param $modules array of module objects
258 * @param $pageSet ApiPageSet
260 private function addCustomFldsToPageSet( $modules, $pageSet ) {
261 // Query all requested modules.
262 foreach ( $modules as $module ) {
263 $module->requestExtraData( $pageSet );
268 * Create instances of all modules requested by the client
269 * @param $modules array to append instatiated modules to
270 * @param $param string Parameter name to read modules from
271 * @param $moduleList array(modulename => classname)
273 private function InstantiateModules( &$modules, $param, $moduleList ) {
274 $list = @$this->params
[$param];
275 if ( !is_null ( $list ) ) {
276 foreach ( $list as $moduleName ) {
277 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
283 * Appends an element for each page in the current pageSet with the
284 * most general information (id, title), plus any title normalizations
285 * and missing or invalid title/pageids/revids.
287 private function outputGeneralPageInfo() {
288 $pageSet = $this->getPageSet();
289 $result = $this->getResult();
291 // We don't check for a full result set here because we can't be adding
292 // more than 380K. The maximum revision size is in the megabyte range,
293 // and the maximum result size must be even higher than that.
295 // Title normalizations
296 $normValues = array();
297 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
298 $normValues[] = array(
299 'from' => $rawTitleStr,
304 if ( count( $normValues ) ) {
305 $result->setIndexedTagName( $normValues, 'n' );
306 $result->addValue( 'query', 'normalized', $normValues );
310 $intrwValues = array();
311 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
312 $intrwValues[] = array(
313 'title' => $rawTitleStr,
314 'iw' => $interwikiStr
318 if ( count( $intrwValues ) ) {
319 $result->setIndexedTagName( $intrwValues, 'i' );
320 $result->addValue( 'query', 'interwiki', $intrwValues );
323 // Show redirect information
324 $redirValues = array();
325 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
326 $redirValues[] = array(
327 'from' => strval( $titleStrFrom ),
332 if ( count( $redirValues ) ) {
333 $result->setIndexedTagName( $redirValues, 'r' );
334 $result->addValue( 'query', 'redirects', $redirValues );
338 // Missing revision elements
340 $missingRevIDs = $pageSet->getMissingRevisionIDs();
341 if ( count( $missingRevIDs ) ) {
343 foreach ( $missingRevIDs as $revid ) {
344 $revids[$revid] = array(
348 $result->setIndexedTagName( $revids, 'rev' );
349 $result->addValue( 'query', 'badrevids', $revids );
357 // Report any missing titles
358 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
360 ApiQueryBase
::addTitleInfo( $vals, $title );
361 $vals['missing'] = '';
362 $pages[$fakeId] = $vals;
364 // Report any invalid titles
365 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
366 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
368 // Report any missing page ids
369 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
370 $pages[$pageid] = array(
376 // Output general page information for found titles
377 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
379 $vals['pageid'] = $pageid;
380 ApiQueryBase
::addTitleInfo( $vals, $title );
381 $pages[$pageid] = $vals;
384 if ( count( $pages ) ) {
385 if ( $this->params
['indexpageids'] ) {
386 $pageIDs = array_keys( $pages );
387 // json treats all map keys as strings - converting to match
388 $pageIDs = array_map( 'strval', $pageIDs );
389 $result->setIndexedTagName( $pageIDs, 'id' );
390 $result->addValue( 'query', 'pageids', $pageIDs );
393 $result->setIndexedTagName( $pages, 'page' );
394 $result->addValue( 'query', 'pages', $pages );
396 if ( $this->params
['export'] ) {
397 $exporter = new WikiExporter( $this->getDB() );
398 // WikiExporter writes to stdout, so catch its
401 $exporter->openStream();
402 foreach ( @$pageSet->getGoodTitles() as $title ) {
403 if ( $title->userCanRead() ) {
404 $exporter->pageByTitle( $title );
407 $exporter->closeStream();
408 $exportxml = ob_get_contents();
411 // Don't check the size of exported stuff
412 // It's not continuable, so it would cause more
413 // problems than it'd solve
414 $result->disableSizeCheck();
415 if ( $this->params
['exportnowrap'] ) {
417 // Raw formatter will handle this
418 $result->addValue( null, 'text', $exportxml );
419 $result->addValue( null, 'mime', 'text/xml' );
422 ApiResult
::setContent( $r, $exportxml );
423 $result->addValue( 'query', 'export', $r );
425 $result->enableSizeCheck();
430 * For generator mode, execute generator, and use its output as new
432 * @param $generatorName string Module name
433 * @param $modules array of module objects
435 protected function executeGeneratorModule( $generatorName, $modules ) {
436 // Find class that implements requested generator
437 if ( isset( $this->mQueryListModules
[$generatorName] ) ) {
438 $className = $this->mQueryListModules
[$generatorName];
439 } elseif ( isset( $this->mQueryPropModules
[$generatorName] ) ) {
440 $className = $this->mQueryPropModules
[$generatorName];
442 ApiBase
::dieDebug( __METHOD__
, "Unknown generator=$generatorName" );
446 $resultPageSet = new ApiPageSet( $this, $this->redirects
);
448 // Create and execute the generator
449 $generator = new $className ( $this, $generatorName );
450 if ( !$generator instanceof ApiQueryGeneratorBase
) {
451 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
454 $generator->setGeneratorMode();
456 // Add any additional fields modules may need
457 $generator->requestExtraData( $this->mPageSet
);
458 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
460 // Populate page information with the original user input
461 $this->mPageSet
->execute();
463 // populate resultPageSet with the generator output
464 $generator->profileIn();
465 $generator->executeGenerator( $resultPageSet );
466 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
467 $resultPageSet->finishPageSetGeneration();
468 $generator->profileOut();
470 // Swap the resulting pageset back in
471 $this->mPageSet
= $resultPageSet;
474 public function getAllowedParams() {
477 ApiBase
::PARAM_ISMULTI
=> true,
478 ApiBase
::PARAM_TYPE
=> $this->mPropModuleNames
481 ApiBase
::PARAM_ISMULTI
=> true,
482 ApiBase
::PARAM_TYPE
=> $this->mListModuleNames
485 ApiBase
::PARAM_ISMULTI
=> true,
486 ApiBase
::PARAM_TYPE
=> $this->mMetaModuleNames
488 'generator' => array(
489 ApiBase
::PARAM_TYPE
=> $this->mAllowedGenerators
491 'redirects' => false,
492 'indexpageids' => false,
494 'exportnowrap' => false,
499 * Override the parent to generate help messages for all available query modules.
502 public function makeHelpMsg() {
505 // Make sure the internal object is empty
506 // (just in case a sub-module decides to optimize during instantiation)
507 $this->mPageSet
= null;
508 $this->mAllowedGenerators
= array(); // Will be repopulated
510 $astriks = str_repeat( '--- ', 8 );
511 $astriks2 = str_repeat( '*** ', 10 );
512 $msg .= "\n$astriks Query: Prop $astriks\n\n";
513 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules
, 'prop' );
514 $msg .= "\n$astriks Query: List $astriks\n\n";
515 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules
, 'list' );
516 $msg .= "\n$astriks Query: Meta $astriks\n\n";
517 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules
, 'meta' );
518 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
520 // Perform the base call last because the $this->mAllowedGenerators
521 // will be updated inside makeHelpMsgHelper()
522 // Use parent to make default message for the query module
523 $msg = parent
::makeHelpMsg() . $msg;
529 * For all modules in $moduleList, generate help messages and join them together
530 * @param $moduleList array(modulename => classname)
531 * @param $paramName string Parameter name
534 private function makeHelpMsgHelper( $moduleList, $paramName ) {
535 $moduleDescriptions = array();
537 foreach ( $moduleList as $moduleName => $moduleClass ) {
538 $module = new $moduleClass ( $this, $moduleName, null );
540 $msg = ApiMain
::makeHelpMsgHeader( $module, $paramName );
541 $msg2 = $module->makeHelpMsg();
542 if ( $msg2 !== false ) {
545 if ( $module instanceof ApiQueryGeneratorBase
) {
546 $this->mAllowedGenerators
[] = $moduleName;
547 $msg .= "Generator:\n This module may be used as a generator\n";
549 $moduleDescriptions[] = $msg;
552 return implode( "\n", $moduleDescriptions );
556 * Override to add extra parameters from PageSet
559 public function makeHelpMsgParameters() {
560 $psModule = new ApiPageSet( $this );
561 return $psModule->makeHelpMsgParameters() . parent
::makeHelpMsgParameters();
564 public function shouldCheckMaxlag() {
568 public function getParamDescription() {
570 'prop' => 'Which properties to get for the titles/revisions/pageids',
571 'list' => 'Which lists to get',
572 'meta' => 'Which meta data to get about the site',
573 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
574 'NOTE: generator parameter names must be prefixed with a \'g\', see examples.' ),
575 'redirects' => 'Automatically resolve redirects',
576 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
577 'export' => 'Export the current revisions of all given or generated pages',
578 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
582 public function getDescription() {
584 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
585 'and is loosely based on the old query.php interface.',
586 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
590 public function getPossibleErrors() {
591 return array_merge( parent
::getPossibleErrors(), array(
592 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
596 protected function getExamples() {
598 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
599 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
603 public function getVersion() {
604 $psModule = new ApiPageSet( $this );
606 $vers[] = __CLASS__
. ': $Id$';
607 $vers[] = $psModule->getVersion();