* Add a nice fieldset around the input form
[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 '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',
80 );
81
82 private $mQueryMetaModules = array (
83 'siteinfo' => 'ApiQuerySiteinfo',
84 'userinfo' => 'ApiQueryUserInfo',
85 'allmessages' => 'ApiQueryAllmessages',
86 );
87
88 private $mSlaveDB = null;
89 private $mNamedDB = array();
90
91 public function __construct($main, $action) {
92 parent :: __construct($main, $action);
93
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);
99
100 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
101 $this->mListModuleNames = array_keys($this->mQueryListModules);
102 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
103
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);
107 }
108
109 /**
110 * Helper function to append any add-in modules to the list
111 */
112 private static function appendUserModules(&$modules, $newModules) {
113 if (is_array( $newModules )) {
114 foreach ( $newModules as $moduleName => $moduleClass) {
115 $modules[$moduleName] = $moduleClass;
116 }
117 }
118 }
119
120 /**
121 * Gets a default slave database connection object
122 */
123 public function getDB() {
124 if (!isset ($this->mSlaveDB)) {
125 $this->profileDBIn();
126 $this->mSlaveDB = wfGetDB(DB_SLAVE);
127 $this->profileDBOut();
128 }
129 return $this->mSlaveDB;
130 }
131
132 /**
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.
137 */
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();
143 }
144 return $this->mNamedDB[$name];
145 }
146
147 /**
148 * Gets the set of pages the user has requested (or generated)
149 */
150 public function getPageSet() {
151 return $this->mPageSet;
152 }
153
154 /**
155 * Get the array mapping module names to class names
156 */
157 function getModules() {
158 return array_merge($this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules);
159 }
160
161 /**
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
170 */
171 public function execute() {
172
173 $this->params = $this->extractRequestParams();
174 $this->redirects = $this->params['redirects'];
175
176 //
177 // Create PageSet
178 //
179 $this->mPageSet = new ApiPageSet($this, $this->redirects);
180
181 //
182 // Instantiate requested modules
183 //
184 $modules = array ();
185 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
186 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
187 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
188
189 //
190 // If given, execute generator to substitute user supplied data with generated data.
191 //
192 if (isset ($this->params['generator'])) {
193 $this->executeGeneratorModule($this->params['generator'], $modules);
194 } else {
195 // Append custom fields and populate page/revision information
196 $this->addCustomFldsToPageSet($modules, $this->mPageSet);
197 $this->mPageSet->execute();
198 }
199
200 //
201 // Record page information (title, namespace, if exists, etc)
202 //
203 $this->outputGeneralPageInfo();
204
205 //
206 // Execute all requested modules.
207 //
208 foreach ($modules as $module) {
209 $module->profileIn();
210 $module->execute();
211 $module->profileOut();
212 }
213 }
214
215 /**
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.
219 */
220 private function addCustomFldsToPageSet($modules, $pageSet) {
221 // Query all requested modules.
222 foreach ($modules as $module) {
223 $module->requestExtraData($pageSet);
224 }
225 }
226
227 /**
228 * Create instances of all modules requested by the client
229 */
230 private function InstantiateModules(&$modules, $param, $moduleList) {
231 $list = $this->params[$param];
232 if (isset ($list))
233 foreach ($list as $moduleName)
234 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
235 }
236
237 /**
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 title/pageids/revids.
240 */
241 private function outputGeneralPageInfo() {
242
243 $pageSet = $this->getPageSet();
244 $result = $this->getResult();
245
246 // Title normalizations
247 $normValues = array ();
248 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
249 $normValues[] = array (
250 'from' => $rawTitleStr,
251 'to' => $titleStr
252 );
253 }
254
255 if (!empty ($normValues)) {
256 $result->setIndexedTagName($normValues, 'n');
257 $result->addValue('query', 'normalized', $normValues);
258 }
259
260 // Interwiki titles
261 $intrwValues = array ();
262 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
263 $intrwValues[] = array (
264 'title' => $rawTitleStr,
265 'iw' => $interwikiStr
266 );
267 }
268
269 if (!empty ($intrwValues)) {
270 $result->setIndexedTagName($intrwValues, 'i');
271 $result->addValue('query', 'interwiki', $intrwValues);
272 }
273
274 // Show redirect information
275 $redirValues = array ();
276 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
277 $redirValues[] = array (
278 'from' => $titleStrFrom,
279 'to' => $titleStrTo
280 );
281 }
282
283 if (!empty ($redirValues)) {
284 $result->setIndexedTagName($redirValues, 'r');
285 $result->addValue('query', 'redirects', $redirValues);
286 }
287
288 //
289 // Missing revision elements
290 //
291 $missingRevIDs = $pageSet->getMissingRevisionIDs();
292 if (!empty ($missingRevIDs)) {
293 $revids = array ();
294 foreach ($missingRevIDs as $revid) {
295 $revids[$revid] = array (
296 'revid' => $revid
297 );
298 }
299 $result->setIndexedTagName($revids, 'rev');
300 $result->addValue('query', 'badrevids', $revids);
301 }
302
303 //
304 // Page elements
305 //
306 $pages = array ();
307
308 // Report any missing titles
309 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
310 $vals = array();
311 ApiQueryBase :: addTitleInfo($vals, $title);
312 $vals['missing'] = '';
313 $pages[$fakeId] = $vals;
314 }
315
316 // Report any missing page ids
317 foreach ($pageSet->getMissingPageIDs() as $pageid) {
318 $pages[$pageid] = array (
319 'pageid' => $pageid,
320 'missing' => ''
321 );
322 }
323
324 // Output general page information for found titles
325 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
326 $vals = array();
327 $vals['pageid'] = $pageid;
328 ApiQueryBase :: addTitleInfo($vals, $title);
329 $pages[$pageid] = $vals;
330 }
331
332 if (!empty ($pages)) {
333
334 if ($this->params['indexpageids']) {
335 $pageIDs = array_keys($pages);
336 // json treats all map keys as strings - converting to match
337 $pageIDs = array_map('strval', $pageIDs);
338 $result->setIndexedTagName($pageIDs, 'id');
339 $result->addValue('query', 'pageids', $pageIDs);
340 }
341
342 $result->setIndexedTagName($pages, 'page');
343 $result->addValue('query', 'pages', $pages);
344 }
345 }
346
347 /**
348 * For generator mode, execute generator, and use its output as new pageSet
349 */
350 protected function executeGeneratorModule($generatorName, $modules) {
351
352 // Find class that implements requested generator
353 if (isset ($this->mQueryListModules[$generatorName])) {
354 $className = $this->mQueryListModules[$generatorName];
355 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
356 $className = $this->mQueryPropModules[$generatorName];
357 } else {
358 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
359 }
360
361 // Generator results
362 $resultPageSet = new ApiPageSet($this, $this->redirects);
363
364 // Create and execute the generator
365 $generator = new $className ($this, $generatorName);
366 if (!$generator instanceof ApiQueryGeneratorBase)
367 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
368
369 $generator->setGeneratorMode();
370
371 // Add any additional fields modules may need
372 $generator->requestExtraData($this->mPageSet);
373 $this->addCustomFldsToPageSet($modules, $resultPageSet);
374
375 // Populate page information with the original user input
376 $this->mPageSet->execute();
377
378 // populate resultPageSet with the generator output
379 $generator->profileIn();
380 $generator->executeGenerator($resultPageSet);
381 $resultPageSet->finishPageSetGeneration();
382 $generator->profileOut();
383
384 // Swap the resulting pageset back in
385 $this->mPageSet = $resultPageSet;
386 }
387
388 /**
389 * Returns the list of allowed parameters for this module.
390 * Qurey module also lists all ApiPageSet parameters as its own.
391 */
392 public function getAllowedParams() {
393 return array (
394 'prop' => array (
395 ApiBase :: PARAM_ISMULTI => true,
396 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
397 ),
398 'list' => array (
399 ApiBase :: PARAM_ISMULTI => true,
400 ApiBase :: PARAM_TYPE => $this->mListModuleNames
401 ),
402 'meta' => array (
403 ApiBase :: PARAM_ISMULTI => true,
404 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
405 ),
406 'generator' => array (
407 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
408 ),
409 'redirects' => false,
410 'indexpageids' => false,
411 );
412 }
413
414 /**
415 * Override the parent to generate help messages for all available query modules.
416 */
417 public function makeHelpMsg() {
418
419 $msg = '';
420
421 // Make sure the internal object is empty
422 // (just in case a sub-module decides to optimize during instantiation)
423 $this->mPageSet = null;
424 $this->mAllowedGenerators = array(); // Will be repopulated
425
426 $astriks = str_repeat('--- ', 8);
427 $astriks2 = str_repeat('*** ', 10);
428 $msg .= "\n$astriks Query: Prop $astriks\n\n";
429 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
430 $msg .= "\n$astriks Query: List $astriks\n\n";
431 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
432 $msg .= "\n$astriks Query: Meta $astriks\n\n";
433 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
434 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
435
436 // Perform the base call last because the $this->mAllowedGenerators
437 // will be updated inside makeHelpMsgHelper()
438 // Use parent to make default message for the query module
439 $msg = parent :: makeHelpMsg() . $msg;
440
441 return $msg;
442 }
443
444 /**
445 * For all modules in $moduleList, generate help messages and join them together
446 */
447 private function makeHelpMsgHelper($moduleList, $paramName) {
448
449 $moduleDscriptions = array ();
450
451 foreach ($moduleList as $moduleName => $moduleClass) {
452 $module = new $moduleClass ($this, $moduleName, null);
453
454 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
455 $msg2 = $module->makeHelpMsg();
456 if ($msg2 !== false)
457 $msg .= $msg2;
458 if ($module instanceof ApiQueryGeneratorBase) {
459 $this->mAllowedGenerators[] = $moduleName;
460 $msg .= "Generator:\n This module may be used as a generator\n";
461 }
462 $moduleDscriptions[] = $msg;
463 }
464
465 return implode("\n", $moduleDscriptions);
466 }
467
468 /**
469 * Override to add extra parameters from PageSet
470 */
471 public function makeHelpMsgParameters() {
472 $psModule = new ApiPageSet($this);
473 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
474 }
475
476 // @todo should work correctly
477 public function shouldCheckMaxlag() {
478 return true;
479 }
480
481 public function getParamDescription() {
482 return array (
483 'prop' => 'Which properties to get for the titles/revisions/pageids',
484 'list' => 'Which lists to get',
485 'meta' => 'Which meta data to get about the site',
486 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
487 'redirects' => 'Automatically resolve redirects',
488 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
489 );
490 }
491
492 public function getDescription() {
493 return array (
494 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
495 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
496 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
497 );
498 }
499
500 protected function getExamples() {
501 return array (
502 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
503 );
504 }
505
506 public function getVersion() {
507 $psModule = new ApiPageSet($this);
508 $vers = array ();
509 $vers[] = __CLASS__ . ': $Id$';
510 $vers[] = $psModule->getVersion();
511 return $vers;
512 }
513 }
514