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 'opensearch' => 'ApiOpenSearch',
60 'feedwatchlist' => 'ApiFeedWatchlist',
65 * List of available formats: format name => format class
67 private static $Formats = array (
68 'json' => 'ApiFormatJson',
69 'jsonfm' => 'ApiFormatJson',
70 'php' => 'ApiFormatPhp',
71 'phpfm' => 'ApiFormatPhp',
72 'wddx' => 'ApiFormatWddx',
73 'wddxfm' => 'ApiFormatWddx',
74 'xml' => 'ApiFormatXml',
75 'xmlfm' => 'ApiFormatXml',
76 'yaml' => 'ApiFormatYaml',
77 'yamlfm' => 'ApiFormatYaml',
78 'raw' => 'ApiFormatRaw',
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 (!$this->mInternalMode
) {
296 //Check usage of raw printer
297 if( $params['format'] == 'raw' ) {
298 if( !$module->supportRaw() ) {
299 ApiBase
:: dieUsage( 'This module doesn\'t support format=raw', 'rawnotsupported' );
305 // See if custom printer is used
306 $this->mPrinter
= $module->getCustomPrinter();
307 if (is_null($this->mPrinter
)) {
308 // Create an appropriate printer
309 $this->mPrinter
= $this->createPrinterByName($params['format']);
312 if ($this->mPrinter
->getNeedsRawData())
313 $this->getResult()->setRawMode();
317 $module->profileIn();
319 $module->profileOut();
321 if (!$this->mInternalMode
) {
323 $this->printResult(false);
328 * Print results using the current printer
330 protected function printResult($isError) {
331 $printer = $this->mPrinter
;
332 $printer->profileIn();
334 /* If the help message is requested in the default (xmlfm) format,
335 * tell the printer not to escape ampersands so that our links do
337 $params = $this->extractRequestParams();
338 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
339 && $params['format'] == ApiMain
::API_DEFAULT_FORMAT
);
341 $printer->initPrinter($isError);
344 $printer->closePrinter();
345 $printer->profileOut();
349 * See ApiBase for description.
351 protected function getAllowedParams() {
354 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
355 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
358 ApiBase
:: PARAM_DFLT
=> 'help',
359 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
366 * See ApiBase for description.
368 protected function getParamDescription() {
370 'format' => 'The format of the output',
371 'action' => 'What action you would like to perform',
372 'version' => 'When showing help, include version for each module'
377 * See ApiBase for description.
379 protected function getDescription() {
383 '******************************************************************',
385 '** This is an auto-generated MediaWiki API documentation page **',
387 '** Documentation and Examples: **',
388 '** http://www.mediawiki.org/wiki/API **',
390 '******************************************************************',
392 'Status: All features shown on this page should be working, but the API',
393 ' is still in active development, and may change at any time.',
394 ' Make sure to monitor our mailing list for any updates.',
396 'Documentation: http://www.mediawiki.org/wiki/API',
397 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
398 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
408 * Returns an array of strings with credits for the API
410 protected function getCredits() {
412 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
413 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
418 * Override the parent to generate help messages for all available modules.
420 public function makeHelpMsg() {
422 // Use parent to make default message for the main module
423 $msg = parent
:: makeHelpMsg();
425 $astriks = str_repeat('*** ', 10);
426 $msg .= "\n\n$astriks Modules $astriks\n\n";
427 foreach( $this->mModules
as $moduleName => $unused ) {
428 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
429 $msg .= self
::makeHelpMsgHeader($module, 'action');
430 $msg2 = $module->makeHelpMsg();
436 $msg .= "\n$astriks Formats $astriks\n\n";
437 foreach( $this->mFormats
as $formatName => $unused ) {
438 $module = $this->createPrinterByName($formatName);
439 $msg .= self
::makeHelpMsgHeader($module, 'format');
440 $msg2 = $module->makeHelpMsg();
446 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
452 public static function makeHelpMsgHeader($module, $paramName) {
453 $modulePrefix = $module->getModulePrefix();
454 if (!empty($modulePrefix))
455 $modulePrefix = "($modulePrefix) ";
457 return "* $paramName={$module->getModuleName()} $modulePrefix*";
460 private $mIsBot = null;
462 private $mIsSysop = null;
465 * Returns true if the currently logged in user is a bot, false otherwise
467 public function isBot() {
468 if (!isset ($this->mIsBot
)) {
470 $this->mIsBot
= $wgUser->isAllowed('bot');
472 return $this->mIsBot
;
476 * Similar to isBot(), this method returns true if the logged in user is
477 * a sysop, and false if not.
479 public function isSysop() {
480 if (!isset ($this->mIsSysop
)) {
482 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
485 return $this->mIsSysop
;
488 public function getShowVersions() {
489 return $this->mShowVersions
;
493 * Returns the version information of this file, plus it includes
494 * the versions for all files that are not callable proper API modules
496 public function getVersion() {
498 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
499 $vers[] = __CLASS__
. ': $Id$';
500 $vers[] = ApiBase
:: getBaseVersion();
501 $vers[] = ApiFormatBase
:: getBaseVersion();
502 $vers[] = ApiQueryBase
:: getBaseVersion();
503 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
508 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
509 * classes who wish to add their own modules to their lexicon or override the
510 * behavior of inherent ones.
513 * @param $mdlName String The identifier for this module.
514 * @param $mdlClass String The class where this module is implemented.
516 protected function addModule( $mdlName, $mdlClass ) {
517 $this->mModules
[$mdlName] = $mdlClass;
521 * Add or overwrite an output format for this ApiMain. Intended for use by extending
522 * classes who wish to add to or modify current formatters.
525 * @param $fmtName The identifier for this format.
526 * @param $fmtClass The class implementing this format.
528 protected function addFormat( $fmtName, $fmtClass ) {
529 $this->mFormats
[$fmtName] = $fmtClass;
534 * This exception will be thrown when dieUsage is called to stop module execution.
535 * The exception handling code will print a help screen explaining how this API may be used.
539 class UsageException
extends Exception
{
543 public function __construct($message, $codestr, $code = 0) {
544 parent
:: __construct($message, $code);
545 $this->mCodestr
= $codestr;
547 public function getCodeString() {
548 return $this->mCodestr
;
550 public function __toString() {
551 return "{$this->getCodeString()}: {$this->getMessage()}";