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