* API: help screen now shows default and allowed parameter values
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2
3
4 /*
5 * Created on Sep 4, 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
33 /**
34 * This is the main API class, used for both external and internal processing.
35 */
36 class ApiMain extends ApiBase {
37
38 /**
39 * When no format parameter is given, this format will be used
40 */
41 const API_DEFAULT_FORMAT = 'xmlfm';
42
43 /**
44 * List of available modules: action name => module class
45 */
46 private static $Modules = array (
47 'help' => 'ApiHelp',
48 'login' => 'ApiLogin',
49 'opensearch' => 'ApiOpenSearch',
50 'feedwatchlist' => 'ApiFeedWatchlist',
51 'query' => 'ApiQuery'
52 );
53
54 /**
55 * List of available formats: format name => format class
56 */
57 private static $Formats = array (
58 'json' => 'ApiFormatJson',
59 'jsonfm' => 'ApiFormatJson',
60 'xml' => 'ApiFormatXml',
61 'xmlfm' => 'ApiFormatXml',
62 'yaml' => 'ApiFormatYaml',
63 'yamlfm' => 'ApiFormatYaml'
64 );
65
66 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
67 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode;
68
69 /**
70 * Constructor
71 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
72 * @param $enableWrite bool should be set to true if the api may modify data
73 */
74 public function __construct($request, $enableWrite = false) {
75 // Special handling for the main module: $parent === $this
76 parent :: __construct($this, 'main');
77
78 $this->mModules =& self::$Modules;
79 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
80 $this->mFormats =& self::$Formats;
81 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
82
83 $this->mResult = new ApiResult($this);
84 $this->mShowVersions = false;
85 $this->mEnableWrite = $enableWrite;
86
87 $this->mRequest =& $request;
88
89 $this->mInternalMode = ($request instanceof FauxRequest);
90 }
91
92 public function & getRequest() {
93 return $this->mRequest;
94 }
95
96 public function & getResult() {
97 return $this->mResult;
98 }
99
100 public function requestWriteMode() {
101 if (!$this->mEnableWrite)
102 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
103 'statement is included in the site\'s LocalSettings.php file', 'readonly');
104 }
105
106 public function createPrinterByName($format) {
107 return new $this->mFormats[$format] ($this, $format);
108 }
109
110 public function execute() {
111 $this->profileIn();
112 if($this->mInternalMode)
113 $this->executeAction();
114 else
115 $this->executeActionWithErrorHandling();
116 $this->profileOut();
117 }
118
119 protected function executeActionWithErrorHandling() {
120
121 // In case an error occurs during data output,
122 // this clear the output buffer and print just the error information
123 ob_start();
124
125 try {
126 $this->executeAction();
127 } catch (Exception $e) {
128 //
129 // Handle any kind of exception by outputing properly formatted error message.
130 // If this fails, an unhandled exception should be thrown so that global error
131 // handler will process and log it.
132 //
133
134 // Printer may not be initialized if the extractRequestParams() fails for the main module
135 if (!isset ($this->mPrinter)) {
136 $this->mPrinter = $this->createPrinterByName(self :: API_DEFAULT_FORMAT);
137 }
138
139 if ($e instanceof UsageException) {
140 //
141 // User entered incorrect parameters - print usage screen
142 //
143 $httpRespCode = $e->getCode();
144 $errMessage = array (
145 'code' => $e->getCodeString(),
146 'info' => $e->getMessage()
147 );
148 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
149
150 } else {
151 //
152 // Something is seriously wrong
153 //
154 $httpRespCode = 0;
155 $errMessage = array (
156 'code' => 'internal_api_error',
157 'info' => "Exception Caught: {$e->getMessage()}"
158 );
159 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
160 }
161
162 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
163 if ($e->getCode() === 0)
164 header($headerStr, true);
165 else
166 header($headerStr, true, $e->getCode());
167
168 // Reset and print just the error message
169 ob_clean();
170 $this->mResult->Reset();
171 $this->mResult->addValue(null, 'error', $errMessage);
172 $this->printResult(true);
173 }
174
175 ob_end_flush();
176 }
177
178 /**
179 * Execute the actual module, without any error handling
180 */
181 protected function executeAction() {
182 $action = $format = $version = null;
183 extract($this->extractRequestParams());
184 $this->mShowVersions = $version;
185
186 // Instantiate the module requested by the user
187 $module = new $this->mModules[$action] ($this, $action);
188
189 if (!$this->mInternalMode) {
190
191 // See if custom printer is used
192 $this->mPrinter = $module->getCustomPrinter();
193
194 if (is_null($this->mPrinter)) {
195 // Create an appropriate printer
196 $this->mPrinter = $this->createPrinterByName($format);
197 }
198 }
199
200 // Execute
201 $module->profileIn();
202 $module->execute();
203 $module->profileOut();
204
205 if (!$this->mInternalMode) {
206 // Print result data
207 $this->printResult(false);
208 }
209 }
210
211 /**
212 * Internal printer
213 */
214 protected function printResult($isError) {
215 $printer = $this->mPrinter;
216 $printer->profileIn();
217 $printer->initPrinter($isError);
218 if (!$printer->getNeedsRawData())
219 $this->getResult()->SanitizeData();
220 $printer->execute();
221 $printer->closePrinter();
222 $printer->profileOut();
223 }
224
225 protected function getAllowedParams() {
226 return array (
227 'format' => array (
228 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
229 ApiBase :: PARAM_TYPE => $this->mFormatNames
230 ),
231 'action' => array (
232 ApiBase :: PARAM_DFLT => 'help',
233 ApiBase :: PARAM_TYPE => $this->mModuleNames
234 ),
235 'version' => false
236 );
237 }
238
239 protected function getParamDescription() {
240 return array (
241 'format' => 'The format of the output',
242 'action' => 'What action you would like to perform',
243 'version' => 'When showing help, include version for each module'
244 );
245 }
246
247 protected function getDescription() {
248 return array (
249 '',
250 'This API allows programs to access various functions of MediaWiki software.',
251 'For more details see API Home Page @ http://meta.wikimedia.org/wiki/API',
252 ''
253 );
254 }
255
256 /**
257 * Override the parent to generate help messages for all available modules.
258 */
259 public function makeHelpMsg() {
260
261 // Use parent to make default message for the main module
262 $msg = parent :: makeHelpMsg();
263
264 $astriks = str_repeat('*** ', 10);
265 $msg .= "\n\n$astriks Modules $astriks\n\n";
266 foreach ($this->mModules as $moduleName => $moduleClass) {
267 $msg .= "* action=$moduleName *";
268 $module = new $this->mModules[$moduleName] ($this, $moduleName);
269 $msg2 = $module->makeHelpMsg();
270 if ($msg2 !== false)
271 $msg .= $msg2;
272 $msg .= "\n";
273 }
274
275 $msg .= "\n$astriks Formats $astriks\n\n";
276 foreach ($this->mFormats as $formatName => $moduleClass) {
277 $msg .= "* format=$formatName *";
278 $module = $this->createPrinterByName($formatName);
279 $msg2 = $module->makeHelpMsg();
280 if ($msg2 !== false)
281 $msg .= $msg2;
282 $msg .= "\n";
283 }
284
285 return $msg;
286 }
287
288 private $mIsBot = null;
289 public function isBot() {
290 if (!isset ($this->mIsBot)) {
291 global $wgUser;
292 $this->mIsBot = $wgUser->isAllowed('bot');
293 }
294 return $this->mIsBot;
295 }
296
297 public function getShowVersions() {
298 return $this->mShowVersions;
299 }
300
301 public function getVersion() {
302 $vers = array ();
303 $vers[] = __CLASS__ . ': $Id$';
304 $vers[] = ApiBase :: getBaseVersion();
305 $vers[] = ApiFormatBase :: getBaseVersion();
306 $vers[] = ApiQueryBase :: getBaseVersion();
307 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
308 return $vers;
309 }
310 }
311
312 /**
313 * @desc This exception will be thrown when dieUsage is called to stop module execution.
314 */
315 class UsageException extends Exception {
316
317 private $mCodestr;
318
319 public function __construct($message, $codestr, $code = 0) {
320 parent :: __construct($message, $code);
321 $this->mCodestr = $codestr;
322 }
323 public function getCodeString() {
324 return $this->mCodestr;
325 }
326 public function __toString() {
327 return "{$this->getCodeString()}: {$this->getMessage()}";
328 }
329 }
330 ?>