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',
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 'help' => self
::$Modules['help']
124 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
125 $this->mModules
= $wgAPIModules + self
:: $Modules;
126 if($wgEnableWriteAPI)
127 $this->mModules +
= self
::$WriteModules;
129 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
130 $this->mFormats
= self
:: $Formats;
131 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
133 $this->mResult
= new ApiResult($this);
134 $this->mShowVersions
= false;
135 $this->mEnableWrite
= $enableWrite;
137 $this->mRequest
= & $request;
139 $this->mSquidMaxage
= 0;
143 * Return true if the API was started by other PHP code using FauxRequest
145 public function isInternalMode() {
146 return $this->mInternalMode
;
150 * Return the request object that contains client's request
152 public function getRequest() {
153 return $this->mRequest
;
157 * Get the ApiResult object asscosiated with current request
159 public function getResult() {
160 return $this->mResult
;
164 * This method will simply cause an error if the write mode was disabled for this api.
166 public function requestWriteMode() {
167 if (!$this->mEnableWrite
)
168 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
169 'statement is included in the site\'s LocalSettings.php file', 'noapiwrite');
173 * Set how long the response should be cached.
175 public function setCacheMaxAge($maxage) {
176 $this->mSquidMaxage
= $maxage;
180 * Create an instance of an output formatter by its name
182 public function createPrinterByName($format) {
183 return new $this->mFormats
[$format] ($this, $format);
187 * Execute api request. Any errors will be handled if the API was called by the remote client.
189 public function execute() {
191 if ($this->mInternalMode
)
192 $this->executeAction();
194 $this->executeActionWithErrorHandling();
199 * Execute an action, and in case of an error, erase whatever partial results
200 * have been accumulated, and replace it with an error message and a help screen.
202 protected function executeActionWithErrorHandling() {
204 // In case an error occurs during data output,
205 // clear the output buffer and print just the error information
209 $this->executeAction();
210 } catch (Exception
$e) {
212 // Handle any kind of exception by outputing properly formatted error message.
213 // If this fails, an unhandled exception should be thrown so that global error
214 // handler will process and log it.
217 $errCode = $this->substituteResultWithError($e);
219 // Error results should not be cached
220 $this->setCacheMaxAge(0);
222 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
223 if ($e->getCode() === 0)
224 header($headerStr, true);
226 header($headerStr, true, $e->getCode());
228 // Reset and print just the error message
231 // If the error occured during printing, do a printer->profileOut()
232 $this->mPrinter
->safeProfileOut();
233 $this->printResult(true);
236 // Set the cache expiration at the last moment, as any errors may change the expiration.
237 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
238 $expires = $this->mSquidMaxage
== 0 ?
1 : time() +
$this->mSquidMaxage
;
239 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
240 header('Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0');
242 if($this->mPrinter
->getIsHtml())
249 * Replace the result data with the information about an exception.
250 * Returns the error code
252 protected function substituteResultWithError($e) {
254 // Printer may not be initialized if the extractRequestParams() fails for the main module
255 if (!isset ($this->mPrinter
)) {
256 // The printer has not been created yet. Try to manually get formatter value.
257 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
258 if (!in_array($value, $this->mFormatNames
))
259 $value = self
::API_DEFAULT_FORMAT
;
261 $this->mPrinter
= $this->createPrinterByName($value);
262 if ($this->mPrinter
->getNeedsRawData())
263 $this->getResult()->setRawMode();
266 if ($e instanceof UsageException
) {
268 // User entered incorrect parameters - print usage screen
270 $errMessage = array (
271 'code' => $e->getCodeString(),
272 'info' => $e->getMessage());
274 // Only print the help message when this is for the developer, not runtime
275 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
276 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
280 // Something is seriously wrong
282 $errMessage = array (
283 'code' => 'internal_api_error_'. get_class($e),
284 'info' => "Exception Caught: {$e->getMessage()}"
286 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
289 $this->getResult()->reset();
290 $this->getResult()->addValue(null, 'error', $errMessage);
292 return $errMessage['code'];
296 * Execute the actual module, without any error handling
298 protected function executeAction() {
300 $params = $this->extractRequestParams();
302 $this->mShowVersions
= $params['version'];
303 $this->mAction
= $params['action'];
305 // Instantiate the module requested by the user
306 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
308 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
310 global $wgLoadBalancer, $wgShowHostnames;
311 $maxLag = $params['maxlag'];
312 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
313 if ( $lag > $maxLag ) {
314 if( $wgShowHostnames ) {
315 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
317 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
323 if (!$this->mInternalMode
) {
325 // See if custom printer is used
326 $this->mPrinter
= $module->getCustomPrinter();
327 if (is_null($this->mPrinter
)) {
328 // Create an appropriate printer
329 $this->mPrinter
= $this->createPrinterByName($params['format']);
332 if ($this->mPrinter
->getNeedsRawData())
333 $this->getResult()->setRawMode();
337 $module->profileIn();
339 $module->profileOut();
341 if (!$this->mInternalMode
) {
343 $this->printResult(false);
348 * Print results using the current printer
350 protected function printResult($isError) {
351 $printer = $this->mPrinter
;
352 $printer->profileIn();
354 /* If the help message is requested in the default (xmlfm) format,
355 * tell the printer not to escape ampersands so that our links do
357 $params = $this->extractRequestParams();
358 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
359 && $params['format'] == ApiMain
::API_DEFAULT_FORMAT
);
361 $printer->initPrinter($isError);
364 $printer->closePrinter();
365 $printer->profileOut();
369 * See ApiBase for description.
371 protected function getAllowedParams() {
374 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
375 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
378 ApiBase
:: PARAM_DFLT
=> 'help',
379 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
383 ApiBase
:: PARAM_TYPE
=> 'integer'
389 * See ApiBase for description.
391 protected function getParamDescription() {
393 'format' => 'The format of the output',
394 'action' => 'What action you would like to perform',
395 'version' => 'When showing help, include version for each module',
396 'maxlag' => 'Maximum lag'
401 * See ApiBase for description.
403 protected function getDescription() {
407 '******************************************************************',
409 '** This is an auto-generated MediaWiki API documentation page **',
411 '** Documentation and Examples: **',
412 '** http://www.mediawiki.org/wiki/API **',
414 '******************************************************************',
416 'Status: All features shown on this page should be working, but the API',
417 ' is still in active development, and may change at any time.',
418 ' Make sure to monitor our mailing list for any updates.',
420 'Documentation: http://www.mediawiki.org/wiki/API',
421 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
422 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
432 * Returns an array of strings with credits for the API
434 protected function getCredits() {
436 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
437 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
442 * Override the parent to generate help messages for all available modules.
444 public function makeHelpMsg() {
446 $this->mPrinter
->setHelp();
448 // Use parent to make default message for the main module
449 $msg = parent
:: makeHelpMsg();
451 $astriks = str_repeat('*** ', 10);
452 $msg .= "\n\n$astriks Modules $astriks\n\n";
453 foreach( $this->mModules
as $moduleName => $unused ) {
454 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
455 $msg .= self
::makeHelpMsgHeader($module, 'action');
456 $msg2 = $module->makeHelpMsg();
462 $msg .= "\n$astriks Formats $astriks\n\n";
463 foreach( $this->mFormats
as $formatName => $unused ) {
464 $module = $this->createPrinterByName($formatName);
465 $msg .= self
::makeHelpMsgHeader($module, 'format');
466 $msg2 = $module->makeHelpMsg();
472 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
478 public static function makeHelpMsgHeader($module, $paramName) {
479 $modulePrefix = $module->getModulePrefix();
480 if (!empty($modulePrefix))
481 $modulePrefix = "($modulePrefix) ";
483 return "* $paramName={$module->getModuleName()} $modulePrefix*";
486 private $mIsBot = null;
487 private $mIsSysop = null;
488 private $mCanApiHighLimits = null;
491 * Returns true if the currently logged in user is a bot, false otherwise
492 * OBSOLETE, use canApiHighLimits() instead
494 public function isBot() {
495 if (!isset ($this->mIsBot
)) {
497 $this->mIsBot
= $wgUser->isAllowed('bot');
499 return $this->mIsBot
;
503 * Similar to isBot(), this method returns true if the logged in user is
504 * a sysop, and false if not.
505 * OBSOLETE, use canApiHighLimits() instead
507 public function isSysop() {
508 if (!isset ($this->mIsSysop
)) {
510 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
513 return $this->mIsSysop
;
516 public function canApiHighLimits() {
517 if (!isset($this->mCanApiHighLimits
)) {
519 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
522 return $this->mCanApiHighLimits
;
525 public function getShowVersions() {
526 return $this->mShowVersions
;
530 * Returns the version information of this file, plus it includes
531 * the versions for all files that are not callable proper API modules
533 public function getVersion() {
535 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
536 $vers[] = __CLASS__
. ': $Id$';
537 $vers[] = ApiBase
:: getBaseVersion();
538 $vers[] = ApiFormatBase
:: getBaseVersion();
539 $vers[] = ApiQueryBase
:: getBaseVersion();
540 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
545 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
546 * classes who wish to add their own modules to their lexicon or override the
547 * behavior of inherent ones.
550 * @param $mdlName String The identifier for this module.
551 * @param $mdlClass String The class where this module is implemented.
553 protected function addModule( $mdlName, $mdlClass ) {
554 $this->mModules
[$mdlName] = $mdlClass;
558 * Add or overwrite an output format for this ApiMain. Intended for use by extending
559 * classes who wish to add to or modify current formatters.
562 * @param $fmtName The identifier for this format.
563 * @param $fmtClass The class implementing this format.
565 protected function addFormat( $fmtName, $fmtClass ) {
566 $this->mFormats
[$fmtName] = $fmtClass;
571 * This exception will be thrown when dieUsage is called to stop module execution.
572 * The exception handling code will print a help screen explaining how this API may be used.
576 class UsageException
extends Exception
{
580 public function __construct($message, $codestr, $code = 0) {
581 parent
:: __construct($message, $code);
582 $this->mCodestr
= $codestr;
584 public function getCodeString() {
585 return $this->mCodestr
;
587 public function __toString() {
588 return "{$this->getCodeString()}: {$this->getMessage()}";