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