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