5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
44 * When no format parameter is given, this format will be used
46 const API_DEFAULT_FORMAT
= 'xmlfm';
49 * List of available modules: action name => module class
51 private static $Modules = array(
52 'login' => 'ApiLogin',
53 'logout' => 'ApiLogout',
54 'createaccount' => 'ApiCreateAccount',
55 'query' => 'ApiQuery',
56 'expandtemplates' => 'ApiExpandTemplates',
57 'parse' => 'ApiParse',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedwatchlist' => 'ApiFeedWatchlist',
62 'paraminfo' => 'ApiParamInfo',
64 'compare' => 'ApiComparePages',
65 'tokens' => 'ApiTokens',
68 'purge' => 'ApiPurge',
69 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
70 'rollback' => 'ApiRollback',
71 'delete' => 'ApiDelete',
72 'undelete' => 'ApiUndelete',
73 'protect' => 'ApiProtect',
74 'block' => 'ApiBlock',
75 'unblock' => 'ApiUnblock',
77 'edit' => 'ApiEditPage',
78 'upload' => 'ApiUpload',
79 'filerevert' => 'ApiFileRevert',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'userrights' => 'ApiUserrights',
85 'options' => 'ApiOptions',
86 'imagerotate' => 'ApiImageRotate',
90 * List of available formats: format name => format class
92 private static $Formats = array(
93 'json' => 'ApiFormatJson',
94 'jsonfm' => 'ApiFormatJson',
95 'php' => 'ApiFormatPhp',
96 'phpfm' => 'ApiFormatPhp',
97 'wddx' => 'ApiFormatWddx',
98 'wddxfm' => 'ApiFormatWddx',
99 'xml' => 'ApiFormatXml',
100 'xmlfm' => 'ApiFormatXml',
101 'yaml' => 'ApiFormatYaml',
102 'yamlfm' => 'ApiFormatYaml',
103 'rawfm' => 'ApiFormatJson',
104 'txt' => 'ApiFormatTxt',
105 'txtfm' => 'ApiFormatTxt',
106 'dbg' => 'ApiFormatDbg',
107 'dbgfm' => 'ApiFormatDbg',
108 'dump' => 'ApiFormatDump',
109 'dumpfm' => 'ApiFormatDump',
110 'none' => 'ApiFormatNone',
114 * List of user roles that are specifically relevant to the API.
115 * array( 'right' => array ( 'msg' => 'Some message with a $1',
116 * 'params' => array ( $someVarToSubst ) ),
119 private static $mRights = array(
121 'msg' => 'Use of the write API',
124 'apihighlimits' => array(
125 '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.',
126 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
135 private $mModuleMgr, $mResult;
137 private $mEnableWrite;
138 private $mInternalMode, $mSquidMaxage, $mModule;
140 private $mCacheMode = 'private';
141 private $mCacheControl = array();
142 private $mParamsUsed = array();
145 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
147 * @param $context IContextSource|WebRequest - if this is an instance of FauxRequest, errors are thrown and no printing occurs
148 * @param bool $enableWrite should be set to true if the api may modify data
150 public function __construct( $context = null, $enableWrite = false ) {
151 if ( $context === null ) {
152 $context = RequestContext
::getMain();
153 } elseif ( $context instanceof WebRequest
) {
156 $context = RequestContext
::getMain();
158 // We set a derivative context so we can change stuff later
159 $this->setContext( new DerivativeContext( $context ) );
161 if ( isset( $request ) ) {
162 $this->getContext()->setRequest( $request );
165 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
167 // Special handling for the main module: $parent === $this
168 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
170 if ( !$this->mInternalMode
) {
171 // Impose module restrictions.
172 // If the current user cannot read,
173 // Remove all modules other than login
176 if ( $this->getVal( 'callback' ) !== null ) {
177 // JSON callback allows cross-site reads.
178 // For safety, strip user credentials.
179 wfDebug( "API: stripping user credentials for JSON callback\n" );
180 $wgUser = new User();
181 $this->getContext()->setUser( $wgUser );
185 global $wgAPIModules;
186 $this->mModuleMgr
= new ApiModuleManager( $this );
187 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
188 $this->mModuleMgr
->addModules( $wgAPIModules, 'action' );
189 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
191 $this->mResult
= new ApiResult( $this );
192 $this->mEnableWrite
= $enableWrite;
194 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
195 $this->mCommit
= false;
199 * Return true if the API was started by other PHP code using FauxRequest
202 public function isInternalMode() {
203 return $this->mInternalMode
;
207 * Get the ApiResult object associated with current request
211 public function getResult() {
212 return $this->mResult
;
216 * Get the API module object. Only works after executeAction()
220 public function getModule() {
221 return $this->mModule
;
225 * Get the result formatter object. Only works after setupExecuteAction()
227 * @return ApiFormatBase
229 public function getPrinter() {
230 return $this->mPrinter
;
234 * Set how long the response should be cached.
238 public function setCacheMaxAge( $maxage ) {
239 $this->setCacheControl( array(
240 'max-age' => $maxage,
241 's-maxage' => $maxage
246 * Set the type of caching headers which will be sent.
248 * @param string $mode One of:
249 * - 'public': Cache this object in public caches, if the maxage or smaxage
250 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
251 * not provided by any of these means, the object will be private.
252 * - 'private': Cache this object only in private client-side caches.
253 * - 'anon-public-user-private': Make this object cacheable for logged-out
254 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
255 * set consistently for a given URL, it cannot be set differently depending on
256 * things like the contents of the database, or whether the user is logged in.
258 * If the wiki does not allow anonymous users to read it, the mode set here
259 * will be ignored, and private caching headers will always be sent. In other words,
260 * the "public" mode is equivalent to saying that the data sent is as public as a page
263 * For user-dependent data, the private mode should generally be used. The
264 * anon-public-user-private mode should only be used where there is a particularly
265 * good performance reason for caching the anonymous response, but where the
266 * response to logged-in users may differ, or may contain private data.
268 * If this function is never called, then the default will be the private mode.
270 public function setCacheMode( $mode ) {
271 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
272 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
274 // Ignore for forwards-compatibility
278 if ( !User
::isEveryoneAllowed( 'read' ) ) {
279 // Private wiki, only private headers
280 if ( $mode !== 'private' ) {
281 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
287 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
288 $this->mCacheMode
= $mode;
292 * @deprecated since 1.17 Private caching is now the default, so there is usually no
293 * need to call this function. If there is a need, you can use
294 * $this->setCacheMode('private')
296 public function setCachePrivate() {
297 wfDeprecated( __METHOD__
, '1.17' );
298 $this->setCacheMode( 'private' );
302 * Set directives (key/value pairs) for the Cache-Control header.
303 * Boolean values will be formatted as such, by including or omitting
304 * without an equals sign.
306 * Cache control values set here will only be used if the cache mode is not
307 * private, see setCacheMode().
309 * @param $directives array
311 public function setCacheControl( $directives ) {
312 $this->mCacheControl
= $directives +
$this->mCacheControl
;
316 * Make sure Vary: Cookie and friends are set. Use this when the output of a request
317 * may be cached for anons but may not be cached for logged-in users.
319 * WARNING: This function must be called CONSISTENTLY for a given URL. This means that a
320 * given URL must either always or never call this function; if it sometimes does and
321 * sometimes doesn't, stuff will break.
323 * @deprecated since 1.17 Use setCacheMode( 'anon-public-user-private' )
325 public function setVaryCookie() {
326 wfDeprecated( __METHOD__
, '1.17' );
327 $this->setCacheMode( 'anon-public-user-private' );
331 * Create an instance of an output formatter by its name
333 * @param $format string
335 * @return ApiFormatBase
337 public function createPrinterByName( $format ) {
338 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
339 if ( $printer === null ) {
340 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
347 * Execute api request. Any errors will be handled if the API was called by the remote client.
349 public function execute() {
351 if ( $this->mInternalMode
) {
352 $this->executeAction();
354 $this->executeActionWithErrorHandling();
361 * Execute an action, and in case of an error, erase whatever partial results
362 * have been accumulated, and replace it with an error message and a help screen.
364 protected function executeActionWithErrorHandling() {
365 // Verify the CORS header before executing the action
366 if ( !$this->handleCORS() ) {
367 // handleCORS() has sent a 403, abort
371 // Exit here if the request method was OPTIONS
372 // (assume there will be a followup GET or POST)
373 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
377 // In case an error occurs during data output,
378 // clear the output buffer and print just the error information
381 $t = microtime( true );
383 $this->executeAction();
384 } catch ( Exception
$e ) {
385 // Allow extra cleanup and logging
386 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
389 if ( !( $e instanceof UsageException
) ) {
390 MWExceptionHandler
::logException( $e );
393 // Handle any kind of exception by outputting properly formatted error message.
394 // If this fails, an unhandled exception should be thrown so that global error
395 // handler will process and log it.
397 $errCode = $this->substituteResultWithError( $e );
399 // Error results should not be cached
400 $this->setCacheMode( 'private' );
402 $response = $this->getRequest()->response();
403 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
404 if ( $e->getCode() === 0 ) {
405 $response->header( $headerStr );
407 $response->header( $headerStr, true, $e->getCode() );
410 // Reset and print just the error message
413 // If the error occurred during printing, do a printer->profileOut()
414 $this->mPrinter
->safeProfileOut();
415 $this->printResult( true );
418 // Log the request whether or not there was an error
419 $this->logRequest( microtime( true ) - $t );
421 // Send cache headers after any code which might generate an error, to
422 // avoid sending public cache headers for errors.
423 $this->sendCacheHeaders();
425 if ( $this->mPrinter
->getIsHtml() && !$this->mPrinter
->isDisabled() ) {
433 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
435 * If no origin parameter is present, nothing happens.
436 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
437 * is set and false is returned.
438 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
439 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
442 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
444 protected function handleCORS() {
445 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
447 $originParam = $this->getParameter( 'origin' ); // defaults to null
448 if ( $originParam === null ) {
449 // No origin parameter, nothing to do
453 $request = $this->getRequest();
454 $response = $request->response();
455 // Origin: header is a space-separated list of origins, check all of them
456 $originHeader = $request->getHeader( 'Origin' );
457 if ( $originHeader === false ) {
460 $origins = explode( ' ', $originHeader );
462 if ( !in_array( $originParam, $origins ) ) {
463 // origin parameter set but incorrect
464 // Send a 403 response
465 $message = HttpStatus
::getMessage( 403 );
466 $response->header( "HTTP/1.1 403 $message", true, 403 );
467 $response->header( 'Cache-Control: no-cache' );
468 echo "'origin' parameter does not match Origin header\n";
472 if ( self
::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
473 $response->header( "Access-Control-Allow-Origin: $originParam" );
474 $response->header( 'Access-Control-Allow-Credentials: true' );
475 $this->getOutput()->addVaryHeader( 'Origin' );
482 * Attempt to match an Origin header against a set of rules and a set of exceptions
483 * @param string $value Origin header
484 * @param array $rules Set of wildcard rules
485 * @param array $exceptions Set of wildcard rules
486 * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
488 protected static function matchOrigin( $value, $rules, $exceptions ) {
489 foreach ( $rules as $rule ) {
490 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
491 // Rule matches, check exceptions
492 foreach ( $exceptions as $exc ) {
493 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
506 * Helper function to convert wildcard string into a regex
510 * @param string $wildcard String with wildcards
511 * @return string Regular expression
513 protected static function wildcardToRegex( $wildcard ) {
514 $wildcard = preg_quote( $wildcard, '/' );
515 $wildcard = str_replace(
521 return "/https?:\/\/$wildcard/";
524 protected function sendCacheHeaders() {
525 global $wgUseXVO, $wgVaryOnXFP;
526 $response = $this->getRequest()->response();
527 $out = $this->getOutput();
529 if ( $wgVaryOnXFP ) {
530 $out->addVaryHeader( 'X-Forwarded-Proto' );
533 if ( $this->mCacheMode
== 'private' ) {
534 $response->header( 'Cache-Control: private' );
539 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
540 $out->addVaryHeader( 'Cookie' );
541 $response->header( $out->getVaryHeader() );
543 $response->header( $out->getXVO() );
544 if ( $out->haveCacheVaryCookies() ) {
545 // Logged in, mark this request private
546 $response->header( 'Cache-Control: private' );
550 // Logged out, send normal public headers below
551 } elseif ( session_id() != '' ) {
552 // Logged in or otherwise has session (e.g. anonymous users who have edited)
553 // Mark request private
554 $response->header( 'Cache-Control: private' );
557 } // else no XVO and anonymous, send public headers below
560 // Send public headers
561 $response->header( $out->getVaryHeader() );
563 $response->header( $out->getXVO() );
566 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
567 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
568 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
570 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
571 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
574 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
575 // Public cache not requested
576 // Sending a Vary header in this case is harmless, and protects us
577 // against conditional calls of setCacheMaxAge().
578 $response->header( 'Cache-Control: private' );
583 $this->mCacheControl
['public'] = true;
585 // Send an Expires header
586 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
587 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
588 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
590 // Construct the Cache-Control header
593 foreach ( $this->mCacheControl
as $name => $value ) {
594 if ( is_bool( $value ) ) {
596 $ccHeader .= $separator . $name;
600 $ccHeader .= $separator . "$name=$value";
605 $response->header( "Cache-Control: $ccHeader" );
609 * Replace the result data with the information about an exception.
610 * Returns the error code
611 * @param $e Exception
614 protected function substituteResultWithError( $e ) {
615 global $wgShowHostnames;
617 $result = $this->getResult();
618 // Printer may not be initialized if the extractRequestParams() fails for the main module
619 if ( !isset( $this->mPrinter
) ) {
620 // The printer has not been created yet. Try to manually get formatter value.
621 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
622 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
623 $value = self
::API_DEFAULT_FORMAT
;
626 $this->mPrinter
= $this->createPrinterByName( $value );
627 if ( $this->mPrinter
->getNeedsRawData() ) {
628 $result->setRawMode();
632 if ( $e instanceof UsageException
) {
633 // User entered incorrect parameters - print usage screen
634 $errMessage = $e->getMessageArray();
636 // Only print the help message when this is for the developer, not runtime
637 if ( $this->mPrinter
->getWantsHelp() ||
$this->mAction
== 'help' ) {
638 ApiResult
::setContent( $errMessage, $this->makeHelpMsg() );
641 global $wgShowSQLErrors, $wgShowExceptionDetails;
642 // Something is seriously wrong
643 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
644 $info = 'Database query error';
646 $info = "Exception Caught: {$e->getMessage()}";
650 'code' => 'internal_api_error_' . get_class( $e ),
653 ApiResult
::setContent( $errMessage, $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : '' );
656 // Remember all the warnings to re-add them later
657 $oldResult = $result->getData();
658 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
661 $result->disableSizeCheck();
663 $requestid = $this->getParameter( 'requestid' );
664 if ( !is_null( $requestid ) ) {
665 $result->addValue( null, 'requestid', $requestid );
667 if ( $wgShowHostnames ) {
668 // servedby is especially useful when debugging errors
669 $result->addValue( null, 'servedby', wfHostName() );
671 if ( $warnings !== null ) {
672 $result->addValue( null, 'warnings', $warnings );
675 $result->addValue( null, 'error', $errMessage );
677 return $errMessage['code'];
681 * Set up for the execution.
684 protected function setupExecuteAction() {
685 global $wgShowHostnames;
687 // First add the id to the top element
688 $result = $this->getResult();
689 $requestid = $this->getParameter( 'requestid' );
690 if ( !is_null( $requestid ) ) {
691 $result->addValue( null, 'requestid', $requestid );
694 if ( $wgShowHostnames ) {
695 $servedby = $this->getParameter( 'servedby' );
697 $result->addValue( null, 'servedby', wfHostName() );
701 $params = $this->extractRequestParams();
703 $this->mAction
= $params['action'];
705 if ( !is_string( $this->mAction
) ) {
706 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
713 * Set up the module for response
714 * @return ApiBase The module that will handle this action
716 protected function setupModule() {
717 // Instantiate the module requested by the user
718 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
719 if ( $module === null ) {
720 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
722 $moduleParams = $module->extractRequestParams();
724 // Die if token required, but not provided
725 $salt = $module->getTokenSalt();
726 if ( $salt !== false ) {
727 if ( !isset( $moduleParams['token'] ) ) {
728 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
730 if ( !$this->getUser()->matchEditToken( $moduleParams['token'], $salt, $this->getContext()->getRequest() ) ) {
731 $this->dieUsageMsg( 'sessionfailure' );
740 * Check the max lag if necessary
741 * @param $module ApiBase object: Api module being used
742 * @param array $params an array containing the request parameters.
743 * @return boolean True on success, false should exit immediately
745 protected function checkMaxLag( $module, $params ) {
746 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
748 global $wgShowHostnames;
749 $maxLag = $params['maxlag'];
750 list( $host, $lag ) = wfGetLB()->getMaxLag();
751 if ( $lag > $maxLag ) {
752 $response = $this->getRequest()->response();
754 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
755 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
757 if ( $wgShowHostnames ) {
758 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
760 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
771 * Check for sufficient permissions to execute
772 * @param $module ApiBase An Api module
774 protected function checkExecutePermissions( $module ) {
775 $user = $this->getUser();
776 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
777 !$user->isAllowed( 'read' )
779 $this->dieUsageMsg( 'readrequired' );
781 if ( $module->isWriteMode() ) {
782 if ( !$this->mEnableWrite
) {
783 $this->dieUsageMsg( 'writedisabled' );
785 if ( !$user->isAllowed( 'writeapi' ) ) {
786 $this->dieUsageMsg( 'writerequired' );
788 if ( wfReadOnly() ) {
789 $this->dieReadOnly();
793 // Allow extensions to stop execution for arbitrary reasons.
795 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
796 $this->dieUsageMsg( $message );
801 * Check POST for external response and setup result printer
802 * @param $module ApiBase An Api module
803 * @param array $params an array with the request parameters
805 protected function setupExternalResponse( $module, $params ) {
806 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
807 // Module requires POST. GET request might still be allowed
808 // if $wgDebugApi is true, otherwise fail.
809 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
812 // See if custom printer is used
813 $this->mPrinter
= $module->getCustomPrinter();
814 if ( is_null( $this->mPrinter
) ) {
815 // Create an appropriate printer
816 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
819 if ( $this->mPrinter
->getNeedsRawData() ) {
820 $this->getResult()->setRawMode();
825 * Execute the actual module, without any error handling
827 protected function executeAction() {
828 $params = $this->setupExecuteAction();
829 $module = $this->setupModule();
830 $this->mModule
= $module;
832 $this->checkExecutePermissions( $module );
834 if ( !$this->checkMaxLag( $module, $params ) ) {
838 if ( !$this->mInternalMode
) {
839 $this->setupExternalResponse( $module, $params );
843 $module->profileIn();
845 wfRunHooks( 'APIAfterExecute', array( &$module ) );
846 $module->profileOut();
848 $this->reportUnusedParams();
850 if ( !$this->mInternalMode
) {
851 //append Debug information
852 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
855 $this->printResult( false );
860 * Log the preceding request
861 * @param int $time Time in seconds
863 protected function logRequest( $time ) {
864 $request = $this->getRequest();
865 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
867 ' ' . $request->getMethod() .
868 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
869 ' ' . $request->getIP() .
870 ' T=' . $milliseconds . 'ms';
871 foreach ( $this->getParamsUsed() as $name ) {
872 $value = $request->getVal( $name );
873 if ( $value === null ) {
876 $s .= ' ' . $name . '=';
877 if ( strlen( $value ) > 256 ) {
878 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
879 $s .= $encValue . '[...]';
881 $s .= $this->encodeRequestLogValue( $value );
885 wfDebugLog( 'api', $s, false );
889 * Encode a value in a format suitable for a space-separated log line.
891 protected function encodeRequestLogValue( $s ) {
894 $chars = ';@$!*(),/:';
895 for ( $i = 0; $i < strlen( $chars ); $i++
) {
896 $table[rawurlencode( $chars[$i] )] = $chars[$i];
900 return strtr( rawurlencode( $s ), $table );
904 * Get the request parameters used in the course of the preceding execute() request
906 protected function getParamsUsed() {
907 return array_keys( $this->mParamsUsed
);
911 * Get a request value, and register the fact that it was used, for logging.
913 public function getVal( $name, $default = null ) {
914 $this->mParamsUsed
[$name] = true;
916 return $this->getRequest()->getVal( $name, $default );
920 * Get a boolean request value, and register the fact that the parameter
921 * was used, for logging.
923 public function getCheck( $name ) {
924 $this->mParamsUsed
[$name] = true;
926 return $this->getRequest()->getCheck( $name );
930 * Get a request upload, and register the fact that it was used, for logging.
933 * @param string $name Parameter name
934 * @return WebRequestUpload
936 public function getUpload( $name ) {
937 $this->mParamsUsed
[$name] = true;
939 return $this->getRequest()->getUpload( $name );
943 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
944 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
946 protected function reportUnusedParams() {
947 $paramsUsed = $this->getParamsUsed();
948 $allParams = $this->getRequest()->getValueNames();
950 if ( !$this->mInternalMode
) {
951 // Printer has not yet executed; don't warn that its parameters are unused
952 $printerParams = array_map(
953 array( $this->mPrinter
, 'encodeParamName' ),
954 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
956 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
958 $unusedParams = array_diff( $allParams, $paramsUsed );
961 if ( count( $unusedParams ) ) {
962 $s = count( $unusedParams ) > 1 ?
's' : '';
963 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
968 * Print results using the current printer
970 * @param $isError bool
972 protected function printResult( $isError ) {
974 if ( $wgDebugAPI !== false ) {
975 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
978 $this->getResult()->cleanUpUTF8();
979 $printer = $this->mPrinter
;
980 $printer->profileIn();
983 * If the help message is requested in the default (xmlfm) format,
984 * tell the printer not to escape ampersands so that our links do
987 $isHelp = $isError ||
$this->mAction
== 'help';
988 $printer->setUnescapeAmps( $isHelp && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
990 $printer->initPrinter( $isHelp );
993 $printer->closePrinter();
994 $printer->profileOut();
1000 public function isReadMode() {
1005 * See ApiBase for description.
1009 public function getAllowedParams() {
1012 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1013 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'format' )
1016 ApiBase
::PARAM_DFLT
=> 'help',
1017 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'action' )
1020 ApiBase
::PARAM_TYPE
=> 'integer'
1023 ApiBase
::PARAM_TYPE
=> 'integer',
1024 ApiBase
::PARAM_DFLT
=> 0
1027 ApiBase
::PARAM_TYPE
=> 'integer',
1028 ApiBase
::PARAM_DFLT
=> 0
1030 'requestid' => null,
1031 'servedby' => false,
1037 * See ApiBase for description.
1041 public function getParamDescription() {
1043 'format' => 'The format of the output',
1044 'action' => 'What action you would like to perform. See below for module help',
1046 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1047 'To save actions causing any more site replication lag, this parameter can make the client',
1048 'wait until the replication lag is less than the specified value.',
1049 'In case of a replag error, error code "maxlag" is returned, with the message like',
1050 '"Waiting for $host: $lag seconds lagged\n".',
1051 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1053 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1054 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1055 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1056 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
1058 'When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain.',
1059 'This must be included in any pre-flight request, and therefore must be part of the request URI (not the POST body).',
1060 'This must match one of the origins in the Origin: header exactly, so it has to be set to something like http://en.wikipedia.org or https://meta.wikimedia.org .',
1061 'If this parameter does not match the Origin: header, a 403 response will be returned.',
1062 'If this parameter matches the Origin: header and the origin is whitelisted, an Access-Control-Allow-Origin header will be set.',
1068 * See ApiBase for description.
1072 public function getDescription() {
1076 '**********************************************************************************************************',
1078 '** This is an auto-generated MediaWiki API documentation page **',
1080 '** Documentation and Examples: **',
1081 '** https://www.mediawiki.org/wiki/API **',
1083 '**********************************************************************************************************',
1085 'Status: All features shown on this page should be working, but the API',
1086 ' is still in active development, and may change at any time.',
1087 ' Make sure to monitor our mailing list for any updates',
1089 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1090 ' with the key "MediaWiki-API-Error" and then both the value of the',
1091 ' header and the error code sent back will be set to the same value',
1093 ' In the case of an invalid action being passed, these will have a value',
1094 ' of "unknown_action"',
1096 ' For more information see https://www.mediawiki.org/wiki/API:Errors_and_warnings',
1098 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1099 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1100 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1101 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1102 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1114 public function getPossibleErrors() {
1115 return array_merge( parent
::getPossibleErrors(), array(
1116 array( 'readonlytext' ),
1117 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1118 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1119 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1120 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1125 * Returns an array of strings with credits for the API
1128 protected function getCredits() {
1131 ' Roan Kattouw "<Firstname>.<Lastname>@gmail.com" (lead developer Sep 2007-2009)',
1132 ' Victor Vasiliev - vasilvv @ gmail . com',
1133 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
1134 ' Sam Reed - sam @ reedyboy . net',
1135 ' Yuri Astrakhan "<Firstname><Lastname>@gmail.com" (creator, lead developer Sep 2006-Sep 2007, 2012-present)',
1137 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1138 'or file a bug report at https://bugzilla.wikimedia.org/'
1143 * Sets whether the pretty-printer should format *bold* and $italics$
1147 public function setHelp( $help = true ) {
1148 $this->mPrinter
->setHelp( $help );
1152 * Override the parent to generate help messages for all available modules.
1156 public function makeHelpMsg() {
1157 global $wgMemc, $wgAPICacheHelpTimeout;
1159 // Get help text from cache if present
1160 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1161 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1162 if ( $wgAPICacheHelpTimeout > 0 ) {
1163 $cached = $wgMemc->get( $key );
1168 $retval = $this->reallyMakeHelpMsg();
1169 if ( $wgAPICacheHelpTimeout > 0 ) {
1170 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1177 * @return mixed|string
1179 public function reallyMakeHelpMsg() {
1182 // Use parent to make default message for the main module
1183 $msg = parent
::makeHelpMsg();
1185 $astriks = str_repeat( '*** ', 14 );
1186 $msg .= "\n\n$astriks Modules $astriks\n\n";
1188 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1189 $module = $this->mModuleMgr
->getModule( $name );
1190 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1192 $msg2 = $module->makeHelpMsg();
1193 if ( $msg2 !== false ) {
1199 $msg .= "\n$astriks Permissions $astriks\n\n";
1200 foreach ( self
::$mRights as $right => $rightMsg ) {
1201 $groups = User
::getGroupsWithPermission( $right );
1202 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1203 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1206 $msg .= "\n$astriks Formats $astriks\n\n";
1207 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1208 $module = $this->mModuleMgr
->getModule( $name );
1209 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1210 $msg2 = $module->makeHelpMsg();
1211 if ( $msg2 !== false ) {
1217 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1223 * @param $module ApiBase
1224 * @param string $paramName What type of request is this? e.g. action, query, list, prop, meta, format
1227 public static function makeHelpMsgHeader( $module, $paramName ) {
1228 $modulePrefix = $module->getModulePrefix();
1229 if ( strval( $modulePrefix ) !== '' ) {
1230 $modulePrefix = "($modulePrefix) ";
1233 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1236 private $mCanApiHighLimits = null;
1239 * Check whether the current user is allowed to use high limits
1242 public function canApiHighLimits() {
1243 if ( !isset( $this->mCanApiHighLimits
) ) {
1244 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1247 return $this->mCanApiHighLimits
;
1251 * Check whether the user wants us to show version information in the API help
1253 * @deprecated since 1.21, always returns false
1255 public function getShowVersions() {
1256 wfDeprecated( __METHOD__
, '1.21' );
1262 * Overrides to return this instance's module manager.
1263 * @return ApiModuleManager
1265 public function getModuleManager() {
1266 return $this->mModuleMgr
;
1270 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1271 * classes who wish to add their own modules to their lexicon or override the
1272 * behavior of inherent ones.
1274 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1275 * @param string $name The identifier for this module.
1276 * @param $class ApiBase The class where this module is implemented.
1278 protected function addModule( $name, $class ) {
1279 $this->getModuleManager()->addModule( $name, 'action', $class );
1283 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1284 * classes who wish to add to or modify current formatters.
1286 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1287 * @param string $name The identifier for this format.
1288 * @param $class ApiFormatBase The class implementing this format.
1290 protected function addFormat( $name, $class ) {
1291 $this->getModuleManager()->addModule( $name, 'format', $class );
1295 * Get the array mapping module names to class names
1296 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1299 function getModules() {
1300 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1304 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1307 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1310 public function getFormats() {
1311 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1316 * This exception will be thrown when dieUsage is called to stop module execution.
1317 * The exception handling code will print a help screen explaining how this API may be used.
1321 class UsageException
extends MWException
{
1328 private $mExtraData;
1331 * @param $message string
1332 * @param $codestr string
1334 * @param $extradata array|null
1336 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1337 parent
::__construct( $message, $code );
1338 $this->mCodestr
= $codestr;
1339 $this->mExtraData
= $extradata;
1345 public function getCodeString() {
1346 return $this->mCodestr
;
1352 public function getMessageArray() {
1354 'code' => $this->mCodestr
,
1355 'info' => $this->getMessage()
1357 if ( is_array( $this->mExtraData
) ) {
1358 $result = array_merge( $result, $this->mExtraData
);
1367 public function __toString() {
1368 return "{$this->getCodeString()}: {$this->getMessage()}";