83949913a841ef60f1c7a20f8a504c6928284ad2
[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 $action = $format = $version = null;
98 try {
99 extract($this->extractRequestParams());
100 $this->mShowVersions = $version;
101
102 // Create an appropriate printer
103 $this->mPrinter = new $this->mFormats[$format] ($this, $format);
104
105 // Instantiate and execute module requested by the user
106 $module = new $this->mModules[$action] ($this, $action);
107 $module->profileIn();
108 $module->execute();
109 $module->profileOut();
110 $this->printResult(false);
111
112 } catch (UsageException $e) {
113 $this->printError();
114 }
115 $this->profileOut();
116 }
117
118 /**
119 * Internal printer
120 */
121 private function printResult($isError) {
122 $printer = $this->mPrinter;
123 $printer->profileIn();
124 $printer->initPrinter($isError);
125 if (!$printer->getNeedsRawData())
126 $this->getResult()->SanitizeData();
127 $printer->execute();
128 $printer->closePrinter();
129 $printer->profileOut();
130 }
131
132 private function printError() {
133 // Printer may not be initialized if the extractRequestParams() fails for the main module
134 if (!isset ($this->mPrinter))
135 $this->mPrinter = new $this->mFormats[API_DEFAULT_FORMAT] ($this, API_DEFAULT_FORMAT);
136 $this->printResult(true);
137 }
138
139 protected function getDescription() {
140 return array (
141 '',
142 'This API allows programs to access various functions of MediaWiki software.',
143 'For more details see API Home Page @ http://meta.wikimedia.org/wiki/API',
144 ''
145 );
146 }
147
148 public function mainDieUsage($description, $errorCode, $httpRespCode = 0) {
149 if ($httpRespCode === 0)
150 header($errorCode, true);
151 else
152 header($errorCode, true, $httpRespCode);
153
154 $this->makeErrorMessage($description, $errorCode);
155
156 throw new UsageException($description, $errorCode);
157 }
158
159 public function makeErrorMessage($description, $errorCode, $customContent = null) {
160 $this->mResult->Reset();
161 $data = array (
162 'code' => $errorCode,
163 'info' => $description
164 );
165
166 ApiResult :: setContent($data,
167 is_null($customContent) ? $this->makeHelpMsg() : $customContent);
168
169 $this->mResult->addValue(null, 'error', $data);
170 }
171
172 /**
173 * Override the parent to generate help messages for all available modules.
174 */
175 public function makeHelpMsg() {
176
177 // Use parent to make default message for the main module
178 $msg = parent :: makeHelpMsg();
179
180 $astriks = str_repeat('*** ', 10);
181 $msg .= "\n\n$astriks Modules $astriks\n\n";
182 foreach ($this->mModules as $moduleName => $moduleClass) {
183 $msg .= "* action=$moduleName *";
184 $module = new $this->mModules[$moduleName] ($this, $moduleName);
185 $msg2 = $module->makeHelpMsg();
186 if ($msg2 !== false)
187 $msg .= $msg2;
188 $msg .= "\n";
189 }
190
191 $msg .= "\n$astriks Formats $astriks\n\n";
192 foreach ($this->mFormats as $moduleName => $moduleClass) {
193 $msg .= "* format=$moduleName *";
194 $module = new $this->mFormats[$moduleName] ($this, $moduleName);
195 $msg2 = $module->makeHelpMsg();
196 if ($msg2 !== false)
197 $msg .= $msg2;
198 $msg .= "\n";
199 }
200
201 return $msg;
202 }
203
204 /**
205 * Exception handler which simulates the appropriate catch() handling:
206 *
207 * try {
208 * ...
209 * } catch ( MWException $e ) {
210 * dieUsage()
211 * } catch ( Exception $e ) {
212 * echo $e->__toString();
213 * }
214 *
215 *
216 *
217 *
218 * !!!!!!!!!!!!! REVIEW needed !!!!!!!!!!!!!!!!!!
219 *
220 * this method needs to be reviewed/cleaned up
221 *
222 *
223 *
224 */
225 public function exceptionHandler( $e ) {
226 global $wgFullyInitialised;
227 if ( is_a( $e, 'MWException' ) ) {
228 try {
229 $msg = "Exception Caught: {$e->getMessage()}";
230 $this->makeErrorMessage($msg, 'internal_error', "\n\n{$e->getTraceAsString()}\n\n");
231 $this->printError();
232 } catch (Exception $e2) {
233 echo $e->__toString();
234 }
235 } else {
236 echo $e->__toString();
237 }
238
239 // Final cleanup, similar to wfErrorExit()
240 if ( $wgFullyInitialised ) {
241 try {
242 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
243 } catch ( Exception $e ) {}
244 }
245
246 // Exit value should be nonzero for the benefit of shell jobs
247 exit( 1 );
248 }
249
250
251 private $mIsBot = null;
252 public function isBot() {
253 if (!isset ($this->mIsBot)) {
254 global $wgUser;
255 $this->mIsBot = $wgUser->isAllowed('bot');
256 }
257 return $this->mIsBot;
258 }
259
260 public function getVersion() {
261 $vers = array ();
262 $vers[] = __CLASS__ . ': $Id$';
263 $vers[] = ApiBase :: getBaseVersion();
264 $vers[] = ApiFormatBase :: getBaseVersion();
265 $vers[] = ApiQueryBase :: getBaseVersion();
266 return $vers;
267 }
268 }
269
270 /**
271 * @desc This exception will be thrown when dieUsage is called to stop module execution.
272 */
273 class UsageException extends Exception {
274
275 private $codestr;
276
277 public function __construct($message, $codestr) {
278 parent :: __construct($message);
279 $this->codestr = $codestr;
280 }
281 public function __toString() {
282 return "{$this->codestr}: {$this->message}";
283 }
284 }
285 ?>