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');
34 * This is the main API class, used for both external and internal processing.
36 class ApiMain
extends ApiBase
{
39 * When no format parameter is given, this format will be used
41 const API_DEFAULT_FORMAT
= 'xmlfm';
44 * List of available modules: action name => module class
46 private static $Modules = array (
48 'login' => 'ApiLogin',
49 'opensearch' => 'ApiOpenSearch',
50 'feedwatchlist' => 'ApiFeedWatchlist',
55 * List of available formats: format name => format class
57 private static $Formats = array (
58 'json' => 'ApiFormatJson',
59 'jsonfm' => 'ApiFormatJson',
60 'raw' => 'ApiFormatJson',
61 'rawfm' => 'ApiFormatJson',
62 'xml' => 'ApiFormatXml',
63 'xmlfm' => 'ApiFormatXml',
64 'yaml' => 'ApiFormatYaml',
65 'yamlfm' => 'ApiFormatYaml'
68 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
69 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode;
73 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
74 * @param $enableWrite bool should be set to true if the api may modify data
76 public function __construct($request, $enableWrite = false) {
77 // Special handling for the main module: $parent === $this
78 parent
:: __construct($this, 'main');
80 $this->mModules
=& self
::$Modules;
81 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
82 $this->mFormats
=& self
::$Formats;
83 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
85 $this->mResult
= new ApiResult($this);
86 $this->mShowVersions
= false;
87 $this->mEnableWrite
= $enableWrite;
89 $this->mRequest
=& $request;
91 $this->mInternalMode
= ($request instanceof FauxRequest
);
94 public function & getRequest() {
95 return $this->mRequest
;
98 public function & getResult() {
99 return $this->mResult
;
102 public function requestWriteMode() {
103 if (!$this->mEnableWrite
)
104 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
105 'statement is included in the site\'s LocalSettings.php file', 'readonly');
108 public function createPrinterByName($format) {
109 return new $this->mFormats
[$format] ($this, $format);
112 public function execute() {
114 if($this->mInternalMode
)
115 $this->executeAction();
117 $this->executeActionWithErrorHandling();
121 protected function executeActionWithErrorHandling() {
123 // In case an error occurs during data output,
124 // this clear the output buffer and print just the error information
128 $this->executeAction();
129 } catch (Exception
$e) {
131 // Handle any kind of exception by outputing properly formatted error message.
132 // If this fails, an unhandled exception should be thrown so that global error
133 // handler will process and log it.
136 // Printer may not be initialized if the extractRequestParams() fails for the main module
137 if (!isset ($this->mPrinter
)) {
138 $this->mPrinter
= $this->createPrinterByName(self
:: API_DEFAULT_FORMAT
);
139 if ($this->mPrinter
->getNeedsRawData())
140 $this->getResult()->setRawMode();
143 if ($e instanceof UsageException
) {
145 // User entered incorrect parameters - print usage screen
147 $errMessage = array (
148 'code' => $e->getCodeString(),
149 'info' => $e->getMessage()
151 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
155 // Something is seriously wrong
157 $errMessage = array (
158 'code' => 'internal_api_error',
159 'info' => "Exception Caught: {$e->getMessage()}"
161 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
164 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
165 if ($e->getCode() === 0)
166 header($headerStr, true);
168 header($headerStr, true, $e->getCode());
170 // Reset and print just the error message
172 $this->getResult()->reset();
173 $this->getResult()->addValue(null, 'error', $errMessage);
175 // If the error occured during printing, do a printer->profileOut()
176 $this->mPrinter
->safeProfileOut();
177 $this->printResult(true);
184 * Execute the actual module, without any error handling
186 protected function executeAction() {
187 $action = $format = $version = null;
188 extract($this->extractRequestParams());
189 $this->mShowVersions
= $version;
191 // Instantiate the module requested by the user
192 $module = new $this->mModules
[$action] ($this, $action);
194 if (!$this->mInternalMode
) {
196 // See if custom printer is used
197 $this->mPrinter
= $module->getCustomPrinter();
198 if (is_null($this->mPrinter
)) {
199 // Create an appropriate printer
200 $this->mPrinter
= $this->createPrinterByName($format);
203 if ($this->mPrinter
->getNeedsRawData())
204 $this->getResult()->setRawMode();
208 $module->profileIn();
210 $module->profileOut();
212 if (!$this->mInternalMode
) {
214 $this->printResult(false);
221 protected function printResult($isError) {
222 $printer = $this->mPrinter
;
223 $printer->profileIn();
224 $printer->initPrinter($isError);
226 $printer->closePrinter();
227 $printer->profileOut();
230 protected function getAllowedParams() {
233 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
234 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
237 ApiBase
:: PARAM_DFLT
=> 'help',
238 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
244 protected function getParamDescription() {
246 'format' => 'The format of the output',
247 'action' => 'What action you would like to perform',
248 'version' => 'When showing help, include version for each module'
252 protected function getDescription() {
255 'This API allows programs to access various functions of MediaWiki software.',
256 'For more details see API Home Page @ http://meta.wikimedia.org/wiki/API',
262 * Override the parent to generate help messages for all available modules.
264 public function makeHelpMsg() {
266 // Use parent to make default message for the main module
267 $msg = parent
:: makeHelpMsg();
269 $astriks = str_repeat('*** ', 10);
270 $msg .= "\n\n$astriks Modules $astriks\n\n";
271 foreach ($this->mModules
as $moduleName => $moduleClass) {
272 $msg .= "* action=$moduleName *";
273 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
274 $msg2 = $module->makeHelpMsg();
280 $msg .= "\n$astriks Formats $astriks\n\n";
281 foreach ($this->mFormats
as $formatName => $moduleClass) {
282 $msg .= "* format=$formatName *";
283 $module = $this->createPrinterByName($formatName);
284 $msg2 = $module->makeHelpMsg();
293 private $mIsBot = null;
294 public function isBot() {
295 if (!isset ($this->mIsBot
)) {
297 $this->mIsBot
= $wgUser->isAllowed('bot');
299 return $this->mIsBot
;
302 public function getShowVersions() {
303 return $this->mShowVersions
;
306 public function getVersion() {
308 $vers[] = __CLASS__
. ': $Id$';
309 $vers[] = ApiBase
:: getBaseVersion();
310 $vers[] = ApiFormatBase
:: getBaseVersion();
311 $vers[] = ApiQueryBase
:: getBaseVersion();
312 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
318 * @desc This exception will be thrown when dieUsage is called to stop module execution.
320 class UsageException
extends Exception
{
324 public function __construct($message, $codestr, $code = 0) {
325 parent
:: __construct($message, $code);
326 $this->mCodestr
= $codestr;
328 public function getCodeString() {
329 return $this->mCodestr
;
331 public function __toString() {
332 return "{$this->getCodeString()}: {$this->getMessage()}";