acf3e5009e031198e6d280d71699a5dd2b5d8092
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 'rawfm' => 'ApiFormatJson'
81 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
82 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
85 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
87 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
88 * @param $enableWrite bool should be set to true if the api may modify data
90 public function __construct($request, $enableWrite = false) {
92 $this->mInternalMode
= ($request instanceof FauxRequest
);
94 // Special handling for the main module: $parent === $this
95 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
97 if (!$this->mInternalMode
) {
99 // Impose module restrictions.
100 // If the current user cannot read,
101 // Remove all modules other than login
103 if (!$wgUser->isAllowed('read')) {
104 self
::$Modules = array(
105 'login' => self
::$Modules['login'],
106 'help' => self
::$Modules['help']
111 global $wgAPIModules; // extension modules
112 $this->mModules
= $wgAPIModules + self
:: $Modules;
114 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
115 $this->mFormats
= self
:: $Formats;
116 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
118 $this->mResult
= new ApiResult($this);
119 $this->mShowVersions
= false;
120 $this->mEnableWrite
= $enableWrite;
122 $this->mRequest
= & $request;
124 $this->mSquidMaxage
= 0;
128 * Return true if the API was started by other PHP code using FauxRequest
130 public function isInternalMode() {
131 return $this->mInternalMode
;
135 * Return the request object that contains client's request
137 public function getRequest() {
138 return $this->mRequest
;
142 * Get the ApiResult object asscosiated with current request
144 public function getResult() {
145 return $this->mResult
;
149 * This method will simply cause an error if the write mode was disabled for this api.
151 public function requestWriteMode() {
152 if (!$this->mEnableWrite
)
153 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
154 'statement is included in the site\'s LocalSettings.php file', 'readonly');
158 * Set how long the response should be cached.
160 public function setCacheMaxAge($maxage) {
161 $this->mSquidMaxage
= $maxage;
165 * Create an instance of an output formatter by its name
167 public function createPrinterByName($format) {
168 return new $this->mFormats
[$format] ($this, $format);
172 * Execute api request. Any errors will be handled if the API was called by the remote client.
174 public function execute() {
176 if ($this->mInternalMode
)
177 $this->executeAction();
179 $this->executeActionWithErrorHandling();
184 * Execute an action, and in case of an error, erase whatever partial results
185 * have been accumulated, and replace it with an error message and a help screen.
187 protected function executeActionWithErrorHandling() {
189 // In case an error occurs during data output,
190 // clear the output buffer and print just the error information
194 $this->executeAction();
195 } catch (Exception
$e) {
197 // Handle any kind of exception by outputing properly formatted error message.
198 // If this fails, an unhandled exception should be thrown so that global error
199 // handler will process and log it.
202 $errCode = $this->substituteResultWithError($e);
204 // Error results should not be cached
205 $this->setCacheMaxAge(0);
207 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
208 if ($e->getCode() === 0)
209 header($headerStr, true);
211 header($headerStr, true, $e->getCode());
213 // Reset and print just the error message
216 // If the error occured during printing, do a printer->profileOut()
217 $this->mPrinter
->safeProfileOut();
218 $this->printResult(true);
221 // Set the cache expiration at the last moment, as any errors may change the expiration.
222 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
223 $expires = $this->mSquidMaxage
== 0 ?
1 : time() +
$this->mSquidMaxage
;
224 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
225 header('Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0');
227 if($this->mPrinter
->getIsHtml())
234 * Replace the result data with the information about an exception.
235 * Returns the error code
237 protected function substituteResultWithError($e) {
239 // Printer may not be initialized if the extractRequestParams() fails for the main module
240 if (!isset ($this->mPrinter
)) {
241 // The printer has not been created yet. Try to manually get formatter value.
242 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
243 if (!in_array($value, $this->mFormatNames
))
244 $value = self
::API_DEFAULT_FORMAT
;
246 $this->mPrinter
= $this->createPrinterByName($value);
247 if ($this->mPrinter
->getNeedsRawData())
248 $this->getResult()->setRawMode();
251 if ($e instanceof UsageException
) {
253 // User entered incorrect parameters - print usage screen
255 $errMessage = array (
256 'code' => $e->getCodeString(),
257 'info' => $e->getMessage());
259 // Only print the help message when this is for the developer, not runtime
260 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
261 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
265 // Something is seriously wrong
267 $errMessage = array (
268 'code' => 'internal_api_error_'. get_class($e),
269 'info' => "Exception Caught: {$e->getMessage()}"
271 ApiResult
:: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
274 $this->getResult()->reset();
275 $this->getResult()->addValue(null, 'error', $errMessage);
277 return $errMessage['code'];
281 * Execute the actual module, without any error handling
283 protected function executeAction() {
285 $params = $this->extractRequestParams();
287 $this->mShowVersions
= $params['version'];
288 $this->mAction
= $params['action'];
290 // Instantiate the module requested by the user
291 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
293 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
295 global $wgLoadBalancer, $wgShowHostnames;
296 $maxLag = $params['maxlag'];
297 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
298 if ( $lag > $maxLag ) {
299 if( $wgShowHostnames ) {
300 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
302 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
308 if (!$this->mInternalMode
) {
310 // See if custom printer is used
311 $this->mPrinter
= $module->getCustomPrinter();
312 if (is_null($this->mPrinter
)) {
313 // Create an appropriate printer
314 $this->mPrinter
= $this->createPrinterByName($params['format']);
317 if ($this->mPrinter
->getNeedsRawData())
318 $this->getResult()->setRawMode();
322 $module->profileIn();
324 $module->profileOut();
326 if (!$this->mInternalMode
) {
328 $this->printResult(false);
333 * Print results using the current printer
335 protected function printResult($isError) {
336 $printer = $this->mPrinter
;
337 $printer->profileIn();
339 /* If the help message is requested in the default (xmlfm) format,
340 * tell the printer not to escape ampersands so that our links do
342 $params = $this->extractRequestParams();
343 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
344 && $params['format'] == ApiMain
::API_DEFAULT_FORMAT
);
346 $printer->initPrinter($isError);
349 $printer->closePrinter();
350 $printer->profileOut();
354 * See ApiBase for description.
356 protected function getAllowedParams() {
359 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
360 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
363 ApiBase
:: PARAM_DFLT
=> 'help',
364 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
368 ApiBase
:: PARAM_TYPE
=> 'integer'
374 * See ApiBase for description.
376 protected function getParamDescription() {
378 'format' => 'The format of the output',
379 'action' => 'What action you would like to perform',
380 'version' => 'When showing help, include version for each module',
381 'maxlag' => 'Maximum lag'
386 * See ApiBase for description.
388 protected function getDescription() {
392 '******************************************************************',
394 '** This is an auto-generated MediaWiki API documentation page **',
396 '** Documentation and Examples: **',
397 '** http://www.mediawiki.org/wiki/API **',
399 '******************************************************************',
401 'Status: All features shown on this page should be working, but the API',
402 ' is still in active development, and may change at any time.',
403 ' Make sure to monitor our mailing list for any updates.',
405 'Documentation: http://www.mediawiki.org/wiki/API',
406 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
407 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
417 * Returns an array of strings with credits for the API
419 protected function getCredits() {
421 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
422 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
427 * Override the parent to generate help messages for all available modules.
429 public function makeHelpMsg() {
431 // Use parent to make default message for the main module
432 $msg = parent
:: makeHelpMsg();
434 $astriks = str_repeat('*** ', 10);
435 $msg .= "\n\n$astriks Modules $astriks\n\n";
436 foreach( $this->mModules
as $moduleName => $unused ) {
437 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
438 $msg .= self
::makeHelpMsgHeader($module, 'action');
439 $msg2 = $module->makeHelpMsg();
445 $msg .= "\n$astriks Formats $astriks\n\n";
446 foreach( $this->mFormats
as $formatName => $unused ) {
447 $module = $this->createPrinterByName($formatName);
448 $msg .= self
::makeHelpMsgHeader($module, 'format');
449 $msg2 = $module->makeHelpMsg();
455 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
461 public static function makeHelpMsgHeader($module, $paramName) {
462 $modulePrefix = $module->getModulePrefix();
463 if (!empty($modulePrefix))
464 $modulePrefix = "($modulePrefix) ";
466 return "* $paramName={$module->getModuleName()} $modulePrefix*";
469 private $mIsBot = null;
470 private $mIsSysop = null;
471 private $mCanApiHighLimits = null;
474 * Returns true if the currently logged in user is a bot, false otherwise
475 * OBSOLETE, use canApiHighLimits() instead
477 public function isBot() {
478 if (!isset ($this->mIsBot
)) {
480 $this->mIsBot
= $wgUser->isAllowed('bot');
482 return $this->mIsBot
;
486 * Similar to isBot(), this method returns true if the logged in user is
487 * a sysop, and false if not.
488 * OBSOLETE, use canApiHighLimits() instead
490 public function isSysop() {
491 if (!isset ($this->mIsSysop
)) {
493 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
496 return $this->mIsSysop
;
499 public function canApiHighLimits() {
500 if (!is_null ($this->mCanApiHighLimits
)) {
502 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
505 return $this->mCanApiHighLimits
;
508 public function getShowVersions() {
509 return $this->mShowVersions
;
513 * Returns the version information of this file, plus it includes
514 * the versions for all files that are not callable proper API modules
516 public function getVersion() {
518 $vers[] = 'MediaWiki ' . SpecialVersion
::getVersion();
519 $vers[] = __CLASS__
. ': $Id$';
520 $vers[] = ApiBase
:: getBaseVersion();
521 $vers[] = ApiFormatBase
:: getBaseVersion();
522 $vers[] = ApiQueryBase
:: getBaseVersion();
523 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
528 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
529 * classes who wish to add their own modules to their lexicon or override the
530 * behavior of inherent ones.
533 * @param $mdlName String The identifier for this module.
534 * @param $mdlClass String The class where this module is implemented.
536 protected function addModule( $mdlName, $mdlClass ) {
537 $this->mModules
[$mdlName] = $mdlClass;
541 * Add or overwrite an output format for this ApiMain. Intended for use by extending
542 * classes who wish to add to or modify current formatters.
545 * @param $fmtName The identifier for this format.
546 * @param $fmtClass The class implementing this format.
548 protected function addFormat( $fmtName, $fmtClass ) {
549 $this->mFormats
[$fmtName] = $fmtClass;
554 * This exception will be thrown when dieUsage is called to stop module execution.
555 * The exception handling code will print a help screen explaining how this API may be used.
559 class UsageException
extends Exception
{
563 public function __construct($message, $codestr, $code = 0) {
564 parent
:: __construct($message, $code);
565 $this->mCodestr
= $codestr;
567 public function getCodeString() {
568 return $this->mCodestr
;
570 public function __toString() {
571 return "{$this->getCodeString()}: {$this->getMessage()}";