f72eb6d9ea42f54cda2cc26f16d1ab99ca95382f
[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 or invalid 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' => strval($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 // Report any invalid titles
316 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
317 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
318 // Report any missing page ids
319 foreach ($pageSet->getMissingPageIDs() as $pageid) {
320 $pages[$pageid] = array (
321 'pageid' => $pageid,
322 'missing' => ''
323 );
324 }
325
326 // Output general page information for found titles
327 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
328 $vals = array();
329 $vals['pageid'] = $pageid;
330 ApiQueryBase :: addTitleInfo($vals, $title);
331 $pages[$pageid] = $vals;
332 }
333
334 if (!empty ($pages)) {
335
336 if ($this->params['indexpageids']) {
337 $pageIDs = array_keys($pages);
338 // json treats all map keys as strings - converting to match
339 $pageIDs = array_map('strval', $pageIDs);
340 $result->setIndexedTagName($pageIDs, 'id');
341 $result->addValue('query', 'pageids', $pageIDs);
342 }
343
344 $result->setIndexedTagName($pages, 'page');
345 $result->addValue('query', 'pages', $pages);
346 }
347 }
348
349 /**
350 * For generator mode, execute generator, and use its output as new pageSet
351 */
352 protected function executeGeneratorModule($generatorName, $modules) {
353
354 // Find class that implements requested generator
355 if (isset ($this->mQueryListModules[$generatorName])) {
356 $className = $this->mQueryListModules[$generatorName];
357 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
358 $className = $this->mQueryPropModules[$generatorName];
359 } else {
360 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
361 }
362
363 // Generator results
364 $resultPageSet = new ApiPageSet($this, $this->redirects);
365
366 // Create and execute the generator
367 $generator = new $className ($this, $generatorName);
368 if (!$generator instanceof ApiQueryGeneratorBase)
369 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
370
371 $generator->setGeneratorMode();
372
373 // Add any additional fields modules may need
374 $generator->requestExtraData($this->mPageSet);
375 $this->addCustomFldsToPageSet($modules, $resultPageSet);
376
377 // Populate page information with the original user input
378 $this->mPageSet->execute();
379
380 // populate resultPageSet with the generator output
381 $generator->profileIn();
382 $generator->executeGenerator($resultPageSet);
383 $resultPageSet->finishPageSetGeneration();
384 $generator->profileOut();
385
386 // Swap the resulting pageset back in
387 $this->mPageSet = $resultPageSet;
388 }
389
390 /**
391 * Returns the list of allowed parameters for this module.
392 * Qurey module also lists all ApiPageSet parameters as its own.
393 */
394 public function getAllowedParams() {
395 return array (
396 'prop' => array (
397 ApiBase :: PARAM_ISMULTI => true,
398 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
399 ),
400 'list' => array (
401 ApiBase :: PARAM_ISMULTI => true,
402 ApiBase :: PARAM_TYPE => $this->mListModuleNames
403 ),
404 'meta' => array (
405 ApiBase :: PARAM_ISMULTI => true,
406 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
407 ),
408 'generator' => array (
409 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
410 ),
411 'redirects' => false,
412 'indexpageids' => false,
413 );
414 }
415
416 /**
417 * Override the parent to generate help messages for all available query modules.
418 */
419 public function makeHelpMsg() {
420
421 $msg = '';
422
423 // Make sure the internal object is empty
424 // (just in case a sub-module decides to optimize during instantiation)
425 $this->mPageSet = null;
426 $this->mAllowedGenerators = array(); // Will be repopulated
427
428 $astriks = str_repeat('--- ', 8);
429 $astriks2 = str_repeat('*** ', 10);
430 $msg .= "\n$astriks Query: Prop $astriks\n\n";
431 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
432 $msg .= "\n$astriks Query: List $astriks\n\n";
433 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
434 $msg .= "\n$astriks Query: Meta $astriks\n\n";
435 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
436 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
437
438 // Perform the base call last because the $this->mAllowedGenerators
439 // will be updated inside makeHelpMsgHelper()
440 // Use parent to make default message for the query module
441 $msg = parent :: makeHelpMsg() . $msg;
442
443 return $msg;
444 }
445
446 /**
447 * For all modules in $moduleList, generate help messages and join them together
448 */
449 private function makeHelpMsgHelper($moduleList, $paramName) {
450
451 $moduleDscriptions = array ();
452
453 foreach ($moduleList as $moduleName => $moduleClass) {
454 $module = new $moduleClass ($this, $moduleName, null);
455
456 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
457 $msg2 = $module->makeHelpMsg();
458 if ($msg2 !== false)
459 $msg .= $msg2;
460 if ($module instanceof ApiQueryGeneratorBase) {
461 $this->mAllowedGenerators[] = $moduleName;
462 $msg .= "Generator:\n This module may be used as a generator\n";
463 }
464 $moduleDscriptions[] = $msg;
465 }
466
467 return implode("\n", $moduleDscriptions);
468 }
469
470 /**
471 * Override to add extra parameters from PageSet
472 */
473 public function makeHelpMsgParameters() {
474 $psModule = new ApiPageSet($this);
475 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
476 }
477
478 // @todo should work correctly
479 public function shouldCheckMaxlag() {
480 return true;
481 }
482
483 public function getParamDescription() {
484 return array (
485 'prop' => 'Which properties to get for the titles/revisions/pageids',
486 'list' => 'Which lists to get',
487 'meta' => 'Which meta data to get about the site',
488 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
489 'redirects' => 'Automatically resolve redirects',
490 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
491 );
492 }
493
494 public function getDescription() {
495 return array (
496 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
497 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
498 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
499 );
500 }
501
502 protected function getExamples() {
503 return array (
504 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
505 );
506 }
507
508 public function getVersion() {
509 $psModule = new ApiPageSet($this);
510 $vers = array ();
511 $vers[] = __CLASS__ . ': $Id$';
512 $vers[] = $psModule->getVersion();
513 return $vers;
514 }
515 }
516