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, $mAction, $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 if (!$this->mInternalMode
) {
97 // Impose module restrictions.
98 // If the current user cannot read,
99 // Remove all modules other than login
101 if (!$wgUser->isAllowed('read')) {
102 self
::$Modules = array(
103 'login' => self
::$Modules['login'],
104 'help' => self
::$Modules['help']
109 $this->mModules
= self
:: $Modules;
110 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
111 $this->mFormats
= self
:: $Formats;
112 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
114 $this->mResult
= new ApiResult($this);
115 $this->mShowVersions
= false;
116 $this->mEnableWrite
= $enableWrite;
118 $this->mRequest
= & $request;
120 $this->mSquidMaxage
= 0;
124 * Return true if the API was started by other PHP code using FauxRequest
126 public function isInternalMode() {
127 return $this->mInternalMode
;
131 * Return the request object that contains client's request
133 public function getRequest() {
134 return $this->mRequest
;
138 * Get the ApiResult object asscosiated with current request
140 public function getResult() {
141 return $this->mResult
;
145 * This method will simply cause an error if the write mode was disabled for this api.
147 public function requestWriteMode() {
148 if (!$this->mEnableWrite
)
149 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
150 'statement is included in the site\'s LocalSettings.php file', 'readonly');
154 * Set how long the response should be cached.
156 public function setCacheMaxAge($maxage) {
157 $this->mSquidMaxage
= $maxage;
161 * Create an instance of an output formatter by its name
163 public function createPrinterByName($format) {
164 return new $this->mFormats
[$format] ($this, $format);
168 * Execute api request. Any errors will be handled if the API was called by the remote client.
170 public function execute() {
172 if ($this->mInternalMode
)
173 $this->executeAction();
175 $this->executeActionWithErrorHandling();
180 * Execute an action, and in case of an error, erase whatever partial results
181 * have been accumulated, and replace it with an error message and a help screen.
183 protected function executeActionWithErrorHandling() {
185 // In case an error occurs during data output,
186 // clear the output buffer and print just the error information
190 $this->executeAction();
191 } catch (Exception
$e) {
193 // Handle any kind of exception by outputing properly formatted error message.
194 // If this fails, an unhandled exception should be thrown so that global error
195 // handler will process and log it.
198 $errCode = $this->substituteResultWithError($e);
200 // Error results should not be cached
201 $this->setCacheMaxAge(0);
203 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
204 if ($e->getCode() === 0)
205 header($headerStr, true);
207 header($headerStr, true, $e->getCode());
209 // Reset and print just the error message
212 // If the error occured during printing, do a printer->profileOut()
213 $this->mPrinter
->safeProfileOut();
214 $this->printResult(true);
217 // Set the cache expiration at the last moment, as any errors may change the expiration.
218 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
219 $expires = $this->mSquidMaxage
== 0 ?
1 : time() +
$this->mSquidMaxage
;
220 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
221 header('Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0');
223 if($this->mPrinter
->getIsHtml())
230 * Replace the result data with the information about an exception.
231 * Returns the error code
233 protected function substituteResultWithError($e) {
235 // Printer may not be initialized if the extractRequestParams() fails for the main module
236 if (!isset ($this->mPrinter
)) {
237 // The printer has not been created yet. Try to manually get formatter value.
238 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
239 if (!in_array($value, $this->mFormatNames
))
240 $value = self
::API_DEFAULT_FORMAT
;
242 $this->mPrinter
= $this->createPrinterByName($value);
243 if ($this->mPrinter
->getNeedsRawData())
244 $this->getResult()->setRawMode();
247 if ($e instanceof UsageException
) {
249 // User entered incorrect parameters - print usage screen
251 $errMessage = array (
252 'code' => $e->getCodeString(),
253 'info' => $e->getMessage());
255 // Only print the help message when this is for the developer, not runtime
256 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
257 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
261 // Something is seriously wrong
263 $errMessage = array (
264 'code' => 'internal_api_error',
265 'info' => "Exception Caught: {$e->getMessage()}"
267 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
270 $this->getResult()->reset();
271 $this->getResult()->addValue(null, 'error', $errMessage);
273 return $errMessage['code'];
277 * Execute the actual module, without any error handling
279 protected function executeAction() {
281 $params = $this->extractRequestParams();
283 $this->mShowVersions
= $params['version'];
284 $this->mAction
= $params['action'];
286 // Instantiate the module requested by the user
287 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
289 if (!$this->mInternalMode
) {
291 // See if custom printer is used
292 $this->mPrinter
= $module->getCustomPrinter();
293 if (is_null($this->mPrinter
)) {
294 // Create an appropriate printer
295 $this->mPrinter
= $this->createPrinterByName($params['format']);
298 if ($this->mPrinter
->getNeedsRawData())
299 $this->getResult()->setRawMode();
303 $module->profileIn();
305 $module->profileOut();
307 if (!$this->mInternalMode
) {
309 $this->printResult(false);
314 * Print results using the current printer
316 protected function printResult($isError) {
317 $printer = $this->mPrinter
;
318 $printer->profileIn();
319 $printer->initPrinter($isError);
321 $printer->closePrinter();
322 $printer->profileOut();
326 * See ApiBase for description.
328 protected function getAllowedParams() {
331 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
332 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
335 ApiBase
:: PARAM_DFLT
=> 'help',
336 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
343 * See ApiBase for description.
345 protected function getParamDescription() {
347 'format' => 'The format of the output',
348 'action' => 'What action you would like to perform',
349 'version' => 'When showing help, include version for each module'
354 * See ApiBase for description.
356 protected function getDescription() {
360 '******************************************************************',
362 '** This is an auto-generated MediaWiki API documentation page **',
364 '** Documentation and Examples: **',
365 '** http://www.mediawiki.org/wiki/API **',
367 '******************************************************************',
369 'Status: All features shown on this page should be working, but the API',
370 ' is still in active development, and may change at any time.',
371 ' Make sure to monitor our mailing list for any updates.',
373 'Documentation: http://www.mediawiki.org/wiki/API',
374 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
375 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
385 * Returns an array of strings with credits for the API
387 protected function getCredits() {
389 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
390 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
395 * Override the parent to generate help messages for all available modules.
397 public function makeHelpMsg() {
399 // Use parent to make default message for the main module
400 $msg = parent
:: makeHelpMsg();
402 $astriks = str_repeat('*** ', 10);
403 $msg .= "\n\n$astriks Modules $astriks\n\n";
404 foreach( $this->mModules
as $moduleName => $unused ) {
405 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
406 $msg .= self
::makeHelpMsgHeader($module, 'action');
407 $msg2 = $module->makeHelpMsg();
413 $msg .= "\n$astriks Formats $astriks\n\n";
414 foreach( $this->mFormats
as $formatName => $unused ) {
415 $module = $this->createPrinterByName($formatName);
416 $msg .= self
::makeHelpMsgHeader($module, 'format');
417 $msg2 = $module->makeHelpMsg();
423 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
429 public static function makeHelpMsgHeader($module, $paramName) {
430 $modulePrefix = $module->getModulePrefix();
431 if (!empty($modulePrefix))
432 $modulePrefix = "($modulePrefix) ";
434 return "* $paramName={$module->getModuleName()} $modulePrefix*";
437 private $mIsBot = null;
439 private $mIsSysop = null;
442 * Returns true if the currently logged in user is a bot, false otherwise
444 public function isBot() {
445 if (!isset ($this->mIsBot
)) {
447 $this->mIsBot
= $wgUser->isAllowed('bot');
449 return $this->mIsBot
;
453 * Similar to isBot(), this method returns true if the logged in user is
454 * a sysop, and false if not.
456 public function isSysop() {
457 if (!isset ($this->mIsSysop
)) {
459 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
462 return $this->mIsSysop
;
465 public function getShowVersions() {
466 return $this->mShowVersions
;
470 * Returns the version information of this file, plus it includes
471 * the versions for all files that are not callable proper API modules
473 public function getVersion() {
475 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
476 $vers[] = __CLASS__
. ': $Id$';
477 $vers[] = ApiBase
:: getBaseVersion();
478 $vers[] = ApiFormatBase
:: getBaseVersion();
479 $vers[] = ApiQueryBase
:: getBaseVersion();
480 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
485 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
486 * classes who wish to add their own modules to their lexicon or override the
487 * behavior of inherent ones.
490 * @param $mdlName String The identifier for this module.
491 * @param $mdlClass String The class where this module is implemented.
493 protected function addModule( $mdlName, $mdlClass ) {
494 $this->mModules
[$mdlName] = $mdlClass;
498 * Add or overwrite an output format for this ApiMain. Intended for use by extending
499 * classes who wish to add to or modify current formatters.
502 * @param $fmtName The identifier for this format.
503 * @param $fmtClass The class implementing this format.
505 protected function addFormat( $fmtName, $fmtClass ) {
506 $this->mFormats
[$fmtName] = $fmtClass;
511 * This exception will be thrown when dieUsage is called to stop module execution.
512 * The exception handling code will print a help screen explaining how this API may be used.
516 class UsageException
extends Exception
{
520 public function __construct($message, $codestr, $code = 0) {
521 parent
:: __construct($message, $code);
522 $this->mCodestr
= $codestr;
524 public function getCodeString() {
525 return $this->mCodestr
;
527 public function __toString() {
528 return "{$this->getCodeString()}: {$this->getMessage()}";