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',
65 private static $WriteModules = array (
66 'rollback' => 'ApiRollback',
67 'delete' => 'ApiDelete',
68 'undelete' => 'ApiUndelete',
69 'protect' => 'ApiProtect',
70 'block' => 'ApiBlock',
71 'unblock' => 'ApiUnblock',
76 * List of available formats: format name => format class
78 private static $Formats = array (
79 'json' => 'ApiFormatJson',
80 'jsonfm' => 'ApiFormatJson',
81 'php' => 'ApiFormatPhp',
82 'phpfm' => 'ApiFormatPhp',
83 'wddx' => 'ApiFormatWddx',
84 'wddxfm' => 'ApiFormatWddx',
85 'xml' => 'ApiFormatXml',
86 'xmlfm' => 'ApiFormatXml',
87 'yaml' => 'ApiFormatYaml',
88 'yamlfm' => 'ApiFormatYaml',
89 'rawfm' => 'ApiFormatJson'
92 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
93 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
96 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
98 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
99 * @param $enableWrite bool should be set to true if the api may modify data
101 public function __construct($request, $enableWrite = false) {
103 $this->mInternalMode
= ($request instanceof FauxRequest
);
105 // Special handling for the main module: $parent === $this
106 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
108 if (!$this->mInternalMode
) {
110 // Impose module restrictions.
111 // If the current user cannot read,
112 // Remove all modules other than login
114 if (!$wgUser->isAllowed('read')) {
115 self
::$Modules = array(
116 'login' => self
::$Modules['login'],
117 'help' => self
::$Modules['help']
122 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
123 $this->mModules
= $wgAPIModules + self
:: $Modules;
124 if($wgEnableWriteAPI)
125 $this->mModules +
= self
::$WriteModules;
127 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
128 $this->mFormats
= self
:: $Formats;
129 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
131 $this->mResult
= new ApiResult($this);
132 $this->mShowVersions
= false;
133 $this->mEnableWrite
= $enableWrite;
135 $this->mRequest
= & $request;
137 $this->mSquidMaxage
= 0;
141 * Return true if the API was started by other PHP code using FauxRequest
143 public function isInternalMode() {
144 return $this->mInternalMode
;
148 * Return the request object that contains client's request
150 public function getRequest() {
151 return $this->mRequest
;
155 * Get the ApiResult object asscosiated with current request
157 public function getResult() {
158 return $this->mResult
;
162 * This method will simply cause an error if the write mode was disabled for this api.
164 public function requestWriteMode() {
165 if (!$this->mEnableWrite
)
166 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
167 'statement is included in the site\'s LocalSettings.php file', 'noapiwrite');
171 * Set how long the response should be cached.
173 public function setCacheMaxAge($maxage) {
174 $this->mSquidMaxage
= $maxage;
178 * Create an instance of an output formatter by its name
180 public function createPrinterByName($format) {
181 return new $this->mFormats
[$format] ($this, $format);
185 * Execute api request. Any errors will be handled if the API was called by the remote client.
187 public function execute() {
189 if ($this->mInternalMode
)
190 $this->executeAction();
192 $this->executeActionWithErrorHandling();
197 * Execute an action, and in case of an error, erase whatever partial results
198 * have been accumulated, and replace it with an error message and a help screen.
200 protected function executeActionWithErrorHandling() {
202 // In case an error occurs during data output,
203 // clear the output buffer and print just the error information
207 $this->executeAction();
208 } catch (Exception
$e) {
210 // Handle any kind of exception by outputing properly formatted error message.
211 // If this fails, an unhandled exception should be thrown so that global error
212 // handler will process and log it.
215 $errCode = $this->substituteResultWithError($e);
217 // Error results should not be cached
218 $this->setCacheMaxAge(0);
220 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
221 if ($e->getCode() === 0)
222 header($headerStr, true);
224 header($headerStr, true, $e->getCode());
226 // Reset and print just the error message
229 // If the error occured during printing, do a printer->profileOut()
230 $this->mPrinter
->safeProfileOut();
231 $this->printResult(true);
234 // Set the cache expiration at the last moment, as any errors may change the expiration.
235 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
236 $expires = $this->mSquidMaxage
== 0 ?
1 : time() +
$this->mSquidMaxage
;
237 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
238 header('Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0');
240 if($this->mPrinter
->getIsHtml())
247 * Replace the result data with the information about an exception.
248 * Returns the error code
250 protected function substituteResultWithError($e) {
252 // Printer may not be initialized if the extractRequestParams() fails for the main module
253 if (!isset ($this->mPrinter
)) {
254 // The printer has not been created yet. Try to manually get formatter value.
255 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
256 if (!in_array($value, $this->mFormatNames
))
257 $value = self
::API_DEFAULT_FORMAT
;
259 $this->mPrinter
= $this->createPrinterByName($value);
260 if ($this->mPrinter
->getNeedsRawData())
261 $this->getResult()->setRawMode();
264 if ($e instanceof UsageException
) {
266 // User entered incorrect parameters - print usage screen
268 $errMessage = array (
269 'code' => $e->getCodeString(),
270 'info' => $e->getMessage());
272 // Only print the help message when this is for the developer, not runtime
273 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
274 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
278 // Something is seriously wrong
280 $errMessage = array (
281 'code' => 'internal_api_error_'. get_class($e),
282 'info' => "Exception Caught: {$e->getMessage()}"
284 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
287 $this->getResult()->reset();
288 $this->getResult()->addValue(null, 'error', $errMessage);
290 return $errMessage['code'];
294 * Execute the actual module, without any error handling
296 protected function executeAction() {
298 $params = $this->extractRequestParams();
300 $this->mShowVersions
= $params['version'];
301 $this->mAction
= $params['action'];
303 // Instantiate the module requested by the user
304 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
306 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
308 global $wgLoadBalancer, $wgShowHostnames;
309 $maxLag = $params['maxlag'];
310 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
311 if ( $lag > $maxLag ) {
312 if( $wgShowHostnames ) {
313 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
315 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
321 if (!$this->mInternalMode
) {
323 // See if custom printer is used
324 $this->mPrinter
= $module->getCustomPrinter();
325 if (is_null($this->mPrinter
)) {
326 // Create an appropriate printer
327 $this->mPrinter
= $this->createPrinterByName($params['format']);
330 if ($this->mPrinter
->getNeedsRawData())
331 $this->getResult()->setRawMode();
335 $module->profileIn();
337 $module->profileOut();
339 if (!$this->mInternalMode
) {
341 $this->printResult(false);
346 * Print results using the current printer
348 protected function printResult($isError) {
349 $printer = $this->mPrinter
;
350 $printer->profileIn();
352 /* If the help message is requested in the default (xmlfm) format,
353 * tell the printer not to escape ampersands so that our links do
355 $params = $this->extractRequestParams();
356 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
357 && $params['format'] == ApiMain
::API_DEFAULT_FORMAT
);
359 $printer->initPrinter($isError);
362 $printer->closePrinter();
363 $printer->profileOut();
367 * See ApiBase for description.
369 protected function getAllowedParams() {
372 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
373 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
376 ApiBase
:: PARAM_DFLT
=> 'help',
377 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
381 ApiBase
:: PARAM_TYPE
=> 'integer'
387 * See ApiBase for description.
389 protected function getParamDescription() {
391 'format' => 'The format of the output',
392 'action' => 'What action you would like to perform',
393 'version' => 'When showing help, include version for each module',
394 'maxlag' => 'Maximum lag'
399 * See ApiBase for description.
401 protected function getDescription() {
405 '******************************************************************',
407 '** This is an auto-generated MediaWiki API documentation page **',
409 '** Documentation and Examples: **',
410 '** http://www.mediawiki.org/wiki/API **',
412 '******************************************************************',
414 'Status: All features shown on this page should be working, but the API',
415 ' is still in active development, and may change at any time.',
416 ' Make sure to monitor our mailing list for any updates.',
418 'Documentation: http://www.mediawiki.org/wiki/API',
419 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
420 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
430 * Returns an array of strings with credits for the API
432 protected function getCredits() {
434 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
435 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
440 * Override the parent to generate help messages for all available modules.
442 public function makeHelpMsg() {
444 $this->mPrinter
->setHelp();
446 // Use parent to make default message for the main module
447 $msg = parent
:: makeHelpMsg();
449 $astriks = str_repeat('*** ', 10);
450 $msg .= "\n\n$astriks Modules $astriks\n\n";
451 foreach( $this->mModules
as $moduleName => $unused ) {
452 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
453 $msg .= self
::makeHelpMsgHeader($module, 'action');
454 $msg2 = $module->makeHelpMsg();
460 $msg .= "\n$astriks Formats $astriks\n\n";
461 foreach( $this->mFormats
as $formatName => $unused ) {
462 $module = $this->createPrinterByName($formatName);
463 $msg .= self
::makeHelpMsgHeader($module, 'format');
464 $msg2 = $module->makeHelpMsg();
470 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
476 public static function makeHelpMsgHeader($module, $paramName) {
477 $modulePrefix = $module->getModulePrefix();
478 if (!empty($modulePrefix))
479 $modulePrefix = "($modulePrefix) ";
481 return "* $paramName={$module->getModuleName()} $modulePrefix*";
484 private $mIsBot = null;
485 private $mIsSysop = null;
486 private $mCanApiHighLimits = null;
489 * Returns true if the currently logged in user is a bot, false otherwise
490 * OBSOLETE, use canApiHighLimits() instead
492 public function isBot() {
493 if (!isset ($this->mIsBot
)) {
495 $this->mIsBot
= $wgUser->isAllowed('bot');
497 return $this->mIsBot
;
501 * Similar to isBot(), this method returns true if the logged in user is
502 * a sysop, and false if not.
503 * OBSOLETE, use canApiHighLimits() instead
505 public function isSysop() {
506 if (!isset ($this->mIsSysop
)) {
508 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
511 return $this->mIsSysop
;
514 public function canApiHighLimits() {
515 if (!isset($this->mCanApiHighLimits
)) {
517 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
520 return $this->mCanApiHighLimits
;
523 public function getShowVersions() {
524 return $this->mShowVersions
;
528 * Returns the version information of this file, plus it includes
529 * the versions for all files that are not callable proper API modules
531 public function getVersion() {
533 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
534 $vers[] = __CLASS__
. ': $Id$';
535 $vers[] = ApiBase
:: getBaseVersion();
536 $vers[] = ApiFormatBase
:: getBaseVersion();
537 $vers[] = ApiQueryBase
:: getBaseVersion();
538 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
543 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
544 * classes who wish to add their own modules to their lexicon or override the
545 * behavior of inherent ones.
548 * @param $mdlName String The identifier for this module.
549 * @param $mdlClass String The class where this module is implemented.
551 protected function addModule( $mdlName, $mdlClass ) {
552 $this->mModules
[$mdlName] = $mdlClass;
556 * Add or overwrite an output format for this ApiMain. Intended for use by extending
557 * classes who wish to add to or modify current formatters.
560 * @param $fmtName The identifier for this format.
561 * @param $fmtClass The class implementing this format.
563 protected function addFormat( $fmtName, $fmtClass ) {
564 $this->mFormats
[$fmtName] = $fmtClass;
569 * This exception will be thrown when dieUsage is called to stop module execution.
570 * The exception handling code will print a help screen explaining how this API may be used.
574 class UsageException
extends Exception
{
578 public function __construct($message, $codestr, $code = 0) {
579 parent
:: __construct($message, $code);
580 $this->mCodestr
= $codestr;
582 public function getCodeString() {
583 return $this->mCodestr
;
585 public function __toString() {
586 return "{$this->getCodeString()}: {$this->getMessage()}";