* Use ui language now that it is possible
[mediawiki.git] / includes / api / ApiMain.php
blob43d1da432160c06899fc122b904a5e76eefac261
1 <?php
4 /*
5 * Created on Sep 4, 2006
7 * API for MediaWiki 1.8+
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
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.
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.
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
27 if (!defined('MEDIAWIKI')) {
28 // Eclipse helper - will be ignored in production
29 require_once ('ApiBase.php');
32 /**
33 * This is the main API class, used for both external and internal processing.
35 class ApiMain extends ApiBase {
37 /**
38 * When no format parameter is given, this format will be used
40 const API_DEFAULT_FORMAT = 'xmlfm';
42 /**
43 * List of available modules: action name => module class
45 private static $Modules = array (
46 'help' => 'ApiHelp',
47 'login' => 'ApiLogin',
48 'opensearch' => 'ApiOpenSearch',
49 'feedwatchlist' => 'ApiFeedWatchlist',
50 'query' => 'ApiQuery'
53 /**
54 * List of available formats: format name => format class
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'
70 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
71 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
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
78 public function __construct($request, $enableWrite = false) {
80 $this->mInternalMode = ($request instanceof FauxRequest);
82 // Special handling for the main module: $parent === $this
83 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
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
90 $this->mResult = new ApiResult($this);
91 $this->mShowVersions = false;
92 $this->mEnableWrite = $enableWrite;
94 $this->mRequest = & $request;
96 $this->mSquidMaxage = 0;
99 public function & getRequest() {
100 return $this->mRequest;
103 public function getResult() {
104 return $this->mResult;
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');
113 public function setCacheMaxAge($maxage) {
114 $this->mSquidMaxage = $maxage;
117 public function createPrinterByName($format) {
118 return new $this->mFormats[$format] ($this, $format);
121 public function execute() {
122 $this->profileIn();
123 if ($this->mInternalMode)
124 $this->executeAction();
125 else
126 $this->executeActionWithErrorHandling();
127 $this->profileOut();
130 protected function executeActionWithErrorHandling() {
132 // In case an error occurs during data output,
133 // this clear the output buffer and print just the error information
134 ob_start();
136 try {
137 $this->executeAction();
138 } catch (Exception $e) {
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.
145 // Error results should not be cached
146 $this->setCacheMaxAge(0);
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();
155 if ($e instanceof UsageException) {
157 // User entered incorrect parameters - print usage screen
159 $errMessage = array (
160 'code' => $e->getCodeString(), 'info' => $e->getMessage());
161 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
163 } else {
165 // Something is seriously wrong
167 $errMessage = array (
168 'code' => 'internal_api_error',
169 'info' => "Exception Caught: {$e->getMessage()}"
171 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
174 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
175 if ($e->getCode() === 0)
176 header($headerStr, true);
177 else
178 header($headerStr, true, $e->getCode());
180 // Reset and print just the error message
181 ob_clean();
182 $this->getResult()->reset();
183 $this->getResult()->addValue(null, 'error', $errMessage);
185 // If the error occured during printing, do a printer->profileOut()
186 $this->mPrinter->safeProfileOut();
187 $this->printResult(true);
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');
196 ob_end_flush();
200 * Execute the actual module, without any error handling
202 protected function executeAction() {
203 $action = $format = $version = null;
204 extract($this->extractRequestParams());
205 $this->mShowVersions = $version;
207 // Instantiate the module requested by the user
208 $module = new $this->mModules[$action] ($this, $action);
210 if (!$this->mInternalMode) {
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);
219 if ($this->mPrinter->getNeedsRawData())
220 $this->getResult()->setRawMode();
223 // Execute
224 $module->profileIn();
225 $module->execute();
226 $module->profileOut();
228 if (!$this->mInternalMode) {
229 // Print result data
230 $this->printResult(false);
235 * Internal printer
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();
246 protected function getAllowedParams() {
247 return array (
248 'format' => array (
249 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
250 ApiBase :: PARAM_TYPE => $this->mFormatNames
252 'action' => array (
253 ApiBase :: PARAM_DFLT => 'help',
254 ApiBase :: PARAM_TYPE => $this->mModuleNames
256 'version' => false
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'
268 protected function getDescription() {
269 return array (
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',
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.',
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'
290 * Override the parent to generate help messages for all available modules.
292 public function makeHelpMsg() {
294 // Use parent to make default message for the main module
295 $msg = parent :: makeHelpMsg();
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";
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";
318 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
321 return $msg;
324 private $mIsBot = null;
325 public function isBot() {
326 if (!isset ($this->mIsBot)) {
327 global $wgUser;
328 $this->mIsBot = $wgUser->isAllowed('bot');
330 return $this->mIsBot;
333 public function getShowVersions() {
334 return $this->mShowVersions;
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;
349 * @desc This exception will be thrown when dieUsage is called to stop module execution.
351 class UsageException extends Exception {
353 private $mCodestr;
355 public function __construct($message, $codestr, $code = 0) {
356 parent :: __construct($message, $code);
357 $this->mCodestr = $codestr;
359 public function getCodeString() {
360 return $this->mCodestr;
362 public function __toString() {
363 return "{$this->getCodeString()}: {$this->getMessage()}";