af7f8304061036e5d419f681f865e2126b8fa6e9
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 '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',
63 private $mQueryListModules = array(
64 'allimages' => 'ApiQueryAllimages',
65 'allpages' => 'ApiQueryAllpages',
66 'alllinks' => 'ApiQueryAllLinks',
67 'allcategories' => 'ApiQueryAllCategories',
68 'allusers' => 'ApiQueryAllUsers',
69 'backlinks' => 'ApiQueryBacklinks',
70 'blocks' => 'ApiQueryBlocks',
71 'categorymembers' => 'ApiQueryCategoryMembers',
72 'deletedrevs' => 'ApiQueryDeletedrevs',
73 'embeddedin' => 'ApiQueryBacklinks',
74 'filearchive' => 'ApiQueryFilearchive',
75 'imageusage' => 'ApiQueryBacklinks',
76 'logevents' => 'ApiQueryLogEvents',
77 'recentchanges' => 'ApiQueryRecentChanges',
78 'search' => 'ApiQuerySearch',
79 'tags' => 'ApiQueryTags',
80 'usercontribs' => 'ApiQueryContributions',
81 'watchlist' => 'ApiQueryWatchlist',
82 'watchlistraw' => 'ApiQueryWatchlistRaw',
83 'exturlusage' => 'ApiQueryExtLinksUsage',
84 'users' => 'ApiQueryUsers',
85 'random' => 'ApiQueryRandom',
86 'protectedtitles' => 'ApiQueryProtectedTitles',
89 private $mQueryMetaModules = array(
90 'siteinfo' => 'ApiQuerySiteinfo',
91 'userinfo' => 'ApiQueryUserInfo',
92 'allmessages' => 'ApiQueryAllmessages',
95 private $mSlaveDB = null;
96 private $mNamedDB = array();
98 public function __construct( $main, $action ) {
99 parent
::__construct( $main, $action );
101 // Allow custom modules to be added in LocalSettings.php
102 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
103 self
::appendUserModules( $this->mQueryPropModules
, $wgAPIPropModules );
104 self
::appendUserModules( $this->mQueryListModules
, $wgAPIListModules );
105 self
::appendUserModules( $this->mQueryMetaModules
, $wgAPIMetaModules );
107 $this->mPropModuleNames
= array_keys( $this->mQueryPropModules
);
108 $this->mListModuleNames
= array_keys( $this->mQueryListModules
);
109 $this->mMetaModuleNames
= array_keys( $this->mQueryMetaModules
);
111 // Allow the entire list of modules at first,
112 // but during module instantiation check if it can be used as a generator.
113 $this->mAllowedGenerators
= array_merge( $this->mListModuleNames
, $this->mPropModuleNames
);
117 * Helper function to append any add-in modules to the list
118 * @param $modules array Module array
119 * @param $newModules array Module array to add to $modules
121 private static function appendUserModules( &$modules, $newModules ) {
122 if ( is_array( $newModules ) ) {
123 foreach ( $newModules as $moduleName => $moduleClass ) {
124 $modules[$moduleName] = $moduleClass;
130 * Gets a default slave database connection object
133 public function getDB() {
134 if ( !isset( $this->mSlaveDB
) ) {
135 $this->profileDBIn();
136 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
137 $this->profileDBOut();
139 return $this->mSlaveDB
;
143 * Get the query database connection with the given name.
144 * If no such connection has been requested before, it will be created.
145 * Subsequent calls with the same $name will return the same connection
146 * as the first, regardless of the values of $db and $groups
147 * @param $name string Name to assign to the database connection
148 * @param $db int One of the DB_* constants
149 * @param $groups array Query groups
152 public function getNamedDB( $name, $db, $groups ) {
153 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
154 $this->profileDBIn();
155 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
156 $this->profileDBOut();
158 return $this->mNamedDB
[$name];
162 * Gets the set of pages the user has requested (or generated)
165 public function getPageSet() {
166 return $this->mPageSet
;
170 * Get the array mapping module names to class names
171 * @return array(modulename => classname)
173 function getModules() {
174 return array_merge( $this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
178 * Get whether the specified module is a prop, list or a meta query module
179 * @param $moduleName string Name of the module to find type for
180 * @return mixed string or null
182 function getModuleType( $moduleName ) {
183 if ( array_key_exists ( $moduleName, $this->mQueryPropModules
) ) {
187 if ( array_key_exists ( $moduleName, $this->mQueryListModules
) ) {
191 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules
) ) {
198 public function getCustomPrinter() {
199 // If &exportnowrap is set, use the raw formatter
200 if ( $this->getParameter( 'export' ) &&
201 $this->getParameter( 'exportnowrap' ) )
203 return new ApiFormatRaw( $this->getMain(),
204 $this->getMain()->createPrinterByName( 'xml' ) );
211 * Query execution happens in the following steps:
212 * #1 Create a PageSet object with any pages requested by the user
213 * #2 If using a generator, execute it to get a new ApiPageSet object
214 * #3 Instantiate all requested modules.
215 * This way the PageSet object will know what shared data is required,
216 * and minimize DB calls.
217 * #4 Output all normalization and redirect resolution information
218 * #5 Execute all requested modules
220 public function execute() {
221 $this->params
= $this->extractRequestParams();
222 $this->redirects
= $this->params
['redirects'];
225 $this->mPageSet
= new ApiPageSet( $this, $this->redirects
);
227 // Instantiate requested modules
229 $this->InstantiateModules( $modules, 'prop', $this->mQueryPropModules
);
230 $this->InstantiateModules( $modules, 'list', $this->mQueryListModules
);
231 $this->InstantiateModules( $modules, 'meta', $this->mQueryMetaModules
);
233 // If given, execute generator to substitute user supplied data with generated data.
234 if ( isset( $this->params
['generator'] ) ) {
235 $this->executeGeneratorModule( $this->params
['generator'], $modules );
237 // Append custom fields and populate page/revision information
238 $this->addCustomFldsToPageSet( $modules, $this->mPageSet
);
239 $this->mPageSet
->execute();
242 // Record page information (title, namespace, if exists, etc)
243 $this->outputGeneralPageInfo();
245 // Execute all requested modules.
246 foreach ( $modules as $module ) {
247 $module->profileIn();
249 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
250 $module->profileOut();
255 * Query modules may optimize data requests through the $this->getPageSet() object
256 * by adding extra fields from the page table.
257 * This function will gather all the extra request fields from the modules.
258 * @param $modules array of module objects
259 * @param $pageSet ApiPageSet
261 private function addCustomFldsToPageSet( $modules, $pageSet ) {
262 // Query all requested modules.
263 foreach ( $modules as $module ) {
264 $module->requestExtraData( $pageSet );
269 * Create instances of all modules requested by the client
270 * @param $modules array to append instatiated modules to
271 * @param $param string Parameter name to read modules from
272 * @param $moduleList array(modulename => classname)
274 private function InstantiateModules( &$modules, $param, $moduleList ) {
275 $list = @$this->params
[$param];
276 if ( !is_null ( $list ) ) {
277 foreach ( $list as $moduleName ) {
278 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
284 * Appends an element for each page in the current pageSet with the
285 * most general information (id, title), plus any title normalizations
286 * and missing or invalid title/pageids/revids.
288 private function outputGeneralPageInfo() {
289 $pageSet = $this->getPageSet();
290 $result = $this->getResult();
292 // We don't check for a full result set here because we can't be adding
293 // more than 380K. The maximum revision size is in the megabyte range,
294 // and the maximum result size must be even higher than that.
296 // Title normalizations
297 $normValues = array();
298 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
299 $normValues[] = array(
300 'from' => $rawTitleStr,
305 if ( count( $normValues ) ) {
306 $result->setIndexedTagName( $normValues, 'n' );
307 $result->addValue( 'query', 'normalized', $normValues );
311 $intrwValues = array();
312 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
313 $intrwValues[] = array(
314 'title' => $rawTitleStr,
315 'iw' => $interwikiStr
319 if ( count( $intrwValues ) ) {
320 $result->setIndexedTagName( $intrwValues, 'i' );
321 $result->addValue( 'query', 'interwiki', $intrwValues );
324 // Show redirect information
325 $redirValues = array();
326 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
327 $redirValues[] = array(
328 'from' => strval( $titleStrFrom ),
333 if ( count( $redirValues ) ) {
334 $result->setIndexedTagName( $redirValues, 'r' );
335 $result->addValue( 'query', 'redirects', $redirValues );
339 // Missing revision elements
341 $missingRevIDs = $pageSet->getMissingRevisionIDs();
342 if ( count( $missingRevIDs ) ) {
344 foreach ( $missingRevIDs as $revid ) {
345 $revids[$revid] = array(
349 $result->setIndexedTagName( $revids, 'rev' );
350 $result->addValue( 'query', 'badrevids', $revids );
358 // Report any missing titles
359 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
361 ApiQueryBase
::addTitleInfo( $vals, $title );
362 $vals['missing'] = '';
363 $pages[$fakeId] = $vals;
365 // Report any invalid titles
366 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
367 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
369 // Report any missing page ids
370 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
371 $pages[$pageid] = array(
377 // Output general page information for found titles
378 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
380 $vals['pageid'] = $pageid;
381 ApiQueryBase
::addTitleInfo( $vals, $title );
382 $pages[$pageid] = $vals;
385 if ( count( $pages ) ) {
386 if ( $this->params
['indexpageids'] ) {
387 $pageIDs = array_keys( $pages );
388 // json treats all map keys as strings - converting to match
389 $pageIDs = array_map( 'strval', $pageIDs );
390 $result->setIndexedTagName( $pageIDs, 'id' );
391 $result->addValue( 'query', 'pageids', $pageIDs );
394 $result->setIndexedTagName( $pages, 'page' );
395 $result->addValue( 'query', 'pages', $pages );
397 if ( $this->params
['export'] ) {
398 $exporter = new WikiExporter( $this->getDB() );
399 // WikiExporter writes to stdout, so catch its
402 $exporter->openStream();
403 foreach ( @$pageSet->getGoodTitles() as $title ) {
404 if ( $title->userCanRead() ) {
405 $exporter->pageByTitle( $title );
408 $exporter->closeStream();
409 $exportxml = ob_get_contents();
412 // Don't check the size of exported stuff
413 // It's not continuable, so it would cause more
414 // problems than it'd solve
415 $result->disableSizeCheck();
416 if ( $this->params
['exportnowrap'] ) {
418 // Raw formatter will handle this
419 $result->addValue( null, 'text', $exportxml );
420 $result->addValue( null, 'mime', 'text/xml' );
423 ApiResult
::setContent( $r, $exportxml );
424 $result->addValue( 'query', 'export', $r );
426 $result->enableSizeCheck();
431 * For generator mode, execute generator, and use its output as new
433 * @param $generatorName string Module name
434 * @param $modules array of module objects
436 protected function executeGeneratorModule( $generatorName, $modules ) {
437 // Find class that implements requested generator
438 if ( isset( $this->mQueryListModules
[$generatorName] ) ) {
439 $className = $this->mQueryListModules
[$generatorName];
440 } elseif ( isset( $this->mQueryPropModules
[$generatorName] ) ) {
441 $className = $this->mQueryPropModules
[$generatorName];
443 ApiBase
::dieDebug( __METHOD__
, "Unknown generator=$generatorName" );
447 $resultPageSet = new ApiPageSet( $this, $this->redirects
);
449 // Create and execute the generator
450 $generator = new $className ( $this, $generatorName );
451 if ( !$generator instanceof ApiQueryGeneratorBase
) {
452 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
455 $generator->setGeneratorMode();
457 // Add any additional fields modules may need
458 $generator->requestExtraData( $this->mPageSet
);
459 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
461 // Populate page information with the original user input
462 $this->mPageSet
->execute();
464 // populate resultPageSet with the generator output
465 $generator->profileIn();
466 $generator->executeGenerator( $resultPageSet );
467 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
468 $resultPageSet->finishPageSetGeneration();
469 $generator->profileOut();
471 // Swap the resulting pageset back in
472 $this->mPageSet
= $resultPageSet;
475 public function getAllowedParams() {
478 ApiBase
::PARAM_ISMULTI
=> true,
479 ApiBase
::PARAM_TYPE
=> $this->mPropModuleNames
482 ApiBase
::PARAM_ISMULTI
=> true,
483 ApiBase
::PARAM_TYPE
=> $this->mListModuleNames
486 ApiBase
::PARAM_ISMULTI
=> true,
487 ApiBase
::PARAM_TYPE
=> $this->mMetaModuleNames
489 'generator' => array(
490 ApiBase
::PARAM_TYPE
=> $this->mAllowedGenerators
492 'redirects' => false,
493 'indexpageids' => false,
495 'exportnowrap' => false,
500 * Override the parent to generate help messages for all available query modules.
503 public function makeHelpMsg() {
506 // Make sure the internal object is empty
507 // (just in case a sub-module decides to optimize during instantiation)
508 $this->mPageSet
= null;
509 $this->mAllowedGenerators
= array(); // Will be repopulated
511 $astriks = str_repeat( '--- ', 8 );
512 $astriks2 = str_repeat( '*** ', 10 );
513 $msg .= "\n$astriks Query: Prop $astriks\n\n";
514 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules
, 'prop' );
515 $msg .= "\n$astriks Query: List $astriks\n\n";
516 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules
, 'list' );
517 $msg .= "\n$astriks Query: Meta $astriks\n\n";
518 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules
, 'meta' );
519 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
521 // Perform the base call last because the $this->mAllowedGenerators
522 // will be updated inside makeHelpMsgHelper()
523 // Use parent to make default message for the query module
524 $msg = parent
::makeHelpMsg() . $msg;
530 * For all modules in $moduleList, generate help messages and join them together
531 * @param $moduleList array(modulename => classname)
532 * @param $paramName string Parameter name
535 private function makeHelpMsgHelper( $moduleList, $paramName ) {
536 $moduleDescriptions = array();
538 foreach ( $moduleList as $moduleName => $moduleClass ) {
539 $module = new $moduleClass ( $this, $moduleName, null );
541 $msg = ApiMain
::makeHelpMsgHeader( $module, $paramName );
542 $msg2 = $module->makeHelpMsg();
543 if ( $msg2 !== false ) {
546 if ( $module instanceof ApiQueryGeneratorBase
) {
547 $this->mAllowedGenerators
[] = $moduleName;
548 $msg .= "Generator:\n This module may be used as a generator\n";
550 $moduleDescriptions[] = $msg;
553 return implode( "\n", $moduleDescriptions );
557 * Override to add extra parameters from PageSet
560 public function makeHelpMsgParameters() {
561 $psModule = new ApiPageSet( $this );
562 return $psModule->makeHelpMsgParameters() . parent
::makeHelpMsgParameters();
565 public function shouldCheckMaxlag() {
569 public function getParamDescription() {
571 'prop' => 'Which properties to get for the titles/revisions/pageids',
572 'list' => 'Which lists to get',
573 'meta' => 'Which metadata to get about the site',
574 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
575 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
576 'redirects' => 'Automatically resolve redirects',
577 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
578 'export' => 'Export the current revisions of all given or generated pages',
579 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
583 public function getDescription() {
585 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
586 'and is loosely based on the old query.php interface.',
587 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
591 public function getPossibleErrors() {
592 return array_merge( parent
::getPossibleErrors(), array(
593 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
597 protected function getExamples() {
599 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
600 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
604 public function getVersion() {
605 $psModule = new ApiPageSet( $this );
607 $vers[] = __CLASS__
. ': $Id$';
608 $vers[] = $psModule->getVersion();