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