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