* (bug 12584) Don't reset cl_timestamp when auto-updating sort key on move
[mediawiki.git] / includes / api / ApiQuery.php
blobc42e7c98f1d8254ef9757be92ad780d07d78a53f
1 <?php
3 /*
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');
31 /**
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.
40 * @addtogroup API
42 class ApiQuery extends ApiBase {
44 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
45 private $mPageSet;
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 * Query execution happens in the following steps:
153 * #1 Create a PageSet object with any pages requested by the user
154 * #2 If using generator, execute it to get a new PageSet object
155 * #3 Instantiate all requested modules.
156 * This way the PageSet object will know what shared data is required,
157 * and minimize DB calls.
158 * #4 Output all normalization and redirect resolution information
159 * #5 Execute all requested modules
161 public function execute() {
163 $this->params = $this->extractRequestParams();
164 $this->redirects = $this->params['redirects'];
167 // Create PageSet
169 $this->mPageSet = new ApiPageSet($this, $this->redirects);
172 // Instantiate requested modules
174 $modules = array ();
175 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
176 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
177 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
180 // If given, execute generator to substitute user supplied data with generated data.
182 if (isset ($this->params['generator'])) {
183 $this->executeGeneratorModule($this->params['generator'], $modules);
184 } else {
185 // Append custom fields and populate page/revision information
186 $this->addCustomFldsToPageSet($modules, $this->mPageSet);
187 $this->mPageSet->execute();
191 // Record page information (title, namespace, if exists, etc)
193 $this->outputGeneralPageInfo();
196 // Execute all requested modules.
198 foreach ($modules as $module) {
199 $module->profileIn();
200 $module->execute();
201 $module->profileOut();
206 * Query modules may optimize data requests through the $this->getPageSet() object
207 * by adding extra fields from the page table.
208 * This function will gather all the extra request fields from the modules.
210 private function addCustomFldsToPageSet($modules, $pageSet) {
211 // Query all requested modules.
212 foreach ($modules as $module) {
213 $module->requestExtraData($pageSet);
218 * Create instances of all modules requested by the client
220 private function InstantiateModules(&$modules, $param, $moduleList) {
221 $list = $this->params[$param];
222 if (isset ($list))
223 foreach ($list as $moduleName)
224 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
228 * Appends an element for each page in the current pageSet with the most general
229 * information (id, title), plus any title normalizations and missing title/pageids/revids.
231 private function outputGeneralPageInfo() {
233 $pageSet = $this->getPageSet();
234 $result = $this->getResult();
236 // Title normalizations
237 $normValues = array ();
238 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
239 $normValues[] = array (
240 'from' => $rawTitleStr,
241 'to' => $titleStr
245 if (!empty ($normValues)) {
246 $result->setIndexedTagName($normValues, 'n');
247 $result->addValue('query', 'normalized', $normValues);
250 // Interwiki titles
251 $intrwValues = array ();
252 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
253 $intrwValues[] = array (
254 'title' => $rawTitleStr,
255 'iw' => $interwikiStr
259 if (!empty ($intrwValues)) {
260 $result->setIndexedTagName($intrwValues, 'i');
261 $result->addValue('query', 'interwiki', $intrwValues);
264 // Show redirect information
265 $redirValues = array ();
266 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
267 $redirValues[] = array (
268 'from' => $titleStrFrom,
269 'to' => $titleStrTo
273 if (!empty ($redirValues)) {
274 $result->setIndexedTagName($redirValues, 'r');
275 $result->addValue('query', 'redirects', $redirValues);
279 // Missing revision elements
281 $missingRevIDs = $pageSet->getMissingRevisionIDs();
282 if (!empty ($missingRevIDs)) {
283 $revids = array ();
284 foreach ($missingRevIDs as $revid) {
285 $revids[$revid] = array (
286 'revid' => $revid
289 $result->setIndexedTagName($revids, 'rev');
290 $result->addValue('query', 'badrevids', $revids);
294 // Page elements
296 $pages = array ();
298 // Report any missing titles
299 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
300 $vals = array();
301 ApiQueryBase :: addTitleInfo($vals, $title);
302 $vals['missing'] = '';
303 $pages[$fakeId] = $vals;
306 // Report any missing page ids
307 foreach ($pageSet->getMissingPageIDs() as $pageid) {
308 $pages[$pageid] = array (
309 'pageid' => $pageid,
310 'missing' => ''
314 // Output general page information for found titles
315 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
316 $vals = array();
317 $vals['pageid'] = $pageid;
318 ApiQueryBase :: addTitleInfo($vals, $title);
319 $pages[$pageid] = $vals;
322 if (!empty ($pages)) {
324 if ($this->params['indexpageids']) {
325 $pageIDs = array_keys($pages);
326 // json treats all map keys as strings - converting to match
327 $pageIDs = array_map('strval', $pageIDs);
328 $result->setIndexedTagName($pageIDs, 'id');
329 $result->addValue('query', 'pageids', $pageIDs);
332 $result->setIndexedTagName($pages, 'page');
333 $result->addValue('query', 'pages', $pages);
338 * For generator mode, execute generator, and use its output as new pageSet
340 protected function executeGeneratorModule($generatorName, $modules) {
342 // Find class that implements requested generator
343 if (isset ($this->mQueryListModules[$generatorName])) {
344 $className = $this->mQueryListModules[$generatorName];
345 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
346 $className = $this->mQueryPropModules[$generatorName];
347 } else {
348 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
351 // Generator results
352 $resultPageSet = new ApiPageSet($this, $this->redirects);
354 // Create and execute the generator
355 $generator = new $className ($this, $generatorName);
356 if (!$generator instanceof ApiQueryGeneratorBase)
357 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
359 $generator->setGeneratorMode();
361 // Add any additional fields modules may need
362 $generator->requestExtraData($this->mPageSet);
363 $this->addCustomFldsToPageSet($modules, $resultPageSet);
365 // Populate page information with the original user input
366 $this->mPageSet->execute();
368 // populate resultPageSet with the generator output
369 $generator->profileIn();
370 $generator->executeGenerator($resultPageSet);
371 $resultPageSet->finishPageSetGeneration();
372 $generator->profileOut();
374 // Swap the resulting pageset back in
375 $this->mPageSet = $resultPageSet;
379 * Returns the list of allowed parameters for this module.
380 * Qurey module also lists all ApiPageSet parameters as its own.
382 protected function getAllowedParams() {
383 return array (
384 'prop' => array (
385 ApiBase :: PARAM_ISMULTI => true,
386 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
388 'list' => array (
389 ApiBase :: PARAM_ISMULTI => true,
390 ApiBase :: PARAM_TYPE => $this->mListModuleNames
392 'meta' => array (
393 ApiBase :: PARAM_ISMULTI => true,
394 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
396 'generator' => array (
397 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
399 'redirects' => false,
400 'indexpageids' => false,
405 * Override the parent to generate help messages for all available query modules.
407 public function makeHelpMsg() {
409 $msg = '';
411 // Make sure the internal object is empty
412 // (just in case a sub-module decides to optimize during instantiation)
413 $this->mPageSet = null;
414 $this->mAllowedGenerators = array(); // Will be repopulated
416 $astriks = str_repeat('--- ', 8);
417 $msg .= "\n$astriks Query: Prop $astriks\n\n";
418 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
419 $msg .= "\n$astriks Query: List $astriks\n\n";
420 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
421 $msg .= "\n$astriks Query: Meta $astriks\n\n";
422 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
424 // Perform the base call last because the $this->mAllowedGenerators
425 // will be updated inside makeHelpMsgHelper()
426 // Use parent to make default message for the query module
427 $msg = parent :: makeHelpMsg() . $msg;
429 return $msg;
433 * For all modules in $moduleList, generate help messages and join them together
435 private function makeHelpMsgHelper($moduleList, $paramName) {
437 $moduleDscriptions = array ();
439 foreach ($moduleList as $moduleName => $moduleClass) {
440 $module = new $moduleClass ($this, $moduleName, null);
442 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
443 $msg2 = $module->makeHelpMsg();
444 if ($msg2 !== false)
445 $msg .= $msg2;
446 if ($module instanceof ApiQueryGeneratorBase) {
447 $this->mAllowedGenerators[] = $moduleName;
448 $msg .= "Generator:\n This module may be used as a generator\n";
450 $moduleDscriptions[] = $msg;
453 return implode("\n", $moduleDscriptions);
457 * Override to add extra parameters from PageSet
459 public function makeHelpMsgParameters() {
460 $psModule = new ApiPageSet($this);
461 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
464 // @todo should work correctly
465 public function shouldCheckMaxlag() {
466 return true;
469 protected function getParamDescription() {
470 return array (
471 'prop' => 'Which properties to get for the titles/revisions/pageids',
472 'list' => 'Which lists to get',
473 'meta' => 'Which meta data to get about the site',
474 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
475 'redirects' => 'Automatically resolve redirects',
476 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
480 protected function getDescription() {
481 return array (
482 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
483 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
484 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
488 protected function getExamples() {
489 return array (
490 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
494 public function getVersion() {
495 $psModule = new ApiPageSet($this);
496 $vers = array ();
497 $vers[] = __CLASS__ . ': $Id$';
498 $vers[] = $psModule->getVersion();
499 return $vers;