3f1ae8b0ca89cf8172212f145093a9c728c18a80
[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 }
140
141 if ($e instanceof UsageException) {
142 //
143 // User entered incorrect parameters - print usage screen
144 //
145 $errMessage = array (
146 'code' => $e->getCodeString(),
147 'info' => $e->getMessage()
148 );
149 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
150
151 } else {
152 //
153 // Something is seriously wrong
154 //
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
173 // If the error occured during printing, do a printer->profileOut()
174 $this->mPrinter->safeProfileOut();
175 $this->printResult(true);
176 }
177
178 ob_end_flush();
179 }
180
181 /**
182 * Execute the actual module, without any error handling
183 */
184 protected function executeAction() {
185 $action = $format = $version = null;
186 extract($this->extractRequestParams());
187 $this->mShowVersions = $version;
188
189 // Instantiate the module requested by the user
190 $module = new $this->mModules[$action] ($this, $action);
191
192 if (!$this->mInternalMode) {
193
194 // See if custom printer is used
195 $this->mPrinter = $module->getCustomPrinter();
196
197 if (is_null($this->mPrinter)) {
198 // Create an appropriate printer
199 $this->mPrinter = $this->createPrinterByName($format);
200 }
201 }
202
203 // Execute
204 $module->profileIn();
205 $module->execute();
206 $module->profileOut();
207
208 if (!$this->mInternalMode) {
209 // Print result data
210 $this->printResult(false);
211 }
212 }
213
214 /**
215 * Internal printer
216 */
217 protected function printResult($isError) {
218 $printer = $this->mPrinter;
219 $printer->profileIn();
220 $printer->initPrinter($isError);
221 if (!$printer->getNeedsRawData())
222 $this->getResult()->SanitizeData();
223 $printer->execute();
224 $printer->closePrinter();
225 $printer->profileOut();
226 }
227
228 protected function getAllowedParams() {
229 return array (
230 'format' => array (
231 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
232 ApiBase :: PARAM_TYPE => $this->mFormatNames
233 ),
234 'action' => array (
235 ApiBase :: PARAM_DFLT => 'help',
236 ApiBase :: PARAM_TYPE => $this->mModuleNames
237 ),
238 'version' => false
239 );
240 }
241
242 protected function getParamDescription() {
243 return array (
244 'format' => 'The format of the output',
245 'action' => 'What action you would like to perform',
246 'version' => 'When showing help, include version for each module'
247 );
248 }
249
250 protected function getDescription() {
251 return array (
252 '',
253 'This API allows programs to access various functions of MediaWiki software.',
254 'For more details see API Home Page @ http://meta.wikimedia.org/wiki/API',
255 ''
256 );
257 }
258
259 /**
260 * Override the parent to generate help messages for all available modules.
261 */
262 public function makeHelpMsg() {
263
264 // Use parent to make default message for the main module
265 $msg = parent :: makeHelpMsg();
266
267 $astriks = str_repeat('*** ', 10);
268 $msg .= "\n\n$astriks Modules $astriks\n\n";
269 foreach ($this->mModules as $moduleName => $moduleClass) {
270 $msg .= "* action=$moduleName *";
271 $module = new $this->mModules[$moduleName] ($this, $moduleName);
272 $msg2 = $module->makeHelpMsg();
273 if ($msg2 !== false)
274 $msg .= $msg2;
275 $msg .= "\n";
276 }
277
278 $msg .= "\n$astriks Formats $astriks\n\n";
279 foreach ($this->mFormats as $formatName => $moduleClass) {
280 $msg .= "* format=$formatName *";
281 $module = $this->createPrinterByName($formatName);
282 $msg2 = $module->makeHelpMsg();
283 if ($msg2 !== false)
284 $msg .= $msg2;
285 $msg .= "\n";
286 }
287
288 return $msg;
289 }
290
291 private $mIsBot = null;
292 public function isBot() {
293 if (!isset ($this->mIsBot)) {
294 global $wgUser;
295 $this->mIsBot = $wgUser->isAllowed('bot');
296 }
297 return $this->mIsBot;
298 }
299
300 public function getShowVersions() {
301 return $this->mShowVersions;
302 }
303
304 public function getVersion() {
305 $vers = array ();
306 $vers[] = __CLASS__ . ': $Id$';
307 $vers[] = ApiBase :: getBaseVersion();
308 $vers[] = ApiFormatBase :: getBaseVersion();
309 $vers[] = ApiQueryBase :: getBaseVersion();
310 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
311 return $vers;
312 }
313 }
314
315 /**
316 * @desc This exception will be thrown when dieUsage is called to stop module execution.
317 */
318 class UsageException extends Exception {
319
320 private $mCodestr;
321
322 public function __construct($message, $codestr, $code = 0) {
323 parent :: __construct($message, $code);
324 $this->mCodestr = $codestr;
325 }
326 public function getCodeString() {
327 return $this->mCodestr;
328 }
329 public function __toString() {
330 return "{$this->getCodeString()}: {$this->getMessage()}";
331 }
332 }
333 ?>