4 * Created on Sep 4, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
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.
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.
44 class ApiMain
extends ApiBase
{
47 * When no format parameter is given, this format will be used
49 const API_DEFAULT_FORMAT
= 'xmlfm';
52 * List of available modules: action name => module class
54 private static $Modules = array (
55 'login' => 'ApiLogin',
56 'query' => 'ApiQuery',
57 'opensearch' => 'ApiOpenSearch',
58 'feedwatchlist' => 'ApiFeedWatchlist',
63 * List of available formats: format name => format class
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'
79 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
80 private $mResult, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
83 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
85 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
86 * @param $enableWrite bool should be set to true if the api may modify data
88 public function __construct($request, $enableWrite = false) {
90 $this->mInternalMode
= ($request instanceof FauxRequest
);
92 // Special handling for the main module: $parent === $this
93 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
95 $this->mModules
= self
:: $Modules;
96 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
97 $this->mFormats
= self
:: $Formats;
98 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
100 $this->mResult
= new ApiResult($this);
101 $this->mShowVersions
= false;
102 $this->mEnableWrite
= $enableWrite;
104 $this->mRequest
= & $request;
106 $this->mSquidMaxage
= 0;
110 * Return the request object that contains client's request
112 public function getRequest() {
113 return $this->mRequest
;
117 * Get the ApiResult object asscosiated with current request
119 public function getResult() {
120 return $this->mResult
;
124 * This method will simply cause an error if the write mode was disabled for this api.
126 public function requestWriteMode() {
127 if (!$this->mEnableWrite
)
128 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
129 'statement is included in the site\'s LocalSettings.php file', 'readonly');
133 * Set how long the response should be cached.
135 public function setCacheMaxAge($maxage) {
136 $this->mSquidMaxage
= $maxage;
140 * Create an instance of an output formatter by its name
142 public function createPrinterByName($format) {
143 return new $this->mFormats
[$format] ($this, $format);
147 * Execute api request. Any errors will be handled if the API was called by the remote client.
149 public function execute() {
151 if ($this->mInternalMode
)
152 $this->executeAction();
154 $this->executeActionWithErrorHandling();
159 * Execute an action, and in case of an error, erase whatever partial results
160 * have been accumulated, and replace it with an error message and a help screen.
162 protected function executeActionWithErrorHandling() {
164 // In case an error occurs during data output,
165 // clear the output buffer and print just the error information
169 $this->executeAction();
170 } catch (Exception
$e) {
172 // Handle any kind of exception by outputing properly formatted error message.
173 // If this fails, an unhandled exception should be thrown so that global error
174 // handler will process and log it.
177 // Error results should not be cached
178 $this->setCacheMaxAge(0);
180 // Printer may not be initialized if the extractRequestParams() fails for the main module
181 if (!isset ($this->mPrinter
)) {
182 $this->mPrinter
= $this->createPrinterByName(self
:: API_DEFAULT_FORMAT
);
183 if ($this->mPrinter
->getNeedsRawData())
184 $this->getResult()->setRawMode();
187 if ($e instanceof UsageException
) {
189 // User entered incorrect parameters - print usage screen
191 $errMessage = array (
192 'code' => $e->getCodeString(), 'info' => $e->getMessage());
193 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
197 // Something is seriously wrong
199 $errMessage = array (
200 'code' => 'internal_api_error',
201 'info' => "Exception Caught: {$e->getMessage()}"
203 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
206 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
207 if ($e->getCode() === 0)
208 header($headerStr, true);
210 header($headerStr, true, $e->getCode());
212 // Reset and print just the error message
214 $this->getResult()->reset();
215 $this->getResult()->addValue(null, 'error', $errMessage);
217 // If the error occured during printing, do a printer->profileOut()
218 $this->mPrinter
->safeProfileOut();
219 $this->printResult(true);
222 // Set the cache expiration at the last moment, as any errors may change the expiration.
223 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
224 $expires = $this->mSquidMaxage
== 0 ?
1 : time() +
$this->mSquidMaxage
;
225 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
226 header('Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0');
228 if($this->mPrinter
->getIsHtml())
235 * Execute the actual module, without any error handling
237 protected function executeAction() {
238 $action = $format = $version = null;
239 extract($this->extractRequestParams());
240 $this->mShowVersions
= $version;
242 // Instantiate the module requested by the user
243 $module = new $this->mModules
[$action] ($this, $action);
245 if (!$this->mInternalMode
) {
247 // See if custom printer is used
248 $this->mPrinter
= $module->getCustomPrinter();
249 if (is_null($this->mPrinter
)) {
250 // Create an appropriate printer
251 $this->mPrinter
= $this->createPrinterByName($format);
254 if ($this->mPrinter
->getNeedsRawData())
255 $this->getResult()->setRawMode();
259 $module->profileIn();
261 $module->profileOut();
263 if (!$this->mInternalMode
) {
265 $this->printResult(false);
270 * Print results using the current printer
272 protected function printResult($isError) {
273 $printer = $this->mPrinter
;
274 $printer->profileIn();
275 $printer->initPrinter($isError);
277 $printer->closePrinter();
278 $printer->profileOut();
282 * See ApiBase for description.
284 protected function getAllowedParams() {
287 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
288 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
291 ApiBase
:: PARAM_DFLT
=> 'help',
292 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
299 * See ApiBase for description.
301 protected function getParamDescription() {
303 'format' => 'The format of the output',
304 'action' => 'What action you would like to perform',
305 'version' => 'When showing help, include version for each module'
310 * See ApiBase for description.
312 protected function getDescription() {
315 'This API allows programs to access various functions of MediaWiki software.',
316 'For more details see API Home Page @ http://www.mediawiki.org/wiki/API',
318 'Status: ALPHA -- all features shown on this page should be working,',
319 ' but the API is still in active development, and may change at any time.',
320 ' Make sure you monitor changes to this page, wikitech-l mailing list,',
321 ' or the source code in the includes/api directory for any changes.',
327 * Returns an array of strings with credits for the API
329 protected function getCredits() {
331 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
332 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
337 * Override the parent to generate help messages for all available modules.
339 public function makeHelpMsg() {
341 // Use parent to make default message for the main module
342 $msg = parent
:: makeHelpMsg();
344 $astriks = str_repeat('*** ', 10);
345 $msg .= "\n\n$astriks Modules $astriks\n\n";
346 foreach( $this->mModules
as $moduleName => $unused ) {
347 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
348 $msg .= self
::makeHelpMsgHeader($module, 'action');
349 $msg2 = $module->makeHelpMsg();
355 $msg .= "\n$astriks Formats $astriks\n\n";
356 foreach( $this->mFormats
as $formatName => $unused ) {
357 $module = $this->createPrinterByName($formatName);
358 $msg .= self
::makeHelpMsgHeader($module, 'format');
359 $msg2 = $module->makeHelpMsg();
365 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
371 public static function makeHelpMsgHeader($module, $paramName) {
372 $paramPrefix = $module->getParamPrefix();
373 if (!empty($paramPrefix))
374 $paramPrefix = "($paramPrefix) ";
376 return "* $paramName={$module->getModuleName()} $paramPrefix*";
379 private $mIsBot = null;
381 private $mIsSysop = null;
384 * Returns true if the currently logged in user is a bot, false otherwise
386 public function isBot() {
387 if (!isset ($this->mIsBot
)) {
389 $this->mIsBot
= $wgUser->isAllowed('bot');
391 return $this->mIsBot
;
395 * Similar to isBot(), this method returns true if the logged in user is
396 * a sysop, and false if not.
398 public function isSysop() {
399 if (!isset ($this->mIsSysop
)) {
401 $this->mIsSysop
= in_array( 'sysop',
402 $wgUser->getGroups());
405 return $this->mIsSysop
;
408 public function getShowVersions() {
409 return $this->mShowVersions
;
413 * Returns the version information of this file, plus it includes
414 * the versions for all files that are not callable proper API modules
416 public function getVersion() {
418 $vers[] = __CLASS__
. ': $Id$';
419 $vers[] = ApiBase
:: getBaseVersion();
420 $vers[] = ApiFormatBase
:: getBaseVersion();
421 $vers[] = ApiQueryBase
:: getBaseVersion();
422 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
428 * This exception will be thrown when dieUsage is called to stop module execution.
429 * The exception handling code will print a help screen explaining how this API may be used.
433 class UsageException
extends Exception
{
437 public function __construct($message, $codestr, $code = 0) {
438 parent
:: __construct($message, $code);
439 $this->mCodestr
= $codestr;
441 public function getCodeString() {
442 return $this->mCodestr
;
444 public function __toString() {
445 return "{$this->getCodeString()}: {$this->getMessage()}";