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 'allcategories' => 'ApiQueryAllCategories',
64 'allusers' => 'ApiQueryAllUsers',
65 'backlinks' => 'ApiQueryBacklinks',
66 'blocks' => 'ApiQueryBlocks',
67 'categorymembers' => 'ApiQueryCategoryMembers',
68 'deletedrevs' => 'ApiQueryDeletedrevs',
69 'embeddedin' => 'ApiQueryBacklinks',
70 'imageusage' => 'ApiQueryBacklinks',
71 'logevents' => 'ApiQueryLogEvents',
72 'recentchanges' => 'ApiQueryRecentChanges',
73 'search' => 'ApiQuerySearch',
74 'usercontribs' => 'ApiQueryContributions',
75 'watchlist' => 'ApiQueryWatchlist',
76 'exturlusage' => 'ApiQueryExtLinksUsage',
77 'users' => 'ApiQueryUsers',
78 'random' => 'ApiQueryRandom',
81 private $mQueryMetaModules = array (
82 'siteinfo' => 'ApiQuerySiteinfo',
83 'userinfo' => 'ApiQueryUserInfo',
84 'allmessages' => 'ApiQueryAllmessages',
87 private $mSlaveDB = null;
88 private $mNamedDB = array();
90 public function __construct($main, $action) {
91 parent
:: __construct($main, $action);
93 // Allow custom modules to be added in LocalSettings.php
94 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
95 self
:: appendUserModules($this->mQueryPropModules
, $wgApiQueryPropModules);
96 self
:: appendUserModules($this->mQueryListModules
, $wgApiQueryListModules);
97 self
:: appendUserModules($this->mQueryMetaModules
, $wgApiQueryMetaModules);
99 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
100 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
101 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
103 // Allow the entire list of modules at first,
104 // but during module instantiation check if it can be used as a generator.
105 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
109 * Helper function to append any add-in modules to the list
111 private static function appendUserModules(&$modules, $newModules) {
112 if (is_array( $newModules )) {
113 foreach ( $newModules as $moduleName => $moduleClass) {
114 $modules[$moduleName] = $moduleClass;
120 * Gets a default slave database connection object
122 public function getDB() {
123 if (!isset ($this->mSlaveDB
)) {
124 $this->profileDBIn();
125 $this->mSlaveDB
= wfGetDB(DB_SLAVE
);
126 $this->profileDBOut();
128 return $this->mSlaveDB
;
132 * Get the query database connection with the given name.
133 * If no such connection has been requested before, it will be created.
134 * Subsequent calls with the same $name will return the same connection
135 * as the first, regardless of $db or $groups new values.
137 public function getNamedDB($name, $db, $groups) {
138 if (!array_key_exists($name, $this->mNamedDB
)) {
139 $this->profileDBIn();
140 $this->mNamedDB
[$name] = wfGetDB($db, $groups);
141 $this->profileDBOut();
143 return $this->mNamedDB
[$name];
147 * Gets the set of pages the user has requested (or generated)
149 public function getPageSet() {
150 return $this->mPageSet
;
154 * Get the array mapping module names to class names
156 function getModules() {
157 return array_merge($this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
161 * Query execution happens in the following steps:
162 * #1 Create a PageSet object with any pages requested by the user
163 * #2 If using generator, execute it to get a new PageSet object
164 * #3 Instantiate all requested modules.
165 * This way the PageSet object will know what shared data is required,
166 * and minimize DB calls.
167 * #4 Output all normalization and redirect resolution information
168 * #5 Execute all requested modules
170 public function execute() {
172 $this->params
= $this->extractRequestParams();
173 $this->redirects
= $this->params
['redirects'];
178 $this->mPageSet
= new ApiPageSet($this, $this->redirects
);
181 // Instantiate requested modules
184 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules
);
185 $this->InstantiateModules($modules, 'list', $this->mQueryListModules
);
186 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules
);
189 // If given, execute generator to substitute user supplied data with generated data.
191 if (isset ($this->params
['generator'])) {
192 $this->executeGeneratorModule($this->params
['generator'], $modules);
194 // Append custom fields and populate page/revision information
195 $this->addCustomFldsToPageSet($modules, $this->mPageSet
);
196 $this->mPageSet
->execute();
200 // Record page information (title, namespace, if exists, etc)
202 $this->outputGeneralPageInfo();
205 // Execute all requested modules.
207 foreach ($modules as $module) {
208 $module->profileIn();
210 $module->profileOut();
215 * Query modules may optimize data requests through the $this->getPageSet() object
216 * by adding extra fields from the page table.
217 * This function will gather all the extra request fields from the modules.
219 private function addCustomFldsToPageSet($modules, $pageSet) {
220 // Query all requested modules.
221 foreach ($modules as $module) {
222 $module->requestExtraData($pageSet);
227 * Create instances of all modules requested by the client
229 private function InstantiateModules(&$modules, $param, $moduleList) {
230 $list = $this->params
[$param];
232 foreach ($list as $moduleName)
233 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
237 * Appends an element for each page in the current pageSet with the most general
238 * information (id, title), plus any title normalizations and missing title/pageids/revids.
240 private function outputGeneralPageInfo() {
242 $pageSet = $this->getPageSet();
243 $result = $this->getResult();
245 // Title normalizations
246 $normValues = array ();
247 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
248 $normValues[] = array (
249 'from' => $rawTitleStr,
254 if (!empty ($normValues)) {
255 $result->setIndexedTagName($normValues, 'n');
256 $result->addValue('query', 'normalized', $normValues);
260 $intrwValues = array ();
261 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
262 $intrwValues[] = array (
263 'title' => $rawTitleStr,
264 'iw' => $interwikiStr
268 if (!empty ($intrwValues)) {
269 $result->setIndexedTagName($intrwValues, 'i');
270 $result->addValue('query', 'interwiki', $intrwValues);
273 // Show redirect information
274 $redirValues = array ();
275 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
276 $redirValues[] = array (
277 'from' => $titleStrFrom,
282 if (!empty ($redirValues)) {
283 $result->setIndexedTagName($redirValues, 'r');
284 $result->addValue('query', 'redirects', $redirValues);
288 // Missing revision elements
290 $missingRevIDs = $pageSet->getMissingRevisionIDs();
291 if (!empty ($missingRevIDs)) {
293 foreach ($missingRevIDs as $revid) {
294 $revids[$revid] = array (
298 $result->setIndexedTagName($revids, 'rev');
299 $result->addValue('query', 'badrevids', $revids);
307 // Report any missing titles
308 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
310 ApiQueryBase
:: addTitleInfo($vals, $title);
311 $vals['missing'] = '';
312 $pages[$fakeId] = $vals;
315 // Report any missing page ids
316 foreach ($pageSet->getMissingPageIDs() as $pageid) {
317 $pages[$pageid] = array (
323 // Output general page information for found titles
324 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
326 $vals['pageid'] = $pageid;
327 ApiQueryBase
:: addTitleInfo($vals, $title);
328 $pages[$pageid] = $vals;
331 if (!empty ($pages)) {
333 if ($this->params
['indexpageids']) {
334 $pageIDs = array_keys($pages);
335 // json treats all map keys as strings - converting to match
336 $pageIDs = array_map('strval', $pageIDs);
337 $result->setIndexedTagName($pageIDs, 'id');
338 $result->addValue('query', 'pageids', $pageIDs);
341 $result->setIndexedTagName($pages, 'page');
342 $result->addValue('query', 'pages', $pages);
347 * For generator mode, execute generator, and use its output as new pageSet
349 protected function executeGeneratorModule($generatorName, $modules) {
351 // Find class that implements requested generator
352 if (isset ($this->mQueryListModules
[$generatorName])) {
353 $className = $this->mQueryListModules
[$generatorName];
354 } elseif (isset ($this->mQueryPropModules
[$generatorName])) {
355 $className = $this->mQueryPropModules
[$generatorName];
357 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
361 $resultPageSet = new ApiPageSet($this, $this->redirects
);
363 // Create and execute the generator
364 $generator = new $className ($this, $generatorName);
365 if (!$generator instanceof ApiQueryGeneratorBase
)
366 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
368 $generator->setGeneratorMode();
370 // Add any additional fields modules may need
371 $generator->requestExtraData($this->mPageSet
);
372 $this->addCustomFldsToPageSet($modules, $resultPageSet);
374 // Populate page information with the original user input
375 $this->mPageSet
->execute();
377 // populate resultPageSet with the generator output
378 $generator->profileIn();
379 $generator->executeGenerator($resultPageSet);
380 $resultPageSet->finishPageSetGeneration();
381 $generator->profileOut();
383 // Swap the resulting pageset back in
384 $this->mPageSet
= $resultPageSet;
388 * Returns the list of allowed parameters for this module.
389 * Qurey module also lists all ApiPageSet parameters as its own.
391 public function getAllowedParams() {
394 ApiBase
:: PARAM_ISMULTI
=> true,
395 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
398 ApiBase
:: PARAM_ISMULTI
=> true,
399 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
402 ApiBase
:: PARAM_ISMULTI
=> true,
403 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
405 'generator' => array (
406 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
408 'redirects' => false,
409 'indexpageids' => false,
414 * Override the parent to generate help messages for all available query modules.
416 public function makeHelpMsg() {
420 // Make sure the internal object is empty
421 // (just in case a sub-module decides to optimize during instantiation)
422 $this->mPageSet
= null;
423 $this->mAllowedGenerators
= array(); // Will be repopulated
425 $astriks = str_repeat('--- ', 8);
426 $msg .= "\n$astriks Query: Prop $astriks\n\n";
427 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
428 $msg .= "\n$astriks Query: List $astriks\n\n";
429 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
430 $msg .= "\n$astriks Query: Meta $astriks\n\n";
431 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
433 // Perform the base call last because the $this->mAllowedGenerators
434 // will be updated inside makeHelpMsgHelper()
435 // Use parent to make default message for the query module
436 $msg = parent
:: makeHelpMsg() . $msg;
442 * For all modules in $moduleList, generate help messages and join them together
444 private function makeHelpMsgHelper($moduleList, $paramName) {
446 $moduleDscriptions = array ();
448 foreach ($moduleList as $moduleName => $moduleClass) {
449 $module = new $moduleClass ($this, $moduleName, null);
451 $msg = ApiMain
::makeHelpMsgHeader($module, $paramName);
452 $msg2 = $module->makeHelpMsg();
455 if ($module instanceof ApiQueryGeneratorBase
) {
456 $this->mAllowedGenerators
[] = $moduleName;
457 $msg .= "Generator:\n This module may be used as a generator\n";
459 $moduleDscriptions[] = $msg;
462 return implode("\n", $moduleDscriptions);
466 * Override to add extra parameters from PageSet
468 public function makeHelpMsgParameters() {
469 $psModule = new ApiPageSet($this);
470 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
473 // @todo should work correctly
474 public function shouldCheckMaxlag() {
478 public function getParamDescription() {
480 'prop' => 'Which properties to get for the titles/revisions/pageids',
481 'list' => 'Which lists to get',
482 'meta' => 'Which meta data to get about the site',
483 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
484 'redirects' => 'Automatically resolve redirects',
485 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
489 public function getDescription() {
491 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
492 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
493 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
497 protected function getExamples() {
499 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
503 public function getVersion() {
504 $psModule = new ApiPageSet($this);
506 $vers[] = __CLASS__
. ': $Id$';
507 $vers[] = $psModule->getVersion();