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