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 'purge' => 'ApiPurge',
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
78 'edit' => 'ApiEditPage',
79 'upload' => 'ApiUpload',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'userrights' => 'ApiUserrights',
88 * List of available formats: format name => format class
90 private static $Formats = array (
91 'json' => 'ApiFormatJson',
92 'jsonfm' => 'ApiFormatJson',
93 'php' => 'ApiFormatPhp',
94 'phpfm' => 'ApiFormatPhp',
95 'wddx' => 'ApiFormatWddx',
96 'wddxfm' => 'ApiFormatWddx',
97 'xml' => 'ApiFormatXml',
98 'xmlfm' => 'ApiFormatXml',
99 'yaml' => 'ApiFormatYaml',
100 'yamlfm' => 'ApiFormatYaml',
101 'rawfm' => 'ApiFormatJson',
102 'txt' => 'ApiFormatTxt',
103 'txtfm' => 'ApiFormatTxt',
104 'dbg' => 'ApiFormatDbg',
105 'dbgfm' => 'ApiFormatDbg'
109 * List of user roles that are specifically relevant to the API.
110 * array( 'right' => array ( 'msg' => 'Some message with a $1',
111 * 'params' => array ( $someVarToSubst ) ),
114 private static $mRights = array( 'writeapi' => array(
115 'msg' => 'Use of the write API',
118 'apihighlimits' => array(
119 '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.',
120 'params' => array ( ApiMain
::LIMIT_SML2
, ApiMain
::LIMIT_BIG2
)
125 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
126 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest;
127 private $mInternalMode, $mSquidMaxage, $mModule;
130 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
132 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
133 * @param $enableWrite bool should be set to true if the api may modify data
135 public function __construct( $request, $enableWrite = false ) {
137 $this->mInternalMode
= ( $request instanceof FauxRequest
);
139 // Special handling for the main module: $parent === $this
140 parent
:: __construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
142 if ( !$this->mInternalMode
) {
144 // Impose module restrictions.
145 // If the current user cannot read,
146 // Remove all modules other than login
149 if ( $request->getVal( 'callback' ) !== null ) {
150 // JSON callback allows cross-site reads.
151 // For safety, strip user credentials.
152 wfDebug( "API: stripping user credentials for JSON callback\n" );
153 $wgUser = new User();
157 global $wgAPIModules; // extension modules
158 $this->mModules
= $wgAPIModules + self
:: $Modules;
160 $this->mModuleNames
= array_keys( $this->mModules
);
161 $this->mFormats
= self
:: $Formats;
162 $this->mFormatNames
= array_keys( $this->mFormats
);
164 $this->mResult
= new ApiResult( $this );
165 $this->mShowVersions
= false;
166 $this->mEnableWrite
= $enableWrite;
168 $this->mRequest
= & $request;
170 $this->mSquidMaxage
= - 1; // flag for executeActionWithErrorHandling()
171 $this->mCommit
= false;
175 * Return true if the API was started by other PHP code using FauxRequest
177 public function isInternalMode() {
178 return $this->mInternalMode
;
182 * Return the request object that contains client's request
184 public function getRequest() {
185 return $this->mRequest
;
189 * Get the ApiResult object associated with current request
191 public function getResult() {
192 return $this->mResult
;
196 * Get the API module object. Only works after executeAction()
198 public function getModule() {
199 return $this->mModule
;
203 * Only kept for backwards compatibility
204 * @deprecated Use isWriteMode() instead
206 public function requestWriteMode() {
207 if ( !$this->mEnableWrite
)
208 $this->dieUsageMsg( array( 'writedisabled' ) );
210 $this->dieUsageMsg( array( 'readonlytext' ) );
214 * Set how long the response should be cached.
216 public function setCacheMaxAge( $maxage ) {
217 $this->mSquidMaxage
= $maxage;
221 * Create an instance of an output formatter by its name
223 public function createPrinterByName( $format ) {
224 if ( !isset( $this->mFormats
[$format] ) )
225 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
226 return new $this->mFormats
[$format] ( $this, $format );
230 * Execute api request. Any errors will be handled if the API was called by the remote client.
232 public function execute() {
234 if ( $this->mInternalMode
)
235 $this->executeAction();
237 $this->executeActionWithErrorHandling();
243 * Execute an action, and in case of an error, erase whatever partial results
244 * have been accumulated, and replace it with an error message and a help screen.
246 protected function executeActionWithErrorHandling() {
248 // In case an error occurs during data output,
249 // clear the output buffer and print just the error information
253 $this->executeAction();
254 } catch ( Exception
$e ) {
256 if ( $e instanceof MWException
) {
257 wfDebugLog( 'exception', $e->getLogMessage() );
261 // Handle any kind of exception by outputing properly formatted error message.
262 // If this fails, an unhandled exception should be thrown so that global error
263 // handler will process and log it.
266 $errCode = $this->substituteResultWithError( $e );
268 // Error results should not be cached
269 $this->setCacheMaxAge( 0 );
271 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
272 if ( $e->getCode() === 0 )
273 header( $headerStr );
275 header( $headerStr, true, $e->getCode() );
277 // Reset and print just the error message
280 // If the error occured during printing, do a printer->profileOut()
281 $this->mPrinter
->safeProfileOut();
282 $this->printResult( true );
285 if ( $this->mSquidMaxage
== - 1 )
287 // Nobody called setCacheMaxAge(), use the (s)maxage parameters
288 $smaxage = $this->getParameter( 'smaxage' );
289 $maxage = $this->getParameter( 'maxage' );
292 $smaxage = $maxage = $this->mSquidMaxage
;
294 // Set the cache expiration at the last moment, as any errors may change the expiration.
295 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
296 $exp = min( $smaxage, $maxage );
297 $expires = ( $exp == 0 ?
1 : time() +
$exp );
298 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expires ) );
299 header( 'Cache-Control: s-maxage=' . $smaxage . ', must-revalidate, max-age=' . $maxage );
301 if ( $this->mPrinter
->getIsHtml() )
308 * Replace the result data with the information about an exception.
309 * Returns the error code
311 protected function substituteResultWithError( $e ) {
313 // Printer may not be initialized if the extractRequestParams() fails for the main module
314 if ( !isset ( $this->mPrinter
) ) {
315 // The printer has not been created yet. Try to manually get formatter value.
316 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
317 if ( !in_array( $value, $this->mFormatNames
) )
318 $value = self
::API_DEFAULT_FORMAT
;
320 $this->mPrinter
= $this->createPrinterByName( $value );
321 if ( $this->mPrinter
->getNeedsRawData() )
322 $this->getResult()->setRawMode();
325 if ( $e instanceof UsageException
) {
327 // User entered incorrect parameters - print usage screen
329 $errMessage = $e->getMessageArray();
331 // Only print the help message when this is for the developer, not runtime
332 if ( $this->mPrinter
->getWantsHelp() ||
$this->mAction
== 'help' )
333 ApiResult
:: setContent( $errMessage, $this->makeHelpMsg() );
336 global $wgShowSQLErrors, $wgShowExceptionDetails;
338 // Something is seriously wrong
340 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
341 $info = "Database query error";
343 $info = "Exception Caught: {$e->getMessage()}";
346 $errMessage = array (
347 'code' => 'internal_api_error_' . get_class( $e ),
350 ApiResult
:: setContent( $errMessage, $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : "" );
353 $this->getResult()->reset();
354 $this->getResult()->disableSizeCheck();
356 $requestid = $this->getParameter( 'requestid' );
357 if ( !is_null( $requestid ) )
358 $this->getResult()->addValue( null, 'requestid', $requestid );
359 $this->getResult()->addValue( null, 'error', $errMessage );
361 return $errMessage['code'];
365 * Execute the actual module, without any error handling
367 protected function executeAction() {
368 // First add the id to the top element
369 $requestid = $this->getParameter( 'requestid' );
370 if ( !is_null( $requestid ) )
371 $this->getResult()->addValue( null, 'requestid', $requestid );
373 $params = $this->extractRequestParams();
375 $this->mShowVersions
= $params['version'];
376 $this->mAction
= $params['action'];
378 if ( !is_string( $this->mAction
) ) {
379 $this->dieUsage( "The API requires a valid action parameter", 'unknown_action' );
382 // Instantiate the module requested by the user
383 $module = new $this->mModules
[$this->mAction
] ( $this, $this->mAction
);
384 $this->mModule
= $module;
386 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
388 global $wgShowHostnames;
389 $maxLag = $params['maxlag'];
390 list( $host, $lag ) = wfGetLB()->getMaxLag();
391 if ( $lag > $maxLag ) {
392 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
393 header( 'X-Database-Lag: ' . intval( $lag ) );
394 if ( $wgShowHostnames ) {
395 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
397 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
404 if ( $module->isReadMode() && !$wgUser->isAllowed( 'read' ) )
405 $this->dieUsageMsg( array( 'readrequired' ) );
406 if ( $module->isWriteMode() ) {
407 if ( !$this->mEnableWrite
)
408 $this->dieUsageMsg( array( 'writedisabled' ) );
409 if ( !$wgUser->isAllowed( 'writeapi' ) )
410 $this->dieUsageMsg( array( 'writerequired' ) );
412 $this->dieReadOnly();
415 if ( !$this->mInternalMode
) {
416 // Ignore mustBePosted() for internal calls
417 if ( $module->mustBePosted() && !$this->mRequest
->wasPosted() )
418 $this->dieUsageMsg( array ('mustbeposted', $this->mAction
) );
420 // See if custom printer is used
421 $this->mPrinter
= $module->getCustomPrinter();
422 if ( is_null( $this->mPrinter
) ) {
423 // Create an appropriate printer
424 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
427 if ( $this->mPrinter
->getNeedsRawData() )
428 $this->getResult()->setRawMode();
432 $module->profileIn();
434 wfRunHooks( 'APIAfterExecute', array( &$module ) );
435 $module->profileOut();
437 if ( !$this->mInternalMode
) {
439 $this->printResult( false );
444 * Print results using the current printer
446 protected function printResult( $isError ) {
447 $this->getResult()->cleanUpUTF8();
448 $printer = $this->mPrinter
;
449 $printer->profileIn();
451 /* If the help message is requested in the default (xmlfm) format,
452 * tell the printer not to escape ampersands so that our links do
454 $printer->setUnescapeAmps ( ( $this->mAction
== 'help' ||
$isError )
455 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
457 $printer->initPrinter( $isError );
460 $printer->closePrinter();
461 $printer->profileOut();
464 public function isReadMode() {
469 * See ApiBase for description.
471 public function getAllowedParams() {
474 ApiBase
:: PARAM_DFLT
=> ApiMain
:: API_DEFAULT_FORMAT
,
475 ApiBase
:: PARAM_TYPE
=> $this->mFormatNames
478 ApiBase
:: PARAM_DFLT
=> 'help',
479 ApiBase
:: PARAM_TYPE
=> $this->mModuleNames
483 ApiBase
:: PARAM_TYPE
=> 'integer'
486 ApiBase
:: PARAM_TYPE
=> 'integer',
487 ApiBase
:: PARAM_DFLT
=> 0
490 ApiBase
:: PARAM_TYPE
=> 'integer',
491 ApiBase
:: PARAM_DFLT
=> 0
498 * See ApiBase for description.
500 public function getParamDescription() {
502 'format' => 'The format of the output',
503 'action' => 'What action you would like to perform',
504 'version' => 'When showing help, include version for each module',
505 'maxlag' => 'Maximum lag',
506 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
507 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
508 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
513 * See ApiBase for description.
515 public function getDescription() {
519 '******************************************************************',
521 '** This is an auto-generated MediaWiki API documentation page **',
523 '** Documentation and Examples: **',
524 '** http://www.mediawiki.org/wiki/API **',
526 '******************************************************************',
528 'Status: All features shown on this page should be working, but the API',
529 ' is still in active development, and may change at any time.',
530 ' Make sure to monitor our mailing list for any updates.',
532 'Documentation: http://www.mediawiki.org/wiki/API',
533 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
534 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
543 public function getPossibleErrors() {
544 return array_merge( parent
::getPossibleErrors(), array(
545 array( 'readonlytext' ),
546 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
547 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
548 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
549 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
554 * Returns an array of strings with credits for the API
556 protected function getCredits() {
559 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
560 ' Victor Vasiliev - vasilvv at gee mail dot com',
561 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
562 ' Sam Reed - sam @ reedyboy . net',
563 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
565 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
566 'or file a bug report at http://bugzilla.wikimedia.org/'
571 * Override the parent to generate help messages for all available modules.
573 public function makeHelpMsg() {
574 global $wgMemc, $wgAPICacheHelp, $wgAPICacheHelpTimeout;
575 $this->mPrinter
->setHelp();
576 // Get help text from cache if present
577 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
578 SpecialVersion
::getVersion( 'nodb' ) .
579 $this->getMain()->getShowVersions() );
580 if ( $wgAPICacheHelp ) {
581 $cached = $wgMemc->get( $key );
585 $retval = $this->reallyMakeHelpMsg();
586 if ( $wgAPICacheHelp )
587 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
591 public function reallyMakeHelpMsg() {
593 $this->mPrinter
->setHelp();
595 // Use parent to make default message for the main module
596 $msg = parent
:: makeHelpMsg();
598 $astriks = str_repeat( '*** ', 10 );
599 $msg .= "\n\n$astriks Modules $astriks\n\n";
600 foreach ( $this->mModules
as $moduleName => $unused ) {
601 $module = new $this->mModules
[$moduleName] ( $this, $moduleName );
602 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
603 $msg2 = $module->makeHelpMsg();
604 if ( $msg2 !== false )
609 $msg .= "\n$astriks Permissions $astriks\n\n";
610 foreach ( self
:: $mRights as $right => $rightMsg ) {
611 $groups = User
::getGroupsWithPermission( $right );
612 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
613 "\nGranted to:\n " . str_replace( "*", "all", implode( ", ", $groups ) ) . "\n";
617 $msg .= "\n$astriks Formats $astriks\n\n";
618 foreach ( $this->mFormats
as $formatName => $unused ) {
619 $module = $this->createPrinterByName( $formatName );
620 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
621 $msg2 = $module->makeHelpMsg();
622 if ( $msg2 !== false )
627 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
633 public static function makeHelpMsgHeader( $module, $paramName ) {
634 $modulePrefix = $module->getModulePrefix();
635 if ( strval( $modulePrefix ) !== '' )
636 $modulePrefix = "($modulePrefix) ";
638 return "* $paramName={$module->getModuleName()} $modulePrefix*";
641 private $mIsBot = null;
642 private $mIsSysop = null;
643 private $mCanApiHighLimits = null;
646 * Returns true if the currently logged in user is a bot, false otherwise
647 * OBSOLETE, use canApiHighLimits() instead
649 public function isBot() {
650 if ( !isset ( $this->mIsBot
) ) {
652 $this->mIsBot
= $wgUser->isAllowed( 'bot' );
654 return $this->mIsBot
;
658 * Similar to isBot(), this method returns true if the logged in user is
659 * a sysop, and false if not.
660 * OBSOLETE, use canApiHighLimits() instead
662 public function isSysop() {
663 if ( !isset ( $this->mIsSysop
) ) {
665 $this->mIsSysop
= in_array( 'sysop', $wgUser->getGroups() );
668 return $this->mIsSysop
;
672 * Check whether the current user is allowed to use high limits
675 public function canApiHighLimits() {
676 if ( !isset( $this->mCanApiHighLimits
) ) {
678 $this->mCanApiHighLimits
= $wgUser->isAllowed( 'apihighlimits' );
681 return $this->mCanApiHighLimits
;
685 * Check whether the user wants us to show version information in the API help
688 public function getShowVersions() {
689 return $this->mShowVersions
;
693 * Returns the version information of this file, plus it includes
694 * the versions for all files that are not callable proper API modules
696 public function getVersion() {
698 $vers[] = 'MediaWiki: ' . SpecialVersion
::getVersion() . "\n http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
699 $vers[] = __CLASS__
. ': $Id$';
700 $vers[] = ApiBase
:: getBaseVersion();
701 $vers[] = ApiFormatBase
:: getBaseVersion();
702 $vers[] = ApiQueryBase
:: getBaseVersion();
707 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
708 * classes who wish to add their own modules to their lexicon or override the
709 * behavior of inherent ones.
712 * @param $mdlName String The identifier for this module.
713 * @param $mdlClass String The class where this module is implemented.
715 protected function addModule( $mdlName, $mdlClass ) {
716 $this->mModules
[$mdlName] = $mdlClass;
720 * Add or overwrite an output format for this ApiMain. Intended for use by extending
721 * classes who wish to add to or modify current formatters.
724 * @param $fmtName The identifier for this format.
725 * @param $fmtClass The class implementing this format.
727 protected function addFormat( $fmtName, $fmtClass ) {
728 $this->mFormats
[$fmtName] = $fmtClass;
732 * Get the array mapping module names to class names
734 function getModules() {
735 return $this->mModules
;
740 * This exception will be thrown when dieUsage is called to stop module execution.
741 * The exception handling code will print a help screen explaining how this API may be used.
745 class UsageException
extends Exception
{
750 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
751 parent
:: __construct( $message, $code );
752 $this->mCodestr
= $codestr;
753 $this->mExtraData
= $extradata;
755 public function getCodeString() {
756 return $this->mCodestr
;
758 public function getMessageArray() {
760 'code' => $this->mCodestr
,
761 'info' => $this->getMessage()
763 if ( is_array( $this->mExtraData
) )
764 $result = array_merge( $result, $this->mExtraData
);
767 public function __toString() {
768 return "{$this->getCodeString()}: {$this->getMessage()}";