7ff6e67e9a7332139d79e32b653ec16fc8f3f172
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 'allcategories' => 'ApiQueryAllCategories',
64 'allusers' => 'ApiQueryAllUsers',
65 'backlinks' => 'ApiQueryBacklinks',
66 'blocks' => 'ApiQueryBlocks',
67 'categorymembers' => 'ApiQueryCategoryMembers',
68 'deletedrevs' => 'ApiQueryDeletedrevs',
69 'embeddedin' => 'ApiQueryBacklinks',
70 'imageusage' => 'ApiQueryBacklinks',
71 'logevents' => 'ApiQueryLogEvents',
72 'recentchanges' => 'ApiQueryRecentChanges',
73 'search' => 'ApiQuerySearch',
74 'usercontribs' => 'ApiQueryContributions',
75 'watchlist' => 'ApiQueryWatchlist',
76 'exturlusage' => 'ApiQueryExtLinksUsage',
79 private $mQueryMetaModules = array (
80 'siteinfo' => 'ApiQuerySiteinfo',
81 'userinfo' => 'ApiQueryUserInfo',
82 'allmessages' => 'ApiQueryAllmessages',
85 private $mSlaveDB = null;
86 private $mNamedDB = array();
88 public function __construct($main, $action) {
89 parent
:: __construct($main, $action);
91 // Allow custom modules to be added in LocalSettings.php
92 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
93 self
:: appendUserModules($this->mQueryPropModules
, $wgApiQueryPropModules);
94 self
:: appendUserModules($this->mQueryListModules
, $wgApiQueryListModules);
95 self
:: appendUserModules($this->mQueryMetaModules
, $wgApiQueryMetaModules);
97 $this->mPropModuleNames
= array_keys($this->mQueryPropModules
);
98 $this->mListModuleNames
= array_keys($this->mQueryListModules
);
99 $this->mMetaModuleNames
= array_keys($this->mQueryMetaModules
);
101 // Allow the entire list of modules at first,
102 // but during module instantiation check if it can be used as a generator.
103 $this->mAllowedGenerators
= array_merge($this->mListModuleNames
, $this->mPropModuleNames
);
107 * Helper function to append any add-in modules to the list
109 private static function appendUserModules(&$modules, $newModules) {
110 if (is_array( $newModules )) {
111 foreach ( $newModules as $moduleName => $moduleClass) {
112 $modules[$moduleName] = $moduleClass;
118 * Gets a default slave database connection object
120 public function getDB() {
121 if (!isset ($this->mSlaveDB
)) {
122 $this->profileDBIn();
123 $this->mSlaveDB
= wfGetDB(DB_SLAVE
);
124 $this->profileDBOut();
126 return $this->mSlaveDB
;
130 * Get the query database connection with the given name.
131 * If no such connection has been requested before, it will be created.
132 * Subsequent calls with the same $name will return the same connection
133 * as the first, regardless of $db or $groups new values.
135 public function getNamedDB($name, $db, $groups) {
136 if (!array_key_exists($name, $this->mNamedDB
)) {
137 $this->profileDBIn();
138 $this->mNamedDB
[$name] = wfGetDB($db, $groups);
139 $this->profileDBOut();
141 return $this->mNamedDB
[$name];
145 * Gets the set of pages the user has requested (or generated)
147 public function getPageSet() {
148 return $this->mPageSet
;
152 * Get the array mapping module names to class names
154 function getModules() {
155 return array_merge($this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
159 * Query execution happens in the following steps:
160 * #1 Create a PageSet object with any pages requested by the user
161 * #2 If using generator, execute it to get a new PageSet object
162 * #3 Instantiate all requested modules.
163 * This way the PageSet object will know what shared data is required,
164 * and minimize DB calls.
165 * #4 Output all normalization and redirect resolution information
166 * #5 Execute all requested modules
168 public function execute() {
170 $this->params
= $this->extractRequestParams();
171 $this->redirects
= $this->params
['redirects'];
176 $this->mPageSet
= new ApiPageSet($this, $this->redirects
);
179 // Instantiate requested modules
182 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules
);
183 $this->InstantiateModules($modules, 'list', $this->mQueryListModules
);
184 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules
);
187 // If given, execute generator to substitute user supplied data with generated data.
189 if (isset ($this->params
['generator'])) {
190 $this->executeGeneratorModule($this->params
['generator'], $modules);
192 // Append custom fields and populate page/revision information
193 $this->addCustomFldsToPageSet($modules, $this->mPageSet
);
194 $this->mPageSet
->execute();
198 // Record page information (title, namespace, if exists, etc)
200 $this->outputGeneralPageInfo();
203 // Execute all requested modules.
205 foreach ($modules as $module) {
206 $module->profileIn();
208 $module->profileOut();
213 * Query modules may optimize data requests through the $this->getPageSet() object
214 * by adding extra fields from the page table.
215 * This function will gather all the extra request fields from the modules.
217 private function addCustomFldsToPageSet($modules, $pageSet) {
218 // Query all requested modules.
219 foreach ($modules as $module) {
220 $module->requestExtraData($pageSet);
225 * Create instances of all modules requested by the client
227 private function InstantiateModules(&$modules, $param, $moduleList) {
228 $list = $this->params
[$param];
230 foreach ($list as $moduleName)
231 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
235 * Appends an element for each page in the current pageSet with the most general
236 * information (id, title), plus any title normalizations and missing title/pageids/revids.
238 private function outputGeneralPageInfo() {
240 $pageSet = $this->getPageSet();
241 $result = $this->getResult();
243 // Title normalizations
244 $normValues = array ();
245 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
246 $normValues[] = array (
247 'from' => $rawTitleStr,
252 if (!empty ($normValues)) {
253 $result->setIndexedTagName($normValues, 'n');
254 $result->addValue('query', 'normalized', $normValues);
258 $intrwValues = array ();
259 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
260 $intrwValues[] = array (
261 'title' => $rawTitleStr,
262 'iw' => $interwikiStr
266 if (!empty ($intrwValues)) {
267 $result->setIndexedTagName($intrwValues, 'i');
268 $result->addValue('query', 'interwiki', $intrwValues);
271 // Show redirect information
272 $redirValues = array ();
273 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
274 $redirValues[] = array (
275 'from' => $titleStrFrom,
280 if (!empty ($redirValues)) {
281 $result->setIndexedTagName($redirValues, 'r');
282 $result->addValue('query', 'redirects', $redirValues);
286 // Missing revision elements
288 $missingRevIDs = $pageSet->getMissingRevisionIDs();
289 if (!empty ($missingRevIDs)) {
291 foreach ($missingRevIDs as $revid) {
292 $revids[$revid] = array (
296 $result->setIndexedTagName($revids, 'rev');
297 $result->addValue('query', 'badrevids', $revids);
305 // Report any missing titles
306 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
308 ApiQueryBase
:: addTitleInfo($vals, $title);
309 $vals['missing'] = '';
310 $pages[$fakeId] = $vals;
313 // Report any missing page ids
314 foreach ($pageSet->getMissingPageIDs() as $pageid) {
315 $pages[$pageid] = array (
321 // Output general page information for found titles
322 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
324 $vals['pageid'] = $pageid;
325 ApiQueryBase
:: addTitleInfo($vals, $title);
326 $pages[$pageid] = $vals;
329 if (!empty ($pages)) {
331 if ($this->params
['indexpageids']) {
332 $pageIDs = array_keys($pages);
333 // json treats all map keys as strings - converting to match
334 $pageIDs = array_map('strval', $pageIDs);
335 $result->setIndexedTagName($pageIDs, 'id');
336 $result->addValue('query', 'pageids', $pageIDs);
339 $result->setIndexedTagName($pages, 'page');
340 $result->addValue('query', 'pages', $pages);
345 * For generator mode, execute generator, and use its output as new pageSet
347 protected function executeGeneratorModule($generatorName, $modules) {
349 // Find class that implements requested generator
350 if (isset ($this->mQueryListModules
[$generatorName])) {
351 $className = $this->mQueryListModules
[$generatorName];
352 } elseif (isset ($this->mQueryPropModules
[$generatorName])) {
353 $className = $this->mQueryPropModules
[$generatorName];
355 ApiBase
:: dieDebug(__METHOD__
, "Unknown generator=$generatorName");
359 $resultPageSet = new ApiPageSet($this, $this->redirects
);
361 // Create and execute the generator
362 $generator = new $className ($this, $generatorName);
363 if (!$generator instanceof ApiQueryGeneratorBase
)
364 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
366 $generator->setGeneratorMode();
368 // Add any additional fields modules may need
369 $generator->requestExtraData($this->mPageSet
);
370 $this->addCustomFldsToPageSet($modules, $resultPageSet);
372 // Populate page information with the original user input
373 $this->mPageSet
->execute();
375 // populate resultPageSet with the generator output
376 $generator->profileIn();
377 $generator->executeGenerator($resultPageSet);
378 $resultPageSet->finishPageSetGeneration();
379 $generator->profileOut();
381 // Swap the resulting pageset back in
382 $this->mPageSet
= $resultPageSet;
386 * Returns the list of allowed parameters for this module.
387 * Qurey module also lists all ApiPageSet parameters as its own.
389 protected function getAllowedParams() {
392 ApiBase
:: PARAM_ISMULTI
=> true,
393 ApiBase
:: PARAM_TYPE
=> $this->mPropModuleNames
396 ApiBase
:: PARAM_ISMULTI
=> true,
397 ApiBase
:: PARAM_TYPE
=> $this->mListModuleNames
400 ApiBase
:: PARAM_ISMULTI
=> true,
401 ApiBase
:: PARAM_TYPE
=> $this->mMetaModuleNames
403 'generator' => array (
404 ApiBase
:: PARAM_TYPE
=> $this->mAllowedGenerators
406 'redirects' => false,
407 'indexpageids' => false,
412 * Override the parent to generate help messages for all available query modules.
414 public function makeHelpMsg() {
418 // Make sure the internal object is empty
419 // (just in case a sub-module decides to optimize during instantiation)
420 $this->mPageSet
= null;
421 $this->mAllowedGenerators
= array(); // Will be repopulated
423 $astriks = str_repeat('--- ', 8);
424 $msg .= "\n$astriks Query: Prop $astriks\n\n";
425 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules
, 'prop');
426 $msg .= "\n$astriks Query: List $astriks\n\n";
427 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules
, 'list');
428 $msg .= "\n$astriks Query: Meta $astriks\n\n";
429 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules
, 'meta');
431 // Perform the base call last because the $this->mAllowedGenerators
432 // will be updated inside makeHelpMsgHelper()
433 // Use parent to make default message for the query module
434 $msg = parent
:: makeHelpMsg() . $msg;
440 * For all modules in $moduleList, generate help messages and join them together
442 private function makeHelpMsgHelper($moduleList, $paramName) {
444 $moduleDscriptions = array ();
446 foreach ($moduleList as $moduleName => $moduleClass) {
447 $module = new $moduleClass ($this, $moduleName, null);
449 $msg = ApiMain
::makeHelpMsgHeader($module, $paramName);
450 $msg2 = $module->makeHelpMsg();
453 if ($module instanceof ApiQueryGeneratorBase
) {
454 $this->mAllowedGenerators
[] = $moduleName;
455 $msg .= "Generator:\n This module may be used as a generator\n";
457 $moduleDscriptions[] = $msg;
460 return implode("\n", $moduleDscriptions);
464 * Override to add extra parameters from PageSet
466 public function makeHelpMsgParameters() {
467 $psModule = new ApiPageSet($this);
468 return $psModule->makeHelpMsgParameters() . parent
:: makeHelpMsgParameters();
471 // @todo should work correctly
472 public function shouldCheckMaxlag() {
476 protected function getParamDescription() {
478 'prop' => 'Which properties to get for the titles/revisions/pageids',
479 'list' => 'Which lists to get',
480 'meta' => 'Which meta data to get about the site',
481 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
482 'redirects' => 'Automatically resolve redirects',
483 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
487 protected function getDescription() {
489 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
490 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
491 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
495 protected function getExamples() {
497 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
501 public function getVersion() {
502 $psModule = new ApiPageSet($this);
504 $vers[] = __CLASS__
. ': $Id$';
505 $vers[] = $psModule->getVersion();