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