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');
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.
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',
60 private $mQueryListModules = array (
61 'allpages' => 'ApiQueryAllpages',
62 'alllinks' => 'ApiQueryAllLinks',
63 'allusers' => 'ApiQueryAllUsers',
64 'backlinks' => 'ApiQueryBacklinks',
65 'blocks' => 'ApiQueryBlocks',
66 'categorymembers' => 'ApiQueryCategoryMembers',
67 'deletedrevs' => 'ApiQueryDeletedrevs',
68 'embeddedin' => 'ApiQueryBacklinks',
69 'imageusage' => 'ApiQueryBacklinks',
70 'logevents' => 'ApiQueryLogEvents',
71 'recentchanges' => 'ApiQueryRecentChanges',
72 'search' => 'ApiQuerySearch',
73 'usercontribs' => 'ApiQueryContributions',
74 'watchlist' => 'ApiQueryWatchlist',
75 'exturlusage' => 'ApiQueryExtLinksUsage',
78 private $mQueryMetaModules = array (
79 'siteinfo' => 'ApiQuerySiteinfo',
80 'userinfo' => 'ApiQueryUserInfo',
81 'allmessages' => 'ApiQueryAllmessages',
84 private $mSlaveDB = null;
85 private $mNamedDB = array();
87 public function __construct($main, $action) {
88 parent
:: __construct($main, $action);
90 // Allow custom modules to be added in LocalSettings.php
91 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
92 self
:: appendUserModules($this->mQueryPropModules
, $wgApiQueryPropModules);
93 self
:: appendUserModules($this->mQueryListModules
, $wgApiQueryListModules);
94 self
:: appendUserModules($this->mQueryMetaModules
, $wgApiQueryMetaModules);
96 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
97 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
98 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
100 // Allow the entire list of modules at first,
101 // but during module instantiation check if it can be used as a generator.
102 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
106 * Helper function to append any add-in modules to the list
108 private static function appendUserModules(&$modules, $newModules) {
109 if (is_array( $newModules )) {
110 foreach ( $newModules as $moduleName => $moduleClass) {
111 $modules[$moduleName] = $moduleClass;
117 * Gets a default slave database connection object
119 public function getDB() {
120 if (!isset ($this->mSlaveDB
)) {
121 $this->profileDBIn();
122 $this->mSlaveDB
= wfGetDB(DB_SLAVE
);
123 $this->profileDBOut();
125 return $this->mSlaveDB
;
129 * Get the query database connection with the given name.
130 * If no such connection has been requested before, it will be created.
131 * Subsequent calls with the same $name will return the same connection
132 * as the first, regardless of $db or $groups new values.
134 public function getNamedDB($name, $db, $groups) {
135 if (!array_key_exists($name, $this->mNamedDB
)) {
136 $this->profileDBIn();
137 $this->mNamedDB
[$name] = wfGetDB($db, $groups);
138 $this->profileDBOut();
140 return $this->mNamedDB
[$name];
144 * Gets the set of pages the user has requested (or generated)
146 public function getPageSet() {
147 return $this->mPageSet
;
151 * Query execution happens in the following steps:
152 * #1 Create a PageSet object with any pages requested by the user
153 * #2 If using generator, execute it to get a new PageSet object
154 * #3 Instantiate all requested modules.
155 * This way the PageSet object will know what shared data is required,
156 * and minimize DB calls.
157 * #4 Output all normalization and redirect resolution information
158 * #5 Execute all requested modules
160 public function execute() {
162 $this->params
= $this->extractRequestParams();
163 $this->redirects
= $this->params
['redirects'];
168 $this->mPageSet
= new ApiPageSet($this, $this->redirects
);
171 // Instantiate requested modules
174 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules
);
175 $this->InstantiateModules($modules, 'list', $this->mQueryListModules
);
176 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules
);
179 // If given, execute generator to substitute user supplied data with generated data.
181 if (isset ($this->params
['generator'])) {
182 $this->executeGeneratorModule($this->params
['generator'], $modules);
184 // Append custom fields and populate page/revision information
185 $this->addCustomFldsToPageSet($modules, $this->mPageSet
);
186 $this->mPageSet
->execute();
190 // Record page information (title, namespace, if exists, etc)
192 $this->outputGeneralPageInfo();
195 // Execute all requested modules.
197 foreach ($modules as $module) {
198 $module->profileIn();
200 $module->profileOut();
205 * Query modules may optimize data requests through the $this->getPageSet() object
206 * by adding extra fields from the page table.
207 * This function will gather all the extra request fields from the modules.
209 private function addCustomFldsToPageSet($modules, $pageSet) {
210 // Query all requested modules.
211 foreach ($modules as $module) {
212 $module->requestExtraData($pageSet);
217 * Create instances of all modules requested by the client
219 private function InstantiateModules(&$modules, $param, $moduleList) {
220 $list = $this->params
[$param];
222 foreach ($list as $moduleName)
223 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
227 * Appends an element for each page in the current pageSet with the most general
228 * information (id, title), plus any title normalizations and missing title/pageids/revids.
230 private function outputGeneralPageInfo() {
232 $pageSet = $this->getPageSet();
233 $result = $this->getResult();
235 // Title normalizations
236 $normValues = array ();
237 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
238 $normValues[] = array (
239 'from' => $rawTitleStr,
244 if (!empty ($normValues)) {
245 $result->setIndexedTagName($normValues, 'n');
246 $result->addValue('query', 'normalized', $normValues);
250 $intrwValues = array ();
251 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
252 $intrwValues[] = array (
253 'title' => $rawTitleStr,
254 'iw' => $interwikiStr
258 if (!empty ($intrwValues)) {
259 $result->setIndexedTagName($intrwValues, 'i');
260 $result->addValue('query', 'interwiki', $intrwValues);
263 // Show redirect information
264 $redirValues = array ();
265 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
266 $redirValues[] = array (
267 'from' => $titleStrFrom,
272 if (!empty ($redirValues)) {
273 $result->setIndexedTagName($redirValues, 'r');
274 $result->addValue('query', 'redirects', $redirValues);
278 // Missing revision elements
280 $missingRevIDs = $pageSet->getMissingRevisionIDs();
281 if (!empty ($missingRevIDs)) {
283 foreach ($missingRevIDs as $revid) {
284 $revids[$revid] = array (
288 $result->setIndexedTagName($revids, 'rev');
289 $result->addValue('query', 'badrevids', $revids);
297 // Report any missing titles
298 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
300 ApiQueryBase
:: addTitleInfo($vals, $title);
301 $vals['missing'] = '';
302 $pages[$fakeId] = $vals;
305 // Report any missing page ids
306 foreach ($pageSet->getMissingPageIDs() as $pageid) {
307 $pages[$pageid] = array (
313 // Output general page information for found titles
314 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
316 $vals['pageid'] = $pageid;
317 ApiQueryBase
:: addTitleInfo($vals, $title);
318 $pages[$pageid] = $vals;
321 if (!empty ($pages)) {
323 if ($this->params
['indexpageids']) {
324 $pageIDs = array_keys($pages);
325 // json treats all map keys as strings - converting to match
326 $pageIDs = array_map('strval', $pageIDs);
327 $result->setIndexedTagName($pageIDs, 'id');
328 $result->addValue('query', 'pageids', $pageIDs);
331 $result->setIndexedTagName($pages, 'page');
332 $result->addValue('query', 'pages', $pages);
337 * For generator mode, execute generator, and use its output as new pageSet
339 protected function executeGeneratorModule($generatorName, $modules) {
341 // Find class that implements requested generator
342 if (isset ($this->mQueryListModules
[$generatorName])) {
343 $className = $this->mQueryListModules
[$generatorName];
344 } elseif (isset ($this->mQueryPropModules
[$generatorName])) {
345 $className = $this->mQueryPropModules
[$generatorName];
347 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
351 $resultPageSet = new ApiPageSet($this, $this->redirects
);
353 // Create and execute the generator
354 $generator = new $className ($this, $generatorName);
355 if (!$generator instanceof ApiQueryGeneratorBase
)
356 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
358 $generator->setGeneratorMode();
360 // Add any additional fields modules may need
361 $generator->requestExtraData($this->mPageSet
);
362 $this->addCustomFldsToPageSet($modules, $resultPageSet);
364 // Populate page information with the original user input
365 $this->mPageSet
->execute();
367 // populate resultPageSet with the generator output
368 $generator->profileIn();
369 $generator->executeGenerator($resultPageSet);
370 $resultPageSet->finishPageSetGeneration();
371 $generator->profileOut();
373 // Swap the resulting pageset back in
374 $this->mPageSet
= $resultPageSet;
378 * Returns the list of allowed parameters for this module.
379 * Qurey module also lists all ApiPageSet parameters as its own.
381 protected function getAllowedParams() {
384 ApiBase
:: PARAM_ISMULTI
=> true,
385 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
388 ApiBase
:: PARAM_ISMULTI
=> true,
389 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
392 ApiBase
:: PARAM_ISMULTI
=> true,
393 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
395 'generator' => array (
396 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
398 'redirects' => false,
399 'indexpageids' => false,
404 * Override the parent to generate help messages for all available query modules.
406 public function makeHelpMsg() {
410 // Make sure the internal object is empty
411 // (just in case a sub-module decides to optimize during instantiation)
412 $this->mPageSet
= null;
413 $this->mAllowedGenerators
= array(); // Will be repopulated
415 $astriks = str_repeat('--- ', 8);
416 $msg .= "\n$astriks Query: Prop $astriks\n\n";
417 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
418 $msg .= "\n$astriks Query: List $astriks\n\n";
419 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
420 $msg .= "\n$astriks Query: Meta $astriks\n\n";
421 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
423 // Perform the base call last because the $this->mAllowedGenerators
424 // will be updated inside makeHelpMsgHelper()
425 // Use parent to make default message for the query module
426 $msg = parent
:: makeHelpMsg() . $msg;
432 * For all modules in $moduleList, generate help messages and join them together
434 private function makeHelpMsgHelper($moduleList, $paramName) {
436 $moduleDscriptions = array ();
438 foreach ($moduleList as $moduleName => $moduleClass) {
439 $module = new $moduleClass ($this, $moduleName, null);
441 $msg = ApiMain
::makeHelpMsgHeader($module, $paramName);
442 $msg2 = $module->makeHelpMsg();
445 if ($module instanceof ApiQueryGeneratorBase
) {
446 $this->mAllowedGenerators
[] = $moduleName;
447 $msg .= "Generator:\n This module may be used as a generator\n";
449 $moduleDscriptions[] = $msg;
452 return implode("\n", $moduleDscriptions);
456 * Override to add extra parameters from PageSet
458 public function makeHelpMsgParameters() {
459 $psModule = new ApiPageSet($this);
460 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
463 // @todo should work correctly
464 public function shouldCheckMaxlag() {
468 protected function getParamDescription() {
470 'prop' => 'Which properties to get for the titles/revisions/pageids',
471 'list' => 'Which lists to get',
472 'meta' => 'Which meta data to get about the site',
473 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
474 'redirects' => 'Automatically resolve redirects',
475 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
479 protected function getDescription() {
481 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
482 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
483 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
487 protected function getExamples() {
489 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
493 public function getVersion() {
494 $psModule = new ApiPageSet($this);
496 $vers[] = __CLASS__
. ': $Id$';
497 $vers[] = $psModule->getVersion();