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 'allimages' => 'ApiQueryAllimages',
62 'allpages' => 'ApiQueryAllpages',
63 'alllinks' => 'ApiQueryAllLinks',
64 'allcategories' => 'ApiQueryAllCategories',
65 'allusers' => 'ApiQueryAllUsers',
66 'backlinks' => 'ApiQueryBacklinks',
67 'blocks' => 'ApiQueryBlocks',
68 'categorymembers' => 'ApiQueryCategoryMembers',
69 'deletedrevs' => 'ApiQueryDeletedrevs',
70 'embeddedin' => 'ApiQueryBacklinks',
71 'imageusage' => 'ApiQueryBacklinks',
72 'logevents' => 'ApiQueryLogEvents',
73 'recentchanges' => 'ApiQueryRecentChanges',
74 'search' => 'ApiQuerySearch',
75 'usercontribs' => 'ApiQueryContributions',
76 'watchlist' => 'ApiQueryWatchlist',
77 'exturlusage' => 'ApiQueryExtLinksUsage',
78 'users' => 'ApiQueryUsers',
79 'random' => 'ApiQueryRandom',
82 private $mQueryMetaModules = array (
83 'siteinfo' => 'ApiQuerySiteinfo',
84 'userinfo' => 'ApiQueryUserInfo',
85 'allmessages' => 'ApiQueryAllmessages',
88 private $mSlaveDB = null;
89 private $mNamedDB = array();
91 public function __construct($main, $action) {
92 parent
:: __construct($main, $action);
94 // Allow custom modules to be added in LocalSettings.php
95 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
96 self
:: appendUserModules($this->mQueryPropModules
, $wgApiQueryPropModules);
97 self
:: appendUserModules($this->mQueryListModules
, $wgApiQueryListModules);
98 self
:: appendUserModules($this->mQueryMetaModules
, $wgApiQueryMetaModules);
100 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
101 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
102 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
104 // Allow the entire list of modules at first,
105 // but during module instantiation check if it can be used as a generator.
106 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
110 * Helper function to append any add-in modules to the list
112 private static function appendUserModules(&$modules, $newModules) {
113 if (is_array( $newModules )) {
114 foreach ( $newModules as $moduleName => $moduleClass) {
115 $modules[$moduleName] = $moduleClass;
121 * Gets a default slave database connection object
123 public function getDB() {
124 if (!isset ($this->mSlaveDB
)) {
125 $this->profileDBIn();
126 $this->mSlaveDB
= wfGetDB(DB_SLAVE
);
127 $this->profileDBOut();
129 return $this->mSlaveDB
;
133 * Get the query database connection with the given name.
134 * If no such connection has been requested before, it will be created.
135 * Subsequent calls with the same $name will return the same connection
136 * as the first, regardless of $db or $groups new values.
138 public function getNamedDB($name, $db, $groups) {
139 if (!array_key_exists($name, $this->mNamedDB
)) {
140 $this->profileDBIn();
141 $this->mNamedDB
[$name] = wfGetDB($db, $groups);
142 $this->profileDBOut();
144 return $this->mNamedDB
[$name];
148 * Gets the set of pages the user has requested (or generated)
150 public function getPageSet() {
151 return $this->mPageSet
;
155 * Get the array mapping module names to class names
157 function getModules() {
158 return array_merge($this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
162 * Query execution happens in the following steps:
163 * #1 Create a PageSet object with any pages requested by the user
164 * #2 If using generator, execute it to get a new PageSet object
165 * #3 Instantiate all requested modules.
166 * This way the PageSet object will know what shared data is required,
167 * and minimize DB calls.
168 * #4 Output all normalization and redirect resolution information
169 * #5 Execute all requested modules
171 public function execute() {
173 $this->params
= $this->extractRequestParams();
174 $this->redirects
= $this->params
['redirects'];
179 $this->mPageSet
= new ApiPageSet($this, $this->redirects
);
182 // Instantiate requested modules
185 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules
);
186 $this->InstantiateModules($modules, 'list', $this->mQueryListModules
);
187 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules
);
190 // If given, execute generator to substitute user supplied data with generated data.
192 if (isset ($this->params
['generator'])) {
193 $this->executeGeneratorModule($this->params
['generator'], $modules);
195 // Append custom fields and populate page/revision information
196 $this->addCustomFldsToPageSet($modules, $this->mPageSet
);
197 $this->mPageSet
->execute();
201 // Record page information (title, namespace, if exists, etc)
203 $this->outputGeneralPageInfo();
206 // Execute all requested modules.
208 foreach ($modules as $module) {
209 $module->profileIn();
211 $module->profileOut();
216 * Query modules may optimize data requests through the $this->getPageSet() object
217 * by adding extra fields from the page table.
218 * This function will gather all the extra request fields from the modules.
220 private function addCustomFldsToPageSet($modules, $pageSet) {
221 // Query all requested modules.
222 foreach ($modules as $module) {
223 $module->requestExtraData($pageSet);
228 * Create instances of all modules requested by the client
230 private function InstantiateModules(&$modules, $param, $moduleList) {
231 $list = $this->params
[$param];
233 foreach ($list as $moduleName)
234 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
238 * Appends an element for each page in the current pageSet with the most general
239 * information (id, title), plus any title normalizations and missing or invalid title/pageids/revids.
241 private function outputGeneralPageInfo() {
243 $pageSet = $this->getPageSet();
244 $result = $this->getResult();
246 // Title normalizations
247 $normValues = array ();
248 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
249 $normValues[] = array (
250 'from' => $rawTitleStr,
255 if (!empty ($normValues)) {
256 $result->setIndexedTagName($normValues, 'n');
257 $result->addValue('query', 'normalized', $normValues);
261 $intrwValues = array ();
262 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
263 $intrwValues[] = array (
264 'title' => $rawTitleStr,
265 'iw' => $interwikiStr
269 if (!empty ($intrwValues)) {
270 $result->setIndexedTagName($intrwValues, 'i');
271 $result->addValue('query', 'interwiki', $intrwValues);
274 // Show redirect information
275 $redirValues = array ();
276 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
277 $redirValues[] = array (
278 'from' => strval($titleStrFrom),
283 if (!empty ($redirValues)) {
284 $result->setIndexedTagName($redirValues, 'r');
285 $result->addValue('query', 'redirects', $redirValues);
289 // Missing revision elements
291 $missingRevIDs = $pageSet->getMissingRevisionIDs();
292 if (!empty ($missingRevIDs)) {
294 foreach ($missingRevIDs as $revid) {
295 $revids[$revid] = array (
299 $result->setIndexedTagName($revids, 'rev');
300 $result->addValue('query', 'badrevids', $revids);
308 // Report any missing titles
309 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
311 ApiQueryBase
:: addTitleInfo($vals, $title);
312 $vals['missing'] = '';
313 $pages[$fakeId] = $vals;
315 // Report any invalid titles
316 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
317 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
318 // Report any missing page ids
319 foreach ($pageSet->getMissingPageIDs() as $pageid) {
320 $pages[$pageid] = array (
326 // Output general page information for found titles
327 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
329 $vals['pageid'] = $pageid;
330 ApiQueryBase
:: addTitleInfo($vals, $title);
331 $pages[$pageid] = $vals;
334 if (!empty ($pages)) {
336 if ($this->params
['indexpageids']) {
337 $pageIDs = array_keys($pages);
338 // json treats all map keys as strings - converting to match
339 $pageIDs = array_map('strval', $pageIDs);
340 $result->setIndexedTagName($pageIDs, 'id');
341 $result->addValue('query', 'pageids', $pageIDs);
344 $result->setIndexedTagName($pages, 'page');
345 $result->addValue('query', 'pages', $pages);
350 * For generator mode, execute generator, and use its output as new pageSet
352 protected function executeGeneratorModule($generatorName, $modules) {
354 // Find class that implements requested generator
355 if (isset ($this->mQueryListModules
[$generatorName])) {
356 $className = $this->mQueryListModules
[$generatorName];
357 } elseif (isset ($this->mQueryPropModules
[$generatorName])) {
358 $className = $this->mQueryPropModules
[$generatorName];
360 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
364 $resultPageSet = new ApiPageSet($this, $this->redirects
);
366 // Create and execute the generator
367 $generator = new $className ($this, $generatorName);
368 if (!$generator instanceof ApiQueryGeneratorBase
)
369 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
371 $generator->setGeneratorMode();
373 // Add any additional fields modules may need
374 $generator->requestExtraData($this->mPageSet
);
375 $this->addCustomFldsToPageSet($modules, $resultPageSet);
377 // Populate page information with the original user input
378 $this->mPageSet
->execute();
380 // populate resultPageSet with the generator output
381 $generator->profileIn();
382 $generator->executeGenerator($resultPageSet);
383 $resultPageSet->finishPageSetGeneration();
384 $generator->profileOut();
386 // Swap the resulting pageset back in
387 $this->mPageSet
= $resultPageSet;
391 * Returns the list of allowed parameters for this module.
392 * Qurey module also lists all ApiPageSet parameters as its own.
394 public function getAllowedParams() {
397 ApiBase
:: PARAM_ISMULTI
=> true,
398 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
401 ApiBase
:: PARAM_ISMULTI
=> true,
402 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
405 ApiBase
:: PARAM_ISMULTI
=> true,
406 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
408 'generator' => array (
409 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
411 'redirects' => false,
412 'indexpageids' => false,
417 * Override the parent to generate help messages for all available query modules.
419 public function makeHelpMsg() {
423 // Make sure the internal object is empty
424 // (just in case a sub-module decides to optimize during instantiation)
425 $this->mPageSet
= null;
426 $this->mAllowedGenerators
= array(); // Will be repopulated
428 $astriks = str_repeat('--- ', 8);
429 $astriks2 = str_repeat('*** ', 10);
430 $msg .= "\n$astriks Query: Prop $astriks\n\n";
431 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
432 $msg .= "\n$astriks Query: List $astriks\n\n";
433 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
434 $msg .= "\n$astriks Query: Meta $astriks\n\n";
435 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
436 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
438 // Perform the base call last because the $this->mAllowedGenerators
439 // will be updated inside makeHelpMsgHelper()
440 // Use parent to make default message for the query module
441 $msg = parent
:: makeHelpMsg() . $msg;
447 * For all modules in $moduleList, generate help messages and join them together
449 private function makeHelpMsgHelper($moduleList, $paramName) {
451 $moduleDscriptions = array ();
453 foreach ($moduleList as $moduleName => $moduleClass) {
454 $module = new $moduleClass ($this, $moduleName, null);
456 $msg = ApiMain
::makeHelpMsgHeader($module, $paramName);
457 $msg2 = $module->makeHelpMsg();
460 if ($module instanceof ApiQueryGeneratorBase
) {
461 $this->mAllowedGenerators
[] = $moduleName;
462 $msg .= "Generator:\n This module may be used as a generator\n";
464 $moduleDscriptions[] = $msg;
467 return implode("\n", $moduleDscriptions);
471 * Override to add extra parameters from PageSet
473 public function makeHelpMsgParameters() {
474 $psModule = new ApiPageSet($this);
475 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
478 // @todo should work correctly
479 public function shouldCheckMaxlag() {
483 public function getParamDescription() {
485 'prop' => 'Which properties to get for the titles/revisions/pageids',
486 'list' => 'Which lists to get',
487 'meta' => 'Which meta data to get about the site',
488 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
489 'redirects' => 'Automatically resolve redirects',
490 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
494 public function getDescription() {
496 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
497 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
498 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
502 protected function getExamples() {
504 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
508 public function getVersion() {
509 $psModule = new ApiPageSet($this);
511 $vers[] = __CLASS__
. ': $Id$';
512 $vers[] = $psModule->getVersion();