46dc8f0ff172d3fa1a114f214cddb5256fd3bf05
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 'backlinks' => 'ApiQueryBacklinks',
64 'categorymembers' => 'ApiQueryCategoryMembers',
65 'embeddedin' => 'ApiQueryBacklinks',
66 'imageusage' => 'ApiQueryBacklinks',
67 'logevents' => 'ApiQueryLogEvents',
68 'recentchanges' => 'ApiQueryRecentChanges',
69 'usercontribs' => 'ApiQueryContributions',
70 'watchlist' => 'ApiQueryWatchlist',
71 // 'users' => 'ApiQueryUsers',
72 'exturlusage' => 'ApiQueryExtLinksUsage',
75 private $mQueryMetaModules = array (
76 'siteinfo' => 'ApiQuerySiteinfo',
77 // 'userinfo' => 'ApiQueryUserinfo',
80 private $mSlaveDB = null;
81 private $mNamedDB = array();
83 public function __construct($main, $action) {
84 parent
:: __construct($main, $action);
86 // Allow custom modules to be added in LocalSettings.php
87 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
88 self
:: appendUserModules($this->mQueryPropModules
, $wgApiQueryPropModules);
89 self
:: appendUserModules($this->mQueryListModules
, $wgApiQueryListModules);
90 self
:: appendUserModules($this->mQueryMetaModules
, $wgApiQueryMetaModules);
92 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
93 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
94 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
96 // Allow the entire list of modules at first,
97 // but during module instantiation check if it can be used as a generator.
98 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
102 * Helper function to append any add-in modules to the list
104 private static function appendUserModules(&$modules, $newModules) {
105 if (is_array( $newModules )) {
106 foreach ( $newModules as $moduleName => $moduleClass) {
107 $modules[$moduleName] = $moduleClass;
113 * Gets a default slave database connection object
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];
140 * Gets the set of pages the user has requested (or generated)
142 public function getPageSet() {
143 return $this->mPageSet
;
147 * Query execution happens in the following steps:
148 * #1 Create a PageSet object with any pages requested by the user
149 * #2 If using generator, execute it to get a new PageSet object
150 * #3 Instantiate all requested modules.
151 * This way the PageSet object will know what shared data is required,
152 * and minimize DB calls.
153 * #4 Output all normalization and redirect resolution information
154 * #5 Execute all requested modules
156 public function execute() {
158 $this->params
= $this->extractRequestParams();
159 $this->redirects
= $this->params
['redirects'];
164 $this->mPageSet
= new ApiPageSet($this, $this->redirects
);
167 // Instantiate requested modules
170 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules
);
171 $this->InstantiateModules($modules, 'list', $this->mQueryListModules
);
172 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules
);
175 // If given, execute generator to substitute user supplied data with generated data.
177 if (isset ($this->params
['generator'])) {
178 $this->executeGeneratorModule($this->params
['generator'], $modules);
180 // Append custom fields and populate page/revision information
181 $this->addCustomFldsToPageSet($modules, $this->mPageSet
);
182 $this->mPageSet
->execute();
186 // Record page information (title, namespace, if exists, etc)
188 $this->outputGeneralPageInfo();
191 // Execute all requested modules.
193 foreach ($modules as $module) {
194 $module->profileIn();
196 $module->profileOut();
201 * Query modules may optimize data requests through the $this->getPageSet() object
202 * by adding extra fields from the page table.
203 * This function will gather all the extra request fields from the modules.
205 private function addCustomFldsToPageSet($modules, $pageSet) {
206 // Query all requested modules.
207 foreach ($modules as $module) {
208 $module->requestExtraData($pageSet);
213 * Create instances of all modules requested by the client
215 private function InstantiateModules(&$modules, $param, $moduleList) {
216 $list = $this->params
[$param];
218 foreach ($list as $moduleName)
219 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
223 * Appends an element for each page in the current pageSet with the most general
224 * information (id, title), plus any title normalizations and missing title/pageids/revids.
226 private function outputGeneralPageInfo() {
228 $pageSet = $this->getPageSet();
229 $result = $this->getResult();
231 // Title normalizations
232 $normValues = array ();
233 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
234 $normValues[] = array (
235 'from' => $rawTitleStr,
240 if (!empty ($normValues)) {
241 $result->setIndexedTagName($normValues, 'n');
242 $result->addValue('query', 'normalized', $normValues);
246 $intrwValues = array ();
247 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
248 $intrwValues[] = array (
249 'title' => $rawTitleStr,
250 'iw' => $interwikiStr
254 if (!empty ($intrwValues)) {
255 $result->setIndexedTagName($intrwValues, 'i');
256 $result->addValue('query', 'interwiki', $intrwValues);
259 // Show redirect information
260 $redirValues = array ();
261 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
262 $redirValues[] = array (
263 'from' => $titleStrFrom,
268 if (!empty ($redirValues)) {
269 $result->setIndexedTagName($redirValues, 'r');
270 $result->addValue('query', 'redirects', $redirValues);
274 // Missing revision elements
276 $missingRevIDs = $pageSet->getMissingRevisionIDs();
277 if (!empty ($missingRevIDs)) {
279 foreach ($missingRevIDs as $revid) {
280 $revids[$revid] = array (
284 $result->setIndexedTagName($revids, 'rev');
285 $result->addValue('query', 'badrevids', $revids);
293 // Report any missing titles
294 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
296 ApiQueryBase
:: addTitleInfo($vals, $title, true);
297 $vals['missing'] = '';
298 $pages[$fakeId] = $vals;
301 // Report any missing page ids
302 foreach ($pageSet->getMissingPageIDs() as $pageid) {
303 $pages[$pageid] = array (
309 // Output general page information for found titles
310 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
312 $vals['pageid'] = $pageid;
313 ApiQueryBase
:: addTitleInfo($vals, $title, true);
314 $pages[$pageid] = $vals;
317 if (!empty ($pages)) {
319 if ($this->params
['indexpageids']) {
320 $pageIDs = array_keys($pages);
321 // json treats all map keys as strings - converting to match
322 $pageIDs = array_map('strval', $pageIDs);
323 $result->setIndexedTagName($pageIDs, 'id');
324 $result->addValue('query', 'pageids', $pageIDs);
327 $result->setIndexedTagName($pages, 'page');
328 $result->addValue('query', 'pages', $pages);
333 * For generator mode, execute generator, and use its output as new pageSet
335 protected function executeGeneratorModule($generatorName, $modules) {
337 // Find class that implements requested generator
338 if (isset ($this->mQueryListModules
[$generatorName])) {
339 $className = $this->mQueryListModules
[$generatorName];
340 } elseif (isset ($this->mQueryPropModules
[$generatorName])) {
341 $className = $this->mQueryPropModules
[$generatorName];
343 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
347 $resultPageSet = new ApiPageSet($this, $this->redirects
);
349 // Create and execute the generator
350 $generator = new $className ($this, $generatorName);
351 if (!$generator instanceof ApiQueryGeneratorBase
)
352 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
354 $generator->setGeneratorMode();
356 // Add any additional fields modules may need
357 $generator->requestExtraData($this->mPageSet
);
358 $this->addCustomFldsToPageSet($modules, $resultPageSet);
360 // Populate page information with the original user input
361 $this->mPageSet
->execute();
363 // populate resultPageSet with the generator output
364 $generator->profileIn();
365 $generator->executeGenerator($resultPageSet);
366 $resultPageSet->finishPageSetGeneration();
367 $generator->profileOut();
369 // Swap the resulting pageset back in
370 $this->mPageSet
= $resultPageSet;
374 * Returns the list of allowed parameters for this module.
375 * Qurey module also lists all ApiPageSet parameters as its own.
377 protected function getAllowedParams() {
380 ApiBase
:: PARAM_ISMULTI
=> true,
381 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
384 ApiBase
:: PARAM_ISMULTI
=> true,
385 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
388 ApiBase
:: PARAM_ISMULTI
=> true,
389 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
391 'generator' => array (
392 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
394 'redirects' => false,
395 'indexpageids' => false,
400 * Override the parent to generate help messages for all available query modules.
402 public function makeHelpMsg() {
406 // Make sure the internal object is empty
407 // (just in case a sub-module decides to optimize during instantiation)
408 $this->mPageSet
= null;
409 $this->mAllowedGenerators
= array(); // Will be repopulated
411 $astriks = str_repeat('--- ', 8);
412 $msg .= "\n$astriks Query: Prop $astriks\n\n";
413 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
414 $msg .= "\n$astriks Query: List $astriks\n\n";
415 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
416 $msg .= "\n$astriks Query: Meta $astriks\n\n";
417 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
419 // Perform the base call last because the $this->mAllowedGenerators
420 // will be updated inside makeHelpMsgHelper()
421 // Use parent to make default message for the query module
422 $msg = parent
:: makeHelpMsg() . $msg;
428 * For all modules in $moduleList, generate help messages and join them together
430 private function makeHelpMsgHelper($moduleList, $paramName) {
432 $moduleDscriptions = array ();
434 foreach ($moduleList as $moduleName => $moduleClass) {
435 $module = new $moduleClass ($this, $moduleName, null);
437 $msg = ApiMain
::makeHelpMsgHeader($module, $paramName);
438 $msg2 = $module->makeHelpMsg();
441 if ($module instanceof ApiQueryGeneratorBase
) {
442 $this->mAllowedGenerators
[] = $moduleName;
443 $msg .= "Generator:\n This module may be used as a generator\n";
445 $moduleDscriptions[] = $msg;
448 return implode("\n", $moduleDscriptions);
452 * Override to add extra parameters from PageSet
454 public function makeHelpMsgParameters() {
455 $psModule = new ApiPageSet($this);
456 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
459 protected function getParamDescription() {
461 'prop' => 'Which properties to get for the titles/revisions/pageids',
462 'list' => 'Which lists to get',
463 'meta' => 'Which meta data to get about the site',
464 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
465 'redirects' => 'Automatically resolve redirects',
466 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
470 protected function getDescription() {
472 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
473 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
474 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
478 protected function getExamples() {
480 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
484 public function getVersion() {
485 $psModule = new ApiPageSet($this);
487 $vers[] = __CLASS__
. ': $Id$';
488 $vers[] = $psModule->getVersion();