2c437f1320351604cd690a42fe21726f136a34ba
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',
54 * List of available formats: format name => format class
56 private static $Formats = array (
57 'json' => 'ApiFormatJson',
58 'jsonfm' => 'ApiFormatJson',
59 'xml' => 'ApiFormatXml',
60 'xmlfm' => 'ApiFormatXml',
61 'yaml' => 'ApiFormatYaml',
62 'yamlfm' => 'ApiFormatYaml'
65 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
66 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode;
70 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
71 * @param $enableWrite bool should be set to true if the api may modify data
73 public function __construct($request, $enableWrite = false) {
74 // Special handling for the main module: $parent === $this
75 parent
:: __construct($this, 'main');
77 $this->mModules
=& self
::$Modules;
78 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
79 $this->mFormats
=& self
::$Formats;
80 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
82 $this->mResult
= new ApiResult($this);
83 $this->mShowVersions
= false;
84 $this->mEnableWrite
= $enableWrite;
86 $this->mRequest
=& $request;
88 $this->mInternalMode
= ($request instanceof FauxRequest
);
91 public function & getRequest() {
92 return $this->mRequest
;
95 public function & getResult() {
96 return $this->mResult
;
99 public function requestWriteMode() {
100 if (!$this->mEnableWrite
)
101 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
102 'statement is included in the site\'s LocalSettings.php file', 'readonly');
105 public function execute() {
107 if($this->mInternalMode
)
108 $this->executeAction();
110 $this->executeActionWithErrorHandling();
114 protected function executeActionWithErrorHandling() {
116 // In case an error occurs during data output,
117 // this clear the output buffer and print just the error information
121 $this->executeAction();
122 } catch (Exception
$e) {
124 // Handle any kind of exception by outputing properly formatted error message.
125 // If this fails, an unhandled exception should be thrown so that global error
126 // handler will process and log it.
129 // Printer may not be initialized if the extractRequestParams() fails for the main module
130 if (!isset ($this->mPrinter
)) {
131 $format = self
:: API_DEFAULT_FORMAT
;
132 $this->mPrinter
= new $this->mFormats
[$format] ($this, $format);
135 if ($e instanceof UsageException
) {
137 // User entered incorrect parameters - print usage screen
139 $httpRespCode = $e->getCode();
140 $errMessage = array (
141 'code' => $e->getCodeString(),
142 'info' => $e->getMessage()
144 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
148 // Something is seriously wrong
151 $errMessage = array (
152 'code' => 'internal_api_error',
153 'info' => "Exception Caught: {$e->getMessage()}"
155 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
158 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
159 if ($e->getCode() === 0)
160 header($headerStr, true);
162 header($headerStr, true, $e->getCode());
164 // Reset and print just the error message
166 $this->mResult
->Reset();
167 $this->mResult
->addValue(null, 'error', $errMessage);
168 $this->printResult(true);
175 * Execute the actual module, without any error handling
177 protected function executeAction() {
178 $action = $format = $version = null;
179 extract($this->extractRequestParams());
180 $this->mShowVersions
= $version;
182 // Instantiate the module requested by the user
183 $module = new $this->mModules
[$action] ($this, $action);
185 if (!$this->mInternalMode
) {
186 if ($module instanceof ApiFormatBase
) {
187 // The requested module will print data in its own format
188 $this->mPrinter
= $module;
190 // Create an appropriate printer
191 $this->mPrinter
= new $this->mFormats
[$format] ($this, $format);
196 $module->profileIn();
198 $module->profileOut();
200 if (!$this->mInternalMode
) {
202 $this->printResult(false);
209 protected function printResult($isError) {
210 $printer = $this->mPrinter
;
211 $printer->profileIn();
212 $printer->initPrinter($isError);
213 if (!$printer->getNeedsRawData())
214 $this->getResult()->SanitizeData();
215 $printer->executePrinter();
216 $printer->closePrinter();
217 $printer->profileOut();
220 protected function getAllowedParams() {
223 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
224 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
227 ApiBase
:: PARAM_DFLT
=> 'help',
228 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
234 protected function getParamDescription() {
236 'format' => 'The format of the output',
237 'action' => 'What action you would like to perform',
238 'version' => 'When showing help, include version for each module'
242 protected function getDescription() {
245 'This API allows programs to access various functions of MediaWiki software.',
246 'For more details see API Home Page @ http://meta.wikimedia.org/wiki/API',
252 * Override the parent to generate help messages for all available modules.
254 public function makeHelpMsg() {
256 // Use parent to make default message for the main module
257 $msg = parent
:: makeHelpMsg();
259 $astriks = str_repeat('*** ', 10);
260 $msg .= "\n\n$astriks Modules $astriks\n\n";
261 foreach ($this->mModules
as $moduleName => $moduleClass) {
262 $msg .= "* action=$moduleName *";
263 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
264 $msg2 = $module->makeHelpMsg();
270 $msg .= "\n$astriks Formats $astriks\n\n";
271 foreach ($this->mFormats
as $moduleName => $moduleClass) {
272 $msg .= "* format=$moduleName *";
273 $module = new $this->mFormats
[$moduleName] ($this, $moduleName);
274 $msg2 = $module->makeHelpMsg();
283 private $mIsBot = null;
284 public function isBot() {
285 if (!isset ($this->mIsBot
)) {
287 $this->mIsBot
= $wgUser->isAllowed('bot');
289 return $this->mIsBot
;
292 public function getShowVersions() {
293 return $this->mShowVersions
;
296 public function getVersion() {
298 $vers[] = __CLASS__
. ': $Id$';
299 $vers[] = ApiBase
:: getBaseVersion();
300 $vers[] = ApiFormatBase
:: getBaseVersion();
301 $vers[] = ApiQueryBase
:: getBaseVersion();
307 * @desc This exception will be thrown when dieUsage is called to stop module execution.
309 class UsageException
extends Exception
{
313 public function __construct($message, $codestr, $code = 0) {
314 parent
:: __construct($message, $code);
315 $this->mCodestr
= $codestr;
317 public function getCodeString() {
318 return $this->mCodestr
;
320 public function __toString() {
321 return "{$this->getCodeString()}: {$this->getMessage()}";