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 'logout' => 'ApiLogout',
57 'query' => 'ApiQuery',
58 'expandtemplates' => 'ApiExpandTemplates',
59 'parse' => 'ApiParse',
60 'opensearch' => 'ApiOpenSearch',
61 'feedwatchlist' => 'ApiFeedWatchlist',
65 private static $WriteModules = array (
66 'rollback' => 'ApiRollback',
67 'delete' => 'ApiDelete',
68 'undelete' => 'ApiUndelete',
69 'protect' => 'ApiProtect',
70 'block' => 'ApiBlock',
71 'unblock' => 'ApiUnblock',
73 #'changerights' => 'ApiChangeRights'
78 * List of available formats: format name => format class
80 private static $Formats = array (
81 'json' => 'ApiFormatJson',
82 'jsonfm' => 'ApiFormatJson',
83 'php' => 'ApiFormatPhp',
84 'phpfm' => 'ApiFormatPhp',
85 'wddx' => 'ApiFormatWddx',
86 'wddxfm' => 'ApiFormatWddx',
87 'xml' => 'ApiFormatXml',
88 'xmlfm' => 'ApiFormatXml',
89 'yaml' => 'ApiFormatYaml',
90 'yamlfm' => 'ApiFormatYaml',
91 'rawfm' => 'ApiFormatJson'
94 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
95 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
98 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
100 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
101 * @param $enableWrite bool should be set to true if the api may modify data
103 public function __construct($request, $enableWrite = false) {
105 $this->mInternalMode
= ($request instanceof FauxRequest
);
107 // Special handling for the main module: $parent === $this
108 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
110 if (!$this->mInternalMode
) {
112 // Impose module restrictions.
113 // If the current user cannot read,
114 // Remove all modules other than login
116 if (!$wgUser->isAllowed('read')) {
117 self
::$Modules = array(
118 'login' => self
::$Modules['login'],
119 'logout' => self
::$Modules['logout'],
120 'help' => self
::$Modules['help'],
125 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
126 $this->mModules
= $wgAPIModules + self
:: $Modules;
127 if($wgEnableWriteAPI)
128 $this->mModules +
= self
::$WriteModules;
130 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
131 $this->mFormats
= self
:: $Formats;
132 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
134 $this->mResult
= new ApiResult($this);
135 $this->mShowVersions
= false;
136 $this->mEnableWrite
= $enableWrite;
138 $this->mRequest
= & $request;
140 $this->mSquidMaxage
= 0;
144 * Return true if the API was started by other PHP code using FauxRequest
146 public function isInternalMode() {
147 return $this->mInternalMode
;
151 * Return the request object that contains client's request
153 public function getRequest() {
154 return $this->mRequest
;
158 * Get the ApiResult object asscosiated with current request
160 public function getResult() {
161 return $this->mResult
;
165 * This method will simply cause an error if the write mode was disabled for this api.
167 public function requestWriteMode() {
168 if (!$this->mEnableWrite
)
169 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
170 'statement is included in the site\'s LocalSettings.php file', 'noapiwrite');
174 * Set how long the response should be cached.
176 public function setCacheMaxAge($maxage) {
177 $this->mSquidMaxage
= $maxage;
181 * Create an instance of an output formatter by its name
183 public function createPrinterByName($format) {
184 return new $this->mFormats
[$format] ($this, $format);
188 * Execute api request. Any errors will be handled if the API was called by the remote client.
190 public function execute() {
192 if ($this->mInternalMode
)
193 $this->executeAction();
195 $this->executeActionWithErrorHandling();
200 * Execute an action, and in case of an error, erase whatever partial results
201 * have been accumulated, and replace it with an error message and a help screen.
203 protected function executeActionWithErrorHandling() {
205 // In case an error occurs during data output,
206 // clear the output buffer and print just the error information
210 $this->executeAction();
211 } catch (Exception
$e) {
213 // Handle any kind of exception by outputing properly formatted error message.
214 // If this fails, an unhandled exception should be thrown so that global error
215 // handler will process and log it.
218 $errCode = $this->substituteResultWithError($e);
220 // Error results should not be cached
221 $this->setCacheMaxAge(0);
223 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
224 if ($e->getCode() === 0)
225 header($headerStr, true);
227 header($headerStr, true, $e->getCode());
229 // Reset and print just the error message
232 // If the error occured during printing, do a printer->profileOut()
233 $this->mPrinter
->safeProfileOut();
234 $this->printResult(true);
237 // Set the cache expiration at the last moment, as any errors may change the expiration.
238 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
239 $expires = $this->mSquidMaxage
== 0 ?
1 : time() +
$this->mSquidMaxage
;
240 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
241 header('Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0');
243 if($this->mPrinter
->getIsHtml())
250 * Replace the result data with the information about an exception.
251 * Returns the error code
253 protected function substituteResultWithError($e) {
255 // Printer may not be initialized if the extractRequestParams() fails for the main module
256 if (!isset ($this->mPrinter
)) {
257 // The printer has not been created yet. Try to manually get formatter value.
258 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
259 if (!in_array($value, $this->mFormatNames
))
260 $value = self
::API_DEFAULT_FORMAT
;
262 $this->mPrinter
= $this->createPrinterByName($value);
263 if ($this->mPrinter
->getNeedsRawData())
264 $this->getResult()->setRawMode();
267 if ($e instanceof UsageException
) {
269 // User entered incorrect parameters - print usage screen
271 $errMessage = array (
272 'code' => $e->getCodeString(),
273 'info' => $e->getMessage());
275 // Only print the help message when this is for the developer, not runtime
276 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
277 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
281 // Something is seriously wrong
283 $errMessage = array (
284 'code' => 'internal_api_error_'. get_class($e),
285 'info' => "Exception Caught: {$e->getMessage()}"
287 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
290 $this->getResult()->reset();
291 $this->getResult()->addValue(null, 'error', $errMessage);
293 return $errMessage['code'];
297 * Execute the actual module, without any error handling
299 protected function executeAction() {
301 $params = $this->extractRequestParams();
303 $this->mShowVersions
= $params['version'];
304 $this->mAction
= $params['action'];
306 // Instantiate the module requested by the user
307 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
309 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
311 global $wgLoadBalancer, $wgShowHostnames;
312 $maxLag = $params['maxlag'];
313 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
314 if ( $lag > $maxLag ) {
315 if( $wgShowHostnames ) {
316 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
318 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
324 if (!$this->mInternalMode
) {
325 // Ignore mustBePosted() for internal calls
326 if($module->mustBePosted() && !$this->mRequest
->wasPosted())
327 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
329 // See if custom printer is used
330 $this->mPrinter
= $module->getCustomPrinter();
331 if (is_null($this->mPrinter
)) {
332 // Create an appropriate printer
333 $this->mPrinter
= $this->createPrinterByName($params['format']);
336 if ($this->mPrinter
->getNeedsRawData())
337 $this->getResult()->setRawMode();
341 $module->profileIn();
343 $module->profileOut();
345 if (!$this->mInternalMode
) {
347 $this->printResult(false);
352 * Print results using the current printer
354 protected function printResult($isError) {
355 $printer = $this->mPrinter
;
356 $printer->profileIn();
358 /* If the help message is requested in the default (xmlfm) format,
359 * tell the printer not to escape ampersands so that our links do
361 $params = $this->extractRequestParams();
362 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
363 && $params['format'] == ApiMain
::API_DEFAULT_FORMAT
);
365 $printer->initPrinter($isError);
368 $printer->closePrinter();
369 $printer->profileOut();
373 * See ApiBase for description.
375 protected function getAllowedParams() {
378 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
379 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
382 ApiBase
:: PARAM_DFLT
=> 'help',
383 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
387 ApiBase
:: PARAM_TYPE
=> 'integer'
393 * See ApiBase for description.
395 protected function getParamDescription() {
397 'format' => 'The format of the output',
398 'action' => 'What action you would like to perform',
399 'version' => 'When showing help, include version for each module',
400 'maxlag' => 'Maximum lag'
405 * See ApiBase for description.
407 protected function getDescription() {
411 '******************************************************************',
413 '** This is an auto-generated MediaWiki API documentation page **',
415 '** Documentation and Examples: **',
416 '** http://www.mediawiki.org/wiki/API **',
418 '******************************************************************',
420 'Status: All features shown on this page should be working, but the API',
421 ' is still in active development, and may change at any time.',
422 ' Make sure to monitor our mailing list for any updates.',
424 'Documentation: http://www.mediawiki.org/wiki/API',
425 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
426 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
436 * Returns an array of strings with credits for the API
438 protected function getCredits() {
440 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
441 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
446 * Override the parent to generate help messages for all available modules.
448 public function makeHelpMsg() {
450 $this->mPrinter
->setHelp();
452 // Use parent to make default message for the main module
453 $msg = parent
:: makeHelpMsg();
455 $astriks = str_repeat('*** ', 10);
456 $msg .= "\n\n$astriks Modules $astriks\n\n";
457 foreach( $this->mModules
as $moduleName => $unused ) {
458 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
459 $msg .= self
::makeHelpMsgHeader($module, 'action');
460 $msg2 = $module->makeHelpMsg();
466 $msg .= "\n$astriks Formats $astriks\n\n";
467 foreach( $this->mFormats
as $formatName => $unused ) {
468 $module = $this->createPrinterByName($formatName);
469 $msg .= self
::makeHelpMsgHeader($module, 'format');
470 $msg2 = $module->makeHelpMsg();
476 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
482 public static function makeHelpMsgHeader($module, $paramName) {
483 $modulePrefix = $module->getModulePrefix();
484 if (!empty($modulePrefix))
485 $modulePrefix = "($modulePrefix) ";
487 return "* $paramName={$module->getModuleName()} $modulePrefix*";
490 private $mIsBot = null;
491 private $mIsSysop = null;
492 private $mCanApiHighLimits = null;
495 * Returns true if the currently logged in user is a bot, false otherwise
496 * OBSOLETE, use canApiHighLimits() instead
498 public function isBot() {
499 if (!isset ($this->mIsBot
)) {
501 $this->mIsBot
= $wgUser->isAllowed('bot');
503 return $this->mIsBot
;
507 * Similar to isBot(), this method returns true if the logged in user is
508 * a sysop, and false if not.
509 * OBSOLETE, use canApiHighLimits() instead
511 public function isSysop() {
512 if (!isset ($this->mIsSysop
)) {
514 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
517 return $this->mIsSysop
;
520 public function canApiHighLimits() {
521 if (!isset($this->mCanApiHighLimits
)) {
523 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
526 return $this->mCanApiHighLimits
;
529 public function getShowVersions() {
530 return $this->mShowVersions
;
534 * Returns the version information of this file, plus it includes
535 * the versions for all files that are not callable proper API modules
537 public function getVersion() {
539 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
540 $vers[] = __CLASS__
. ': $Id$';
541 $vers[] = ApiBase
:: getBaseVersion();
542 $vers[] = ApiFormatBase
:: getBaseVersion();
543 $vers[] = ApiQueryBase
:: getBaseVersion();
544 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
549 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
550 * classes who wish to add their own modules to their lexicon or override the
551 * behavior of inherent ones.
554 * @param $mdlName String The identifier for this module.
555 * @param $mdlClass String The class where this module is implemented.
557 protected function addModule( $mdlName, $mdlClass ) {
558 $this->mModules
[$mdlName] = $mdlClass;
562 * Add or overwrite an output format for this ApiMain. Intended for use by extending
563 * classes who wish to add to or modify current formatters.
566 * @param $fmtName The identifier for this format.
567 * @param $fmtClass The class implementing this format.
569 protected function addFormat( $fmtName, $fmtClass ) {
570 $this->mFormats
[$fmtName] = $fmtClass;
575 * This exception will be thrown when dieUsage is called to stop module execution.
576 * The exception handling code will print a help screen explaining how this API may be used.
580 class UsageException
extends Exception
{
584 public function __construct($message, $codestr, $code = 0) {
585 parent
:: __construct($message, $code);
586 $this->mCodestr
= $codestr;
588 public function getCodeString() {
589 return $this->mCodestr
;
591 public function __toString() {
592 return "{$this->getCodeString()}: {$this->getMessage()}";