API: documentation and cleanup.
[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 <Firstname><Lastname>@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 /**
109 * Return the request object that contains client's request
110 */
111 public function getRequest() {
112 return $this->mRequest;
113 }
114
115 /**
116 * Get the ApiResult object asscosiated with current request
117 */
118 public function getResult() {
119 return $this->mResult;
120 }
121
122 /**
123 * This method will simply cause an error if the write mode was disabled for this api.
124 */
125 public function requestWriteMode() {
126 if (!$this->mEnableWrite)
127 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
128 'statement is included in the site\'s LocalSettings.php file', 'readonly');
129 }
130
131 /**
132 * Set how long the response should be cached.
133 */
134 public function setCacheMaxAge($maxage) {
135 $this->mSquidMaxage = $maxage;
136 }
137
138 /**
139 * Create an instance of an output formatter by its name
140 */
141 public function createPrinterByName($format) {
142 return new $this->mFormats[$format] ($this, $format);
143 }
144
145 /**
146 * Execute api request. Any errors will be handled if the API was called by the remote client.
147 */
148 public function execute() {
149 $this->profileIn();
150 if ($this->mInternalMode)
151 $this->executeAction();
152 else
153 $this->executeActionWithErrorHandling();
154 $this->profileOut();
155 }
156
157 /**
158 * Execute an action, and in case of an error, erase whatever partial results
159 * have been accumulated, and replace it with an error message and a help screen.
160 */
161 protected function executeActionWithErrorHandling() {
162
163 // In case an error occurs during data output,
164 // clear the output buffer and print just the error information
165 ob_start();
166
167 try {
168 $this->executeAction();
169 } catch (Exception $e) {
170 //
171 // Handle any kind of exception by outputing properly formatted error message.
172 // If this fails, an unhandled exception should be thrown so that global error
173 // handler will process and log it.
174 //
175
176 // Error results should not be cached
177 $this->setCacheMaxAge(0);
178
179 // Printer may not be initialized if the extractRequestParams() fails for the main module
180 if (!isset ($this->mPrinter)) {
181 $this->mPrinter = $this->createPrinterByName(self :: API_DEFAULT_FORMAT);
182 if ($this->mPrinter->getNeedsRawData())
183 $this->getResult()->setRawMode();
184 }
185
186 if ($e instanceof UsageException) {
187 //
188 // User entered incorrect parameters - print usage screen
189 //
190 $errMessage = array (
191 'code' => $e->getCodeString(), 'info' => $e->getMessage());
192 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
193
194 } else {
195 //
196 // Something is seriously wrong
197 //
198 $errMessage = array (
199 'code' => 'internal_api_error',
200 'info' => "Exception Caught: {$e->getMessage()}"
201 );
202 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
203 }
204
205 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
206 if ($e->getCode() === 0)
207 header($headerStr, true);
208 else
209 header($headerStr, true, $e->getCode());
210
211 // Reset and print just the error message
212 ob_clean();
213 $this->getResult()->reset();
214 $this->getResult()->addValue(null, 'error', $errMessage);
215
216 // If the error occured during printing, do a printer->profileOut()
217 $this->mPrinter->safeProfileOut();
218 $this->printResult(true);
219 }
220
221 // Set the cache expiration at the last moment, as any errors may change the expiration.
222 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
223 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
224 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
225 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
226
227 if($this->mPrinter->getIsHtml())
228 echo wfReportTime();
229
230 ob_end_flush();
231 }
232
233 /**
234 * Execute the actual module, without any error handling
235 */
236 protected function executeAction() {
237 $action = $format = $version = null;
238 extract($this->extractRequestParams());
239 $this->mShowVersions = $version;
240
241 // Instantiate the module requested by the user
242 $module = new $this->mModules[$action] ($this, $action);
243
244 if (!$this->mInternalMode) {
245
246 // See if custom printer is used
247 $this->mPrinter = $module->getCustomPrinter();
248 if (is_null($this->mPrinter)) {
249 // Create an appropriate printer
250 $this->mPrinter = $this->createPrinterByName($format);
251 }
252
253 if ($this->mPrinter->getNeedsRawData())
254 $this->getResult()->setRawMode();
255 }
256
257 // Execute
258 $module->profileIn();
259 $module->execute();
260 $module->profileOut();
261
262 if (!$this->mInternalMode) {
263 // Print result data
264 $this->printResult(false);
265 }
266 }
267
268 /**
269 * Print results using the current printer
270 */
271 protected function printResult($isError) {
272 $printer = $this->mPrinter;
273 $printer->profileIn();
274 $printer->initPrinter($isError);
275 $printer->execute();
276 $printer->closePrinter();
277 $printer->profileOut();
278 }
279
280 /**
281 * See ApiBase for description.
282 */
283 protected function getAllowedParams() {
284 return array (
285 'format' => array (
286 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
287 ApiBase :: PARAM_TYPE => $this->mFormatNames
288 ),
289 'action' => array (
290 ApiBase :: PARAM_DFLT => 'help',
291 ApiBase :: PARAM_TYPE => $this->mModuleNames
292 ),
293 'version' => false
294 );
295 }
296
297 /**
298 * See ApiBase for description.
299 */
300 protected function getParamDescription() {
301 return array (
302 'format' => 'The format of the output',
303 'action' => 'What action you would like to perform',
304 'version' => 'When showing help, include version for each module'
305 );
306 }
307
308 /**
309 * See ApiBase for description.
310 */
311 protected function getDescription() {
312 return array (
313 '',
314 'This API allows programs to access various functions of MediaWiki software.',
315 'For more details see API Home Page @ http://www.mediawiki.org/wiki/API',
316 '',
317 'Status: ALPHA -- all features shown on this page should be working,',
318 ' but the API is still in active development, and may change at any time.',
319 ' Make sure you monitor changes to this page, wikitech-l mailing list,',
320 ' or the source code in the includes/api directory for any changes.',
321 ''
322 );
323 }
324
325 /**
326 * Returns an array of strings with credits for the API
327 */
328 protected function getCredits() {
329 return array(
330 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
331 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
332 );
333 }
334
335 /**
336 * Override the parent to generate help messages for all available modules.
337 */
338 public function makeHelpMsg() {
339
340 // Use parent to make default message for the main module
341 $msg = parent :: makeHelpMsg();
342
343 $astriks = str_repeat('*** ', 10);
344 $msg .= "\n\n$astriks Modules $astriks\n\n";
345 foreach( $this->mModules as $moduleName => $unused ) {
346 $msg .= "* action=$moduleName *";
347 $module = new $this->mModules[$moduleName] ($this, $moduleName);
348 $msg2 = $module->makeHelpMsg();
349 if ($msg2 !== false)
350 $msg .= $msg2;
351 $msg .= "\n";
352 }
353
354 $msg .= "\n$astriks Formats $astriks\n\n";
355 foreach( $this->mFormats as $formatName => $unused ) {
356 $msg .= "* format=$formatName *";
357 $module = $this->createPrinterByName($formatName);
358 $msg2 = $module->makeHelpMsg();
359 if ($msg2 !== false)
360 $msg .= $msg2;
361 $msg .= "\n";
362 }
363
364 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
365
366
367 return $msg;
368 }
369
370 private $mIsBot = null;
371
372 /**
373 * Returns true if the currently logged in user is a bot, false otherwise
374 */
375 public function isBot() {
376 if (!isset ($this->mIsBot)) {
377 global $wgUser;
378 $this->mIsBot = $wgUser->isAllowed('bot');
379 }
380 return $this->mIsBot;
381 }
382
383 public function getShowVersions() {
384 return $this->mShowVersions;
385 }
386
387 /**
388 * Returns the version information of this file, plus it includes
389 * the versions for all files that are not callable proper API modules
390 */
391 public function getVersion() {
392 $vers = array ();
393 $vers[] = __CLASS__ . ': $Id$';
394 $vers[] = ApiBase :: getBaseVersion();
395 $vers[] = ApiFormatBase :: getBaseVersion();
396 $vers[] = ApiQueryBase :: getBaseVersion();
397 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
398 return $vers;
399 }
400 }
401
402 /**
403 * This exception will be thrown when dieUsage is called to stop module execution.
404 * The exception handling code will print a help screen explaining how this API may be used.
405 *
406 * @addtogroup API
407 */
408 class UsageException extends Exception {
409
410 private $mCodestr;
411
412 public function __construct($message, $codestr, $code = 0) {
413 parent :: __construct($message, $code);
414 $this->mCodestr = $codestr;
415 }
416 public function getCodeString() {
417 return $this->mCodestr;
418 }
419 public function __toString() {
420 return "{$this->getCodeString()}: {$this->getMessage()}";
421 }
422 }
423 ?>