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',
79 'emailuser' => 'ApiEmailUser',
83 * List of available formats: format name => format class
85 private static $Formats = array (
86 'json' => 'ApiFormatJson',
87 'jsonfm' => 'ApiFormatJson',
88 'php' => 'ApiFormatPhp',
89 'phpfm' => 'ApiFormatPhp',
90 'wddx' => 'ApiFormatWddx',
91 'wddxfm' => 'ApiFormatWddx',
92 'xml' => 'ApiFormatXml',
93 'xmlfm' => 'ApiFormatXml',
94 'yaml' => 'ApiFormatYaml',
95 'yamlfm' => 'ApiFormatYaml',
96 'rawfm' => 'ApiFormatJson',
97 'txt' => 'ApiFormatTxt',
98 'txtfm' => 'ApiFormatTxt',
99 'dbg' => 'ApiFormatDbg',
100 'dbgfm' => 'ApiFormatDbg'
103 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
104 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
107 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
109 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
110 * @param $enableWrite bool should be set to true if the api may modify data
112 public function __construct($request, $enableWrite = false) {
114 $this->mInternalMode
= ($request instanceof FauxRequest
);
116 // Special handling for the main module: $parent === $this
117 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
119 if (!$this->mInternalMode
) {
121 // Impose module restrictions.
122 // If the current user cannot read,
123 // Remove all modules other than login
126 if( $request->getVal( 'callback' ) !== null ) {
127 // JSON callback allows cross-site reads.
128 // For safety, strip user credentials.
129 wfDebug( "API: stripping user credentials for JSON callback\n" );
130 $wgUser = new User();
133 if (!$wgUser->isAllowed('read')) {
134 self
::$Modules = array(
135 'login' => self
::$Modules['login'],
136 'logout' => self
::$Modules['logout'],
137 'help' => self
::$Modules['help'],
142 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
143 $this->mModules
= $wgAPIModules + self
:: $Modules;
144 if($wgEnableWriteAPI)
145 $this->mModules +
= self
::$WriteModules;
147 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
148 $this->mFormats
= self
:: $Formats;
149 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
151 $this->mResult
= new ApiResult($this);
152 $this->mShowVersions
= false;
153 $this->mEnableWrite
= $enableWrite;
155 $this->mRequest
= & $request;
157 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
158 $this->mCommit
= false;
162 * Return true if the API was started by other PHP code using FauxRequest
164 public function isInternalMode() {
165 return $this->mInternalMode
;
169 * Return the request object that contains client's request
171 public function getRequest() {
172 return $this->mRequest
;
176 * Get the ApiResult object asscosiated with current request
178 public function getResult() {
179 return $this->mResult
;
183 * This method will simply cause an error if the write mode was disabled
184 * or if the current user doesn't have the right to use it
186 public function requestWriteMode() {
188 if (!$this->mEnableWrite
)
189 $this->dieUsage('Editing of this wiki through the API' .
190 ' is disabled. Make sure the $wgEnableWriteAPI=true; ' .
191 'statement is included in the wiki\'s ' .
192 'LocalSettings.php file', 'noapiwrite');
193 if (!$wgUser->isAllowed('writeapi'))
194 $this->dieUsage('You\'re not allowed to edit this ' .
195 'wiki through the API', 'writeapidenied');
199 * Set how long the response should be cached.
201 public function setCacheMaxAge($maxage) {
202 $this->mSquidMaxage
= $maxage;
206 * Create an instance of an output formatter by its name
208 public function createPrinterByName($format) {
209 return new $this->mFormats
[$format] ($this, $format);
213 * Execute api request. Any errors will be handled if the API was called by the remote client.
215 public function execute() {
217 if ($this->mInternalMode
)
218 $this->executeAction();
220 $this->executeActionWithErrorHandling();
226 * Execute an action, and in case of an error, erase whatever partial results
227 * have been accumulated, and replace it with an error message and a help screen.
229 protected function executeActionWithErrorHandling() {
231 // In case an error occurs during data output,
232 // clear the output buffer and print just the error information
236 $this->executeAction();
237 } catch (Exception
$e) {
239 // Handle any kind of exception by outputing properly formatted error message.
240 // If this fails, an unhandled exception should be thrown so that global error
241 // handler will process and log it.
244 $errCode = $this->substituteResultWithError($e);
246 // Error results should not be cached
247 $this->setCacheMaxAge(0);
249 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
250 if ($e->getCode() === 0)
251 header($headerStr, true);
253 header($headerStr, true, $e->getCode());
255 // Reset and print just the error message
258 // If the error occured during printing, do a printer->profileOut()
259 $this->mPrinter
->safeProfileOut();
260 $this->printResult(true);
263 $params = $this->extractRequestParams();
264 if($this->mSquidMaxage
== -1)
266 # Nobody called setCacheMaxAge(), use the (s)maxage parameters
267 $smaxage = $params['smaxage'];
268 $maxage = $params['maxage'];
271 $smaxage = $maxage = $this->mSquidMaxage
;
273 // Set the cache expiration at the last moment, as any errors may change the expiration.
274 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
275 $exp = min($smaxage, $maxage);
276 $expires = ($exp == 0 ?
1 : time() +
$exp);
277 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
278 header('Cache-Control: s-maxage=' . $smaxage . ', must-revalidate, max-age=' . $maxage);
280 if($this->mPrinter
->getIsHtml())
287 * Replace the result data with the information about an exception.
288 * Returns the error code
290 protected function substituteResultWithError($e) {
292 // Printer may not be initialized if the extractRequestParams() fails for the main module
293 if (!isset ($this->mPrinter
)) {
294 // The printer has not been created yet. Try to manually get formatter value.
295 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
296 if (!in_array($value, $this->mFormatNames
))
297 $value = self
::API_DEFAULT_FORMAT
;
299 $this->mPrinter
= $this->createPrinterByName($value);
300 if ($this->mPrinter
->getNeedsRawData())
301 $this->getResult()->setRawMode();
304 if ($e instanceof UsageException
) {
306 // User entered incorrect parameters - print usage screen
308 $errMessage = array (
309 'code' => $e->getCodeString(),
310 'info' => $e->getMessage());
312 // Only print the help message when this is for the developer, not runtime
313 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
314 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
317 global $wgShowSQLErrors, $wgShowExceptionDetails;
319 // Something is seriously wrong
321 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
322 $info = "Database query error";
324 $info = "Exception Caught: {$e->getMessage()}";
327 $errMessage = array (
328 'code' => 'internal_api_error_'. get_class($e),
331 ApiResult
:: setContent($errMessage, $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : "" );
334 $this->getResult()->reset();
335 $this->getResult()->addValue(null, 'error', $errMessage);
337 return $errMessage['code'];
341 * Execute the actual module, without any error handling
343 protected function executeAction() {
345 $params = $this->extractRequestParams();
347 $this->mShowVersions
= $params['version'];
348 $this->mAction
= $params['action'];
350 // Instantiate the module requested by the user
351 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
353 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
355 global $wgShowHostnames;
356 $maxLag = $params['maxlag'];
357 list( $host, $lag ) = wfGetLB()->getMaxLag();
358 if ( $lag > $maxLag ) {
359 if( $wgShowHostnames ) {
360 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
362 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
368 if (!$this->mInternalMode
) {
369 // Ignore mustBePosted() for internal calls
370 if($module->mustBePosted() && !$this->mRequest
->wasPosted())
371 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
373 // See if custom printer is used
374 $this->mPrinter
= $module->getCustomPrinter();
375 if (is_null($this->mPrinter
)) {
376 // Create an appropriate printer
377 $this->mPrinter
= $this->createPrinterByName($params['format']);
380 if ($this->mPrinter
->getNeedsRawData())
381 $this->getResult()->setRawMode();
385 $module->profileIn();
387 $module->profileOut();
389 if (!$this->mInternalMode
) {
391 $this->printResult(false);
396 * Print results using the current printer
398 protected function printResult($isError) {
399 $printer = $this->mPrinter
;
400 $printer->profileIn();
402 /* If the help message is requested in the default (xmlfm) format,
403 * tell the printer not to escape ampersands so that our links do
405 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
406 && $this->getParameter('format') == ApiMain
::API_DEFAULT_FORMAT
);
408 $printer->initPrinter($isError);
411 $printer->closePrinter();
412 $printer->profileOut();
416 * See ApiBase for description.
418 public function getAllowedParams() {
421 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
422 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
425 ApiBase
:: PARAM_DFLT
=> 'help',
426 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
430 ApiBase
:: PARAM_TYPE
=> 'integer'
433 ApiBase
:: PARAM_TYPE
=> 'integer',
434 ApiBase
:: PARAM_DFLT
=> 0
437 ApiBase
:: PARAM_TYPE
=> 'integer',
438 ApiBase
:: PARAM_DFLT
=> 0
444 * See ApiBase for description.
446 public function getParamDescription() {
448 'format' => 'The format of the output',
449 'action' => 'What action you would like to perform',
450 'version' => 'When showing help, include version for each module',
451 'maxlag' => 'Maximum lag',
452 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
453 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
458 * See ApiBase for description.
460 public function getDescription() {
464 '******************************************************************',
466 '** This is an auto-generated MediaWiki API documentation page **',
468 '** Documentation and Examples: **',
469 '** http://www.mediawiki.org/wiki/API **',
471 '******************************************************************',
473 'Status: All features shown on this page should be working, but the API',
474 ' is still in active development, and may change at any time.',
475 ' Make sure to monitor our mailing list for any updates.',
477 'Documentation: http://www.mediawiki.org/wiki/API',
478 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
479 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
489 * Returns an array of strings with credits for the API
491 protected function getCredits() {
494 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
495 ' Victor Vasiliev - vasilvv at gee mail dot com',
496 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
498 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
499 'or file a bug report at http://bugzilla.wikimedia.org/'
504 * Override the parent to generate help messages for all available modules.
506 public function makeHelpMsg() {
508 $this->mPrinter
->setHelp();
510 // Use parent to make default message for the main module
511 $msg = parent
:: makeHelpMsg();
513 $astriks = str_repeat('*** ', 10);
514 $msg .= "\n\n$astriks Modules $astriks\n\n";
515 foreach( $this->mModules
as $moduleName => $unused ) {
516 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
517 $msg .= self
::makeHelpMsgHeader($module, 'action');
518 $msg2 = $module->makeHelpMsg();
524 $msg .= "\n$astriks Formats $astriks\n\n";
525 foreach( $this->mFormats
as $formatName => $unused ) {
526 $module = $this->createPrinterByName($formatName);
527 $msg .= self
::makeHelpMsgHeader($module, 'format');
528 $msg2 = $module->makeHelpMsg();
534 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
540 public static function makeHelpMsgHeader($module, $paramName) {
541 $modulePrefix = $module->getModulePrefix();
542 if (!empty($modulePrefix))
543 $modulePrefix = "($modulePrefix) ";
545 return "* $paramName={$module->getModuleName()} $modulePrefix*";
548 private $mIsBot = null;
549 private $mIsSysop = null;
550 private $mCanApiHighLimits = null;
553 * Returns true if the currently logged in user is a bot, false otherwise
554 * OBSOLETE, use canApiHighLimits() instead
556 public function isBot() {
557 if (!isset ($this->mIsBot
)) {
559 $this->mIsBot
= $wgUser->isAllowed('bot');
561 return $this->mIsBot
;
565 * Similar to isBot(), this method returns true if the logged in user is
566 * a sysop, and false if not.
567 * OBSOLETE, use canApiHighLimits() instead
569 public function isSysop() {
570 if (!isset ($this->mIsSysop
)) {
572 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
575 return $this->mIsSysop
;
579 * Check whether the current user is allowed to use high limits
582 public function canApiHighLimits() {
583 if (!isset($this->mCanApiHighLimits
)) {
585 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
588 return $this->mCanApiHighLimits
;
592 * Check whether the user wants us to show version information in the API help
595 public function getShowVersions() {
596 return $this->mShowVersions
;
600 * Returns the version information of this file, plus it includes
601 * the versions for all files that are not callable proper API modules
603 public function getVersion() {
605 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
606 $vers[] = __CLASS__
. ': $Id$';
607 $vers[] = ApiBase
:: getBaseVersion();
608 $vers[] = ApiFormatBase
:: getBaseVersion();
609 $vers[] = ApiQueryBase
:: getBaseVersion();
610 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
615 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
616 * classes who wish to add their own modules to their lexicon or override the
617 * behavior of inherent ones.
620 * @param $mdlName String The identifier for this module.
621 * @param $mdlClass String The class where this module is implemented.
623 protected function addModule( $mdlName, $mdlClass ) {
624 $this->mModules
[$mdlName] = $mdlClass;
628 * Add or overwrite an output format for this ApiMain. Intended for use by extending
629 * classes who wish to add to or modify current formatters.
632 * @param $fmtName The identifier for this format.
633 * @param $fmtClass The class implementing this format.
635 protected function addFormat( $fmtName, $fmtClass ) {
636 $this->mFormats
[$fmtName] = $fmtClass;
640 * Get the array mapping module names to class names
642 function getModules() {
643 return $this->mModules
;
648 * This exception will be thrown when dieUsage is called to stop module execution.
649 * The exception handling code will print a help screen explaining how this API may be used.
653 class UsageException
extends Exception
{
657 public function __construct($message, $codestr, $code = 0) {
658 parent
:: __construct($message, $code);
659 $this->mCodestr
= $codestr;
661 public function getCodeString() {
662 return $this->mCodestr
;
664 public function __toString() {
665 return "{$this->getCodeString()}: {$this->getMessage()}";