* New properties: links, templates, images, langlinks
[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 * @addtogroup API
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 'query' => 'ApiQuery',
49 'opensearch' => 'ApiOpenSearch',
50 'feedwatchlist' => 'ApiFeedWatchlist'
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 'rawfm' => 'ApiFormatJson'
68 );
69
70 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
71 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
72
73 /**
74 * Constructor
75 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
76 * @param $enableWrite bool should be set to true if the api may modify data
77 */
78 public function __construct($request, $enableWrite = false) {
79
80 $this->mInternalMode = ($request instanceof FauxRequest);
81
82 // Special handling for the main module: $parent === $this
83 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
84
85 $this->mModules = self :: $Modules;
86 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
87 $this->mFormats = self :: $Formats;
88 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
89
90 $this->mResult = new ApiResult($this);
91 $this->mShowVersions = false;
92 $this->mEnableWrite = $enableWrite;
93
94 $this->mRequest = & $request;
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 'Status: ALPHA -- all features shown on this page should be working,',
275 ' but the API is still in active development, and may change at any time.',
276 ' Make sure you monitor changes to this page, wikitech-l mailing list,',
277 ' or the source code in the includes/api directory for any changes.',
278 ''
279 );
280 }
281
282 protected function getCredits() {
283 return array(
284 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / FirstnameLastname@gmail.com',
285 'Please leave your comments and suggestions at http://meta.wikimedia.org/wiki/API'
286 );
287 }
288
289 /**
290 * Override the parent to generate help messages for all available modules.
291 */
292 public function makeHelpMsg() {
293
294 // Use parent to make default message for the main module
295 $msg = parent :: makeHelpMsg();
296
297 $astriks = str_repeat('*** ', 10);
298 $msg .= "\n\n$astriks Modules $astriks\n\n";
299 foreach( $this->mModules as $moduleName => $unused ) {
300 $msg .= "* action=$moduleName *";
301 $module = new $this->mModules[$moduleName] ($this, $moduleName);
302 $msg2 = $module->makeHelpMsg();
303 if ($msg2 !== false)
304 $msg .= $msg2;
305 $msg .= "\n";
306 }
307
308 $msg .= "\n$astriks Formats $astriks\n\n";
309 foreach( $this->mFormats as $formatName => $unused ) {
310 $msg .= "* format=$formatName *";
311 $module = $this->createPrinterByName($formatName);
312 $msg2 = $module->makeHelpMsg();
313 if ($msg2 !== false)
314 $msg .= $msg2;
315 $msg .= "\n";
316 }
317
318 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
319
320
321 return $msg;
322 }
323
324 private $mIsBot = null;
325 public function isBot() {
326 if (!isset ($this->mIsBot)) {
327 global $wgUser;
328 $this->mIsBot = $wgUser->isAllowed('bot');
329 }
330 return $this->mIsBot;
331 }
332
333 public function getShowVersions() {
334 return $this->mShowVersions;
335 }
336
337 public function getVersion() {
338 $vers = array ();
339 $vers[] = __CLASS__ . ': $Id$';
340 $vers[] = ApiBase :: getBaseVersion();
341 $vers[] = ApiFormatBase :: getBaseVersion();
342 $vers[] = ApiQueryBase :: getBaseVersion();
343 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
344 return $vers;
345 }
346 }
347
348 /**
349 * This exception will be thrown when dieUsage is called to stop module execution.
350 * @addtogroup API
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 ?>