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 'xml' => 'ApiFormatXml',
61 'xmlfm' => 'ApiFormatXml',
62 'yaml' => 'ApiFormatYaml',
63 'yamlfm' => 'ApiFormatYaml'
66 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
67 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode;
71 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
72 * @param $enableWrite bool should be set to true if the api may modify data
74 public function __construct($request, $enableWrite = false) {
75 // Special handling for the main module: $parent === $this
76 parent
:: __construct($this, 'main');
78 $this->mModules
=& self
::$Modules;
79 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
80 $this->mFormats
=& self
::$Formats;
81 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
83 $this->mResult
= new ApiResult($this);
84 $this->mShowVersions
= false;
85 $this->mEnableWrite
= $enableWrite;
87 $this->mRequest
=& $request;
89 $this->mInternalMode
= ($request instanceof FauxRequest
);
92 public function & getRequest() {
93 return $this->mRequest
;
96 public function & getResult() {
97 return $this->mResult
;
100 public function requestWriteMode() {
101 if (!$this->mEnableWrite
)
102 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
103 'statement is included in the site\'s LocalSettings.php file', 'readonly');
106 public function createPrinterByName($format) {
107 return new $this->mFormats
[$format] ($this, $format);
110 public function execute() {
112 if($this->mInternalMode
)
113 $this->executeAction();
115 $this->executeActionWithErrorHandling();
119 protected function executeActionWithErrorHandling() {
121 // In case an error occurs during data output,
122 // this clear the output buffer and print just the error information
126 $this->executeAction();
127 } catch (Exception
$e) {
129 // Handle any kind of exception by outputing properly formatted error message.
130 // If this fails, an unhandled exception should be thrown so that global error
131 // handler will process and log it.
134 // Printer may not be initialized if the extractRequestParams() fails for the main module
135 if (!isset ($this->mPrinter
)) {
136 $this->mPrinter
= $this->createPrinterByName(self
:: API_DEFAULT_FORMAT
);
139 if ($e instanceof UsageException
) {
141 // User entered incorrect parameters - print usage screen
143 $httpRespCode = $e->getCode();
144 $errMessage = array (
145 'code' => $e->getCodeString(),
146 'info' => $e->getMessage()
148 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
152 // Something is seriously wrong
155 $errMessage = array (
156 'code' => 'internal_api_error',
157 'info' => "Exception Caught: {$e->getMessage()}"
159 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
162 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
163 if ($e->getCode() === 0)
164 header($headerStr, true);
166 header($headerStr, true, $e->getCode());
168 // Reset and print just the error message
170 $this->mResult
->Reset();
171 $this->mResult
->addValue(null, 'error', $errMessage);
172 $this->printResult(true);
179 * Execute the actual module, without any error handling
181 protected function executeAction() {
182 $action = $format = $version = null;
183 extract($this->extractRequestParams());
184 $this->mShowVersions
= $version;
186 // Instantiate the module requested by the user
187 $module = new $this->mModules
[$action] ($this, $action);
189 if (!$this->mInternalMode
) {
191 // See if custom printer is used
192 $this->mPrinter
= $module->getCustomPrinter();
194 if (is_null($this->mPrinter
)) {
195 // Create an appropriate printer
196 $this->mPrinter
= $this->createPrinterByName($format);
201 $module->profileIn();
203 $module->profileOut();
205 if (!$this->mInternalMode
) {
207 $this->printResult(false);
214 protected function printResult($isError) {
215 $printer = $this->mPrinter
;
216 $printer->profileIn();
217 $printer->initPrinter($isError);
218 if (!$printer->getNeedsRawData())
219 $this->getResult()->SanitizeData();
221 $printer->closePrinter();
222 $printer->profileOut();
225 protected function getAllowedParams() {
228 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
229 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
232 ApiBase
:: PARAM_DFLT
=> 'help',
233 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
239 protected function getParamDescription() {
241 'format' => 'The format of the output',
242 'action' => 'What action you would like to perform',
243 'version' => 'When showing help, include version for each module'
247 protected function getDescription() {
250 'This API allows programs to access various functions of MediaWiki software.',
251 'For more details see API Home Page @ http://meta.wikimedia.org/wiki/API',
257 * Override the parent to generate help messages for all available modules.
259 public function makeHelpMsg() {
261 // Use parent to make default message for the main module
262 $msg = parent
:: makeHelpMsg();
264 $astriks = str_repeat('*** ', 10);
265 $msg .= "\n\n$astriks Modules $astriks\n\n";
266 foreach ($this->mModules
as $moduleName => $moduleClass) {
267 $msg .= "* action=$moduleName *";
268 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
269 $msg2 = $module->makeHelpMsg();
275 $msg .= "\n$astriks Formats $astriks\n\n";
276 foreach ($this->mFormats
as $formatName => $moduleClass) {
277 $msg .= "* format=$formatName *";
278 $module = $this->createPrinterByName($formatName);
279 $msg2 = $module->makeHelpMsg();
288 private $mIsBot = null;
289 public function isBot() {
290 if (!isset ($this->mIsBot
)) {
292 $this->mIsBot
= $wgUser->isAllowed('bot');
294 return $this->mIsBot
;
297 public function getShowVersions() {
298 return $this->mShowVersions
;
301 public function getVersion() {
303 $vers[] = __CLASS__
. ': $Id$';
304 $vers[] = ApiBase
:: getBaseVersion();
305 $vers[] = ApiFormatBase
:: getBaseVersion();
306 $vers[] = ApiQueryBase
:: getBaseVersion();
307 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
313 * @desc This exception will be thrown when dieUsage is called to stop module execution.
315 class UsageException
extends Exception
{
319 public function __construct($message, $codestr, $code = 0) {
320 parent
:: __construct($message, $code);
321 $this->mCodestr
= $codestr;
323 public function getCodeString() {
324 return $this->mCodestr
;
326 public function __toString() {
327 return "{$this->getCodeString()}: {$this->getMessage()}";