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