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');
36 * This is the main API class, used for both external and internal processing.
37 * When executed, it will create the requested formatter object,
38 * instantiate and execute an object associated with the needed action,
39 * and use formatter to print results.
40 * In case of an exception, an error message will be printed using the same formatter.
42 * To use API from another application, run it using FauxRequest object, in which
43 * case any internal exceptions will not be handled but passed up to the caller.
44 * After successful execution, use getResult() for the resulting data.
48 class ApiMain
extends ApiBase
{
51 * When no format parameter is given, this format will be used
53 const API_DEFAULT_FORMAT
= 'xmlfm';
56 * List of available modules: action name => module class
58 private static $Modules = array (
59 'login' => 'ApiLogin',
60 'logout' => 'ApiLogout',
61 'query' => 'ApiQuery',
62 'expandtemplates' => 'ApiExpandTemplates',
63 'parse' => 'ApiParse',
64 'opensearch' => 'ApiOpenSearch',
65 'feedwatchlist' => 'ApiFeedWatchlist',
67 'paraminfo' => 'ApiParamInfo',
70 private static $WriteModules = array (
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
78 'edit' => 'ApiEditPage',
82 * List of available formats: format name => format class
84 private static $Formats = array (
85 'json' => 'ApiFormatJson',
86 'jsonfm' => 'ApiFormatJson',
87 'php' => 'ApiFormatPhp',
88 'phpfm' => 'ApiFormatPhp',
89 'wddx' => 'ApiFormatWddx',
90 'wddxfm' => 'ApiFormatWddx',
91 'xml' => 'ApiFormatXml',
92 'xmlfm' => 'ApiFormatXml',
93 'yaml' => 'ApiFormatYaml',
94 'yamlfm' => 'ApiFormatYaml',
95 'rawfm' => 'ApiFormatJson',
96 'txt' => 'ApiFormatTxt',
97 'txtfm' => 'ApiFormatTxt',
98 'dbg' => 'ApiFormatDbg',
99 'dbgfm' => 'ApiFormatDbg'
102 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
103 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
106 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
108 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
109 * @param $enableWrite bool should be set to true if the api may modify data
111 public function __construct($request, $enableWrite = false) {
113 $this->mInternalMode
= ($request instanceof FauxRequest
);
115 // Special handling for the main module: $parent === $this
116 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
118 if (!$this->mInternalMode
) {
120 // Impose module restrictions.
121 // If the current user cannot read,
122 // Remove all modules other than login
125 if( $request->getVal( 'callback' ) !== null ) {
126 // JSON callback allows cross-site reads.
127 // For safety, strip user credentials.
128 wfDebug( "API: stripping user credentials for JSON callback\n" );
129 $wgUser = new User();
132 if (!$wgUser->isAllowed('read')) {
133 self
::$Modules = array(
134 'login' => self
::$Modules['login'],
135 'logout' => self
::$Modules['logout'],
136 'help' => self
::$Modules['help'],
141 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
142 $this->mModules
= $wgAPIModules + self
:: $Modules;
143 if($wgEnableWriteAPI)
144 $this->mModules +
= self
::$WriteModules;
146 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
147 $this->mFormats
= self
:: $Formats;
148 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
150 $this->mResult
= new ApiResult($this);
151 $this->mShowVersions
= false;
152 $this->mEnableWrite
= $enableWrite;
154 $this->mRequest
= & $request;
156 $this->mSquidMaxage
= 0;
157 $this->mCommit
= false;
161 * Return true if the API was started by other PHP code using FauxRequest
163 public function isInternalMode() {
164 return $this->mInternalMode
;
168 * Return the request object that contains client's request
170 public function getRequest() {
171 return $this->mRequest
;
175 * Get the ApiResult object asscosiated with current request
177 public function getResult() {
178 return $this->mResult
;
182 * This method will simply cause an error if the write mode was disabled for this api.
184 public function requestWriteMode() {
185 if (!$this->mEnableWrite
)
186 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
187 'statement is included in the site\'s LocalSettings.php file', 'noapiwrite');
191 * Set how long the response should be cached.
193 public function setCacheMaxAge($maxage) {
194 $this->mSquidMaxage
= $maxage;
198 * Create an instance of an output formatter by its name
200 public function createPrinterByName($format) {
201 return new $this->mFormats
[$format] ($this, $format);
205 * Execute api request. Any errors will be handled if the API was called by the remote client.
207 public function execute() {
209 if ($this->mInternalMode
)
210 $this->executeAction();
212 $this->executeActionWithErrorHandling();
218 * Execute an action, and in case of an error, erase whatever partial results
219 * have been accumulated, and replace it with an error message and a help screen.
221 protected function executeActionWithErrorHandling() {
223 // In case an error occurs during data output,
224 // clear the output buffer and print just the error information
228 $this->executeAction();
229 } catch (Exception
$e) {
231 // Handle any kind of exception by outputing properly formatted error message.
232 // If this fails, an unhandled exception should be thrown so that global error
233 // handler will process and log it.
236 $errCode = $this->substituteResultWithError($e);
238 // Error results should not be cached
239 $this->setCacheMaxAge(0);
241 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
242 if ($e->getCode() === 0)
243 header($headerStr, true);
245 header($headerStr, true, $e->getCode());
247 // Reset and print just the error message
250 // If the error occured during printing, do a printer->profileOut()
251 $this->mPrinter
->safeProfileOut();
252 $this->printResult(true);
255 // Set the cache expiration at the last moment, as any errors may change the expiration.
256 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
257 $expires = $this->mSquidMaxage
== 0 ?
1 : time() +
$this->mSquidMaxage
;
258 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
259 header('Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0');
261 if($this->mPrinter
->getIsHtml())
268 * Replace the result data with the information about an exception.
269 * Returns the error code
271 protected function substituteResultWithError($e) {
273 // Printer may not be initialized if the extractRequestParams() fails for the main module
274 if (!isset ($this->mPrinter
)) {
275 // The printer has not been created yet. Try to manually get formatter value.
276 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
277 if (!in_array($value, $this->mFormatNames
))
278 $value = self
::API_DEFAULT_FORMAT
;
280 $this->mPrinter
= $this->createPrinterByName($value);
281 if ($this->mPrinter
->getNeedsRawData())
282 $this->getResult()->setRawMode();
285 if ($e instanceof UsageException
) {
287 // User entered incorrect parameters - print usage screen
289 $errMessage = array (
290 'code' => $e->getCodeString(),
291 'info' => $e->getMessage());
293 // Only print the help message when this is for the developer, not runtime
294 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
295 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
299 // Something is seriously wrong
301 $errMessage = array (
302 'code' => 'internal_api_error_'. get_class($e),
303 'info' => "Exception Caught: {$e->getMessage()}"
305 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
308 $this->getResult()->reset();
309 $this->getResult()->addValue(null, 'error', $errMessage);
311 return $errMessage['code'];
315 * Execute the actual module, without any error handling
317 protected function executeAction() {
319 $params = $this->extractRequestParams();
321 $this->mShowVersions
= $params['version'];
322 $this->mAction
= $params['action'];
324 // Instantiate the module requested by the user
325 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
327 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
329 global $wgShowHostnames;
330 $maxLag = $params['maxlag'];
331 list( $host, $lag ) = wfGetLB()->getMaxLag();
332 if ( $lag > $maxLag ) {
333 if( $wgShowHostnames ) {
334 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
336 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
342 if (!$this->mInternalMode
) {
343 // Ignore mustBePosted() for internal calls
344 if($module->mustBePosted() && !$this->mRequest
->wasPosted())
345 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
347 // See if custom printer is used
348 $this->mPrinter
= $module->getCustomPrinter();
349 if (is_null($this->mPrinter
)) {
350 // Create an appropriate printer
351 $this->mPrinter
= $this->createPrinterByName($params['format']);
354 if ($this->mPrinter
->getNeedsRawData())
355 $this->getResult()->setRawMode();
359 $module->profileIn();
361 $module->profileOut();
363 if (!$this->mInternalMode
) {
365 $this->printResult(false);
370 * Print results using the current printer
372 protected function printResult($isError) {
373 $printer = $this->mPrinter
;
374 $printer->profileIn();
376 /* If the help message is requested in the default (xmlfm) format,
377 * tell the printer not to escape ampersands so that our links do
379 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
380 && $this->getParameter('format') == ApiMain
::API_DEFAULT_FORMAT
);
382 $printer->initPrinter($isError);
385 $printer->closePrinter();
386 $printer->profileOut();
390 * See ApiBase for description.
392 public function getAllowedParams() {
395 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
396 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
399 ApiBase
:: PARAM_DFLT
=> 'help',
400 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
404 ApiBase
:: PARAM_TYPE
=> 'integer'
410 * See ApiBase for description.
412 public function getParamDescription() {
414 'format' => 'The format of the output',
415 'action' => 'What action you would like to perform',
416 'version' => 'When showing help, include version for each module',
417 'maxlag' => 'Maximum lag'
422 * See ApiBase for description.
424 public function getDescription() {
428 '******************************************************************',
430 '** This is an auto-generated MediaWiki API documentation page **',
432 '** Documentation and Examples: **',
433 '** http://www.mediawiki.org/wiki/API **',
435 '******************************************************************',
437 'Status: All features shown on this page should be working, but the API',
438 ' is still in active development, and may change at any time.',
439 ' Make sure to monitor our mailing list for any updates.',
441 'Documentation: http://www.mediawiki.org/wiki/API',
442 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
443 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
453 * Returns an array of strings with credits for the API
455 protected function getCredits() {
458 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
459 ' Victor Vasiliev - vasilvv at gee mail dot com',
460 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
462 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
463 'or file a bug report at http://bugzilla.wikimedia.org/'
468 * Override the parent to generate help messages for all available modules.
470 public function makeHelpMsg() {
472 $this->mPrinter
->setHelp();
474 // Use parent to make default message for the main module
475 $msg = parent
:: makeHelpMsg();
477 $astriks = str_repeat('*** ', 10);
478 $msg .= "\n\n$astriks Modules $astriks\n\n";
479 foreach( $this->mModules
as $moduleName => $unused ) {
480 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
481 $msg .= self
::makeHelpMsgHeader($module, 'action');
482 $msg2 = $module->makeHelpMsg();
488 $msg .= "\n$astriks Formats $astriks\n\n";
489 foreach( $this->mFormats
as $formatName => $unused ) {
490 $module = $this->createPrinterByName($formatName);
491 $msg .= self
::makeHelpMsgHeader($module, 'format');
492 $msg2 = $module->makeHelpMsg();
498 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
504 public static function makeHelpMsgHeader($module, $paramName) {
505 $modulePrefix = $module->getModulePrefix();
506 if (!empty($modulePrefix))
507 $modulePrefix = "($modulePrefix) ";
509 return "* $paramName={$module->getModuleName()} $modulePrefix*";
512 private $mIsBot = null;
513 private $mIsSysop = null;
514 private $mCanApiHighLimits = null;
517 * Returns true if the currently logged in user is a bot, false otherwise
518 * OBSOLETE, use canApiHighLimits() instead
520 public function isBot() {
521 if (!isset ($this->mIsBot
)) {
523 $this->mIsBot
= $wgUser->isAllowed('bot');
525 return $this->mIsBot
;
529 * Similar to isBot(), this method returns true if the logged in user is
530 * a sysop, and false if not.
531 * OBSOLETE, use canApiHighLimits() instead
533 public function isSysop() {
534 if (!isset ($this->mIsSysop
)) {
536 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
539 return $this->mIsSysop
;
543 * Check whether the current user is allowed to use high limits
546 public function canApiHighLimits() {
547 if (!isset($this->mCanApiHighLimits
)) {
549 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
552 return $this->mCanApiHighLimits
;
556 * Check whether the user wants us to show version information in the API help
559 public function getShowVersions() {
560 return $this->mShowVersions
;
564 * Returns the version information of this file, plus it includes
565 * the versions for all files that are not callable proper API modules
567 public function getVersion() {
569 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
570 $vers[] = __CLASS__
. ': $Id$';
571 $vers[] = ApiBase
:: getBaseVersion();
572 $vers[] = ApiFormatBase
:: getBaseVersion();
573 $vers[] = ApiQueryBase
:: getBaseVersion();
574 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
579 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
580 * classes who wish to add their own modules to their lexicon or override the
581 * behavior of inherent ones.
584 * @param $mdlName String The identifier for this module.
585 * @param $mdlClass String The class where this module is implemented.
587 protected function addModule( $mdlName, $mdlClass ) {
588 $this->mModules
[$mdlName] = $mdlClass;
592 * Add or overwrite an output format for this ApiMain. Intended for use by extending
593 * classes who wish to add to or modify current formatters.
596 * @param $fmtName The identifier for this format.
597 * @param $fmtClass The class implementing this format.
599 protected function addFormat( $fmtName, $fmtClass ) {
600 $this->mFormats
[$fmtName] = $fmtClass;
604 * Get the array mapping module names to class names
606 function getModules() {
607 return $this->mModules
;
612 * This exception will be thrown when dieUsage is called to stop module execution.
613 * The exception handling code will print a help screen explaining how this API may be used.
617 class UsageException
extends Exception
{
621 public function __construct($message, $codestr, $code = 0) {
622 parent
:: __construct($message, $code);
623 $this->mCodestr
= $codestr;
625 public function getCodeString() {
626 return $this->mCodestr
;
628 public function __toString() {
629 return "{$this->getCodeString()}: {$this->getMessage()}";