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