API: Improved usercontribs module.
[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
47 private $mQueryPropModules = array (
48 'info' => 'ApiQueryInfo',
49 'revisions' => 'ApiQueryRevisions',
50 'links' => 'ApiQueryLinks',
51 'langlinks' => 'ApiQueryLangLinks',
52 'images' => 'ApiQueryImages',
53 'templates' => 'ApiQueryLinks',
54 'categories' => 'ApiQueryCategories',
55 'extlinks' => 'ApiQueryExternalLinks',
56 );
57 // 'categories' => 'ApiQueryCategories',
58 // 'imageinfo' => 'ApiQueryImageinfo',
59 // 'templates' => 'ApiQueryTemplates',
60
61 private $mQueryListModules = array (
62 'allpages' => 'ApiQueryAllpages',
63 'logevents' => 'ApiQueryLogEvents',
64 'watchlist' => 'ApiQueryWatchlist',
65 'recentchanges' => 'ApiQueryRecentChanges',
66 'backlinks' => 'ApiQueryBacklinks',
67 'embeddedin' => 'ApiQueryBacklinks',
68 'imageusage' => 'ApiQueryBacklinks',
69 'usercontribs' => 'ApiQueryContributions'
70 );
71 // 'categorymembers' => 'ApiQueryCategorymembers',
72 // 'recentchanges' => 'ApiQueryRecentchanges',
73 // 'users' => 'ApiQueryUsers',
74 // 'watchlist' => 'ApiQueryWatchlist',
75
76 private $mQueryMetaModules = array (
77 'siteinfo' => 'ApiQuerySiteinfo'
78 );
79 // 'userinfo' => 'ApiQueryUserinfo',
80
81 private $mSlaveDB = null;
82 private $mNamedDB = array();
83
84 public function __construct($main, $action) {
85 parent :: __construct($main, $action);
86
87 // Allow custom modules to be added in LocalSettings.php
88 global $wgApiQueryPropModules, $wgApiQueryListModules, $wgApiQueryMetaModules;
89
90 if (is_array( $wgApiQueryPropModules )) {
91 foreach ( $wgApiQueryPropModules as $moduleName => $moduleClass) {
92 $this->mQueryPropModules[$moduleName] = $moduleClass;
93 }
94 }
95 if (is_array( $wgApiQueryListModules )) {
96 foreach ( $wgApiQueryListModules as $moduleName => $moduleClass) {
97 $this->mQueryListModules[$moduleName] = $moduleClass;
98 }
99 }
100 if (is_array( $wgApiQueryMetaModules )) {
101 foreach ( $wgApiQueryMetaModules as $moduleName => $moduleClass) {
102 $this->mQueryMetaModules[$moduleName] = $moduleClass;
103 }
104 }
105
106 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
107 $this->mListModuleNames = array_keys($this->mQueryListModules);
108 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
109
110 // Allow the entire list of modules at first,
111 // but during module instantiation check if it can be used as a generator.
112 $this->mAllowedGenerators = array_merge($this->mListModuleNames, $this->mPropModuleNames);
113 }
114
115 public function getDB() {
116 if (!isset ($this->mSlaveDB)) {
117 $this->profileDBIn();
118 $this->mSlaveDB = wfGetDB(DB_SLAVE);
119 $this->profileDBOut();
120 }
121 return $this->mSlaveDB;
122 }
123
124 /**
125 * Get the query database connection with the given name.
126 * If no such connection has been requested before, it will be created.
127 * Subsequent calls with the same $name will return the same connection
128 * as the first, regardless of $db or $groups new values.
129 */
130 public function getNamedDB($name, $db, $groups) {
131 if (!array_key_exists($name, $this->mNamedDB)) {
132 $this->profileDBIn();
133 $this->mNamedDB[$name] = wfGetDB($db, $groups);
134 $this->profileDBOut();
135 }
136 return $this->mNamedDB[$name];
137 }
138
139 public function getPageSet() {
140 return $this->mPageSet;
141 }
142
143 /**
144 * Query execution happens in the following steps:
145 * #1 Create a PageSet object with any pages requested by the user
146 * #2 If using generator, execute it to get a new PageSet object
147 * #3 Instantiate all requested modules.
148 * This way the PageSet object will know what shared data is required,
149 * and minimize DB calls.
150 * #4 Output all normalization and redirect resolution information
151 * #5 Execute all requested modules
152 */
153 public function execute() {
154 $prop = $list = $meta = $generator = $redirects = null;
155 extract($this->extractRequestParams());
156
157 //
158 // Create PageSet
159 //
160 $this->mPageSet = new ApiPageSet($this, $redirects);
161
162 // Instantiate required modules
163 $modules = array ();
164 if (isset ($prop))
165 foreach ($prop as $moduleName)
166 $modules[] = new $this->mQueryPropModules[$moduleName] ($this, $moduleName);
167 if (isset ($list))
168 foreach ($list as $moduleName)
169 $modules[] = new $this->mQueryListModules[$moduleName] ($this, $moduleName);
170 if (isset ($meta))
171 foreach ($meta as $moduleName)
172 $modules[] = new $this->mQueryMetaModules[$moduleName] ($this, $moduleName);
173
174 // Modules may optimize data requests through the $this->getPageSet() object
175 // Execute all requested modules.
176 foreach ($modules as $module) {
177 $module->requestExtraData();
178 }
179
180 //
181 // Populate page information for the given pageSet
182 //
183 $this->mPageSet->execute();
184
185 //
186 // If given, execute generator to substitute user supplied data with generated data.
187 //
188 if (isset ($generator))
189 $this->executeGeneratorModule($generator, $redirects);
190
191 //
192 // Record page information (title, namespace, if exists, etc)
193 //
194 $this->outputGeneralPageInfo();
195
196 //
197 // Execute all requested modules.
198 //
199 foreach ($modules as $module) {
200 $module->profileIn();
201 $module->execute();
202 $module->profileOut();
203 }
204 }
205
206 private function outputGeneralPageInfo() {
207
208 $pageSet = $this->getPageSet();
209 $result = $this->getResult();
210
211 // Title normalizations
212 $normValues = array ();
213 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
214 $normValues[] = array (
215 'from' => $rawTitleStr,
216 'to' => $titleStr
217 );
218 }
219
220 if (!empty ($normValues)) {
221 $result->setIndexedTagName($normValues, 'n');
222 $result->addValue('query', 'normalized', $normValues);
223 }
224
225 // Show redirect information
226 $redirValues = array ();
227 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
228 $redirValues[] = array (
229 'from' => $titleStrFrom,
230 'to' => $titleStrTo
231 );
232 }
233
234 if (!empty ($redirValues)) {
235 $result->setIndexedTagName($redirValues, 'r');
236 $result->addValue('query', 'redirects', $redirValues);
237 }
238
239 //
240 // Missing revision elements
241 //
242 $missingRevIDs = $pageSet->getMissingRevisionIDs();
243 if (!empty ($missingRevIDs)) {
244 $revids = array ();
245 foreach ($missingRevIDs as $revid) {
246 $revids[$revid] = array (
247 'revid' => $revid
248 );
249 }
250 $result->setIndexedTagName($revids, 'rev');
251 $result->addValue('query', 'badrevids', $revids);
252 }
253
254 //
255 // Page elements
256 //
257 $pages = array ();
258
259 // Report any missing titles
260 $fakepageid = -1;
261 foreach ($pageSet->getMissingTitles() as $title) {
262 $pages[$fakepageid--] = array (
263 'ns' => $title->getNamespace(), 'title' => $title->getPrefixedText(), 'missing' => '');
264 }
265
266 // Report any missing page ids
267 foreach ($pageSet->getMissingPageIDs() as $pageid) {
268 $pages[$pageid] = array (
269 'pageid' => $pageid,
270 'missing' => ''
271 );
272 }
273
274 // Output general page information for found titles
275 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
276 $pages[$pageid] = array (
277 'pageid' => $pageid,
278 'ns' => $title->getNamespace(), 'title' => $title->getPrefixedText());
279 }
280
281 if (!empty ($pages)) {
282 $result->setIndexedTagName($pages, 'page');
283 $result->addValue('query', 'pages', $pages);
284 }
285 }
286
287 protected function executeGeneratorModule($generatorName, $redirects) {
288
289 // Find class that implements requested generator
290 if (isset ($this->mQueryListModules[$generatorName])) {
291 $className = $this->mQueryListModules[$generatorName];
292 }
293 elseif (isset ($this->mQueryPropModules[$generatorName])) {
294 $className = $this->mQueryPropModules[$generatorName];
295 } else {
296 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
297 }
298
299 // Generator results
300 $resultPageSet = new ApiPageSet($this, $redirects);
301
302 // Create and execute the generator
303 $generator = new $className ($this, $generatorName);
304 if (!$generator instanceof ApiQueryGeneratorBase)
305 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
306
307 $generator->setGeneratorMode();
308 $generator->requestExtraData();
309
310 // populate resultPageSet with the generator output
311 $generator->profileIn();
312 $generator->executeGenerator($resultPageSet);
313 $resultPageSet->finishPageSetGeneration();
314 $generator->profileOut();
315
316 // Swap the resulting pageset back in
317 $this->mPageSet = $resultPageSet;
318 }
319
320 protected function getAllowedParams() {
321 return array (
322 'prop' => array (
323 ApiBase :: PARAM_ISMULTI => true,
324 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
325 ),
326 'list' => array (
327 ApiBase :: PARAM_ISMULTI => true,
328 ApiBase :: PARAM_TYPE => $this->mListModuleNames
329 ),
330 'meta' => array (
331 ApiBase :: PARAM_ISMULTI => true,
332 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
333 ),
334 'generator' => array (
335 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
336 ),
337 'redirects' => false
338 );
339 }
340
341 /**
342 * Override the parent to generate help messages for all available query modules.
343 */
344 public function makeHelpMsg() {
345
346 // Use parent to make default message for the query module
347 $msg = parent :: makeHelpMsg();
348
349 // Make sure the internal object is empty
350 // (just in case a sub-module decides to optimize during instantiation)
351 $this->mPageSet = null;
352
353 $astriks = str_repeat('--- ', 8);
354 $msg .= "\n$astriks Query: Prop $astriks\n\n";
355 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
356 $msg .= "\n$astriks Query: List $astriks\n\n";
357 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
358 $msg .= "\n$astriks Query: Meta $astriks\n\n";
359 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
360
361 return $msg;
362 }
363
364 private function makeHelpMsgHelper($moduleList, $paramName) {
365
366 $moduleDscriptions = array ();
367
368 foreach ($moduleList as $moduleName => $moduleClass) {
369 $msg = "* $paramName=$moduleName *";
370 $module = new $moduleClass ($this, $moduleName, null);
371 $msg2 = $module->makeHelpMsg();
372 if ($msg2 !== false)
373 $msg .= $msg2;
374 if ($module instanceof ApiQueryGeneratorBase)
375 $msg .= "Generator:\n This module may be used as a generator\n";
376 $moduleDscriptions[] = $msg;
377 }
378
379 return implode("\n", $moduleDscriptions);
380 }
381
382 /**
383 * Override to add extra parameters from PageSet
384 */
385 public function makeHelpMsgParameters() {
386 $psModule = new ApiPageSet($this);
387 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
388 }
389
390 protected function getParamDescription() {
391 return array (
392 'prop' => 'Which properties to get for the titles/revisions/pageids',
393 'list' => 'Which lists to get',
394 'meta' => 'Which meta data to get about the site',
395 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
396 'redirects' => 'Automatically resolve redirects'
397 );
398 }
399
400 protected function getDescription() {
401 return array (
402 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
403 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
404 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
405 );
406 }
407
408 protected function getExamples() {
409 return array (
410 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
411 );
412 }
413
414 public function getVersion() {
415 $psModule = new ApiPageSet($this);
416 $vers = array ();
417 $vers[] = __CLASS__ . ': $Id$';
418 $vers[] = $psModule->getVersion();
419 return $vers;
420 }
421 }
422 ?>