b3e05672db1f53b80d16881c0e6992f419ffef31
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;
47 private $mQueryPropModules = array (
48 'info' => 'ApiQueryInfo',
49 'revisions' => 'ApiQueryRevisions',
50 'links' => 'ApiQueryLinks',
51 'langlinks' => 'ApiQueryLangLinks',
52 'images' => 'ApiQueryImages',
53 'templates' => 'ApiQueryLinks',
54 'categories' => 'ApiQueryCategories',
55 'extlinks' => 'ApiQueryExternalLinks',
57 // 'categories' => 'ApiQueryCategories',
58 // 'imageinfo' => 'ApiQueryImageinfo',
59 // 'templates' => 'ApiQueryTemplates',
61 private $mQueryListModules = array (
62 'allpages' => 'ApiQueryAllpages',
63 'logevents' => 'ApiQueryLogEvents',
64 'watchlist' => 'ApiQueryWatchlist',
65 'recentchanges' => 'ApiQueryRecentChanges',
66 'backlinks' => 'ApiQueryBacklinks',
67 'embeddedin' => 'ApiQueryBacklinks',
68 'imageusage' => 'ApiQueryBacklinks',
69 'usercontribs' => 'ApiQueryContributions'
71 // 'categorymembers' => 'ApiQueryCategorymembers',
72 // 'recentchanges' => 'ApiQueryRecentchanges',
73 // 'users' => 'ApiQueryUsers',
74 // 'watchlist' => 'ApiQueryWatchlist',
76 private $mQueryMetaModules = array (
77 'siteinfo' => 'ApiQuerySiteinfo'
79 // '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;
90 if (is_array( $wgApiQueryPropModules )) {
91 foreach ( $wgApiQueryPropModules as $moduleName => $moduleClass) {
92 $this->mQueryPropModules
[$moduleName] = $moduleClass;
95 if (is_array( $wgApiQueryListModules )) {
96 foreach ( $wgApiQueryListModules as $moduleName => $moduleClass) {
97 $this->mQueryListModules
[$moduleName] = $moduleClass;
100 if (is_array( $wgApiQueryMetaModules )) {
101 foreach ( $wgApiQueryMetaModules as $moduleName => $moduleClass) {
102 $this->mQueryMetaModules
[$moduleName] = $moduleClass;
106 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
107 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
108 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
110 // Allow the entire list of modules at first,
111 // but during module instantiation check if it can be used as a generator.
112 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
115 public function getDB() {
116 if (!isset ($this->mSlaveDB
)) {
117 $this->profileDBIn();
118 $this->mSlaveDB
= wfGetDB(DB_SLAVE
);
119 $this->profileDBOut();
121 return $this->mSlaveDB
;
125 * Get the query database connection with the given name.
126 * If no such connection has been requested before, it will be created.
127 * Subsequent calls with the same $name will return the same connection
128 * as the first, regardless of $db or $groups new values.
130 public function getNamedDB($name, $db, $groups) {
131 if (!array_key_exists($name, $this->mNamedDB
)) {
132 $this->profileDBIn();
133 $this->mNamedDB
[$name] = wfGetDB($db, $groups);
134 $this->profileDBOut();
136 return $this->mNamedDB
[$name];
139 public function getPageSet() {
140 return $this->mPageSet
;
144 * Query execution happens in the following steps:
145 * #1 Create a PageSet object with any pages requested by the user
146 * #2 If using generator, execute it to get a new PageSet object
147 * #3 Instantiate all requested modules.
148 * This way the PageSet object will know what shared data is required,
149 * and minimize DB calls.
150 * #4 Output all normalization and redirect resolution information
151 * #5 Execute all requested modules
153 public function execute() {
154 $prop = $list = $meta = $generator = $redirects = null;
155 extract($this->extractRequestParams());
160 $this->mPageSet
= new ApiPageSet($this, $redirects);
162 // Instantiate required modules
165 foreach ($prop as $moduleName)
166 $modules[] = new $this->mQueryPropModules
[$moduleName] ($this, $moduleName);
168 foreach ($list as $moduleName)
169 $modules[] = new $this->mQueryListModules
[$moduleName] ($this, $moduleName);
171 foreach ($meta as $moduleName)
172 $modules[] = new $this->mQueryMetaModules
[$moduleName] ($this, $moduleName);
174 // Modules may optimize data requests through the $this->getPageSet() object
175 // Execute all requested modules.
176 foreach ($modules as $module) {
177 $module->requestExtraData();
181 // Populate page information for the given pageSet
183 $this->mPageSet
->execute();
186 // If given, execute generator to substitute user supplied data with generated data.
188 if (isset ($generator))
189 $this->executeGeneratorModule($generator, $redirects);
192 // Record page information (title, namespace, if exists, etc)
194 $this->outputGeneralPageInfo();
197 // Execute all requested modules.
199 foreach ($modules as $module) {
200 $module->profileIn();
202 $module->profileOut();
206 private function outputGeneralPageInfo() {
208 $pageSet = $this->getPageSet();
209 $result = $this->getResult();
211 // Title normalizations
212 $normValues = array ();
213 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
214 $normValues[] = array (
215 'from' => $rawTitleStr,
220 if (!empty ($normValues)) {
221 $result->setIndexedTagName($normValues, 'n');
222 $result->addValue('query', 'normalized', $normValues);
225 // Show redirect information
226 $redirValues = array ();
227 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
228 $redirValues[] = array (
229 'from' => $titleStrFrom,
234 if (!empty ($redirValues)) {
235 $result->setIndexedTagName($redirValues, 'r');
236 $result->addValue('query', 'redirects', $redirValues);
240 // Missing revision elements
242 $missingRevIDs = $pageSet->getMissingRevisionIDs();
243 if (!empty ($missingRevIDs)) {
245 foreach ($missingRevIDs as $revid) {
246 $revids[$revid] = array (
250 $result->setIndexedTagName($revids, 'rev');
251 $result->addValue('query', 'badrevids', $revids);
259 // Report any missing titles
261 foreach ($pageSet->getMissingTitles() as $title) {
262 $pages[$fakepageid--] = array (
263 'ns' => $title->getNamespace(), 'title' => $title->getPrefixedText(), 'missing' => '');
266 // Report any missing page ids
267 foreach ($pageSet->getMissingPageIDs() as $pageid) {
268 $pages[$pageid] = array (
274 // Output general page information for found titles
275 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
276 $pages[$pageid] = array (
278 'ns' => $title->getNamespace(), 'title' => $title->getPrefixedText());
281 if (!empty ($pages)) {
282 $result->setIndexedTagName($pages, 'page');
283 $result->addValue('query', 'pages', $pages);
287 protected function executeGeneratorModule($generatorName, $redirects) {
289 // Find class that implements requested generator
290 if (isset ($this->mQueryListModules
[$generatorName])) {
291 $className = $this->mQueryListModules
[$generatorName];
293 elseif (isset ($this->mQueryPropModules
[$generatorName])) {
294 $className = $this->mQueryPropModules
[$generatorName];
296 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
300 $resultPageSet = new ApiPageSet($this, $redirects);
302 // Create and execute the generator
303 $generator = new $className ($this, $generatorName);
304 if (!$generator instanceof ApiQueryGeneratorBase
)
305 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
307 $generator->setGeneratorMode();
308 $generator->requestExtraData();
310 // populate resultPageSet with the generator output
311 $generator->profileIn();
312 $generator->executeGenerator($resultPageSet);
313 $resultPageSet->finishPageSetGeneration();
314 $generator->profileOut();
316 // Swap the resulting pageset back in
317 $this->mPageSet
= $resultPageSet;
320 protected function getAllowedParams() {
323 ApiBase
:: PARAM_ISMULTI
=> true,
324 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
327 ApiBase
:: PARAM_ISMULTI
=> true,
328 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
331 ApiBase
:: PARAM_ISMULTI
=> true,
332 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
334 'generator' => array (
335 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
342 * Override the parent to generate help messages for all available query modules.
344 public function makeHelpMsg() {
346 // Use parent to make default message for the query module
347 $msg = parent
:: makeHelpMsg();
349 // Make sure the internal object is empty
350 // (just in case a sub-module decides to optimize during instantiation)
351 $this->mPageSet
= null;
353 $astriks = str_repeat('--- ', 8);
354 $msg .= "\n$astriks Query: Prop $astriks\n\n";
355 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
356 $msg .= "\n$astriks Query: List $astriks\n\n";
357 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
358 $msg .= "\n$astriks Query: Meta $astriks\n\n";
359 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
364 private function makeHelpMsgHelper($moduleList, $paramName) {
366 $moduleDscriptions = array ();
368 foreach ($moduleList as $moduleName => $moduleClass) {
369 $msg = "* $paramName=$moduleName *";
370 $module = new $moduleClass ($this, $moduleName, null);
371 $msg2 = $module->makeHelpMsg();
374 if ($module instanceof ApiQueryGeneratorBase
)
375 $msg .= "Generator:\n This module may be used as a generator\n";
376 $moduleDscriptions[] = $msg;
379 return implode("\n", $moduleDscriptions);
383 * Override to add extra parameters from PageSet
385 public function makeHelpMsgParameters() {
386 $psModule = new ApiPageSet($this);
387 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
390 protected function getParamDescription() {
392 'prop' => 'Which properties to get for the titles/revisions/pageids',
393 'list' => 'Which lists to get',
394 'meta' => 'Which meta data to get about the site',
395 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
396 'redirects' => 'Automatically resolve redirects'
400 protected function getDescription() {
402 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
403 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
404 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
408 protected function getExamples() {
410 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
414 public function getVersion() {
415 $psModule = new ApiPageSet($this);
417 $vers[] = __CLASS__
. ': $Id$';
418 $vers[] = $psModule->getVersion();