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