9c69a41c548f8b7f64e71335c59cac69d5446689
[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 * @ingroup 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 $wgApiPropModules, $wgApiListModules, $wgApiMetaModules;
97 self :: appendUserModules($this->mQueryPropModules, $wgApiPropModules);
98 self :: appendUserModules($this->mQueryListModules, $wgApiListModules);
99 self :: appendUserModules($this->mQueryMetaModules, $wgApiMetaModules);
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 wfRunHooks('APIQueryAfterExecute', array(&$module));
213 $module->profileOut();
214 }
215 }
216
217 /**
218 * Query modules may optimize data requests through the $this->getPageSet() object
219 * by adding extra fields from the page table.
220 * This function will gather all the extra request fields from the modules.
221 */
222 private function addCustomFldsToPageSet($modules, $pageSet) {
223 // Query all requested modules.
224 foreach ($modules as $module) {
225 $module->requestExtraData($pageSet);
226 }
227 }
228
229 /**
230 * Create instances of all modules requested by the client
231 */
232 private function InstantiateModules(&$modules, $param, $moduleList) {
233 $list = @$this->params[$param];
234 if (!is_null ($list))
235 foreach ($list as $moduleName)
236 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
237 }
238
239 /**
240 * Appends an element for each page in the current pageSet with the most general
241 * information (id, title), plus any title normalizations and missing or invalid title/pageids/revids.
242 */
243 private function outputGeneralPageInfo() {
244
245 $pageSet = $this->getPageSet();
246 $result = $this->getResult();
247
248 // Title normalizations
249 $normValues = array ();
250 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
251 $normValues[] = array (
252 'from' => $rawTitleStr,
253 'to' => $titleStr
254 );
255 }
256
257 if (!empty ($normValues)) {
258 $result->setIndexedTagName($normValues, 'n');
259 $result->addValue('query', 'normalized', $normValues);
260 }
261
262 // Interwiki titles
263 $intrwValues = array ();
264 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
265 $intrwValues[] = array (
266 'title' => $rawTitleStr,
267 'iw' => $interwikiStr
268 );
269 }
270
271 if (!empty ($intrwValues)) {
272 $result->setIndexedTagName($intrwValues, 'i');
273 $result->addValue('query', 'interwiki', $intrwValues);
274 }
275
276 // Show redirect information
277 $redirValues = array ();
278 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
279 $redirValues[] = array (
280 'from' => strval($titleStrFrom),
281 'to' => $titleStrTo
282 );
283 }
284
285 if (!empty ($redirValues)) {
286 $result->setIndexedTagName($redirValues, 'r');
287 $result->addValue('query', 'redirects', $redirValues);
288 }
289
290 //
291 // Missing revision elements
292 //
293 $missingRevIDs = $pageSet->getMissingRevisionIDs();
294 if (!empty ($missingRevIDs)) {
295 $revids = array ();
296 foreach ($missingRevIDs as $revid) {
297 $revids[$revid] = array (
298 'revid' => $revid
299 );
300 }
301 $result->setIndexedTagName($revids, 'rev');
302 $result->addValue('query', 'badrevids', $revids);
303 }
304
305 //
306 // Page elements
307 //
308 $pages = array ();
309
310 // Report any missing titles
311 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
312 $vals = array();
313 ApiQueryBase :: addTitleInfo($vals, $title);
314 $vals['missing'] = '';
315 $pages[$fakeId] = $vals;
316 }
317 // Report any invalid titles
318 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
319 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
320 // Report any missing page ids
321 foreach ($pageSet->getMissingPageIDs() as $pageid) {
322 $pages[$pageid] = array (
323 'pageid' => $pageid,
324 'missing' => ''
325 );
326 }
327
328 // Output general page information for found titles
329 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
330 $vals = array();
331 $vals['pageid'] = $pageid;
332 ApiQueryBase :: addTitleInfo($vals, $title);
333 $pages[$pageid] = $vals;
334 }
335
336 if (!empty ($pages)) {
337
338 if ($this->params['indexpageids']) {
339 $pageIDs = array_keys($pages);
340 // json treats all map keys as strings - converting to match
341 $pageIDs = array_map('strval', $pageIDs);
342 $result->setIndexedTagName($pageIDs, 'id');
343 $result->addValue('query', 'pageids', $pageIDs);
344 }
345
346 $result->setIndexedTagName($pages, 'page');
347 $result->addValue('query', 'pages', $pages);
348 }
349 }
350
351 /**
352 * For generator mode, execute generator, and use its output as new pageSet
353 */
354 protected function executeGeneratorModule($generatorName, $modules) {
355
356 // Find class that implements requested generator
357 if (isset ($this->mQueryListModules[$generatorName])) {
358 $className = $this->mQueryListModules[$generatorName];
359 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
360 $className = $this->mQueryPropModules[$generatorName];
361 } else {
362 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
363 }
364
365 // Generator results
366 $resultPageSet = new ApiPageSet($this, $this->redirects);
367
368 // Create and execute the generator
369 $generator = new $className ($this, $generatorName);
370 if (!$generator instanceof ApiQueryGeneratorBase)
371 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
372
373 $generator->setGeneratorMode();
374
375 // Add any additional fields modules may need
376 $generator->requestExtraData($this->mPageSet);
377 $this->addCustomFldsToPageSet($modules, $resultPageSet);
378
379 // Populate page information with the original user input
380 $this->mPageSet->execute();
381
382 // populate resultPageSet with the generator output
383 $generator->profileIn();
384 $generator->executeGenerator($resultPageSet);
385 wfRunHooks('APIQueryGeneratorAfterExecute', array(&$generator, &$resultPageSet));
386 $resultPageSet->finishPageSetGeneration();
387 $generator->profileOut();
388
389 // Swap the resulting pageset back in
390 $this->mPageSet = $resultPageSet;
391 }
392
393 /**
394 * Returns the list of allowed parameters for this module.
395 * Qurey module also lists all ApiPageSet parameters as its own.
396 */
397 public function getAllowedParams() {
398 return array (
399 'prop' => array (
400 ApiBase :: PARAM_ISMULTI => true,
401 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
402 ),
403 'list' => array (
404 ApiBase :: PARAM_ISMULTI => true,
405 ApiBase :: PARAM_TYPE => $this->mListModuleNames
406 ),
407 'meta' => array (
408 ApiBase :: PARAM_ISMULTI => true,
409 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
410 ),
411 'generator' => array (
412 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
413 ),
414 'redirects' => false,
415 'indexpageids' => false,
416 );
417 }
418
419 /**
420 * Override the parent to generate help messages for all available query modules.
421 */
422 public function makeHelpMsg() {
423
424 $msg = '';
425
426 // Make sure the internal object is empty
427 // (just in case a sub-module decides to optimize during instantiation)
428 $this->mPageSet = null;
429 $this->mAllowedGenerators = array(); // Will be repopulated
430
431 $astriks = str_repeat('--- ', 8);
432 $astriks2 = str_repeat('*** ', 10);
433 $msg .= "\n$astriks Query: Prop $astriks\n\n";
434 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
435 $msg .= "\n$astriks Query: List $astriks\n\n";
436 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
437 $msg .= "\n$astriks Query: Meta $astriks\n\n";
438 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
439 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
440
441 // Perform the base call last because the $this->mAllowedGenerators
442 // will be updated inside makeHelpMsgHelper()
443 // Use parent to make default message for the query module
444 $msg = parent :: makeHelpMsg() . $msg;
445
446 return $msg;
447 }
448
449 /**
450 * For all modules in $moduleList, generate help messages and join them together
451 */
452 private function makeHelpMsgHelper($moduleList, $paramName) {
453
454 $moduleDscriptions = array ();
455
456 foreach ($moduleList as $moduleName => $moduleClass) {
457 $module = new $moduleClass ($this, $moduleName, null);
458
459 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
460 $msg2 = $module->makeHelpMsg();
461 if ($msg2 !== false)
462 $msg .= $msg2;
463 if ($module instanceof ApiQueryGeneratorBase) {
464 $this->mAllowedGenerators[] = $moduleName;
465 $msg .= "Generator:\n This module may be used as a generator\n";
466 }
467 $moduleDscriptions[] = $msg;
468 }
469
470 return implode("\n", $moduleDscriptions);
471 }
472
473 /**
474 * Override to add extra parameters from PageSet
475 */
476 public function makeHelpMsgParameters() {
477 $psModule = new ApiPageSet($this);
478 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
479 }
480
481 // @todo should work correctly
482 public function shouldCheckMaxlag() {
483 return true;
484 }
485
486 public function getParamDescription() {
487 return array (
488 'prop' => 'Which properties to get for the titles/revisions/pageids',
489 'list' => 'Which lists to get',
490 'meta' => 'Which meta data to get about the site',
491 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
492 'redirects' => 'Automatically resolve redirects',
493 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
494 );
495 }
496
497 public function getDescription() {
498 return array (
499 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
500 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
501 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
502 );
503 }
504
505 protected function getExamples() {
506 return array (
507 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
508 );
509 }
510
511 public function getVersion() {
512 $psModule = new ApiPageSet($this);
513 $vers = array ();
514 $vers[] = __CLASS__ . ': $Id$';
515 $vers[] = $psModule->getVersion();
516 return $vers;
517 }
518 }