API * Common field output function to simplify result generation
[lhc/web/wiklou.git] / includes / api / ApiQuery.php
1 <?php
2
3
4 /*
5 * Created on Sep 7, 2006
6 *
7 * API for MediaWiki 1.8+
8 *
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
25 */
26
27 if (!defined('MEDIAWIKI')) {
28 // Eclipse helper - will be ignored in production
29 require_once ('ApiBase.php');
30 }
31
32 class ApiQuery extends ApiBase {
33
34 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
35 private $mPageSet;
36 private $mValidNamespaces;
37
38 private $mQueryPropModules = array (
39 'info' => 'ApiQueryInfo',
40 'revisions' => 'ApiQueryRevisions'
41 );
42 // 'categories' => 'ApiQueryCategories',
43 // 'imageinfo' => 'ApiQueryImageinfo',
44 // 'langlinks' => 'ApiQueryLanglinks',
45 // 'links' => 'ApiQueryLinks',
46 // 'templates' => 'ApiQueryTemplates',
47
48 private $mQueryListModules = array (
49 'allpages' => 'ApiQueryAllpages',
50 'logevents' => 'ApiQueryLogEvents',
51 'watchlist' => 'ApiQueryWatchlist',
52 'recentchanges' => 'ApiQueryRecentChanges'
53 );
54 // 'backlinks' => 'ApiQueryBacklinks',
55 // 'categorymembers' => 'ApiQueryCategorymembers',
56 // 'embeddedin' => 'ApiQueryEmbeddedin',
57 // 'imagelinks' => 'ApiQueryImagelinks',
58 // 'recentchanges' => 'ApiQueryRecentchanges',
59 // 'usercontribs' => 'ApiQueryUsercontribs',
60 // 'users' => 'ApiQueryUsers',
61 // 'watchlist' => 'ApiQueryWatchlist',
62
63 private $mQueryMetaModules = array (
64 'siteinfo' => 'ApiQuerySiteinfo'
65 );
66 // 'userinfo' => 'ApiQueryUserinfo',
67
68 private $mSlaveDB = null;
69
70 public function __construct($main, $action) {
71 parent :: __construct($main, $action);
72 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
73 $this->mListModuleNames = array_keys($this->mQueryListModules);
74 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
75 $this->mValidNamespaces = null;
76
77 // Allow the entire list of modules at first,
78 // but during module instantiation check if it can be used as a generator.
79 $this->mAllowedGenerators = array_merge($this->mListModuleNames, $this->mPropModuleNames);
80 }
81
82 public function getDB() {
83 if (!isset ($this->mSlaveDB))
84 $this->mSlaveDB = & wfGetDB(DB_SLAVE);
85 return $this->mSlaveDB;
86 }
87
88 public function getPageSet() {
89 return $this->mPageSet;
90 }
91
92 public function getValidNamespaces() {
93 global $wgContLang;
94
95 if (is_null($this->mValidNamespaces)) {
96 $this->mValidNamespaces = array ();
97 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
98 if ($ns >= 0)
99 $this->mValidNamespaces[] = $ns; // strval($ns);
100 }
101 }
102 return $this->mValidNamespaces;
103 }
104
105 /**
106 * Query execution happens in the following steps:
107 * #1 Create a PageSet object with any pages requested by the user
108 * #2 If using generator, execute it to get a new PageSet object
109 * #3 Instantiate all requested modules.
110 * This way the PageSet object will know what shared data is required,
111 * and minimize DB calls.
112 * #4 Output all normalization and redirect resolution information
113 * #5 Execute all requested modules
114 */
115 public function execute() {
116 $prop = $list = $meta = $generator = $redirects = null;
117 extract($this->extractRequestParams());
118
119 //
120 // Create PageSet
121 //
122 $this->mPageSet = new ApiPageSet($this, $redirects);
123
124 // Instantiate required modules
125 $modules = array ();
126 if (isset ($prop))
127 foreach ($prop as $moduleName)
128 $modules[] = new $this->mQueryPropModules[$moduleName] ($this, $moduleName);
129 if (isset ($list))
130 foreach ($list as $moduleName)
131 $modules[] = new $this->mQueryListModules[$moduleName] ($this, $moduleName);
132 if (isset ($meta))
133 foreach ($meta as $moduleName)
134 $modules[] = new $this->mQueryMetaModules[$moduleName] ($this, $moduleName);
135
136 // Modules may optimize data requests through the $this->getPageSet() object
137 // Execute all requested modules.
138 foreach ($modules as $module) {
139 $module->requestExtraData();
140 }
141
142 //
143 // If given, execute generator to substitute user supplied data with generated data.
144 //
145 if (isset ($generator))
146 $this->executeGeneratorModule($generator, $redirects);
147
148 //
149 // Populate page information for the given pageSet
150 //
151 $this->mPageSet->execute();
152
153 //
154 // Record page information (title, namespace, if exists, etc)
155 //
156 $this->outputGeneralPageInfo();
157
158 //
159 // Execute all requested modules.
160 //
161 foreach ($modules as $module) {
162 $module->profileIn();
163 $module->execute();
164 $module->profileOut();
165 }
166 }
167
168 private function outputGeneralPageInfo() {
169
170 $pageSet = $this->getPageSet();
171 $result = $this->getResult();
172
173 // Title normalizations
174 $normValues = array ();
175 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
176 $normValues[] = array (
177 'from' => $rawTitleStr,
178 'to' => $titleStr
179 );
180 }
181
182 if (!empty ($normValues)) {
183 $result->setIndexedTagName($normValues, 'n');
184 $result->addValue('query', 'normalized', $normValues);
185 }
186
187 // Show redirect information
188 $redirValues = array ();
189 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
190 $redirValues[] = array (
191 'from' => $titleStrFrom,
192 'to' => $titleStrTo
193 );
194 }
195
196 if (!empty ($redirValues)) {
197 $result->setIndexedTagName($redirValues, 'r');
198 $result->addValue('query', 'redirects', $redirValues);
199 }
200
201
202 //
203 // Missing revision elements
204 //
205 $missingRevIDs = $pageSet->getMissingRevisionIDs();
206 if (!empty($missingRevIDs)) {
207 $revids = array();
208 foreach ($missingRevIDs as $revid) {
209 $revids[$revid] = array (
210 'revid' => $revid
211 );
212 }
213 $result->setIndexedTagName($revids, 'rev');
214 $result->addValue('query', 'badrevids', $revids);
215 }
216
217 //
218 // Page elements
219 //
220 $pages = array ();
221
222 // Report any missing titles
223 $fakepageid = -1;
224 foreach ($pageSet->getMissingTitles() as $title) {
225 $pages[$fakepageid--] = array (
226 'ns' => $title->getNamespace(), 'title' => $title->getPrefixedText(), 'missing' => '');
227 }
228
229 // Report any missing page ids
230 foreach ($pageSet->getMissingPageIDs() as $pageid) {
231 $pages[$pageid] = array (
232 'pageid' => $pageid,
233 'missing' => ''
234 );
235 }
236
237 // Output general page information for found titles
238 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
239 $pages[$pageid] = array (
240 'pageid' => $pageid, 'ns' => $title->getNamespace(), 'title' => $title->getPrefixedText());
241 }
242
243 if (!empty ($pages)) {
244 $result->setIndexedTagName($pages, 'page');
245 $result->addValue('query', 'pages', $pages);
246 }
247 }
248
249 protected function executeGeneratorModule($generatorName, $redirects) {
250
251 // Find class that implements requested generator
252 if (isset ($this->mQueryListModules[$generatorName])) {
253 $className = $this->mQueryListModules[$generatorName];
254 }
255 elseif (isset ($this->mQueryPropModules[$generatorName])) {
256 $className = $this->mQueryPropModules[$generatorName];
257 } else {
258 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
259 }
260
261 // Use current pageset as the result, and create a new one just for the generator
262 $resultPageSet = $this->mPageSet;
263 $this->mPageSet = new ApiPageSet($this, $redirects);
264
265 // Create and execute the generator
266 $generator = new $className ($this, $generatorName);
267 if (!$generator instanceof ApiQueryGeneratorBase)
268 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
269
270 $generator->setGeneratorMode();
271 $generator->requestExtraData();
272
273 // execute current pageSet to get the data for the generator module
274 $this->mPageSet->execute();
275
276 // populate resultPageSet with the generator output
277 $generator->profileIn();
278 $generator->executeGenerator($resultPageSet);
279 $resultPageSet->finishPageSetGeneration();
280 $generator->profileOut();
281
282 // Swap the resulting pageset back in
283 $this->mPageSet = $resultPageSet;
284 }
285
286 protected function getAllowedParams() {
287 return array (
288 'prop' => array (
289 ApiBase :: PARAM_ISMULTI => true,
290 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
291 ),
292 'list' => array (
293 ApiBase :: PARAM_ISMULTI => true,
294 ApiBase :: PARAM_TYPE => $this->mListModuleNames
295 ),
296 'meta' => array (
297 ApiBase :: PARAM_ISMULTI => true,
298 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
299 ),
300 'generator' => array (
301 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
302 ),
303 'redirects' => false
304 );
305 }
306
307 /**
308 * Override the parent to generate help messages for all available query modules.
309 */
310 public function makeHelpMsg() {
311
312 // Use parent to make default message for the query module
313 $msg = parent :: makeHelpMsg();
314
315 // Make sure the internal object is empty
316 // (just in case a sub-module decides to optimize during instantiation)
317 $this->mPageSet = null;
318
319 $astriks = str_repeat('--- ', 8);
320 $msg .= "\n$astriks Query: Prop $astriks\n\n";
321 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
322 $msg .= "\n$astriks Query: List $astriks\n\n";
323 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
324 $msg .= "\n$astriks Query: Meta $astriks\n\n";
325 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
326
327 return $msg;
328 }
329
330 private function makeHelpMsgHelper($moduleList, $paramName) {
331
332 $moduleDscriptions = array ();
333
334 foreach ($moduleList as $moduleName => $moduleClass) {
335 $msg = "* $paramName=$moduleName *";
336 $module = new $moduleClass ($this, $moduleName, null);
337 $msg2 = $module->makeHelpMsg();
338 if ($msg2 !== false)
339 $msg .= $msg2;
340 if ($module instanceof ApiQueryGeneratorBase)
341 $msg .= "Generator:\n This module may be used as a generator\n";
342 $moduleDscriptions[] = $msg;
343 }
344
345 return implode("\n", $moduleDscriptions);
346 }
347
348 /**
349 * Override to add extra parameters from PageSet
350 */
351 public function makeHelpMsgParameters() {
352 $psModule = new ApiPageSet($this);
353 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
354 }
355
356 protected function getParamDescription() {
357 return array (
358 'prop' => 'Which properties to get for the titles/revisions/pageids',
359 'list' => 'Which lists to get',
360 'meta' => 'Which meta data to get about the site',
361 'generator' => 'Use the output of a list as the input for other prop/list/meta items',
362 'redirects' => 'Automatically resolve redirects'
363 );
364 }
365
366 protected function getDescription() {
367 return array (
368 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
369 'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
370 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
371 );
372 }
373
374 protected function getExamples() {
375 return array (
376 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
377 );
378 }
379
380 public function getVersion() {
381 $psModule = new ApiPageSet($this);
382 $vers = array ();
383 $vers[] = __CLASS__ . ': $Id$';
384 $vers[] = $psModule->getVersion();
385 return $vers;
386 }
387 }
388 ?>