Follow-up r69203: remove str_replace( '_', ' ', $query ); was only needed for Special...
[mediawiki.git] / includes / api / ApiQuery.php
blob43a2caf1e140546f0342bc38776ab241b0c1f722
1 <?php
3 /**
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' );
31 /**
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.
40 * @ingroup API
42 class ApiQuery extends ApiBase {
44 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
45 private $mPageSet;
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 'iwbacklinks' => 'ApiQueryIWBacklinks',
77 'logevents' => 'ApiQueryLogEvents',
78 'recentchanges' => 'ApiQueryRecentChanges',
79 'search' => 'ApiQuerySearch',
80 'tags' => 'ApiQueryTags',
81 'usercontribs' => 'ApiQueryContributions',
82 'watchlist' => 'ApiQueryWatchlist',
83 'watchlistraw' => 'ApiQueryWatchlistRaw',
84 'exturlusage' => 'ApiQueryExtLinksUsage',
85 'users' => 'ApiQueryUsers',
86 'random' => 'ApiQueryRandom',
87 'protectedtitles' => 'ApiQueryProtectedTitles',
90 private $mQueryMetaModules = array(
91 'siteinfo' => 'ApiQuerySiteinfo',
92 'userinfo' => 'ApiQueryUserInfo',
93 'allmessages' => 'ApiQueryAllmessages',
96 private $mSlaveDB = null;
97 private $mNamedDB = array();
99 public function __construct( $main, $action ) {
100 parent::__construct( $main, $action );
102 // Allow custom modules to be added in LocalSettings.php
103 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
104 self::appendUserModules( $this->mQueryPropModules, $wgAPIPropModules );
105 self::appendUserModules( $this->mQueryListModules, $wgAPIListModules );
106 self::appendUserModules( $this->mQueryMetaModules, $wgAPIMetaModules );
108 $this->mPropModuleNames = array_keys( $this->mQueryPropModules );
109 $this->mListModuleNames = array_keys( $this->mQueryListModules );
110 $this->mMetaModuleNames = array_keys( $this->mQueryMetaModules );
112 // Allow the entire list of modules at first,
113 // but during module instantiation check if it can be used as a generator.
114 $this->mAllowedGenerators = array_merge( $this->mListModuleNames, $this->mPropModuleNames );
118 * Helper function to append any add-in modules to the list
119 * @param $modules array Module array
120 * @param $newModules array Module array to add to $modules
122 private static function appendUserModules( &$modules, $newModules ) {
123 if ( is_array( $newModules ) ) {
124 foreach ( $newModules as $moduleName => $moduleClass ) {
125 $modules[$moduleName] = $moduleClass;
131 * Gets a default slave database connection object
132 * @return Database
134 public function getDB() {
135 if ( !isset( $this->mSlaveDB ) ) {
136 $this->profileDBIn();
137 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
138 $this->profileDBOut();
140 return $this->mSlaveDB;
144 * Get the query database connection with the given name.
145 * If no such connection has been requested before, it will be created.
146 * Subsequent calls with the same $name will return the same connection
147 * as the first, regardless of the values of $db and $groups
148 * @param $name string Name to assign to the database connection
149 * @param $db int One of the DB_* constants
150 * @param $groups array Query groups
151 * @return Database
153 public function getNamedDB( $name, $db, $groups ) {
154 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
155 $this->profileDBIn();
156 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
157 $this->profileDBOut();
159 return $this->mNamedDB[$name];
163 * Gets the set of pages the user has requested (or generated)
164 * @return ApiPageSet
166 public function getPageSet() {
167 return $this->mPageSet;
171 * Get the array mapping module names to class names
172 * @return array(modulename => classname)
174 function getModules() {
175 return array_merge( $this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules );
179 * Get whether the specified module is a prop, list or a meta query module
180 * @param $moduleName string Name of the module to find type for
181 * @return mixed string or null
183 function getModuleType( $moduleName ) {
184 if ( array_key_exists ( $moduleName, $this->mQueryPropModules ) ) {
185 return 'prop';
188 if ( array_key_exists ( $moduleName, $this->mQueryListModules ) ) {
189 return 'list';
192 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules ) ) {
193 return 'meta';
196 return null;
199 public function getCustomPrinter() {
200 // If &exportnowrap is set, use the raw formatter
201 if ( $this->getParameter( 'export' ) &&
202 $this->getParameter( 'exportnowrap' ) )
204 return new ApiFormatRaw( $this->getMain(),
205 $this->getMain()->createPrinterByName( 'xml' ) );
206 } else {
207 return null;
212 * Query execution happens in the following steps:
213 * #1 Create a PageSet object with any pages requested by the user
214 * #2 If using a generator, execute it to get a new ApiPageSet object
215 * #3 Instantiate all requested modules.
216 * This way the PageSet object will know what shared data is required,
217 * and minimize DB calls.
218 * #4 Output all normalization and redirect resolution information
219 * #5 Execute all requested modules
221 public function execute() {
222 $this->params = $this->extractRequestParams();
223 $this->redirects = $this->params['redirects'];
224 $this->convertTitles = $this->params['converttitles'];
226 // Create PageSet
227 $this->mPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
229 // Instantiate requested modules
230 $modules = array();
231 $this->instantiateModules( $modules, 'prop', $this->mQueryPropModules );
232 $this->instantiateModules( $modules, 'list', $this->mQueryListModules );
233 $this->instantiateModules( $modules, 'meta', $this->mQueryMetaModules );
235 // If given, execute generator to substitute user supplied data with generated data.
236 if ( isset( $this->params['generator'] ) ) {
237 $this->executeGeneratorModule( $this->params['generator'], $modules );
238 } else {
239 // Append custom fields and populate page/revision information
240 $this->addCustomFldsToPageSet( $modules, $this->mPageSet );
241 $this->mPageSet->execute();
244 // Record page information (title, namespace, if exists, etc)
245 $this->outputGeneralPageInfo();
247 // Execute all requested modules.
248 foreach ( $modules as $module ) {
249 $module->profileIn();
250 $module->execute();
251 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
252 $module->profileOut();
257 * Query modules may optimize data requests through the $this->getPageSet() object
258 * by adding extra fields from the page table.
259 * This function will gather all the extra request fields from the modules.
260 * @param $modules array of module objects
261 * @param $pageSet ApiPageSet
263 private function addCustomFldsToPageSet( $modules, $pageSet ) {
264 // Query all requested modules.
265 foreach ( $modules as $module ) {
266 $module->requestExtraData( $pageSet );
271 * Create instances of all modules requested by the client
272 * @param $modules array to append instatiated modules to
273 * @param $param string Parameter name to read modules from
274 * @param $moduleList array(modulename => classname)
276 private function instantiateModules( &$modules, $param, $moduleList ) {
277 $list = @$this->params[$param];
278 if ( !is_null ( $list ) ) {
279 foreach ( $list as $moduleName ) {
280 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
286 * Appends an element for each page in the current pageSet with the
287 * most general information (id, title), plus any title normalizations
288 * and missing or invalid title/pageids/revids.
290 private function outputGeneralPageInfo() {
291 $pageSet = $this->getPageSet();
292 $result = $this->getResult();
294 // We don't check for a full result set here because we can't be adding
295 // more than 380K. The maximum revision size is in the megabyte range,
296 // and the maximum result size must be even higher than that.
298 // Title normalizations
299 $normValues = array();
300 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
301 $normValues[] = array(
302 'from' => $rawTitleStr,
303 'to' => $titleStr
307 if ( count( $normValues ) ) {
308 $result->setIndexedTagName( $normValues, 'n' );
309 $result->addValue( 'query', 'normalized', $normValues );
312 // Title conversions
313 $convValues = array();
314 foreach ( $pageSet->getConvertedTitles() as $rawTitleStr => $titleStr ) {
315 $convValues[] = array(
316 'from' => $rawTitleStr,
317 'to' => $titleStr
321 if ( count( $convValues ) ) {
322 $result->setIndexedTagName( $convValues, 'c' );
323 $result->addValue( 'query', 'converted', $convValues );
326 // Interwiki titles
327 $intrwValues = array();
328 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
329 $intrwValues[] = array(
330 'title' => $rawTitleStr,
331 'iw' => $interwikiStr
335 if ( count( $intrwValues ) ) {
336 $result->setIndexedTagName( $intrwValues, 'i' );
337 $result->addValue( 'query', 'interwiki', $intrwValues );
340 // Show redirect information
341 $redirValues = array();
342 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
343 $redirValues[] = array(
344 'from' => strval( $titleStrFrom ),
345 'to' => $titleStrTo
349 if ( count( $redirValues ) ) {
350 $result->setIndexedTagName( $redirValues, 'r' );
351 $result->addValue( 'query', 'redirects', $redirValues );
355 // Missing revision elements
357 $missingRevIDs = $pageSet->getMissingRevisionIDs();
358 if ( count( $missingRevIDs ) ) {
359 $revids = array();
360 foreach ( $missingRevIDs as $revid ) {
361 $revids[$revid] = array(
362 'revid' => $revid
365 $result->setIndexedTagName( $revids, 'rev' );
366 $result->addValue( 'query', 'badrevids', $revids );
370 // Page elements
372 $pages = array();
374 // Report any missing titles
375 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
376 $vals = array();
377 ApiQueryBase::addTitleInfo( $vals, $title );
378 $vals['missing'] = '';
379 $pages[$fakeId] = $vals;
381 // Report any invalid titles
382 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
383 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
385 // Report any missing page ids
386 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
387 $pages[$pageid] = array(
388 'pageid' => $pageid,
389 'missing' => ''
392 // Report special pages
393 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
394 $vals = array();
395 ApiQueryBase::addTitleInfo( $vals, $title );
396 $vals['special'] = '';
397 if ( $title->getNamespace() == NS_SPECIAL &&
398 !SpecialPage::exists( $title->getText() ) ) {
399 $vals['missing'] = '';
401 $pages[$fakeId] = $vals;
404 // Output general page information for found titles
405 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
406 $vals = array();
407 $vals['pageid'] = $pageid;
408 ApiQueryBase::addTitleInfo( $vals, $title );
409 $pages[$pageid] = $vals;
412 if ( count( $pages ) ) {
413 if ( $this->params['indexpageids'] ) {
414 $pageIDs = array_keys( $pages );
415 // json treats all map keys as strings - converting to match
416 $pageIDs = array_map( 'strval', $pageIDs );
417 $result->setIndexedTagName( $pageIDs, 'id' );
418 $result->addValue( 'query', 'pageids', $pageIDs );
421 $result->setIndexedTagName( $pages, 'page' );
422 $result->addValue( 'query', 'pages', $pages );
424 if ( $this->params['export'] ) {
425 $exporter = new WikiExporter( $this->getDB() );
426 // WikiExporter writes to stdout, so catch its
427 // output with an ob
428 ob_start();
429 $exporter->openStream();
430 foreach ( @$pageSet->getGoodTitles() as $title ) {
431 if ( $title->userCanRead() ) {
432 $exporter->pageByTitle( $title );
435 $exporter->closeStream();
436 $exportxml = ob_get_contents();
437 ob_end_clean();
439 // Don't check the size of exported stuff
440 // It's not continuable, so it would cause more
441 // problems than it'd solve
442 $result->disableSizeCheck();
443 if ( $this->params['exportnowrap'] ) {
444 $result->reset();
445 // Raw formatter will handle this
446 $result->addValue( null, 'text', $exportxml );
447 $result->addValue( null, 'mime', 'text/xml' );
448 } else {
449 $r = array();
450 ApiResult::setContent( $r, $exportxml );
451 $result->addValue( 'query', 'export', $r );
453 $result->enableSizeCheck();
458 * For generator mode, execute generator, and use its output as new
459 * ApiPageSet
460 * @param $generatorName string Module name
461 * @param $modules array of module objects
463 protected function executeGeneratorModule( $generatorName, $modules ) {
464 // Find class that implements requested generator
465 if ( isset( $this->mQueryListModules[$generatorName] ) ) {
466 $className = $this->mQueryListModules[$generatorName];
467 } elseif ( isset( $this->mQueryPropModules[$generatorName] ) ) {
468 $className = $this->mQueryPropModules[$generatorName];
469 } else {
470 ApiBase::dieDebug( __METHOD__, "Unknown generator=$generatorName" );
473 // Generator results
474 $resultPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
476 // Create and execute the generator
477 $generator = new $className ( $this, $generatorName );
478 if ( !$generator instanceof ApiQueryGeneratorBase ) {
479 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
482 $generator->setGeneratorMode();
484 // Add any additional fields modules may need
485 $generator->requestExtraData( $this->mPageSet );
486 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
488 // Populate page information with the original user input
489 $this->mPageSet->execute();
491 // populate resultPageSet with the generator output
492 $generator->profileIn();
493 $generator->executeGenerator( $resultPageSet );
494 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
495 $resultPageSet->finishPageSetGeneration();
496 $generator->profileOut();
498 // Swap the resulting pageset back in
499 $this->mPageSet = $resultPageSet;
502 public function getAllowedParams() {
503 return array(
504 'prop' => array(
505 ApiBase::PARAM_ISMULTI => true,
506 ApiBase::PARAM_TYPE => $this->mPropModuleNames
508 'list' => array(
509 ApiBase::PARAM_ISMULTI => true,
510 ApiBase::PARAM_TYPE => $this->mListModuleNames
512 'meta' => array(
513 ApiBase::PARAM_ISMULTI => true,
514 ApiBase::PARAM_TYPE => $this->mMetaModuleNames
516 'generator' => array(
517 ApiBase::PARAM_TYPE => $this->mAllowedGenerators
519 'redirects' => false,
520 'converttitles' => false,
521 'indexpageids' => false,
522 'export' => false,
523 'exportnowrap' => false,
528 * Override the parent to generate help messages for all available query modules.
529 * @return string
531 public function makeHelpMsg() {
532 $msg = '';
534 // Make sure the internal object is empty
535 // (just in case a sub-module decides to optimize during instantiation)
536 $this->mPageSet = null;
537 $this->mAllowedGenerators = array(); // Will be repopulated
539 $astriks = str_repeat( '--- ', 8 );
540 $astriks2 = str_repeat( '*** ', 10 );
541 $msg .= "\n$astriks Query: Prop $astriks\n\n";
542 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules, 'prop' );
543 $msg .= "\n$astriks Query: List $astriks\n\n";
544 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules, 'list' );
545 $msg .= "\n$astriks Query: Meta $astriks\n\n";
546 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules, 'meta' );
547 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
549 // Perform the base call last because the $this->mAllowedGenerators
550 // will be updated inside makeHelpMsgHelper()
551 // Use parent to make default message for the query module
552 $msg = parent::makeHelpMsg() . $msg;
554 return $msg;
558 * For all modules in $moduleList, generate help messages and join them together
559 * @param $moduleList array(modulename => classname)
560 * @param $paramName string Parameter name
561 * @return string
563 private function makeHelpMsgHelper( $moduleList, $paramName ) {
564 $moduleDescriptions = array();
566 foreach ( $moduleList as $moduleName => $moduleClass ) {
567 $module = new $moduleClass ( $this, $moduleName, null );
569 $msg = ApiMain::makeHelpMsgHeader( $module, $paramName );
570 $msg2 = $module->makeHelpMsg();
571 if ( $msg2 !== false ) {
572 $msg .= $msg2;
574 if ( $module instanceof ApiQueryGeneratorBase ) {
575 $this->mAllowedGenerators[] = $moduleName;
576 $msg .= "Generator:\n This module may be used as a generator\n";
578 $moduleDescriptions[] = $msg;
581 return implode( "\n", $moduleDescriptions );
585 * Override to add extra parameters from PageSet
586 * @return string
588 public function makeHelpMsgParameters() {
589 $psModule = new ApiPageSet( $this );
590 return $psModule->makeHelpMsgParameters() . parent::makeHelpMsgParameters();
593 public function shouldCheckMaxlag() {
594 return true;
597 public function getParamDescription() {
598 return array(
599 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
600 'list' => 'Which lists to get. Module help is available below',
601 'meta' => 'Which metadata to get about the site. Module help is available below',
602 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
603 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
604 'redirects' => 'Automatically resolve redirects',
605 'converttitles' => "Convert titles to other variants if necessary. Only works if the wiki's content language supports variant conversion.",
606 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
607 'export' => 'Export the current revisions of all given or generated pages',
608 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
612 public function getDescription() {
613 return array(
614 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
615 'and is loosely based on the old query.php interface.',
616 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
620 public function getPossibleErrors() {
621 return array_merge( parent::getPossibleErrors(), array(
622 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
623 ) );
626 protected function getExamples() {
627 return array(
628 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
629 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
633 public function getVersion() {
634 $psModule = new ApiPageSet( $this );
635 $vers = array();
636 $vers[] = __CLASS__ . ': $Id$';
637 $vers[] = $psModule->getVersion();
638 return $vers;