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 'categorymembers' => 'ApiQueryCategoryMembers',
66 'embeddedin' => 'ApiQueryBacklinks',
67 'imageusage' => 'ApiQueryBacklinks',
68 'logevents' => 'ApiQueryLogEvents',
69 'recentchanges' => 'ApiQueryRecentChanges',
70 'search' => 'ApiQuerySearch',
71 'usercontribs' => 'ApiQueryContributions',
72 'watchlist' => 'ApiQueryWatchlist',
73 'exturlusage' => 'ApiQueryExtLinksUsage',
76 private $mQueryMetaModules = array (
77 'siteinfo' => 'ApiQuerySiteinfo',
78 'userinfo' => 'ApiQueryUserInfo',
81 private $mSlaveDB = null;
82 private $mNamedDB = array();
84 public function __construct($main, $action) {
85 parent
:: __construct($main, $action);
87 // Allow custom modules to be added in LocalSettings.php
88 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
89 self
:: appendUserModules($this->mQueryPropModules
, $wgApiQueryPropModules);
90 self
:: appendUserModules($this->mQueryListModules
, $wgApiQueryListModules);
91 self
:: appendUserModules($this->mQueryMetaModules
, $wgApiQueryMetaModules);
93 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
94 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
95 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
97 // Allow the entire list of modules at first,
98 // but during module instantiation check if it can be used as a generator.
99 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
103 * Helper function to append any add-in modules to the list
105 private static function appendUserModules(&$modules, $newModules) {
106 if (is_array( $newModules )) {
107 foreach ( $newModules as $moduleName => $moduleClass) {
108 $modules[$moduleName] = $moduleClass;
114 * Gets a default slave database connection object
116 public function getDB() {
117 if (!isset ($this->mSlaveDB
)) {
118 $this->profileDBIn();
119 $this->mSlaveDB
= wfGetDB(DB_SLAVE
);
120 $this->profileDBOut();
122 return $this->mSlaveDB
;
126 * Get the query database connection with the given name.
127 * If no such connection has been requested before, it will be created.
128 * Subsequent calls with the same $name will return the same connection
129 * as the first, regardless of $db or $groups new values.
131 public function getNamedDB($name, $db, $groups) {
132 if (!array_key_exists($name, $this->mNamedDB
)) {
133 $this->profileDBIn();
134 $this->mNamedDB
[$name] = wfGetDB($db, $groups);
135 $this->profileDBOut();
137 return $this->mNamedDB
[$name];
141 * Gets the set of pages the user has requested (or generated)
143 public function getPageSet() {
144 return $this->mPageSet
;
148 * Query execution happens in the following steps:
149 * #1 Create a PageSet object with any pages requested by the user
150 * #2 If using generator, execute it to get a new PageSet object
151 * #3 Instantiate all requested modules.
152 * This way the PageSet object will know what shared data is required,
153 * and minimize DB calls.
154 * #4 Output all normalization and redirect resolution information
155 * #5 Execute all requested modules
157 public function execute() {
159 $this->params
= $this->extractRequestParams();
160 $this->redirects
= $this->params
['redirects'];
165 $this->mPageSet
= new ApiPageSet($this, $this->redirects
);
168 // Instantiate requested modules
171 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules
);
172 $this->InstantiateModules($modules, 'list', $this->mQueryListModules
);
173 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules
);
176 // If given, execute generator to substitute user supplied data with generated data.
178 if (isset ($this->params
['generator'])) {
179 $this->executeGeneratorModule($this->params
['generator'], $modules);
181 // Append custom fields and populate page/revision information
182 $this->addCustomFldsToPageSet($modules, $this->mPageSet
);
183 $this->mPageSet
->execute();
187 // Record page information (title, namespace, if exists, etc)
189 $this->outputGeneralPageInfo();
192 // Execute all requested modules.
194 foreach ($modules as $module) {
195 $module->profileIn();
197 $module->profileOut();
202 * Query modules may optimize data requests through the $this->getPageSet() object
203 * by adding extra fields from the page table.
204 * This function will gather all the extra request fields from the modules.
206 private function addCustomFldsToPageSet($modules, $pageSet) {
207 // Query all requested modules.
208 foreach ($modules as $module) {
209 $module->requestExtraData($pageSet);
214 * Create instances of all modules requested by the client
216 private function InstantiateModules(&$modules, $param, $moduleList) {
217 $list = $this->params
[$param];
219 foreach ($list as $moduleName)
220 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
224 * Appends an element for each page in the current pageSet with the most general
225 * information (id, title), plus any title normalizations and missing title/pageids/revids.
227 private function outputGeneralPageInfo() {
229 $pageSet = $this->getPageSet();
230 $result = $this->getResult();
232 // Title normalizations
233 $normValues = array ();
234 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
235 $normValues[] = array (
236 'from' => $rawTitleStr,
241 if (!empty ($normValues)) {
242 $result->setIndexedTagName($normValues, 'n');
243 $result->addValue('query', 'normalized', $normValues);
247 $intrwValues = array ();
248 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
249 $intrwValues[] = array (
250 'title' => $rawTitleStr,
251 'iw' => $interwikiStr
255 if (!empty ($intrwValues)) {
256 $result->setIndexedTagName($intrwValues, 'i');
257 $result->addValue('query', 'interwiki', $intrwValues);
260 // Show redirect information
261 $redirValues = array ();
262 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
263 $redirValues[] = array (
264 'from' => $titleStrFrom,
269 if (!empty ($redirValues)) {
270 $result->setIndexedTagName($redirValues, 'r');
271 $result->addValue('query', 'redirects', $redirValues);
275 // Missing revision elements
277 $missingRevIDs = $pageSet->getMissingRevisionIDs();
278 if (!empty ($missingRevIDs)) {
280 foreach ($missingRevIDs as $revid) {
281 $revids[$revid] = array (
285 $result->setIndexedTagName($revids, 'rev');
286 $result->addValue('query', 'badrevids', $revids);
294 // Report any missing titles
295 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
297 ApiQueryBase
:: addTitleInfo($vals, $title);
298 $vals['missing'] = '';
299 $pages[$fakeId] = $vals;
302 // Report any missing page ids
303 foreach ($pageSet->getMissingPageIDs() as $pageid) {
304 $pages[$pageid] = array (
310 // Output general page information for found titles
311 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
313 $vals['pageid'] = $pageid;
314 ApiQueryBase
:: addTitleInfo($vals, $title);
315 $pages[$pageid] = $vals;
318 if (!empty ($pages)) {
320 if ($this->params
['indexpageids']) {
321 $pageIDs = array_keys($pages);
322 // json treats all map keys as strings - converting to match
323 $pageIDs = array_map('strval', $pageIDs);
324 $result->setIndexedTagName($pageIDs, 'id');
325 $result->addValue('query', 'pageids', $pageIDs);
328 $result->setIndexedTagName($pages, 'page');
329 $result->addValue('query', 'pages', $pages);
334 * For generator mode, execute generator, and use its output as new pageSet
336 protected function executeGeneratorModule($generatorName, $modules) {
338 // Find class that implements requested generator
339 if (isset ($this->mQueryListModules
[$generatorName])) {
340 $className = $this->mQueryListModules
[$generatorName];
341 } elseif (isset ($this->mQueryPropModules
[$generatorName])) {
342 $className = $this->mQueryPropModules
[$generatorName];
344 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
348 $resultPageSet = new ApiPageSet($this, $this->redirects
);
350 // Create and execute the generator
351 $generator = new $className ($this, $generatorName);
352 if (!$generator instanceof ApiQueryGeneratorBase
)
353 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
355 $generator->setGeneratorMode();
357 // Add any additional fields modules may need
358 $generator->requestExtraData($this->mPageSet
);
359 $this->addCustomFldsToPageSet($modules, $resultPageSet);
361 // Populate page information with the original user input
362 $this->mPageSet
->execute();
364 // populate resultPageSet with the generator output
365 $generator->profileIn();
366 $generator->executeGenerator($resultPageSet);
367 $resultPageSet->finishPageSetGeneration();
368 $generator->profileOut();
370 // Swap the resulting pageset back in
371 $this->mPageSet
= $resultPageSet;
375 * Returns the list of allowed parameters for this module.
376 * Qurey module also lists all ApiPageSet parameters as its own.
378 protected function getAllowedParams() {
381 ApiBase
:: PARAM_ISMULTI
=> true,
382 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
385 ApiBase
:: PARAM_ISMULTI
=> true,
386 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
389 ApiBase
:: PARAM_ISMULTI
=> true,
390 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
392 'generator' => array (
393 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
395 'redirects' => false,
396 'indexpageids' => false,
401 * Override the parent to generate help messages for all available query modules.
403 public function makeHelpMsg() {
407 // Make sure the internal object is empty
408 // (just in case a sub-module decides to optimize during instantiation)
409 $this->mPageSet
= null;
410 $this->mAllowedGenerators
= array(); // Will be repopulated
412 $astriks = str_repeat('--- ', 8);
413 $msg .= "\n$astriks Query: Prop $astriks\n\n";
414 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
415 $msg .= "\n$astriks Query: List $astriks\n\n";
416 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
417 $msg .= "\n$astriks Query: Meta $astriks\n\n";
418 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
420 // Perform the base call last because the $this->mAllowedGenerators
421 // will be updated inside makeHelpMsgHelper()
422 // Use parent to make default message for the query module
423 $msg = parent
:: makeHelpMsg() . $msg;
429 * For all modules in $moduleList, generate help messages and join them together
431 private function makeHelpMsgHelper($moduleList, $paramName) {
433 $moduleDscriptions = array ();
435 foreach ($moduleList as $moduleName => $moduleClass) {
436 $module = new $moduleClass ($this, $moduleName, null);
438 $msg = ApiMain
::makeHelpMsgHeader($module, $paramName);
439 $msg2 = $module->makeHelpMsg();
442 if ($module instanceof ApiQueryGeneratorBase
) {
443 $this->mAllowedGenerators
[] = $moduleName;
444 $msg .= "Generator:\n This module may be used as a generator\n";
446 $moduleDscriptions[] = $msg;
449 return implode("\n", $moduleDscriptions);
453 * Override to add extra parameters from PageSet
455 public function makeHelpMsgParameters() {
456 $psModule = new ApiPageSet($this);
457 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
460 // @todo should work correctly
461 public function shouldCheckMaxlag() {
465 protected function getParamDescription() {
467 'prop' => 'Which properties to get for the titles/revisions/pageids',
468 'list' => 'Which lists to get',
469 'meta' => 'Which meta data to get about the site',
470 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
471 'redirects' => 'Automatically resolve redirects',
472 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
476 protected function getDescription() {
478 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
479 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
480 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
484 protected function getExamples() {
486 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
490 public function getVersion() {
491 $psModule = new ApiPageSet($this);
493 $vers[] = __CLASS__
. ': $Id$';
494 $vers[] = $psModule->getVersion();