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',
58 'categoryinfo' => 'ApiQueryCategoryInfo',
59 'duplicatefiles' => 'ApiQueryDuplicateFiles',
62 private $mQueryListModules = array (
63 'allimages' => 'ApiQueryAllimages',
64 'allpages' => 'ApiQueryAllpages',
65 'alllinks' => 'ApiQueryAllLinks',
66 'allcategories' => 'ApiQueryAllCategories',
67 'allusers' => 'ApiQueryAllUsers',
68 'backlinks' => 'ApiQueryBacklinks',
69 'blocks' => 'ApiQueryBlocks',
70 'categorymembers' => 'ApiQueryCategoryMembers',
71 'deletedrevs' => 'ApiQueryDeletedrevs',
72 'embeddedin' => 'ApiQueryBacklinks',
73 'imageusage' => 'ApiQueryBacklinks',
74 'logevents' => 'ApiQueryLogEvents',
75 'recentchanges' => 'ApiQueryRecentChanges',
76 'search' => 'ApiQuerySearch',
77 'usercontribs' => 'ApiQueryContributions',
78 'watchlist' => 'ApiQueryWatchlist',
79 'exturlusage' => 'ApiQueryExtLinksUsage',
80 'users' => 'ApiQueryUsers',
81 'random' => 'ApiQueryRandom',
84 private $mQueryMetaModules = array (
85 'siteinfo' => 'ApiQuerySiteinfo',
86 'userinfo' => 'ApiQueryUserInfo',
87 'allmessages' => 'ApiQueryAllmessages',
90 private $mSlaveDB = null;
91 private $mNamedDB = array();
93 public function __construct($main, $action) {
94 parent
:: __construct($main, $action);
96 // Allow custom modules to be added in LocalSettings.php
97 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
98 self
:: appendUserModules($this->mQueryPropModules
, $wgAPIPropModules);
99 self
:: appendUserModules($this->mQueryListModules
, $wgAPIListModules);
100 self
:: appendUserModules($this->mQueryMetaModules
, $wgAPIMetaModules);
102 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
103 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
104 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
106 // Allow the entire list of modules at first,
107 // but during module instantiation check if it can be used as a generator.
108 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
112 * Helper function to append any add-in modules to the list
114 private static function appendUserModules(&$modules, $newModules) {
115 if (is_array( $newModules )) {
116 foreach ( $newModules as $moduleName => $moduleClass) {
117 $modules[$moduleName] = $moduleClass;
123 * Gets a default slave database connection object
125 public function getDB() {
126 if (!isset ($this->mSlaveDB
)) {
127 $this->profileDBIn();
128 $this->mSlaveDB
= wfGetDB(DB_SLAVE
,'api');
129 $this->profileDBOut();
131 return $this->mSlaveDB
;
135 * Get the query database connection with the given name.
136 * If no such connection has been requested before, it will be created.
137 * Subsequent calls with the same $name will return the same connection
138 * as the first, regardless of $db or $groups new values.
140 public function getNamedDB($name, $db, $groups) {
141 if (!array_key_exists($name, $this->mNamedDB
)) {
142 $this->profileDBIn();
143 $this->mNamedDB
[$name] = wfGetDB($db, $groups);
144 $this->profileDBOut();
146 return $this->mNamedDB
[$name];
150 * Gets the set of pages the user has requested (or generated)
152 public function getPageSet() {
153 return $this->mPageSet
;
157 * Get the array mapping module names to class names
159 function getModules() {
160 return array_merge($this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
164 * Query execution happens in the following steps:
165 * #1 Create a PageSet object with any pages requested by the user
166 * #2 If using generator, execute it to get a new PageSet object
167 * #3 Instantiate all requested modules.
168 * This way the PageSet object will know what shared data is required,
169 * and minimize DB calls.
170 * #4 Output all normalization and redirect resolution information
171 * #5 Execute all requested modules
173 public function execute() {
175 $this->params
= $this->extractRequestParams();
176 $this->redirects
= $this->params
['redirects'];
181 $this->mPageSet
= new ApiPageSet($this, $this->redirects
);
184 // Instantiate requested modules
187 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules
);
188 $this->InstantiateModules($modules, 'list', $this->mQueryListModules
);
189 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules
);
192 // If given, execute generator to substitute user supplied data with generated data.
194 if (isset ($this->params
['generator'])) {
195 $this->executeGeneratorModule($this->params
['generator'], $modules);
197 // Append custom fields and populate page/revision information
198 $this->addCustomFldsToPageSet($modules, $this->mPageSet
);
199 $this->mPageSet
->execute();
203 // Record page information (title, namespace, if exists, etc)
205 $this->outputGeneralPageInfo();
208 // Execute all requested modules.
210 foreach ($modules as $module) {
211 $module->profileIn();
213 wfRunHooks('APIQueryAfterExecute', array(&$module));
214 $module->profileOut();
219 * Query modules may optimize data requests through the $this->getPageSet() object
220 * by adding extra fields from the page table.
221 * This function will gather all the extra request fields from the modules.
223 private function addCustomFldsToPageSet($modules, $pageSet) {
224 // Query all requested modules.
225 foreach ($modules as $module) {
226 $module->requestExtraData($pageSet);
231 * Create instances of all modules requested by the client
233 private function InstantiateModules(&$modules, $param, $moduleList) {
234 $list = @$this->params
[$param];
235 if (!is_null ($list))
236 foreach ($list as $moduleName)
237 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
241 * Appends an element for each page in the current pageSet with the most general
242 * information (id, title), plus any title normalizations and missing or invalid title/pageids/revids.
244 private function outputGeneralPageInfo() {
246 $pageSet = $this->getPageSet();
247 $result = $this->getResult();
249 // Title normalizations
250 $normValues = array ();
251 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
252 $normValues[] = array (
253 'from' => $rawTitleStr,
258 if (!empty ($normValues)) {
259 $result->setIndexedTagName($normValues, 'n');
260 $result->addValue('query', 'normalized', $normValues);
264 $intrwValues = array ();
265 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
266 $intrwValues[] = array (
267 'title' => $rawTitleStr,
268 'iw' => $interwikiStr
272 if (!empty ($intrwValues)) {
273 $result->setIndexedTagName($intrwValues, 'i');
274 $result->addValue('query', 'interwiki', $intrwValues);
277 // Show redirect information
278 $redirValues = array ();
279 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
280 $redirValues[] = array (
281 'from' => strval($titleStrFrom),
286 if (!empty ($redirValues)) {
287 $result->setIndexedTagName($redirValues, 'r');
288 $result->addValue('query', 'redirects', $redirValues);
292 // Missing revision elements
294 $missingRevIDs = $pageSet->getMissingRevisionIDs();
295 if (!empty ($missingRevIDs)) {
297 foreach ($missingRevIDs as $revid) {
298 $revids[$revid] = array (
302 $result->setIndexedTagName($revids, 'rev');
303 $result->addValue('query', 'badrevids', $revids);
311 // Report any missing titles
312 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
314 ApiQueryBase
:: addTitleInfo($vals, $title);
315 $vals['missing'] = '';
316 $pages[$fakeId] = $vals;
318 // Report any invalid titles
319 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
320 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
321 // Report any missing page ids
322 foreach ($pageSet->getMissingPageIDs() as $pageid) {
323 $pages[$pageid] = array (
329 // Output general page information for found titles
330 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
332 $vals['pageid'] = $pageid;
333 ApiQueryBase
:: addTitleInfo($vals, $title);
334 $pages[$pageid] = $vals;
337 if (!empty ($pages)) {
339 if ($this->params
['indexpageids']) {
340 $pageIDs = array_keys($pages);
341 // json treats all map keys as strings - converting to match
342 $pageIDs = array_map('strval', $pageIDs);
343 $result->setIndexedTagName($pageIDs, 'id');
344 $result->addValue('query', 'pageids', $pageIDs);
347 $result->setIndexedTagName($pages, 'page');
348 $result->addValue('query', 'pages', $pages);
353 * For generator mode, execute generator, and use its output as new pageSet
355 protected function executeGeneratorModule($generatorName, $modules) {
357 // Find class that implements requested generator
358 if (isset ($this->mQueryListModules
[$generatorName])) {
359 $className = $this->mQueryListModules
[$generatorName];
360 } elseif (isset ($this->mQueryPropModules
[$generatorName])) {
361 $className = $this->mQueryPropModules
[$generatorName];
363 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
367 $resultPageSet = new ApiPageSet($this, $this->redirects
);
369 // Create and execute the generator
370 $generator = new $className ($this, $generatorName);
371 if (!$generator instanceof ApiQueryGeneratorBase
)
372 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
374 $generator->setGeneratorMode();
376 // Add any additional fields modules may need
377 $generator->requestExtraData($this->mPageSet
);
378 $this->addCustomFldsToPageSet($modules, $resultPageSet);
380 // Populate page information with the original user input
381 $this->mPageSet
->execute();
383 // populate resultPageSet with the generator output
384 $generator->profileIn();
385 $generator->executeGenerator($resultPageSet);
386 wfRunHooks('APIQueryGeneratorAfterExecute', array(&$generator, &$resultPageSet));
387 $resultPageSet->finishPageSetGeneration();
388 $generator->profileOut();
390 // Swap the resulting pageset back in
391 $this->mPageSet
= $resultPageSet;
395 * Returns the list of allowed parameters for this module.
396 * Qurey module also lists all ApiPageSet parameters as its own.
398 public function getAllowedParams() {
401 ApiBase
:: PARAM_ISMULTI
=> true,
402 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
405 ApiBase
:: PARAM_ISMULTI
=> true,
406 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
409 ApiBase
:: PARAM_ISMULTI
=> true,
410 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
412 'generator' => array (
413 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
415 'redirects' => false,
416 'indexpageids' => false,
421 * Override the parent to generate help messages for all available query modules.
423 public function makeHelpMsg() {
427 // Make sure the internal object is empty
428 // (just in case a sub-module decides to optimize during instantiation)
429 $this->mPageSet
= null;
430 $this->mAllowedGenerators
= array(); // Will be repopulated
432 $astriks = str_repeat('--- ', 8);
433 $astriks2 = str_repeat('*** ', 10);
434 $msg .= "\n$astriks Query: Prop $astriks\n\n";
435 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
436 $msg .= "\n$astriks Query: List $astriks\n\n";
437 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
438 $msg .= "\n$astriks Query: Meta $astriks\n\n";
439 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
440 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
442 // Perform the base call last because the $this->mAllowedGenerators
443 // will be updated inside makeHelpMsgHelper()
444 // Use parent to make default message for the query module
445 $msg = parent
:: makeHelpMsg() . $msg;
451 * For all modules in $moduleList, generate help messages and join them together
453 private function makeHelpMsgHelper($moduleList, $paramName) {
455 $moduleDscriptions = array ();
457 foreach ($moduleList as $moduleName => $moduleClass) {
458 $module = new $moduleClass ($this, $moduleName, null);
460 $msg = ApiMain
::makeHelpMsgHeader($module, $paramName);
461 $msg2 = $module->makeHelpMsg();
464 if ($module instanceof ApiQueryGeneratorBase
) {
465 $this->mAllowedGenerators
[] = $moduleName;
466 $msg .= "Generator:\n This module may be used as a generator\n";
468 $moduleDscriptions[] = $msg;
471 return implode("\n", $moduleDscriptions);
475 * Override to add extra parameters from PageSet
477 public function makeHelpMsgParameters() {
478 $psModule = new ApiPageSet($this);
479 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
482 public function shouldCheckMaxlag() {
486 public function getParamDescription() {
488 'prop' => 'Which properties to get for the titles/revisions/pageids',
489 'list' => 'Which lists to get',
490 'meta' => 'Which meta data to get about the site',
491 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
492 'redirects' => 'Automatically resolve redirects',
493 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
497 public function getDescription() {
499 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
500 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
501 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
505 protected function getExamples() {
507 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
511 public function getVersion() {
512 $psModule = new ApiPageSet($this);
514 $vers[] = __CLASS__
. ': $Id$';
515 $vers[] = $psModule->getVersion();