Reverted r42528. Links with href="#" make firefox scroll to the top of the page,...
[mediawiki.git] / includes / api / ApiQuery.php
blobbcec619f6fe174b0b01a35a132b49cefea7d55ec
1 <?php
3 /*
4 * Created on Sep 7, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 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');
31 /**
32 * This is the main query class. It behaves similar to ApiMain: based on the parameters given,
33 * it will create a list of titles to work on (an instance of the ApiPageSet object)
34 * instantiate and execute various property/list/meta modules,
35 * and assemble all resulting data into a single ApiResult object.
37 * In the generator mode, a generator will be first executed to populate a second ApiPageSet object,
38 * 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 '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 'imageusage' => 'ApiQueryBacklinks',
74 'logevents' => 'ApiQueryLogEvents',
75 'recentchanges' => 'ApiQueryRecentChanges',
76 'search' => 'ApiQuerySearch',
77 'usercontribs' => 'ApiQueryContributions',
78 'watchlist' => 'ApiQueryWatchlist',
79 'watchlistraw' => 'ApiQueryWatchlistRaw',
80 'exturlusage' => 'ApiQueryExtLinksUsage',
81 'users' => 'ApiQueryUsers',
82 'random' => 'ApiQueryRandom',
85 private $mQueryMetaModules = array (
86 'siteinfo' => 'ApiQuerySiteinfo',
87 'userinfo' => 'ApiQueryUserInfo',
88 'allmessages' => 'ApiQueryAllmessages',
91 private $mSlaveDB = null;
92 private $mNamedDB = array();
94 public function __construct($main, $action) {
95 parent :: __construct($main, $action);
97 // Allow custom modules to be added in LocalSettings.php
98 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
99 self :: appendUserModules($this->mQueryPropModules, $wgAPIPropModules);
100 self :: appendUserModules($this->mQueryListModules, $wgAPIListModules);
101 self :: appendUserModules($this->mQueryMetaModules, $wgAPIMetaModules);
103 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
104 $this->mListModuleNames = array_keys($this->mQueryListModules);
105 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
107 // Allow the entire list of modules at first,
108 // but during module instantiation check if it can be used as a generator.
109 $this->mAllowedGenerators = array_merge($this->mListModuleNames, $this->mPropModuleNames);
113 * Helper function to append any add-in modules to the list
115 private static function appendUserModules(&$modules, $newModules) {
116 if (is_array( $newModules )) {
117 foreach ( $newModules as $moduleName => $moduleClass) {
118 $modules[$moduleName] = $moduleClass;
124 * Gets a default slave database connection object
126 public function getDB() {
127 if (!isset ($this->mSlaveDB)) {
128 $this->profileDBIn();
129 $this->mSlaveDB = wfGetDB(DB_SLAVE,'api');
130 $this->profileDBOut();
132 return $this->mSlaveDB;
136 * Get the query database connection with the given name.
137 * If no such connection has been requested before, it will be created.
138 * Subsequent calls with the same $name will return the same connection
139 * as the first, regardless of $db or $groups new values.
141 public function getNamedDB($name, $db, $groups) {
142 if (!array_key_exists($name, $this->mNamedDB)) {
143 $this->profileDBIn();
144 $this->mNamedDB[$name] = wfGetDB($db, $groups);
145 $this->profileDBOut();
147 return $this->mNamedDB[$name];
151 * Gets the set of pages the user has requested (or generated)
153 public function getPageSet() {
154 return $this->mPageSet;
158 * Get the array mapping module names to class names
160 function getModules() {
161 return array_merge($this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules);
165 * Query execution happens in the following steps:
166 * #1 Create a PageSet object with any pages requested by the user
167 * #2 If using generator, execute it to get a new PageSet object
168 * #3 Instantiate all requested modules.
169 * This way the PageSet object will know what shared data is required,
170 * and minimize DB calls.
171 * #4 Output all normalization and redirect resolution information
172 * #5 Execute all requested modules
174 public function execute() {
176 $this->params = $this->extractRequestParams();
177 $this->redirects = $this->params['redirects'];
180 // Create PageSet
182 $this->mPageSet = new ApiPageSet($this, $this->redirects);
185 // Instantiate requested modules
187 $modules = array ();
188 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
189 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
190 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
193 // If given, execute generator to substitute user supplied data with generated data.
195 if (isset ($this->params['generator'])) {
196 $this->executeGeneratorModule($this->params['generator'], $modules);
197 } else {
198 // Append custom fields and populate page/revision information
199 $this->addCustomFldsToPageSet($modules, $this->mPageSet);
200 $this->mPageSet->execute();
204 // Record page information (title, namespace, if exists, etc)
206 $this->outputGeneralPageInfo();
209 // Execute all requested modules.
211 foreach ($modules as $module) {
212 $module->profileIn();
213 $module->execute();
214 wfRunHooks('APIQueryAfterExecute', array(&$module));
215 $module->profileOut();
220 * Query modules may optimize data requests through the $this->getPageSet() object
221 * by adding extra fields from the page table.
222 * This function will gather all the extra request fields from the modules.
224 private function addCustomFldsToPageSet($modules, $pageSet) {
225 // Query all requested modules.
226 foreach ($modules as $module) {
227 $module->requestExtraData($pageSet);
232 * Create instances of all modules requested by the client
234 private function InstantiateModules(&$modules, $param, $moduleList) {
235 $list = @$this->params[$param];
236 if (!is_null ($list))
237 foreach ($list as $moduleName)
238 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
242 * Appends an element for each page in the current pageSet with the most general
243 * information (id, title), plus any title normalizations and missing or invalid title/pageids/revids.
245 private function outputGeneralPageInfo() {
247 $pageSet = $this->getPageSet();
248 $result = $this->getResult();
250 // Title normalizations
251 $normValues = array ();
252 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
253 $normValues[] = array (
254 'from' => $rawTitleStr,
255 'to' => $titleStr
259 if (!empty ($normValues)) {
260 $result->setIndexedTagName($normValues, 'n');
261 $result->addValue('query', 'normalized', $normValues);
264 // Interwiki titles
265 $intrwValues = array ();
266 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
267 $intrwValues[] = array (
268 'title' => $rawTitleStr,
269 'iw' => $interwikiStr
273 if (!empty ($intrwValues)) {
274 $result->setIndexedTagName($intrwValues, 'i');
275 $result->addValue('query', 'interwiki', $intrwValues);
278 // Show redirect information
279 $redirValues = array ();
280 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
281 $redirValues[] = array (
282 'from' => strval($titleStrFrom),
283 'to' => $titleStrTo
287 if (!empty ($redirValues)) {
288 $result->setIndexedTagName($redirValues, 'r');
289 $result->addValue('query', 'redirects', $redirValues);
293 // Missing revision elements
295 $missingRevIDs = $pageSet->getMissingRevisionIDs();
296 if (!empty ($missingRevIDs)) {
297 $revids = array ();
298 foreach ($missingRevIDs as $revid) {
299 $revids[$revid] = array (
300 'revid' => $revid
303 $result->setIndexedTagName($revids, 'rev');
304 $result->addValue('query', 'badrevids', $revids);
308 // Page elements
310 $pages = array ();
312 // Report any missing titles
313 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
314 $vals = array();
315 ApiQueryBase :: addTitleInfo($vals, $title);
316 $vals['missing'] = '';
317 $pages[$fakeId] = $vals;
319 // Report any invalid titles
320 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
321 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
322 // Report any missing page ids
323 foreach ($pageSet->getMissingPageIDs() as $pageid) {
324 $pages[$pageid] = array (
325 'pageid' => $pageid,
326 'missing' => ''
330 // Output general page information for found titles
331 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
332 $vals = array();
333 $vals['pageid'] = $pageid;
334 ApiQueryBase :: addTitleInfo($vals, $title);
335 $pages[$pageid] = $vals;
338 if (!empty ($pages)) {
340 if ($this->params['indexpageids']) {
341 $pageIDs = array_keys($pages);
342 // json treats all map keys as strings - converting to match
343 $pageIDs = array_map('strval', $pageIDs);
344 $result->setIndexedTagName($pageIDs, 'id');
345 $result->addValue('query', 'pageids', $pageIDs);
348 $result->setIndexedTagName($pages, 'page');
349 $result->addValue('query', 'pages', $pages);
354 * For generator mode, execute generator, and use its output as new pageSet
356 protected function executeGeneratorModule($generatorName, $modules) {
358 // Find class that implements requested generator
359 if (isset ($this->mQueryListModules[$generatorName])) {
360 $className = $this->mQueryListModules[$generatorName];
361 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
362 $className = $this->mQueryPropModules[$generatorName];
363 } else {
364 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
367 // Generator results
368 $resultPageSet = new ApiPageSet($this, $this->redirects);
370 // Create and execute the generator
371 $generator = new $className ($this, $generatorName);
372 if (!$generator instanceof ApiQueryGeneratorBase)
373 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
375 $generator->setGeneratorMode();
377 // Add any additional fields modules may need
378 $generator->requestExtraData($this->mPageSet);
379 $this->addCustomFldsToPageSet($modules, $resultPageSet);
381 // Populate page information with the original user input
382 $this->mPageSet->execute();
384 // populate resultPageSet with the generator output
385 $generator->profileIn();
386 $generator->executeGenerator($resultPageSet);
387 wfRunHooks('APIQueryGeneratorAfterExecute', array(&$generator, &$resultPageSet));
388 $resultPageSet->finishPageSetGeneration();
389 $generator->profileOut();
391 // Swap the resulting pageset back in
392 $this->mPageSet = $resultPageSet;
396 * Returns the list of allowed parameters for this module.
397 * Qurey module also lists all ApiPageSet parameters as its own.
399 public function getAllowedParams() {
400 return array (
401 'prop' => array (
402 ApiBase :: PARAM_ISMULTI => true,
403 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
405 'list' => array (
406 ApiBase :: PARAM_ISMULTI => true,
407 ApiBase :: PARAM_TYPE => $this->mListModuleNames
409 'meta' => array (
410 ApiBase :: PARAM_ISMULTI => true,
411 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
413 'generator' => array (
414 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
416 'redirects' => false,
417 'indexpageids' => false,
422 * Override the parent to generate help messages for all available query modules.
424 public function makeHelpMsg() {
426 $msg = '';
428 // Make sure the internal object is empty
429 // (just in case a sub-module decides to optimize during instantiation)
430 $this->mPageSet = null;
431 $this->mAllowedGenerators = array(); // Will be repopulated
433 $astriks = str_repeat('--- ', 8);
434 $astriks2 = str_repeat('*** ', 10);
435 $msg .= "\n$astriks Query: Prop $astriks\n\n";
436 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
437 $msg .= "\n$astriks Query: List $astriks\n\n";
438 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
439 $msg .= "\n$astriks Query: Meta $astriks\n\n";
440 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
441 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
443 // Perform the base call last because the $this->mAllowedGenerators
444 // will be updated inside makeHelpMsgHelper()
445 // Use parent to make default message for the query module
446 $msg = parent :: makeHelpMsg() . $msg;
448 return $msg;
452 * For all modules in $moduleList, generate help messages and join them together
454 private function makeHelpMsgHelper($moduleList, $paramName) {
456 $moduleDscriptions = array ();
458 foreach ($moduleList as $moduleName => $moduleClass) {
459 $module = new $moduleClass ($this, $moduleName, null);
461 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
462 $msg2 = $module->makeHelpMsg();
463 if ($msg2 !== false)
464 $msg .= $msg2;
465 if ($module instanceof ApiQueryGeneratorBase) {
466 $this->mAllowedGenerators[] = $moduleName;
467 $msg .= "Generator:\n This module may be used as a generator\n";
469 $moduleDscriptions[] = $msg;
472 return implode("\n", $moduleDscriptions);
476 * Override to add extra parameters from PageSet
478 public function makeHelpMsgParameters() {
479 $psModule = new ApiPageSet($this);
480 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
483 public function shouldCheckMaxlag() {
484 return true;
487 public function getParamDescription() {
488 return array (
489 'prop' => 'Which properties to get for the titles/revisions/pageids',
490 'list' => 'Which lists to get',
491 'meta' => 'Which meta data to get about the site',
492 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
493 'redirects' => 'Automatically resolve redirects',
494 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
498 public function getDescription() {
499 return array (
500 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
501 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
502 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
506 protected function getExamples() {
507 return array (
508 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
512 public function getVersion() {
513 $psModule = new ApiPageSet($this);
514 $vers = array ();
515 $vers[] = __CLASS__ . ': $Id$';
516 $vers[] = $psModule->getVersion();
517 return $vers;