234bc527cb66680060832584572788f43248a156
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2
3 /*
4 * Created on Sep 4, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
29 }
30
31 /**
32 * This is the main API class, used for both external and internal processing.
33 * When executed, it will create the requested formatter object,
34 * instantiate and execute an object associated with the needed action,
35 * and use formatter to print results.
36 * In case of an exception, an error message will be printed using the same formatter.
37 *
38 * To use API from another application, run it using FauxRequest object, in which
39 * case any internal exceptions will not be handled but passed up to the caller.
40 * After successful execution, use getResult() for the resulting data.
41 *
42 * @addtogroup API
43 */
44 class ApiMain extends ApiBase {
45
46 /**
47 * When no format parameter is given, this format will be used
48 */
49 const API_DEFAULT_FORMAT = 'xmlfm';
50
51 /**
52 * List of available modules: action name => module class
53 */
54 private static $Modules = array (
55 // 'login' => 'ApiLogin', // LOGIN is temporarily disabled until it becomes more secure
56 'query' => 'ApiQuery',
57 'opensearch' => 'ApiOpenSearch',
58 'feedwatchlist' => 'ApiFeedWatchlist',
59 'help' => 'ApiHelp',
60 );
61
62 /**
63 * List of available formats: format name => format class
64 */
65 private static $Formats = array (
66 'json' => 'ApiFormatJson',
67 'jsonfm' => 'ApiFormatJson',
68 'php' => 'ApiFormatPhp',
69 'phpfm' => 'ApiFormatPhp',
70 'wddx' => 'ApiFormatWddx',
71 'wddxfm' => 'ApiFormatWddx',
72 'xml' => 'ApiFormatXml',
73 'xmlfm' => 'ApiFormatXml',
74 'yaml' => 'ApiFormatYaml',
75 'yamlfm' => 'ApiFormatYaml',
76 'rawfm' => 'ApiFormatJson'
77 );
78
79 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
80 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
81
82 /**
83 * Constructor
84 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
85 * @param $enableWrite bool should be set to true if the api may modify data
86 */
87 public function __construct($request, $enableWrite = false) {
88
89 $this->mInternalMode = ($request instanceof FauxRequest);
90
91 // Special handling for the main module: $parent === $this
92 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
93
94 $this->mModules = self :: $Modules;
95 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
96 $this->mFormats = self :: $Formats;
97 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
98
99 $this->mResult = new ApiResult($this);
100 $this->mShowVersions = false;
101 $this->mEnableWrite = $enableWrite;
102
103 $this->mRequest = & $request;
104
105 $this->mSquidMaxage = 0;
106 }
107
108 public function & getRequest() {
109 return $this->mRequest;
110 }
111
112 public function getResult() {
113 return $this->mResult;
114 }
115
116 public function requestWriteMode() {
117 if (!$this->mEnableWrite)
118 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
119 'statement is included in the site\'s LocalSettings.php file', 'readonly');
120 }
121
122 public function setCacheMaxAge($maxage) {
123 $this->mSquidMaxage = $maxage;
124 }
125
126 public function createPrinterByName($format) {
127 return new $this->mFormats[$format] ($this, $format);
128 }
129
130 public function execute() {
131 $this->profileIn();
132 if ($this->mInternalMode)
133 $this->executeAction();
134 else
135 $this->executeActionWithErrorHandling();
136 $this->profileOut();
137 }
138
139 protected function executeActionWithErrorHandling() {
140
141 // In case an error occurs during data output,
142 // this clear the output buffer and print just the error information
143 ob_start();
144
145 try {
146 $this->executeAction();
147 } catch (Exception $e) {
148 //
149 // Handle any kind of exception by outputing properly formatted error message.
150 // If this fails, an unhandled exception should be thrown so that global error
151 // handler will process and log it.
152 //
153
154 // Error results should not be cached
155 $this->setCacheMaxAge(0);
156
157 // Printer may not be initialized if the extractRequestParams() fails for the main module
158 if (!isset ($this->mPrinter)) {
159 $this->mPrinter = $this->createPrinterByName(self :: API_DEFAULT_FORMAT);
160 if ($this->mPrinter->getNeedsRawData())
161 $this->getResult()->setRawMode();
162 }
163
164 if ($e instanceof UsageException) {
165 //
166 // User entered incorrect parameters - print usage screen
167 //
168 $errMessage = array (
169 'code' => $e->getCodeString(), 'info' => $e->getMessage());
170 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
171
172 } else {
173 //
174 // Something is seriously wrong
175 //
176 $errMessage = array (
177 'code' => 'internal_api_error',
178 'info' => "Exception Caught: {$e->getMessage()}"
179 );
180 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
181 }
182
183 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
184 if ($e->getCode() === 0)
185 header($headerStr, true);
186 else
187 header($headerStr, true, $e->getCode());
188
189 // Reset and print just the error message
190 ob_clean();
191 $this->getResult()->reset();
192 $this->getResult()->addValue(null, 'error', $errMessage);
193
194 // If the error occured during printing, do a printer->profileOut()
195 $this->mPrinter->safeProfileOut();
196 $this->printResult(true);
197 }
198
199 // Set the cache expiration at the last moment, as any errors may change the expiration.
200 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
201 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
202 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
203 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
204
205 if($this->mPrinter->getIsHtml()) {
206 echo wfReportTime();
207 }
208
209 ob_end_flush();
210 }
211
212 /**
213 * Execute the actual module, without any error handling
214 */
215 protected function executeAction() {
216 $action = $format = $version = null;
217 extract($this->extractRequestParams());
218 $this->mShowVersions = $version;
219
220 // Instantiate the module requested by the user
221 $module = new $this->mModules[$action] ($this, $action);
222
223 if (!$this->mInternalMode) {
224
225 // See if custom printer is used
226 $this->mPrinter = $module->getCustomPrinter();
227 if (is_null($this->mPrinter)) {
228 // Create an appropriate printer
229 $this->mPrinter = $this->createPrinterByName($format);
230 }
231
232 if ($this->mPrinter->getNeedsRawData())
233 $this->getResult()->setRawMode();
234 }
235
236 // Execute
237 $module->profileIn();
238 $module->execute();
239 $module->profileOut();
240
241 if (!$this->mInternalMode) {
242 // Print result data
243 $this->printResult(false);
244 }
245 }
246
247 /**
248 * Internal printer
249 */
250 protected function printResult($isError) {
251 $printer = $this->mPrinter;
252 $printer->profileIn();
253 $printer->initPrinter($isError);
254 $printer->execute();
255 $printer->closePrinter();
256 $printer->profileOut();
257 }
258
259 protected function getAllowedParams() {
260 return array (
261 'format' => array (
262 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
263 ApiBase :: PARAM_TYPE => $this->mFormatNames
264 ),
265 'action' => array (
266 ApiBase :: PARAM_DFLT => 'help',
267 ApiBase :: PARAM_TYPE => $this->mModuleNames
268 ),
269 'version' => false
270 );
271 }
272
273 protected function getParamDescription() {
274 return array (
275 'format' => 'The format of the output',
276 'action' => 'What action you would like to perform',
277 'version' => 'When showing help, include version for each module'
278 );
279 }
280
281 protected function getDescription() {
282 return array (
283 '',
284 'This API allows programs to access various functions of MediaWiki software.',
285 'For more details see API Home Page @ http://www.mediawiki.org/wiki/API',
286 '',
287 'Status: ALPHA -- all features shown on this page should be working,',
288 ' but the API is still in active development, and may change at any time.',
289 ' Make sure you monitor changes to this page, wikitech-l mailing list,',
290 ' or the source code in the includes/api directory for any changes.',
291 ''
292 );
293 }
294
295 protected function getCredits() {
296 return array(
297 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / FirstnameLastname@gmail.com',
298 'Please leave your comments and suggestions at http://meta.wikimedia.org/wiki/API'
299 );
300 }
301
302 /**
303 * Override the parent to generate help messages for all available modules.
304 */
305 public function makeHelpMsg() {
306
307 // Use parent to make default message for the main module
308 $msg = parent :: makeHelpMsg();
309
310 $astriks = str_repeat('*** ', 10);
311 $msg .= "\n\n$astriks Modules $astriks\n\n";
312 foreach( $this->mModules as $moduleName => $unused ) {
313 $msg .= "* action=$moduleName *";
314 $module = new $this->mModules[$moduleName] ($this, $moduleName);
315 $msg2 = $module->makeHelpMsg();
316 if ($msg2 !== false)
317 $msg .= $msg2;
318 $msg .= "\n";
319 }
320
321 $msg .= "\n$astriks Formats $astriks\n\n";
322 foreach( $this->mFormats as $formatName => $unused ) {
323 $msg .= "* format=$formatName *";
324 $module = $this->createPrinterByName($formatName);
325 $msg2 = $module->makeHelpMsg();
326 if ($msg2 !== false)
327 $msg .= $msg2;
328 $msg .= "\n";
329 }
330
331 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
332
333
334 return $msg;
335 }
336
337 private $mIsBot = null;
338 public function isBot() {
339 if (!isset ($this->mIsBot)) {
340 global $wgUser;
341 $this->mIsBot = $wgUser->isAllowed('bot');
342 }
343 return $this->mIsBot;
344 }
345
346 public function getShowVersions() {
347 return $this->mShowVersions;
348 }
349
350 public function getVersion() {
351 $vers = array ();
352 $vers[] = __CLASS__ . ': $Id$';
353 $vers[] = ApiBase :: getBaseVersion();
354 $vers[] = ApiFormatBase :: getBaseVersion();
355 $vers[] = ApiQueryBase :: getBaseVersion();
356 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
357 return $vers;
358 }
359 }
360
361 /**
362 * This exception will be thrown when dieUsage is called to stop module execution.
363 * @addtogroup API
364 */
365 class UsageException extends Exception {
366
367 private $mCodestr;
368
369 public function __construct($message, $codestr, $code = 0) {
370 parent :: __construct($message, $code);
371 $this->mCodestr = $codestr;
372 }
373 public function getCodeString() {
374 return $this->mCodestr;
375 }
376 public function __toString() {
377 return "{$this->getCodeString()}: {$this->getMessage()}";
378 }
379 }
380 ?>