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