* (bug 12506) Allow URL parameter 'section' in Special:Mypage/Mytalk. Patch by Eneas.
[lhc/web/wiklou.git] / includes / api / ApiQuery.php
1 <?php
2
3 /*
4 * Created on Sep 7, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
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.
14 *
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.
19 *
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
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
29 }
30
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.
36 *
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.
39 *
40 * @addtogroup API
41 */
42 class ApiQuery extends ApiBase {
43
44 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
45 private $mPageSet;
46 private $params, $redirect;
47
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 );
59
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',
77 );
78
79 private $mQueryMetaModules = array (
80 'siteinfo' => 'ApiQuerySiteinfo',
81 'userinfo' => 'ApiQueryUserInfo',
82 'allmessages' => 'ApiQueryAllmessages',
83 );
84
85 private $mSlaveDB = null;
86 private $mNamedDB = array();
87
88 public function __construct($main, $action) {
89 parent :: __construct($main, $action);
90
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);
96
97 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
98 $this->mListModuleNames = array_keys($this->mQueryListModules);
99 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
100
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);
104 }
105
106 /**
107 * Helper function to append any add-in modules to the list
108 */
109 private static function appendUserModules(&$modules, $newModules) {
110 if (is_array( $newModules )) {
111 foreach ( $newModules as $moduleName => $moduleClass) {
112 $modules[$moduleName] = $moduleClass;
113 }
114 }
115 }
116
117 /**
118 * Gets a default slave database connection object
119 */
120 public function getDB() {
121 if (!isset ($this->mSlaveDB)) {
122 $this->profileDBIn();
123 $this->mSlaveDB = wfGetDB(DB_SLAVE);
124 $this->profileDBOut();
125 }
126 return $this->mSlaveDB;
127 }
128
129 /**
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.
134 */
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();
140 }
141 return $this->mNamedDB[$name];
142 }
143
144 /**
145 * Gets the set of pages the user has requested (or generated)
146 */
147 public function getPageSet() {
148 return $this->mPageSet;
149 }
150
151 /**
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
160 */
161 public function execute() {
162
163 $this->params = $this->extractRequestParams();
164 $this->redirects = $this->params['redirects'];
165
166 //
167 // Create PageSet
168 //
169 $this->mPageSet = new ApiPageSet($this, $this->redirects);
170
171 //
172 // Instantiate requested modules
173 //
174 $modules = array ();
175 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
176 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
177 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
178
179 //
180 // If given, execute generator to substitute user supplied data with generated data.
181 //
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();
188 }
189
190 //
191 // Record page information (title, namespace, if exists, etc)
192 //
193 $this->outputGeneralPageInfo();
194
195 //
196 // Execute all requested modules.
197 //
198 foreach ($modules as $module) {
199 $module->profileIn();
200 $module->execute();
201 $module->profileOut();
202 }
203 }
204
205 /**
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.
209 */
210 private function addCustomFldsToPageSet($modules, $pageSet) {
211 // Query all requested modules.
212 foreach ($modules as $module) {
213 $module->requestExtraData($pageSet);
214 }
215 }
216
217 /**
218 * Create instances of all modules requested by the client
219 */
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);
225 }
226
227 /**
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.
230 */
231 private function outputGeneralPageInfo() {
232
233 $pageSet = $this->getPageSet();
234 $result = $this->getResult();
235
236 // Title normalizations
237 $normValues = array ();
238 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
239 $normValues[] = array (
240 'from' => $rawTitleStr,
241 'to' => $titleStr
242 );
243 }
244
245 if (!empty ($normValues)) {
246 $result->setIndexedTagName($normValues, 'n');
247 $result->addValue('query', 'normalized', $normValues);
248 }
249
250 // Interwiki titles
251 $intrwValues = array ();
252 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
253 $intrwValues[] = array (
254 'title' => $rawTitleStr,
255 'iw' => $interwikiStr
256 );
257 }
258
259 if (!empty ($intrwValues)) {
260 $result->setIndexedTagName($intrwValues, 'i');
261 $result->addValue('query', 'interwiki', $intrwValues);
262 }
263
264 // Show redirect information
265 $redirValues = array ();
266 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
267 $redirValues[] = array (
268 'from' => $titleStrFrom,
269 'to' => $titleStrTo
270 );
271 }
272
273 if (!empty ($redirValues)) {
274 $result->setIndexedTagName($redirValues, 'r');
275 $result->addValue('query', 'redirects', $redirValues);
276 }
277
278 //
279 // Missing revision elements
280 //
281 $missingRevIDs = $pageSet->getMissingRevisionIDs();
282 if (!empty ($missingRevIDs)) {
283 $revids = array ();
284 foreach ($missingRevIDs as $revid) {
285 $revids[$revid] = array (
286 'revid' => $revid
287 );
288 }
289 $result->setIndexedTagName($revids, 'rev');
290 $result->addValue('query', 'badrevids', $revids);
291 }
292
293 //
294 // Page elements
295 //
296 $pages = array ();
297
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;
304 }
305
306 // Report any missing page ids
307 foreach ($pageSet->getMissingPageIDs() as $pageid) {
308 $pages[$pageid] = array (
309 'pageid' => $pageid,
310 'missing' => ''
311 );
312 }
313
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;
320 }
321
322 if (!empty ($pages)) {
323
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);
330 }
331
332 $result->setIndexedTagName($pages, 'page');
333 $result->addValue('query', 'pages', $pages);
334 }
335 }
336
337 /**
338 * For generator mode, execute generator, and use its output as new pageSet
339 */
340 protected function executeGeneratorModule($generatorName, $modules) {
341
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");
349 }
350
351 // Generator results
352 $resultPageSet = new ApiPageSet($this, $this->redirects);
353
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");
358
359 $generator->setGeneratorMode();
360
361 // Add any additional fields modules may need
362 $generator->requestExtraData($this->mPageSet);
363 $this->addCustomFldsToPageSet($modules, $resultPageSet);
364
365 // Populate page information with the original user input
366 $this->mPageSet->execute();
367
368 // populate resultPageSet with the generator output
369 $generator->profileIn();
370 $generator->executeGenerator($resultPageSet);
371 $resultPageSet->finishPageSetGeneration();
372 $generator->profileOut();
373
374 // Swap the resulting pageset back in
375 $this->mPageSet = $resultPageSet;
376 }
377
378 /**
379 * Returns the list of allowed parameters for this module.
380 * Qurey module also lists all ApiPageSet parameters as its own.
381 */
382 protected function getAllowedParams() {
383 return array (
384 'prop' => array (
385 ApiBase :: PARAM_ISMULTI => true,
386 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
387 ),
388 'list' => array (
389 ApiBase :: PARAM_ISMULTI => true,
390 ApiBase :: PARAM_TYPE => $this->mListModuleNames
391 ),
392 'meta' => array (
393 ApiBase :: PARAM_ISMULTI => true,
394 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
395 ),
396 'generator' => array (
397 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
398 ),
399 'redirects' => false,
400 'indexpageids' => false,
401 );
402 }
403
404 /**
405 * Override the parent to generate help messages for all available query modules.
406 */
407 public function makeHelpMsg() {
408
409 $msg = '';
410
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
415
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');
423
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;
428
429 return $msg;
430 }
431
432 /**
433 * For all modules in $moduleList, generate help messages and join them together
434 */
435 private function makeHelpMsgHelper($moduleList, $paramName) {
436
437 $moduleDscriptions = array ();
438
439 foreach ($moduleList as $moduleName => $moduleClass) {
440 $module = new $moduleClass ($this, $moduleName, null);
441
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";
449 }
450 $moduleDscriptions[] = $msg;
451 }
452
453 return implode("\n", $moduleDscriptions);
454 }
455
456 /**
457 * Override to add extra parameters from PageSet
458 */
459 public function makeHelpMsgParameters() {
460 $psModule = new ApiPageSet($this);
461 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
462 }
463
464 // @todo should work correctly
465 public function shouldCheckMaxlag() {
466 return true;
467 }
468
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.'
477 );
478 }
479
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.'
485 );
486 }
487
488 protected function getExamples() {
489 return array (
490 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
491 );
492 }
493
494 public function getVersion() {
495 $psModule = new ApiPageSet($this);
496 $vers = array ();
497 $vers[] = __CLASS__ . ': $Id$';
498 $vers[] = $psModule->getVersion();
499 return $vers;
500 }
501 }
502