* WTF was I thinking...
[mediawiki.git] / includes / api / ApiQuery.php
blobf14b462c3191828b737e31eb9b1c4b31d18653c5
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',
61 private $mQueryListModules = array (
62 'allimages' => 'ApiQueryAllimages',
63 'allpages' => 'ApiQueryAllpages',
64 'alllinks' => 'ApiQueryAllLinks',
65 'allcategories' => 'ApiQueryAllCategories',
66 'allusers' => 'ApiQueryAllUsers',
67 'backlinks' => 'ApiQueryBacklinks',
68 'blocks' => 'ApiQueryBlocks',
69 'categorymembers' => 'ApiQueryCategoryMembers',
70 'deletedrevs' => 'ApiQueryDeletedrevs',
71 'embeddedin' => 'ApiQueryBacklinks',
72 'imageusage' => 'ApiQueryBacklinks',
73 'logevents' => 'ApiQueryLogEvents',
74 'recentchanges' => 'ApiQueryRecentChanges',
75 'search' => 'ApiQuerySearch',
76 'usercontribs' => 'ApiQueryContributions',
77 'watchlist' => 'ApiQueryWatchlist',
78 'exturlusage' => 'ApiQueryExtLinksUsage',
79 'users' => 'ApiQueryUsers',
80 'random' => 'ApiQueryRandom',
83 private $mQueryMetaModules = array (
84 'siteinfo' => 'ApiQuerySiteinfo',
85 'userinfo' => 'ApiQueryUserInfo',
86 'allmessages' => 'ApiQueryAllmessages',
89 private $mSlaveDB = null;
90 private $mNamedDB = array();
92 public function __construct($main, $action) {
93 parent :: __construct($main, $action);
95 // Allow custom modules to be added in LocalSettings.php
96 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
97 self :: appendUserModules($this->mQueryPropModules, $wgApiQueryPropModules);
98 self :: appendUserModules($this->mQueryListModules, $wgApiQueryListModules);
99 self :: appendUserModules($this->mQueryMetaModules, $wgApiQueryMetaModules);
101 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
102 $this->mListModuleNames = array_keys($this->mQueryListModules);
103 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
105 // Allow the entire list of modules at first,
106 // but during module instantiation check if it can be used as a generator.
107 $this->mAllowedGenerators = array_merge($this->mListModuleNames, $this->mPropModuleNames);
111 * Helper function to append any add-in modules to the list
113 private static function appendUserModules(&$modules, $newModules) {
114 if (is_array( $newModules )) {
115 foreach ( $newModules as $moduleName => $moduleClass) {
116 $modules[$moduleName] = $moduleClass;
122 * Gets a default slave database connection object
124 public function getDB() {
125 if (!isset ($this->mSlaveDB)) {
126 $this->profileDBIn();
127 $this->mSlaveDB = wfGetDB(DB_SLAVE,'api');
128 $this->profileDBOut();
130 return $this->mSlaveDB;
134 * Get the query database connection with the given name.
135 * If no such connection has been requested before, it will be created.
136 * Subsequent calls with the same $name will return the same connection
137 * as the first, regardless of $db or $groups new values.
139 public function getNamedDB($name, $db, $groups) {
140 if (!array_key_exists($name, $this->mNamedDB)) {
141 $this->profileDBIn();
142 $this->mNamedDB[$name] = wfGetDB($db, $groups);
143 $this->profileDBOut();
145 return $this->mNamedDB[$name];
149 * Gets the set of pages the user has requested (or generated)
151 public function getPageSet() {
152 return $this->mPageSet;
156 * Get the array mapping module names to class names
158 function getModules() {
159 return array_merge($this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules);
163 * Query execution happens in the following steps:
164 * #1 Create a PageSet object with any pages requested by the user
165 * #2 If using generator, execute it to get a new PageSet object
166 * #3 Instantiate all requested modules.
167 * This way the PageSet object will know what shared data is required,
168 * and minimize DB calls.
169 * #4 Output all normalization and redirect resolution information
170 * #5 Execute all requested modules
172 public function execute() {
174 $this->params = $this->extractRequestParams();
175 $this->redirects = $this->params['redirects'];
178 // Create PageSet
180 $this->mPageSet = new ApiPageSet($this, $this->redirects);
183 // Instantiate requested modules
185 $modules = array ();
186 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
187 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
188 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
191 // If given, execute generator to substitute user supplied data with generated data.
193 if (isset ($this->params['generator'])) {
194 $this->executeGeneratorModule($this->params['generator'], $modules);
195 } else {
196 // Append custom fields and populate page/revision information
197 $this->addCustomFldsToPageSet($modules, $this->mPageSet);
198 $this->mPageSet->execute();
202 // Record page information (title, namespace, if exists, etc)
204 $this->outputGeneralPageInfo();
207 // Execute all requested modules.
209 foreach ($modules as $module) {
210 $module->profileIn();
211 $module->execute();
212 $module->profileOut();
217 * Query modules may optimize data requests through the $this->getPageSet() object
218 * by adding extra fields from the page table.
219 * This function will gather all the extra request fields from the modules.
221 private function addCustomFldsToPageSet($modules, $pageSet) {
222 // Query all requested modules.
223 foreach ($modules as $module) {
224 $module->requestExtraData($pageSet);
229 * Create instances of all modules requested by the client
231 private function InstantiateModules(&$modules, $param, $moduleList) {
232 $list = $this->params[$param];
233 if (isset ($list))
234 foreach ($list as $moduleName)
235 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
239 * Appends an element for each page in the current pageSet with the most general
240 * information (id, title), plus any title normalizations and missing or invalid title/pageids/revids.
242 private function outputGeneralPageInfo() {
244 $pageSet = $this->getPageSet();
245 $result = $this->getResult();
247 // Title normalizations
248 $normValues = array ();
249 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
250 $normValues[] = array (
251 'from' => $rawTitleStr,
252 'to' => $titleStr
256 if (!empty ($normValues)) {
257 $result->setIndexedTagName($normValues, 'n');
258 $result->addValue('query', 'normalized', $normValues);
261 // Interwiki titles
262 $intrwValues = array ();
263 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
264 $intrwValues[] = array (
265 'title' => $rawTitleStr,
266 'iw' => $interwikiStr
270 if (!empty ($intrwValues)) {
271 $result->setIndexedTagName($intrwValues, 'i');
272 $result->addValue('query', 'interwiki', $intrwValues);
275 // Show redirect information
276 $redirValues = array ();
277 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
278 $redirValues[] = array (
279 'from' => strval($titleStrFrom),
280 'to' => $titleStrTo
284 if (!empty ($redirValues)) {
285 $result->setIndexedTagName($redirValues, 'r');
286 $result->addValue('query', 'redirects', $redirValues);
290 // Missing revision elements
292 $missingRevIDs = $pageSet->getMissingRevisionIDs();
293 if (!empty ($missingRevIDs)) {
294 $revids = array ();
295 foreach ($missingRevIDs as $revid) {
296 $revids[$revid] = array (
297 'revid' => $revid
300 $result->setIndexedTagName($revids, 'rev');
301 $result->addValue('query', 'badrevids', $revids);
305 // Page elements
307 $pages = array ();
309 // Report any missing titles
310 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
311 $vals = array();
312 ApiQueryBase :: addTitleInfo($vals, $title);
313 $vals['missing'] = '';
314 $pages[$fakeId] = $vals;
316 // Report any invalid titles
317 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
318 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
319 // Report any missing page ids
320 foreach ($pageSet->getMissingPageIDs() as $pageid) {
321 $pages[$pageid] = array (
322 'pageid' => $pageid,
323 'missing' => ''
327 // Output general page information for found titles
328 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
329 $vals = array();
330 $vals['pageid'] = $pageid;
331 ApiQueryBase :: addTitleInfo($vals, $title);
332 $pages[$pageid] = $vals;
335 if (!empty ($pages)) {
337 if ($this->params['indexpageids']) {
338 $pageIDs = array_keys($pages);
339 // json treats all map keys as strings - converting to match
340 $pageIDs = array_map('strval', $pageIDs);
341 $result->setIndexedTagName($pageIDs, 'id');
342 $result->addValue('query', 'pageids', $pageIDs);
345 $result->setIndexedTagName($pages, 'page');
346 $result->addValue('query', 'pages', $pages);
351 * For generator mode, execute generator, and use its output as new pageSet
353 protected function executeGeneratorModule($generatorName, $modules) {
355 // Find class that implements requested generator
356 if (isset ($this->mQueryListModules[$generatorName])) {
357 $className = $this->mQueryListModules[$generatorName];
358 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
359 $className = $this->mQueryPropModules[$generatorName];
360 } else {
361 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
364 // Generator results
365 $resultPageSet = new ApiPageSet($this, $this->redirects);
367 // Create and execute the generator
368 $generator = new $className ($this, $generatorName);
369 if (!$generator instanceof ApiQueryGeneratorBase)
370 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
372 $generator->setGeneratorMode();
374 // Add any additional fields modules may need
375 $generator->requestExtraData($this->mPageSet);
376 $this->addCustomFldsToPageSet($modules, $resultPageSet);
378 // Populate page information with the original user input
379 $this->mPageSet->execute();
381 // populate resultPageSet with the generator output
382 $generator->profileIn();
383 $generator->executeGenerator($resultPageSet);
384 $resultPageSet->finishPageSetGeneration();
385 $generator->profileOut();
387 // Swap the resulting pageset back in
388 $this->mPageSet = $resultPageSet;
392 * Returns the list of allowed parameters for this module.
393 * Qurey module also lists all ApiPageSet parameters as its own.
395 public function getAllowedParams() {
396 return array (
397 'prop' => array (
398 ApiBase :: PARAM_ISMULTI => true,
399 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
401 'list' => array (
402 ApiBase :: PARAM_ISMULTI => true,
403 ApiBase :: PARAM_TYPE => $this->mListModuleNames
405 'meta' => array (
406 ApiBase :: PARAM_ISMULTI => true,
407 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
409 'generator' => array (
410 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
412 'redirects' => false,
413 'indexpageids' => false,
418 * Override the parent to generate help messages for all available query modules.
420 public function makeHelpMsg() {
422 $msg = '';
424 // Make sure the internal object is empty
425 // (just in case a sub-module decides to optimize during instantiation)
426 $this->mPageSet = null;
427 $this->mAllowedGenerators = array(); // Will be repopulated
429 $astriks = str_repeat('--- ', 8);
430 $astriks2 = str_repeat('*** ', 10);
431 $msg .= "\n$astriks Query: Prop $astriks\n\n";
432 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
433 $msg .= "\n$astriks Query: List $astriks\n\n";
434 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
435 $msg .= "\n$astriks Query: Meta $astriks\n\n";
436 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
437 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
439 // Perform the base call last because the $this->mAllowedGenerators
440 // will be updated inside makeHelpMsgHelper()
441 // Use parent to make default message for the query module
442 $msg = parent :: makeHelpMsg() . $msg;
444 return $msg;
448 * For all modules in $moduleList, generate help messages and join them together
450 private function makeHelpMsgHelper($moduleList, $paramName) {
452 $moduleDscriptions = array ();
454 foreach ($moduleList as $moduleName => $moduleClass) {
455 $module = new $moduleClass ($this, $moduleName, null);
457 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
458 $msg2 = $module->makeHelpMsg();
459 if ($msg2 !== false)
460 $msg .= $msg2;
461 if ($module instanceof ApiQueryGeneratorBase) {
462 $this->mAllowedGenerators[] = $moduleName;
463 $msg .= "Generator:\n This module may be used as a generator\n";
465 $moduleDscriptions[] = $msg;
468 return implode("\n", $moduleDscriptions);
472 * Override to add extra parameters from PageSet
474 public function makeHelpMsgParameters() {
475 $psModule = new ApiPageSet($this);
476 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
479 // @todo should work correctly
480 public function shouldCheckMaxlag() {
481 return true;
484 public function getParamDescription() {
485 return array (
486 'prop' => 'Which properties to get for the titles/revisions/pageids',
487 'list' => 'Which lists to get',
488 'meta' => 'Which meta data to get about the site',
489 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
490 'redirects' => 'Automatically resolve redirects',
491 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
495 public function getDescription() {
496 return array (
497 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
498 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
499 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
503 protected function getExamples() {
504 return array (
505 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
509 public function getVersion() {
510 $psModule = new ApiPageSet($this);
511 $vers = array ();
512 $vers[] = __CLASS__ . ': $Id$';
513 $vers[] = $psModule->getVersion();
514 return $vers;