a12a1597ab861e30589346d06964d40d9b01ba64
[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 class ApiMain extends ApiBase {
33
34 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
35 private $mApiStartTime, $mResult, $mShowVersions, $mEnableWrite;
36
37 /**
38 * Constructor
39 * $apiStartTime - time of the originating call for profiling purposes
40 * $modules - an array of actions (keys) and classes that handle them (values)
41 */
42 public function __construct($apiStartTime, $modules, $formats, $enableWrite) {
43 // Special handling for the main module: $parent === $this
44 parent :: __construct($this, 'main');
45
46 $this->mModules = $modules;
47 $this->mModuleNames = array_keys($modules);
48 $this->mFormats = $formats;
49 $this->mFormatNames = array_keys($formats);
50 $this->mApiStartTime = $apiStartTime;
51 $this->mResult = new ApiResult($this);
52 $this->mShowVersions = false;
53 $this->mEnableWrite = $enableWrite;
54
55 // Initialize Error handler
56 set_exception_handler( array($this, 'exceptionHandler') );
57 }
58
59 public function & getResult() {
60 return $this->mResult;
61 }
62
63 public function getShowVersions() {
64 return $this->mShowVersions;
65 }
66
67 public function requestWriteMode() {
68 if (!$this->mEnableWrite)
69 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
70 'statement is included in the site\'s LocalSettings.php file', 'readonly');
71 }
72
73 protected function getAllowedParams() {
74 return array (
75 'format' => array (
76 ApiBase :: PARAM_DFLT => API_DEFAULT_FORMAT,
77 ApiBase :: PARAM_TYPE => $this->mFormatNames
78 ),
79 'action' => array (
80 ApiBase :: PARAM_DFLT => 'help',
81 ApiBase :: PARAM_TYPE => $this->mModuleNames
82 ),
83 'version' => false
84 );
85 }
86
87 protected function getParamDescription() {
88 return array (
89 'format' => 'The format of the output',
90 'action' => 'What action you would like to perform',
91 'version' => 'When showing help, include version for each module'
92 );
93 }
94
95 public function execute() {
96 $this->profileIn();
97
98 // Experimental -- in case an error occurs during data output,
99 // this clear the output buffer and print just the error information
100 ob_start();
101
102 try {
103 $action = $format = $version = null;
104 extract($this->extractRequestParams());
105 $this->mShowVersions = $version;
106
107 // Create an appropriate printer
108 $this->mPrinter = new $this->mFormats[$format] ($this, $format);
109
110 // Instantiate and execute module requested by the user
111 $module = new $this->mModules[$action] ($this, $action);
112 $module->profileIn();
113 $module->execute();
114 $module->profileOut();
115 $this->printResult(false);
116
117 } catch (UsageException $e) {
118 $this->printError();
119 }
120
121 ob_end_flush();
122 $this->profileOut();
123 }
124
125 /**
126 * Internal printer
127 */
128 private function printResult($isError) {
129 $printer = $this->mPrinter;
130 $printer->profileIn();
131 $printer->initPrinter($isError);
132 if (!$printer->getNeedsRawData())
133 $this->getResult()->SanitizeData();
134 $printer->execute();
135 $printer->closePrinter();
136 $printer->profileOut();
137 }
138
139 private function printError() {
140 // Printer may not be initialized if the extractRequestParams() fails for the main module
141 if (!isset ($this->mPrinter))
142 $this->mPrinter = new $this->mFormats[API_DEFAULT_FORMAT] ($this, API_DEFAULT_FORMAT);
143
144 // In case of an error, reset anythnig that was printed before
145 ob_clean();
146
147 $this->printResult(true);
148 }
149
150 protected function getDescription() {
151 return array (
152 '',
153 'This API allows programs to access various functions of MediaWiki software.',
154 'For more details see API Home Page @ http://meta.wikimedia.org/wiki/API',
155 ''
156 );
157 }
158
159 public function mainDieUsage($description, $errorCode, $httpRespCode = 0) {
160 if ($httpRespCode === 0)
161 header($errorCode, true);
162 else
163 header($errorCode, true, $httpRespCode);
164
165 $this->makeErrorMessage($description, $errorCode);
166
167 throw new UsageException($description, $errorCode);
168 }
169
170 public function makeErrorMessage($description, $errorCode, $customContent = null) {
171 $this->mResult->Reset();
172 $data = array (
173 'code' => $errorCode,
174 'info' => $description
175 );
176
177 ApiResult :: setContent($data,
178 is_null($customContent) ? $this->makeHelpMsg() : $customContent);
179
180 $this->mResult->addValue(null, 'error', $data);
181 }
182
183 /**
184 * Override the parent to generate help messages for all available modules.
185 */
186 public function makeHelpMsg() {
187
188 // Use parent to make default message for the main module
189 $msg = parent :: makeHelpMsg();
190
191 $astriks = str_repeat('*** ', 10);
192 $msg .= "\n\n$astriks Modules $astriks\n\n";
193 foreach ($this->mModules as $moduleName => $moduleClass) {
194 $msg .= "* action=$moduleName *";
195 $module = new $this->mModules[$moduleName] ($this, $moduleName);
196 $msg2 = $module->makeHelpMsg();
197 if ($msg2 !== false)
198 $msg .= $msg2;
199 $msg .= "\n";
200 }
201
202 $msg .= "\n$astriks Formats $astriks\n\n";
203 foreach ($this->mFormats as $moduleName => $moduleClass) {
204 $msg .= "* format=$moduleName *";
205 $module = new $this->mFormats[$moduleName] ($this, $moduleName);
206 $msg2 = $module->makeHelpMsg();
207 if ($msg2 !== false)
208 $msg .= $msg2;
209 $msg .= "\n";
210 }
211
212 return $msg;
213 }
214
215 /**
216 * Exception handler which simulates the appropriate catch() handling:
217 *
218 * try {
219 * ...
220 * } catch ( MWException $e ) {
221 * dieUsage()
222 * } catch ( Exception $e ) {
223 * echo $e->__toString();
224 * }
225 *
226 *
227 *
228 *
229 * !!!!!!!!!!!!! REVIEW needed !!!!!!!!!!!!!!!!!!
230 *
231 * this method needs to be reviewed/cleaned up
232 *
233 *
234 *
235 */
236 public function exceptionHandler( $e ) {
237 global $wgFullyInitialised;
238 if ( is_a( $e, 'MWException' ) ) {
239 try {
240 $msg = "Exception Caught: {$e->getMessage()}";
241 $this->makeErrorMessage($msg, 'internal_api_error', "\n\n{$e->getTraceAsString()}\n\n");
242 $this->printError();
243 } catch (Exception $e2) {
244 echo $e->__toString();
245 }
246 } else {
247 echo $e->__toString();
248 }
249
250 // Final cleanup, similar to wfErrorExit()
251 if ( $wgFullyInitialised ) {
252 try {
253 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
254 } catch ( Exception $e ) {}
255 }
256
257 // Exit value should be nonzero for the benefit of shell jobs
258 exit( 1 );
259 }
260
261
262 private $mIsBot = null;
263 public function isBot() {
264 if (!isset ($this->mIsBot)) {
265 global $wgUser;
266 $this->mIsBot = $wgUser->isAllowed('bot');
267 }
268 return $this->mIsBot;
269 }
270
271 public function getVersion() {
272 $vers = array ();
273 $vers[] = __CLASS__ . ': $Id$';
274 $vers[] = ApiBase :: getBaseVersion();
275 $vers[] = ApiFormatBase :: getBaseVersion();
276 $vers[] = ApiQueryBase :: getBaseVersion();
277 return $vers;
278 }
279 }
280
281 /**
282 * @desc This exception will be thrown when dieUsage is called to stop module execution.
283 */
284 class UsageException extends Exception {
285
286 private $codestr;
287
288 public function __construct($message, $codestr) {
289 parent :: __construct($message);
290 $this->codestr = $codestr;
291 }
292 public function __toString() {
293 return "{$this->codestr}: {$this->message}";
294 }
295 }
296 ?>