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