c3946e5c34584014db2ea465001c5302c7b0b11b
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',
80 'watch' => 'ApiWatch',
84 * List of available formats: format name => format class
86 private static $Formats = array (
87 'json' => 'ApiFormatJson',
88 'jsonfm' => 'ApiFormatJson',
89 'php' => 'ApiFormatPhp',
90 'phpfm' => 'ApiFormatPhp',
91 'wddx' => 'ApiFormatWddx',
92 'wddxfm' => 'ApiFormatWddx',
93 'xml' => 'ApiFormatXml',
94 'xmlfm' => 'ApiFormatXml',
95 'yaml' => 'ApiFormatYaml',
96 'yamlfm' => 'ApiFormatYaml',
97 'rawfm' => 'ApiFormatJson',
98 'txt' => 'ApiFormatTxt',
99 'txtfm' => 'ApiFormatTxt',
100 'dbg' => 'ApiFormatDbg',
101 'dbgfm' => 'ApiFormatDbg'
105 * List of user roles that are specifically relevant to the API.
106 * array( 'right' => array ( 'msg' => 'Some message with a $1',
107 * 'params' => array ( $someVarToSubst ) ),
110 private static $mRights = array('writeapi' => array(
111 'msg' => 'Use of the write API',
114 'apihighlimits' => array(
115 'msg' => 'Use higher limits in API queries (Slow queries: $1 results; Fast queries: $2 results). The limits for slow queries also apply to multivalue parameters.',
116 'params' => array (ApiMain
::LIMIT_SML2
, ApiMain
::LIMIT_BIG2
)
121 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
122 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
125 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
127 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
128 * @param $enableWrite bool should be set to true if the api may modify data
130 public function __construct($request, $enableWrite = false) {
132 $this->mInternalMode
= ($request instanceof FauxRequest
);
134 // Special handling for the main module: $parent === $this
135 parent
:: __construct($this, $this->mInternalMode ?
'main_int' : 'main');
137 if (!$this->mInternalMode
) {
139 // Impose module restrictions.
140 // If the current user cannot read,
141 // Remove all modules other than login
144 if( $request->getVal( 'callback' ) !== null ) {
145 // JSON callback allows cross-site reads.
146 // For safety, strip user credentials.
147 wfDebug( "API: stripping user credentials for JSON callback\n" );
148 $wgUser = new User();
151 if (!$wgUser->isAllowed('read')) {
152 self
::$Modules = array(
153 'login' => self
::$Modules['login'],
154 'logout' => self
::$Modules['logout'],
155 'help' => self
::$Modules['help'],
160 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
161 $this->mModules
= $wgAPIModules + self
:: $Modules;
162 if($wgEnableWriteAPI)
163 $this->mModules +
= self
::$WriteModules;
165 $this->mModuleNames
= array_keys($this->mModules
); // todo: optimize
166 $this->mFormats
= self
:: $Formats;
167 $this->mFormatNames
= array_keys($this->mFormats
); // todo: optimize
169 $this->mResult
= new ApiResult($this);
170 $this->mShowVersions
= false;
171 $this->mEnableWrite
= $enableWrite;
173 $this->mRequest
= & $request;
175 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
176 $this->mCommit
= false;
180 * Return true if the API was started by other PHP code using FauxRequest
182 public function isInternalMode() {
183 return $this->mInternalMode
;
187 * Return the request object that contains client's request
189 public function getRequest() {
190 return $this->mRequest
;
194 * Get the ApiResult object asscosiated with current request
196 public function getResult() {
197 return $this->mResult
;
201 * This method will simply cause an error if the write mode was disabled
202 * or if the current user doesn't have the right to use it
204 public function requestWriteMode() {
206 if (!$this->mEnableWrite
)
207 $this->dieUsage('Editing of this wiki through the API' .
208 ' is disabled. Make sure the $wgEnableWriteAPI=true; ' .
209 'statement is included in the wiki\'s ' .
210 'LocalSettings.php file', 'noapiwrite');
211 if (!$wgUser->isAllowed('writeapi'))
212 $this->dieUsage('You\'re not allowed to edit this ' .
213 'wiki through the API', 'writeapidenied');
217 * Set how long the response should be cached.
219 public function setCacheMaxAge($maxage) {
220 $this->mSquidMaxage
= $maxage;
224 * Create an instance of an output formatter by its name
226 public function createPrinterByName($format) {
227 return new $this->mFormats
[$format] ($this, $format);
231 * Execute api request. Any errors will be handled if the API was called by the remote client.
233 public function execute() {
235 if ($this->mInternalMode
)
236 $this->executeAction();
238 $this->executeActionWithErrorHandling();
244 * Execute an action, and in case of an error, erase whatever partial results
245 * have been accumulated, and replace it with an error message and a help screen.
247 protected function executeActionWithErrorHandling() {
249 // In case an error occurs during data output,
250 // clear the output buffer and print just the error information
254 $this->executeAction();
255 } catch (Exception
$e) {
257 // Handle any kind of exception by outputing properly formatted error message.
258 // If this fails, an unhandled exception should be thrown so that global error
259 // handler will process and log it.
262 $errCode = $this->substituteResultWithError($e);
264 // Error results should not be cached
265 $this->setCacheMaxAge(0);
267 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
268 if ($e->getCode() === 0)
269 header($headerStr, true);
271 header($headerStr, true, $e->getCode());
273 // Reset and print just the error message
276 // If the error occured during printing, do a printer->profileOut()
277 $this->mPrinter
->safeProfileOut();
278 $this->printResult(true);
281 if($this->mSquidMaxage
== -1)
283 # Nobody called setCacheMaxAge(), use the (s)maxage parameters
284 $smaxage = $this->mRequest
->getVal('smaxage', 0);
285 $maxage = $this->mRequest
->getVal('maxage', 0);
288 $smaxage = $maxage = $this->mSquidMaxage
;
290 // Set the cache expiration at the last moment, as any errors may change the expiration.
291 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
292 $exp = min($smaxage, $maxage);
293 $expires = ($exp == 0 ?
1 : time() +
$exp);
294 header('Expires: ' . wfTimestamp(TS_RFC2822
, $expires));
295 header('Cache-Control: s-maxage=' . $smaxage . ', must-revalidate, max-age=' . $maxage);
297 if($this->mPrinter
->getIsHtml())
304 * Replace the result data with the information about an exception.
305 * Returns the error code
307 protected function substituteResultWithError($e) {
309 // Printer may not be initialized if the extractRequestParams() fails for the main module
310 if (!isset ($this->mPrinter
)) {
311 // The printer has not been created yet. Try to manually get formatter value.
312 $value = $this->getRequest()->getVal('format', self
::API_DEFAULT_FORMAT
);
313 if (!in_array($value, $this->mFormatNames
))
314 $value = self
::API_DEFAULT_FORMAT
;
316 $this->mPrinter
= $this->createPrinterByName($value);
317 if ($this->mPrinter
->getNeedsRawData())
318 $this->getResult()->setRawMode();
321 if ($e instanceof UsageException
) {
323 // User entered incorrect parameters - print usage screen
325 $errMessage = array (
326 'code' => $e->getCodeString(),
327 'info' => $e->getMessage());
329 // Only print the help message when this is for the developer, not runtime
330 if ($this->mPrinter
->getIsHtml() ||
$this->mAction
== 'help')
331 ApiResult
:: setContent($errMessage, $this->makeHelpMsg());
334 global $wgShowSQLErrors, $wgShowExceptionDetails;
336 // Something is seriously wrong
338 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
339 $info = "Database query error";
341 $info = "Exception Caught: {$e->getMessage()}";
344 $errMessage = array (
345 'code' => 'internal_api_error_'. get_class($e),
348 ApiResult
:: setContent($errMessage, $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : "" );
351 $this->getResult()->reset();
353 if($this->mRequest
->getCheck('requestid'))
354 $this->getResult()->addValue(null, 'requestid', $this->mRequest
->getVal('requestid'));
355 $this->getResult()->addValue(null, 'error', $errMessage);
357 return $errMessage['code'];
361 * Execute the actual module, without any error handling
363 protected function executeAction() {
364 // First add the id to the top element
365 if($this->mRequest
->getCheck('requestid'))
366 $this->getResult()->addValue(null, 'requestid', $this->mRequest
->getVal('requestid'));
368 $params = $this->extractRequestParams();
370 $this->mShowVersions
= $params['version'];
371 $this->mAction
= $params['action'];
373 if( !is_string( $this->mAction
) ) {
374 $this->dieUsage( "The API requires a valid action parameter", 'unknown_action' );
377 // Instantiate the module requested by the user
378 $module = new $this->mModules
[$this->mAction
] ($this, $this->mAction
);
380 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
382 global $wgShowHostnames;
383 $maxLag = $params['maxlag'];
384 list( $host, $lag ) = wfGetLB()->getMaxLag();
385 if ( $lag > $maxLag ) {
386 if( $wgShowHostnames ) {
387 ApiBase
:: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
389 ApiBase
:: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
395 if (!$this->mInternalMode
) {
396 // Ignore mustBePosted() for internal calls
397 if($module->mustBePosted() && !$this->mRequest
->wasPosted())
398 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
400 // See if custom printer is used
401 $this->mPrinter
= $module->getCustomPrinter();
402 if (is_null($this->mPrinter
)) {
403 // Create an appropriate printer
404 $this->mPrinter
= $this->createPrinterByName($params['format']);
407 if ($this->mPrinter
->getNeedsRawData())
408 $this->getResult()->setRawMode();
412 $module->profileIn();
414 $module->profileOut();
416 if (!$this->mInternalMode
) {
418 $this->printResult(false);
423 * Print results using the current printer
425 protected function printResult($isError) {
426 $printer = $this->mPrinter
;
427 $printer->profileIn();
429 /* If the help message is requested in the default (xmlfm) format,
430 * tell the printer not to escape ampersands so that our links do
432 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
433 && $this->getParameter('format') == ApiMain
::API_DEFAULT_FORMAT
);
435 $printer->initPrinter($isError);
438 $printer->closePrinter();
439 $printer->profileOut();
443 * See ApiBase for description.
445 public function getAllowedParams() {
448 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
449 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
452 ApiBase
:: PARAM_DFLT
=> 'help',
453 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
457 ApiBase
:: PARAM_TYPE
=> 'integer'
460 ApiBase
:: PARAM_TYPE
=> 'integer',
461 ApiBase
:: PARAM_DFLT
=> 0
464 ApiBase
:: PARAM_TYPE
=> 'integer',
465 ApiBase
:: PARAM_DFLT
=> 0
472 * See ApiBase for description.
474 public function getParamDescription() {
476 'format' => 'The format of the output',
477 'action' => 'What action you would like to perform',
478 'version' => 'When showing help, include version for each module',
479 'maxlag' => 'Maximum lag',
480 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
481 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
482 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
487 * See ApiBase for description.
489 public function getDescription() {
493 '******************************************************************',
495 '** This is an auto-generated MediaWiki API documentation page **',
497 '** Documentation and Examples: **',
498 '** http://www.mediawiki.org/wiki/API **',
500 '******************************************************************',
502 'Status: All features shown on this page should be working, but the API',
503 ' is still in active development, and may change at any time.',
504 ' Make sure to monitor our mailing list for any updates.',
506 'Documentation: http://www.mediawiki.org/wiki/API',
507 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
508 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
518 * Returns an array of strings with credits for the API
520 protected function getCredits() {
523 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
524 ' Victor Vasiliev - vasilvv at gee mail dot com',
525 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
526 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
528 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
529 'or file a bug report at http://bugzilla.wikimedia.org/'
534 * Override the parent to generate help messages for all available modules.
536 public function makeHelpMsg() {
538 $this->mPrinter
->setHelp();
540 // Use parent to make default message for the main module
541 $msg = parent
:: makeHelpMsg();
543 $astriks = str_repeat('*** ', 10);
544 $msg .= "\n\n$astriks Modules $astriks\n\n";
545 foreach( $this->mModules
as $moduleName => $unused ) {
546 $module = new $this->mModules
[$moduleName] ($this, $moduleName);
547 $msg .= self
::makeHelpMsgHeader($module, 'action');
548 $msg2 = $module->makeHelpMsg();
554 $msg .= "\n$astriks Permissions $astriks\n\n";
555 foreach ( self
:: $mRights as $right => $rightMsg ) {
556 $groups = User
::getGroupsWithPermission( $right );
557 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
558 "\nGranted to:\n " . str_replace( "*", "all", implode( ", ", $groups ) ) . "\n";
562 $msg .= "\n$astriks Formats $astriks\n\n";
563 foreach( $this->mFormats
as $formatName => $unused ) {
564 $module = $this->createPrinterByName($formatName);
565 $msg .= self
::makeHelpMsgHeader($module, 'format');
566 $msg2 = $module->makeHelpMsg();
572 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
578 public static function makeHelpMsgHeader($module, $paramName) {
579 $modulePrefix = $module->getModulePrefix();
580 if (!empty($modulePrefix))
581 $modulePrefix = "($modulePrefix) ";
583 return "* $paramName={$module->getModuleName()} $modulePrefix*";
586 private $mIsBot = null;
587 private $mIsSysop = null;
588 private $mCanApiHighLimits = null;
591 * Returns true if the currently logged in user is a bot, false otherwise
592 * OBSOLETE, use canApiHighLimits() instead
594 public function isBot() {
595 if (!isset ($this->mIsBot
)) {
597 $this->mIsBot
= $wgUser->isAllowed('bot');
599 return $this->mIsBot
;
603 * Similar to isBot(), this method returns true if the logged in user is
604 * a sysop, and false if not.
605 * OBSOLETE, use canApiHighLimits() instead
607 public function isSysop() {
608 if (!isset ($this->mIsSysop
)) {
610 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups());
613 return $this->mIsSysop
;
617 * Check whether the current user is allowed to use high limits
620 public function canApiHighLimits() {
621 if (!isset($this->mCanApiHighLimits
)) {
623 $this->mCanApiHighLimits
= $wgUser->isAllowed('apihighlimits');
626 return $this->mCanApiHighLimits
;
630 * Check whether the user wants us to show version information in the API help
633 public function getShowVersions() {
634 return $this->mShowVersions
;
638 * Returns the version information of this file, plus it includes
639 * the versions for all files that are not callable proper API modules
641 public function getVersion() {
643 $vers[] = 'MediaWiki: ' . SpecialVersion
::getVersion() . "\n http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
644 $vers[] = __CLASS__
. ': $Id$';
645 $vers[] = ApiBase
:: getBaseVersion();
646 $vers[] = ApiFormatBase
:: getBaseVersion();
647 $vers[] = ApiQueryBase
:: getBaseVersion();
648 $vers[] = ApiFormatFeedWrapper
:: getVersion(); // not accessible with format=xxx
653 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
654 * classes who wish to add their own modules to their lexicon or override the
655 * behavior of inherent ones.
658 * @param $mdlName String The identifier for this module.
659 * @param $mdlClass String The class where this module is implemented.
661 protected function addModule( $mdlName, $mdlClass ) {
662 $this->mModules
[$mdlName] = $mdlClass;
666 * Add or overwrite an output format for this ApiMain. Intended for use by extending
667 * classes who wish to add to or modify current formatters.
670 * @param $fmtName The identifier for this format.
671 * @param $fmtClass The class implementing this format.
673 protected function addFormat( $fmtName, $fmtClass ) {
674 $this->mFormats
[$fmtName] = $fmtClass;
678 * Get the array mapping module names to class names
680 function getModules() {
681 return $this->mModules
;
686 * This exception will be thrown when dieUsage is called to stop module execution.
687 * The exception handling code will print a help screen explaining how this API may be used.
691 class UsageException
extends Exception
{
695 public function __construct($message, $codestr, $code = 0) {
696 parent
:: __construct($message, $code);
697 $this->mCodestr
= $codestr;
699 public function getCodeString() {
700 return $this->mCodestr
;
702 public function __toString() {
703 return "{$this->getCodeString()}: {$this->getMessage()}";