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 'expandtemplates' => 'ApiExpandTemplates',
58 'render' => 'ApiRender',
59 'parse' => 'ApiParse',
60 'opensearch' => 'ApiOpenSearch',
61 'feedwatchlist' => 'ApiFeedWatchlist',
66 * List of available formats: format name => format class
68 private static $Formats = array (
69 'json' => 'ApiFormatJson',
70 'jsonfm' => 'ApiFormatJson',
71 'php' => 'ApiFormatPhp',
72 'phpfm' => 'ApiFormatPhp',
73 'wddx' => 'ApiFormatWddx',
74 'wddxfm' => 'ApiFormatWddx',
75 'xml' => 'ApiFormatXml',
76 'xmlfm' => 'ApiFormatXml',
77 'yaml' => 'ApiFormatYaml',
78 'yamlfm' => 'ApiFormatYaml',
79 'rawfm' => 'ApiFormatJson'
82 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
83 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
86 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
88 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
89 * @param $enableWrite bool should be set to true if the api may modify data
91 public function __construct($request, $enableWrite = false) {
93 $this->mInternalMode
= ($request instanceof FauxRequest
);
95 // Special handling for the main module: $parent === $this
96 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
98 if (!$this->mInternalMode
) {
100 // Impose module restrictions.
101 // If the current user cannot read,
102 // Remove all modules other than login
104 if (!$wgUser->isAllowed('read')) {
105 self
::$Modules = array(
106 'login' => self
::$Modules['login'],
107 'help' => self
::$Modules['help']
112 global $wgAPIModules; // extension modules
113 $this->mModules
= $wgAPIModules + self
:: $Modules;
115 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
116 $this->mFormats
= self
:: $Formats;
117 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
119 $this->mResult
= new ApiResult($this);
120 $this->mShowVersions
= false;
121 $this->mEnableWrite
= $enableWrite;
123 $this->mRequest
= & $request;
125 $this->mSquidMaxage
= 0;
129 * Return true if the API was started by other PHP code using FauxRequest
131 public function isInternalMode() {
132 return $this->mInternalMode
;
136 * Return the request object that contains client's request
138 public function getRequest() {
139 return $this->mRequest
;
143 * Get the ApiResult object asscosiated with current request
145 public function getResult() {
146 return $this->mResult
;
150 * This method will simply cause an error if the write mode was disabled for this api.
152 public function requestWriteMode() {
153 if (!$this->mEnableWrite
)
154 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
155 'statement is included in the site\'s LocalSettings.php file', 'readonly');
159 * Set how long the response should be cached.
161 public function setCacheMaxAge($maxage) {
162 $this->mSquidMaxage
= $maxage;
166 * Create an instance of an output formatter by its name
168 public function createPrinterByName($format) {
169 return new $this->mFormats
[$format] ($this, $format);
173 * Execute api request. Any errors will be handled if the API was called by the remote client.
175 public function execute() {
177 if ($this->mInternalMode
)
178 $this->executeAction();
180 $this->executeActionWithErrorHandling();
185 * Execute an action, and in case of an error, erase whatever partial results
186 * have been accumulated, and replace it with an error message and a help screen.
188 protected function executeActionWithErrorHandling() {
190 // In case an error occurs during data output,
191 // clear the output buffer and print just the error information
195 $this->executeAction();
196 } catch (Exception
$e) {
198 // Handle any kind of exception by outputing properly formatted error message.
199 // If this fails, an unhandled exception should be thrown so that global error
200 // handler will process and log it.
203 $errCode = $this->substituteResultWithError($e);
205 // Error results should not be cached
206 $this->setCacheMaxAge(0);
208 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
209 if ($e->getCode() === 0)
210 header($headerStr, true);
212 header($headerStr, true, $e->getCode());
214 // Reset and print just the error message
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 * Replace the result data with the information about an exception.
236 * Returns the error code
238 protected function substituteResultWithError($e) {
240 // Printer may not be initialized if the extractRequestParams() fails for the main module
241 if (!isset ($this->mPrinter
)) {
242 // The printer has not been created yet. Try to manually get formatter value.
243 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
244 if (!in_array($value, $this->mFormatNames
))
245 $value = self
::API_DEFAULT_FORMAT
;
247 $this->mPrinter
= $this->createPrinterByName($value);
248 if ($this->mPrinter
->getNeedsRawData())
249 $this->getResult()->setRawMode();
252 if ($e instanceof UsageException
) {
254 // User entered incorrect parameters - print usage screen
256 $errMessage = array (
257 'code' => $e->getCodeString(),
258 'info' => $e->getMessage());
260 // Only print the help message when this is for the developer, not runtime
261 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
262 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
266 // Something is seriously wrong
268 $errMessage = array (
269 'code' => 'internal_api_error_'. get_class($e),
270 'info' => "Exception Caught: {$e->getMessage()}"
272 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
275 $this->getResult()->reset();
276 $this->getResult()->addValue(null, 'error', $errMessage);
278 return $errMessage['code'];
282 * Execute the actual module, without any error handling
284 protected function executeAction() {
286 $params = $this->extractRequestParams();
288 $this->mShowVersions
= $params['version'];
289 $this->mAction
= $params['action'];
291 // Instantiate the module requested by the user
292 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
294 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
296 global $wgLoadBalancer, $wgShowHostnames;
297 $maxLag = $params['maxlag'];
298 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
299 if ( $lag > $maxLag ) {
300 if( $wgShowHostnames ) {
301 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
303 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
309 if (!$this->mInternalMode
) {
311 // See if custom printer is used
312 $this->mPrinter
= $module->getCustomPrinter();
313 if (is_null($this->mPrinter
)) {
314 // Create an appropriate printer
315 $this->mPrinter
= $this->createPrinterByName($params['format']);
318 if ($this->mPrinter
->getNeedsRawData())
319 $this->getResult()->setRawMode();
321 if( $this->mAction
== 'help' )
322 $this->mPrinter
->setHelp();
326 $module->profileIn();
328 $module->profileOut();
330 if (!$this->mInternalMode
) {
332 $this->printResult(false);
337 * Print results using the current printer
339 protected function printResult($isError) {
340 $printer = $this->mPrinter
;
341 $printer->profileIn();
343 /* If the help message is requested in the default (xmlfm) format,
344 * tell the printer not to escape ampersands so that our links do
346 $params = $this->extractRequestParams();
347 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
348 && $params['format'] == ApiMain
::API_DEFAULT_FORMAT
);
350 $printer->initPrinter($isError);
353 $printer->closePrinter();
354 $printer->profileOut();
358 * See ApiBase for description.
360 protected function getAllowedParams() {
363 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
364 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
367 ApiBase
:: PARAM_DFLT
=> 'help',
368 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
372 ApiBase
:: PARAM_TYPE
=> 'integer'
378 * See ApiBase for description.
380 protected function getParamDescription() {
382 'format' => 'The format of the output',
383 'action' => 'What action you would like to perform',
384 'version' => 'When showing help, include version for each module',
385 'maxlag' => 'Maximum lag'
390 * See ApiBase for description.
392 protected function getDescription() {
396 '******************************************************************',
398 '** This is an auto-generated MediaWiki API documentation page **',
400 '** Documentation and Examples: **',
401 '** http://www.mediawiki.org/wiki/API **',
403 '******************************************************************',
405 'Status: All features shown on this page should be working, but the API',
406 ' is still in active development, and may change at any time.',
407 ' Make sure to monitor our mailing list for any updates.',
409 'Documentation: http://www.mediawiki.org/wiki/API',
410 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
411 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
421 * Returns an array of strings with credits for the API
423 protected function getCredits() {
425 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
426 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
431 * Override the parent to generate help messages for all available modules.
433 public function makeHelpMsg() {
435 // Use parent to make default message for the main module
436 $msg = parent
:: makeHelpMsg();
438 $astriks = str_repeat('*** ', 10);
439 $msg .= "\n\n$astriks Modules $astriks\n\n";
440 foreach( $this->mModules
as $moduleName => $unused ) {
441 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
442 $msg .= self
::makeHelpMsgHeader($module, 'action');
443 $msg2 = $module->makeHelpMsg();
449 $msg .= "\n$astriks Formats $astriks\n\n";
450 foreach( $this->mFormats
as $formatName => $unused ) {
451 $module = $this->createPrinterByName($formatName);
452 $msg .= self
::makeHelpMsgHeader($module, 'format');
453 $msg2 = $module->makeHelpMsg();
459 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
465 public static function makeHelpMsgHeader($module, $paramName) {
466 $modulePrefix = $module->getModulePrefix();
467 if (!empty($modulePrefix))
468 $modulePrefix = "($modulePrefix) ";
470 return "* $paramName={$module->getModuleName()} $modulePrefix*";
473 private $mIsBot = null;
474 private $mIsSysop = null;
475 private $mCanApiHighLimits = null;
478 * Returns true if the currently logged in user is a bot, false otherwise
479 * OBSOLETE, use canApiHighLimits() instead
481 public function isBot() {
482 if (!isset ($this->mIsBot
)) {
484 $this->mIsBot
= $wgUser->isAllowed('bot');
486 return $this->mIsBot
;
490 * Similar to isBot(), this method returns true if the logged in user is
491 * a sysop, and false if not.
492 * OBSOLETE, use canApiHighLimits() instead
494 public function isSysop() {
495 if (!isset ($this->mIsSysop
)) {
497 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
500 return $this->mIsSysop
;
503 public function canApiHighLimits() {
504 if (!isset($this->mCanApiHighLimits
)) {
506 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
509 return $this->mCanApiHighLimits
;
512 public function getShowVersions() {
513 return $this->mShowVersions
;
517 * Returns the version information of this file, plus it includes
518 * the versions for all files that are not callable proper API modules
520 public function getVersion() {
522 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
523 $vers[] = __CLASS__
. ': $Id$';
524 $vers[] = ApiBase
:: getBaseVersion();
525 $vers[] = ApiFormatBase
:: getBaseVersion();
526 $vers[] = ApiQueryBase
:: getBaseVersion();
527 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
532 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
533 * classes who wish to add their own modules to their lexicon or override the
534 * behavior of inherent ones.
537 * @param $mdlName String The identifier for this module.
538 * @param $mdlClass String The class where this module is implemented.
540 protected function addModule( $mdlName, $mdlClass ) {
541 $this->mModules
[$mdlName] = $mdlClass;
545 * Add or overwrite an output format for this ApiMain. Intended for use by extending
546 * classes who wish to add to or modify current formatters.
549 * @param $fmtName The identifier for this format.
550 * @param $fmtClass The class implementing this format.
552 protected function addFormat( $fmtName, $fmtClass ) {
553 $this->mFormats
[$fmtName] = $fmtClass;
558 * This exception will be thrown when dieUsage is called to stop module execution.
559 * The exception handling code will print a help screen explaining how this API may be used.
563 class UsageException
extends Exception
{
567 public function __construct($message, $codestr, $code = 0) {
568 parent
:: __construct($message, $code);
569 $this->mCodestr
= $codestr;
571 public function getCodeString() {
572 return $this->mCodestr
;
574 public function __toString() {
575 return "{$this->getCodeString()}: {$this->getMessage()}";