3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Timestamp\TimestampException
;
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
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * When no uselang parameter is given, this language will be used
50 const API_DEFAULT_USELANG
= 'user';
53 * List of available modules: action name => module class
55 private static $Modules = [
56 'login' => ApiLogin
::class,
57 'clientlogin' => ApiClientLogin
::class,
58 'logout' => ApiLogout
::class,
59 'createaccount' => ApiAMCreateAccount
::class,
60 'linkaccount' => ApiLinkAccount
::class,
61 'unlinkaccount' => ApiRemoveAuthenticationData
::class,
62 'changeauthenticationdata' => ApiChangeAuthenticationData
::class,
63 'removeauthenticationdata' => ApiRemoveAuthenticationData
::class,
64 'resetpassword' => ApiResetPassword
::class,
65 'query' => ApiQuery
::class,
66 'expandtemplates' => ApiExpandTemplates
::class,
67 'parse' => ApiParse
::class,
68 'stashedit' => ApiStashEdit
::class,
69 'opensearch' => ApiOpenSearch
::class,
70 'feedcontributions' => ApiFeedContributions
::class,
71 'feedrecentchanges' => ApiFeedRecentChanges
::class,
72 'feedwatchlist' => ApiFeedWatchlist
::class,
73 'help' => ApiHelp
::class,
74 'paraminfo' => ApiParamInfo
::class,
75 'rsd' => ApiRsd
::class,
76 'compare' => ApiComparePages
::class,
77 'tokens' => ApiTokens
::class,
78 'checktoken' => ApiCheckToken
::class,
79 'cspreport' => ApiCSPReport
::class,
80 'validatepassword' => ApiValidatePassword
::class,
83 'purge' => ApiPurge
::class,
84 'setnotificationtimestamp' => ApiSetNotificationTimestamp
::class,
85 'rollback' => ApiRollback
::class,
86 'delete' => ApiDelete
::class,
87 'undelete' => ApiUndelete
::class,
88 'protect' => ApiProtect
::class,
89 'block' => ApiBlock
::class,
90 'unblock' => ApiUnblock
::class,
91 'move' => ApiMove
::class,
92 'edit' => ApiEditPage
::class,
93 'upload' => ApiUpload
::class,
94 'filerevert' => ApiFileRevert
::class,
95 'emailuser' => ApiEmailUser
::class,
96 'watch' => ApiWatch
::class,
97 'patrol' => ApiPatrol
::class,
98 'import' => ApiImport
::class,
99 'clearhasmsg' => ApiClearHasMsg
::class,
100 'userrights' => ApiUserrights
::class,
101 'options' => ApiOptions
::class,
102 'imagerotate' => ApiImageRotate
::class,
103 'revisiondelete' => ApiRevisionDelete
::class,
104 'managetags' => ApiManageTags
::class,
105 'tag' => ApiTag
::class,
106 'mergehistory' => ApiMergeHistory
::class,
107 'setpagelanguage' => ApiSetPageLanguage
::class,
111 * List of available formats: format name => format class
113 private static $Formats = [
114 'json' => ApiFormatJson
::class,
115 'jsonfm' => ApiFormatJson
::class,
116 'php' => ApiFormatPhp
::class,
117 'phpfm' => ApiFormatPhp
::class,
118 'xml' => ApiFormatXml
::class,
119 'xmlfm' => ApiFormatXml
::class,
120 'rawfm' => ApiFormatJson
::class,
121 'none' => ApiFormatNone
::class,
125 * List of user roles that are specifically relevant to the API.
126 * [ 'right' => [ 'msg' => 'Some message with a $1',
127 * 'params' => [ $someVarToSubst ] ],
130 private static $mRights = [
132 'msg' => 'right-writeapi',
136 'msg' => 'api-help-right-apihighlimits',
137 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
146 private $mModuleMgr, $mResult, $mErrorFormatter = null;
147 /** @var ApiContinuationManager|null */
148 private $mContinuationManager;
150 private $mEnableWrite;
151 private $mInternalMode, $mCdnMaxAge;
155 private $mCacheMode = 'private';
157 private $mCacheControl = [];
158 private $mParamsUsed = [];
159 private $mParamsSensitive = [];
161 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
162 private $lacksSameOriginSecurity = null;
165 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
167 * @param IContextSource|WebRequest|null $context If this is an instance of
168 * FauxRequest, errors are thrown and no printing occurs
169 * @param bool $enableWrite Should be set to true if the api may modify data
170 * @suppress PhanUndeclaredMethod
172 public function __construct( $context = null, $enableWrite = false ) {
173 if ( $context === null ) {
174 $context = RequestContext
::getMain();
175 } elseif ( $context instanceof WebRequest
) {
178 $context = RequestContext
::getMain();
180 // We set a derivative context so we can change stuff later
181 $this->setContext( new DerivativeContext( $context ) );
183 if ( isset( $request ) ) {
184 $this->getContext()->setRequest( $request );
186 $request = $this->getRequest();
189 $this->mInternalMode
= ( $request instanceof FauxRequest
);
191 // Special handling for the main module: $parent === $this
192 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
194 $config = $this->getConfig();
196 if ( !$this->mInternalMode
) {
197 // Log if a request with a non-whitelisted Origin header is seen
198 // with session cookies.
199 $originHeader = $request->getHeader( 'Origin' );
200 if ( $originHeader === false ) {
203 $originHeader = trim( $originHeader );
204 $origins = preg_split( '/\s+/', $originHeader );
206 $sessionCookies = array_intersect(
207 array_keys( $_COOKIE ),
208 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
210 if ( $origins && $sessionCookies && (
211 count( $origins ) !== 1 ||
!self
::matchOrigin(
213 $config->get( 'CrossSiteAJAXdomains' ),
214 $config->get( 'CrossSiteAJAXdomainExceptions' )
217 LoggerFactory
::getInstance( 'cors' )->warning(
218 'Non-whitelisted CORS request with session cookies', [
219 'origin' => $originHeader,
220 'cookies' => $sessionCookies,
221 'ip' => $request->getIP(),
222 'userAgent' => $this->getUserAgent(),
223 'wiki' => WikiMap
::getCurrentWikiDbDomain()->getId(),
228 // If we're in a mode that breaks the same-origin policy, strip
229 // user credentials for security.
230 if ( $this->lacksSameOriginSecurity() ) {
232 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
233 $wgUser = new User();
234 $this->getContext()->setUser( $wgUser );
235 $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
239 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
241 // Setup uselang. This doesn't use $this->getParameter()
242 // because we're not ready to handle errors yet.
243 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
244 $uselang = $request->getRawVal( 'uselang', self
::API_DEFAULT_USELANG
);
245 if ( $uselang === 'user' ) {
246 // Assume the parent context is going to return the user language
247 // for uselang=user (see T85635).
249 if ( $uselang === 'content' ) {
250 $uselang = MediaWikiServices
::getInstance()->getContentLanguage()->getCode();
252 $code = RequestContext
::sanitizeLangCode( $uselang );
253 $this->getContext()->setLanguage( $code );
254 if ( !$this->mInternalMode
) {
256 $wgLang = $this->getContext()->getLanguage();
257 RequestContext
::getMain()->setLanguage( $wgLang );
261 // Set up the error formatter. This doesn't use $this->getParameter()
262 // because we're not ready to handle errors yet.
263 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
264 $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
265 $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
266 $errorsUseDB = $request->getCheck( 'errorsuselocal' );
267 if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
268 if ( $errorLangCode === 'uselang' ) {
269 $errorLang = $this->getLanguage();
270 } elseif ( $errorLangCode === 'content' ) {
271 $errorLang = MediaWikiServices
::getInstance()->getContentLanguage();
273 $errorLangCode = RequestContext
::sanitizeLangCode( $errorLangCode );
274 $errorLang = Language
::factory( $errorLangCode );
276 $this->mErrorFormatter
= new ApiErrorFormatter(
277 $this->mResult
, $errorLang, $errorFormat, $errorsUseDB
280 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
282 $this->mResult
->setErrorFormatter( $this->getErrorFormatter() );
284 $this->mModuleMgr
= new ApiModuleManager( $this );
285 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
286 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
287 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
288 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
290 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
292 $this->mContinuationManager
= null;
293 $this->mEnableWrite
= $enableWrite;
295 $this->mCdnMaxAge
= -1; // flag for executeActionWithErrorHandling()
299 * Return true if the API was started by other PHP code using FauxRequest
302 public function isInternalMode() {
303 return $this->mInternalMode
;
307 * Get the ApiResult object associated with current request
311 public function getResult() {
312 return $this->mResult
;
316 * Get the security flag for the current request
319 public function lacksSameOriginSecurity() {
320 if ( $this->lacksSameOriginSecurity
!== null ) {
321 return $this->lacksSameOriginSecurity
;
324 $request = $this->getRequest();
327 if ( $request->getCheck( 'callback' ) ) {
328 $this->lacksSameOriginSecurity
= true;
333 if ( $request->getVal( 'origin' ) === '*' ) {
334 $this->lacksSameOriginSecurity
= true;
338 // Header to be used from XMLHTTPRequest when the request might
339 // otherwise be used for XSS.
340 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
341 $this->lacksSameOriginSecurity
= true;
345 // Allow extensions to override.
346 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
347 return $this->lacksSameOriginSecurity
;
351 * Get the ApiErrorFormatter object associated with current request
352 * @return ApiErrorFormatter
354 public function getErrorFormatter() {
355 return $this->mErrorFormatter
;
359 * Get the continuation manager
360 * @return ApiContinuationManager|null
362 public function getContinuationManager() {
363 return $this->mContinuationManager
;
367 * Set the continuation manager
368 * @param ApiContinuationManager|null $manager
370 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
371 if ( $manager !== null && $this->mContinuationManager
!== null ) {
372 throw new UnexpectedValueException(
373 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
374 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
377 $this->mContinuationManager
= $manager;
381 * Get the API module object. Only works after executeAction()
385 public function getModule() {
386 return $this->mModule
;
390 * Get the result formatter object. Only works after setupExecuteAction()
392 * @return ApiFormatBase
394 public function getPrinter() {
395 return $this->mPrinter
;
399 * Set how long the response should be cached.
403 public function setCacheMaxAge( $maxage ) {
404 $this->setCacheControl( [
405 'max-age' => $maxage,
406 's-maxage' => $maxage
411 * Set the type of caching headers which will be sent.
413 * @param string $mode One of:
414 * - 'public': Cache this object in public caches, if the maxage or smaxage
415 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
416 * not provided by any of these means, the object will be private.
417 * - 'private': Cache this object only in private client-side caches.
418 * - 'anon-public-user-private': Make this object cacheable for logged-out
419 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
420 * set consistently for a given URL, it cannot be set differently depending on
421 * things like the contents of the database, or whether the user is logged in.
423 * If the wiki does not allow anonymous users to read it, the mode set here
424 * will be ignored, and private caching headers will always be sent. In other words,
425 * the "public" mode is equivalent to saying that the data sent is as public as a page
428 * For user-dependent data, the private mode should generally be used. The
429 * anon-public-user-private mode should only be used where there is a particularly
430 * good performance reason for caching the anonymous response, but where the
431 * response to logged-in users may differ, or may contain private data.
433 * If this function is never called, then the default will be the private mode.
435 public function setCacheMode( $mode ) {
436 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
437 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
439 // Ignore for forwards-compatibility
443 if ( !User
::isEveryoneAllowed( 'read' ) ) {
444 // Private wiki, only private headers
445 if ( $mode !== 'private' ) {
446 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
452 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
453 // User language is used for i18n, so we don't want to publicly
454 // cache. Anons are ok, because if they have non-default language
455 // then there's an appropriate Vary header set by whatever set
456 // their non-default language.
457 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
458 "'anon-public-user-private' due to uselang=user\n" );
459 $mode = 'anon-public-user-private';
462 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
463 $this->mCacheMode
= $mode;
467 * Set directives (key/value pairs) for the Cache-Control header.
468 * Boolean values will be formatted as such, by including or omitting
469 * without an equals sign.
471 * Cache control values set here will only be used if the cache mode is not
472 * private, see setCacheMode().
474 * @param array $directives
476 public function setCacheControl( $directives ) {
477 $this->mCacheControl
= $directives +
$this->mCacheControl
;
481 * Create an instance of an output formatter by its name
483 * @param string $format
485 * @return ApiFormatBase
487 public function createPrinterByName( $format ) {
488 $printer = $this->mModuleMgr
->getModule( $format, 'format', /* $ignoreCache */ true );
489 if ( $printer === null ) {
491 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
499 * Execute api request. Any errors will be handled if the API was called by the remote client.
501 public function execute() {
502 if ( $this->mInternalMode
) {
503 $this->executeAction();
505 $this->executeActionWithErrorHandling();
510 * Execute an action, and in case of an error, erase whatever partial results
511 * have been accumulated, and replace it with an error message and a help screen.
513 protected function executeActionWithErrorHandling() {
514 // Verify the CORS header before executing the action
515 if ( !$this->handleCORS() ) {
516 // handleCORS() has sent a 403, abort
520 // Exit here if the request method was OPTIONS
521 // (assume there will be a followup GET or POST)
522 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
526 // In case an error occurs during data output,
527 // clear the output buffer and print just the error information
528 $obLevel = ob_get_level();
531 $t = microtime( true );
534 $this->executeAction();
535 $runTime = microtime( true ) - $t;
536 $this->logRequest( $runTime );
537 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
538 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
540 } catch ( Exception
$e ) { // @todo Remove this block when HHVM is no longer supported
541 $this->handleException( $e );
542 $this->logRequest( microtime( true ) - $t, $e );
544 } catch ( Throwable
$e ) {
545 $this->handleException( $e );
546 $this->logRequest( microtime( true ) - $t, $e );
550 // Commit DBs and send any related cookies and headers
551 MediaWiki
::preOutputCommit( $this->getContext() );
553 // Send cache headers after any code which might generate an error, to
554 // avoid sending public cache headers for errors.
555 $this->sendCacheHeaders( $isError );
557 // Executing the action might have already messed with the output
559 while ( ob_get_level() > $obLevel ) {
565 * Handle an exception as an API response
568 * @param Exception|Throwable $e
570 protected function handleException( $e ) {
571 // T65145: Rollback any open database transactions
572 if ( !$e instanceof ApiUsageException
) {
573 // ApiUsageExceptions are intentional, so don't rollback if that's the case
574 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
577 // Allow extra cleanup and logging
578 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
580 // Handle any kind of exception by outputting properly formatted error message.
581 // If this fails, an unhandled exception should be thrown so that global error
582 // handler will process and log it.
584 $errCodes = $this->substituteResultWithError( $e );
586 // Error results should not be cached
587 $this->setCacheMode( 'private' );
589 $response = $this->getRequest()->response();
590 $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
591 $response->header( $headerStr );
593 // Reset and print just the error message
596 // Printer may not be initialized if the extractRequestParams() fails for the main module
597 $this->createErrorPrinter();
599 // Get desired HTTP code from an ApiUsageException. Don't use codes from other
600 // exception types, as they are unlikely to be intended as an HTTP code.
601 $httpCode = $e instanceof ApiUsageException ?
$e->getCode() : 0;
605 $this->printResult( $httpCode );
606 } catch ( ApiUsageException
$ex ) {
607 // The error printer itself is failing. Try suppressing its request
608 // parameters and redo.
610 $this->addWarning( 'apiwarn-errorprinterfailed' );
611 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
613 $this->mPrinter
->addWarning( $error );
614 } catch ( Exception
$ex2 ) { // @todo Remove this block when HHVM is no longer supported
616 $this->addWarning( $error );
617 } catch ( Throwable
$ex2 ) {
619 $this->addWarning( $error );
624 $this->mPrinter
= null;
625 $this->createErrorPrinter();
626 $this->mPrinter
->forceDefaultParams();
628 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
630 $this->printResult( $httpCode );
635 * Handle an exception from the ApiBeforeMain hook.
637 * This tries to print the exception as an API response, to be more
638 * friendly to clients. If it fails, it will rethrow the exception.
641 * @param Exception|Throwable $e
642 * @throws Exception|Throwable
644 public static function handleApiBeforeMainException( $e ) {
648 $main = new self( RequestContext
::getMain(), false );
649 $main->handleException( $e );
650 $main->logRequest( 0, $e );
651 } catch ( Exception
$e2 ) { // @todo Remove this block when HHVM is no longer supported
652 // Nope, even that didn't work. Punt.
654 } catch ( Throwable
$e2 ) {
655 // Nope, even that didn't work. Punt.
659 // Reset cache headers
660 $main->sendCacheHeaders( true );
666 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
668 * If no origin parameter is present, nothing happens.
669 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
670 * is set and false is returned.
671 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
672 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
674 * https://www.w3.org/TR/cors/#resource-requests
675 * https://www.w3.org/TR/cors/#resource-preflight-requests
677 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
679 protected function handleCORS() {
680 $originParam = $this->getParameter( 'origin' ); // defaults to null
681 if ( $originParam === null ) {
682 // No origin parameter, nothing to do
686 $request = $this->getRequest();
687 $response = $request->response();
689 $matchedOrigin = false;
690 $allowTiming = false;
693 if ( $originParam === '*' ) {
694 // Request for anonymous CORS
695 // Technically we should check for the presence of an Origin header
696 // and not process it as CORS if it's not set, but that would
697 // require us to vary on Origin for all 'origin=*' requests which
698 // we don't want to do.
699 $matchedOrigin = true;
701 $allowCredentials = 'false';
702 $varyOrigin = false; // No need to vary
704 // Non-anonymous CORS, check we allow the domain
706 // Origin: header is a space-separated list of origins, check all of them
707 $originHeader = $request->getHeader( 'Origin' );
708 if ( $originHeader === false ) {
711 $originHeader = trim( $originHeader );
712 $origins = preg_split( '/\s+/', $originHeader );
715 if ( !in_array( $originParam, $origins ) ) {
716 // origin parameter set but incorrect
717 // Send a 403 response
718 $response->statusHeader( 403 );
719 $response->header( 'Cache-Control: no-cache' );
720 echo "'origin' parameter does not match Origin header\n";
725 $config = $this->getConfig();
726 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
728 $config->get( 'CrossSiteAJAXdomains' ),
729 $config->get( 'CrossSiteAJAXdomainExceptions' )
732 $allowOrigin = $originHeader;
733 $allowCredentials = 'true';
734 $allowTiming = $originHeader;
737 if ( $matchedOrigin ) {
738 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
739 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
741 // This is a CORS preflight request
742 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
743 // If method is not a case-sensitive match, do not set any additional headers and terminate.
744 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
747 // We allow the actual request to send the following headers
748 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
749 if ( $requestedHeaders !== false ) {
750 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
751 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
754 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
757 // We only allow the actual request to be GET or POST
758 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
759 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
760 // Unsupported non-preflight method, don't handle it as CORS
762 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
767 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
768 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
769 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
770 if ( $allowTiming !== false ) {
771 $response->header( "Timing-Allow-Origin: $allowTiming" );
776 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
777 . 'MediaWiki-Login-Suppressed'
781 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
785 $this->getOutput()->addVaryHeader( 'Origin' );
792 * Attempt to match an Origin header against a set of rules and a set of exceptions
793 * @param string $value Origin header
794 * @param array $rules Set of wildcard rules
795 * @param array $exceptions Set of wildcard rules
796 * @return bool True if $value matches a rule in $rules and doesn't match
797 * any rules in $exceptions, false otherwise
799 protected static function matchOrigin( $value, $rules, $exceptions ) {
800 foreach ( $rules as $rule ) {
801 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
802 // Rule matches, check exceptions
803 foreach ( $exceptions as $exc ) {
804 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
817 * Attempt to validate the value of Access-Control-Request-Headers against a list
818 * of headers that we allow the follow up request to send.
820 * @param string $requestedHeaders Comma separated list of HTTP headers
821 * @return bool True if all requested headers are in the list of allowed headers
823 protected static function matchRequestedHeaders( $requestedHeaders ) {
824 if ( trim( $requestedHeaders ) === '' ) {
827 $requestedHeaders = explode( ',', $requestedHeaders );
828 $allowedAuthorHeaders = array_flip( [
829 /* simple headers (see spec) */
834 /* non-authorable headers in XHR, which are however requested by some UAs */
838 /* MediaWiki whitelist */
842 foreach ( $requestedHeaders as $rHeader ) {
843 $rHeader = strtolower( trim( $rHeader ) );
844 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
845 LoggerFactory
::getInstance( 'api-warning' )->warning(
846 'CORS preflight failed on requested header: {header}', [
857 * Helper function to convert wildcard string into a regex
861 * @param string $wildcard String with wildcards
862 * @return string Regular expression
864 protected static function wildcardToRegex( $wildcard ) {
865 $wildcard = preg_quote( $wildcard, '/' );
866 $wildcard = str_replace(
872 return "/^https?:\/\/$wildcard$/";
876 * Send caching headers
877 * @param bool $isError Whether an error response is being output
878 * @since 1.26 added $isError parameter
880 protected function sendCacheHeaders( $isError ) {
881 $response = $this->getRequest()->response();
882 $out = $this->getOutput();
884 $out->addVaryHeader( 'Treat-as-Untrusted' );
886 $config = $this->getConfig();
888 if ( $config->get( 'VaryOnXFP' ) ) {
889 $out->addVaryHeader( 'X-Forwarded-Proto' );
892 if ( !$isError && $this->mModule
&&
893 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
895 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
896 if ( $etag !== null ) {
897 $response->header( "ETag: $etag" );
899 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
900 if ( $lastMod !== null ) {
901 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
905 // The logic should be:
906 // $this->mCacheControl['max-age'] is set?
907 // Use it, the module knows better than our guess.
908 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
909 // Use 0 because we can guess caching is probably the wrong thing to do.
910 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
912 if ( isset( $this->mCacheControl
['max-age'] ) ) {
913 $maxage = $this->mCacheControl
['max-age'];
914 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
915 $this->mCacheMode
!== 'private'
917 $maxage = $this->getParameter( 'maxage' );
919 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
921 if ( $this->mCacheMode
== 'private' ) {
922 $response->header( "Cache-Control: $privateCache" );
926 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
927 $out->addVaryHeader( 'Cookie' );
928 $response->header( $out->getVaryHeader() );
929 if ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
930 // Logged in or otherwise has session (e.g. anonymous users who have edited)
931 // Mark request private
932 $response->header( "Cache-Control: $privateCache" );
935 } // else anonymous, send public headers below
938 // Send public headers
939 $response->header( $out->getVaryHeader() );
941 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
942 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
943 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
945 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
946 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
949 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
950 // Public cache not requested
951 // Sending a Vary header in this case is harmless, and protects us
952 // against conditional calls of setCacheMaxAge().
953 $response->header( "Cache-Control: $privateCache" );
958 $this->mCacheControl
['public'] = true;
960 // Send an Expires header
961 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
962 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
963 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
965 // Construct the Cache-Control header
968 foreach ( $this->mCacheControl
as $name => $value ) {
969 if ( is_bool( $value ) ) {
971 $ccHeader .= $separator . $name;
975 $ccHeader .= $separator . "$name=$value";
980 $response->header( "Cache-Control: $ccHeader" );
984 * Create the printer for error output
986 private function createErrorPrinter() {
987 if ( !isset( $this->mPrinter
) ) {
988 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
989 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
990 $value = self
::API_DEFAULT_FORMAT
;
992 $this->mPrinter
= $this->createPrinterByName( $value );
995 // Printer may not be able to handle errors. This is particularly
996 // likely if the module returns something for getCustomPrinter().
997 if ( !$this->mPrinter
->canPrintErrors() ) {
998 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1003 * Create an error message for the given exception.
1005 * If an ApiUsageException, errors/warnings will be extracted from the
1006 * embedded StatusValue.
1008 * Any other exception will be returned with a generic code and wrapper
1009 * text around the exception's (presumably English) message as a single
1010 * error (no warnings).
1012 * @param Exception|Throwable $e
1013 * @param string $type 'error' or 'warning'
1014 * @return ApiMessage[]
1017 protected function errorMessagesFromException( $e, $type = 'error' ) {
1019 if ( $e instanceof ApiUsageException
) {
1020 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1021 $messages[] = ApiMessage
::create( $error );
1023 } elseif ( $type !== 'error' ) {
1024 // None of the rest have any messages for non-error types
1026 // Something is seriously wrong
1027 $config = $this->getConfig();
1028 // TODO: Avoid embedding arbitrary class names in the error code.
1029 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1030 $code = 'internal_api_error_' . $class;
1031 $data = [ 'errorclass' => get_class( $e ) ];
1032 if ( $config->get( 'ShowExceptionDetails' ) ) {
1033 if ( $e instanceof ILocalizedException
) {
1034 $msg = $e->getMessageObject();
1035 } elseif ( $e instanceof MessageSpecifier
) {
1036 $msg = Message
::newFromSpecifier( $e );
1038 $msg = wfEscapeWikiText( $e->getMessage() );
1040 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1042 $params = [ 'apierror-exceptioncaughttype', WebRequest
::getRequestId(), get_class( $e ) ];
1045 $messages[] = ApiMessage
::create( $params, $code, $data );
1051 * Replace the result data with the information about an exception.
1052 * @param Exception|Throwable $e
1053 * @return string[] Error codes
1055 protected function substituteResultWithError( $e ) {
1056 $result = $this->getResult();
1057 $formatter = $this->getErrorFormatter();
1058 $config = $this->getConfig();
1061 // Remember existing warnings and errors across the reset
1062 $errors = $result->getResultData( [ 'errors' ] );
1063 $warnings = $result->getResultData( [ 'warnings' ] );
1065 if ( $warnings !== null ) {
1066 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1068 if ( $errors !== null ) {
1069 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1071 // Collect the copied error codes for the return value
1072 foreach ( $errors as $error ) {
1073 if ( isset( $error['code'] ) ) {
1074 $errorCodes[$error['code']] = true;
1079 // Add errors from the exception
1080 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1081 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1082 if ( ApiErrorFormatter
::isValidApiCode( $msg->getApiCode() ) ) {
1083 $errorCodes[$msg->getApiCode()] = true;
1085 LoggerFactory
::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1086 'code' => $msg->getApiCode(),
1089 $errorCodes['<invalid-code>'] = true;
1091 $formatter->addError( $modulePath, $msg );
1093 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1094 $formatter->addWarning( $modulePath, $msg );
1097 // Add additional data. Path depends on whether we're in BC mode or not.
1098 // Data depends on the type of exception.
1099 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1100 $path = [ 'error' ];
1104 if ( $e instanceof ApiUsageException
) {
1105 $link = wfExpandUrl( wfScript( 'api' ) );
1106 $result->addContentValue(
1110 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1112 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1115 } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1116 $result->addContentValue(
1119 $this->msg( 'api-exception-trace',
1123 MWExceptionHandler
::getRedactedTraceAsString( $e )
1124 )->inLanguage( $formatter->getLanguage() )->text()
1128 // Add the id and such
1129 $this->addRequestedFields( [ 'servedby' ] );
1131 return array_keys( $errorCodes );
1135 * Add requested fields to the result
1136 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1139 protected function addRequestedFields( $force = [] ) {
1140 $result = $this->getResult();
1142 $requestid = $this->getParameter( 'requestid' );
1143 if ( $requestid !== null ) {
1144 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1147 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1148 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1150 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1153 if ( $this->getParameter( 'curtimestamp' ) ) {
1154 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1155 ApiResult
::NO_SIZE_CHECK
);
1158 if ( $this->getParameter( 'responselanginfo' ) ) {
1159 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1160 ApiResult
::NO_SIZE_CHECK
);
1161 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1162 ApiResult
::NO_SIZE_CHECK
);
1167 * Set up for the execution.
1170 protected function setupExecuteAction() {
1171 $this->addRequestedFields();
1173 $params = $this->extractRequestParams();
1174 $this->mAction
= $params['action'];
1180 * Set up the module for response
1181 * @return ApiBase The module that will handle this action
1182 * @throws MWException
1183 * @throws ApiUsageException
1185 protected function setupModule() {
1186 // Instantiate the module requested by the user
1187 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1188 if ( $module === null ) {
1189 // Probably can't happen
1190 // @codeCoverageIgnoreStart
1191 $this->dieWithError(
1192 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1194 // @codeCoverageIgnoreEnd
1196 $moduleParams = $module->extractRequestParams();
1198 // Check token, if necessary
1199 if ( $module->needsToken() === true ) {
1200 throw new MWException(
1201 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1202 'See documentation for ApiBase::needsToken for details.'
1205 if ( $module->needsToken() ) {
1206 if ( !$module->mustBePosted() ) {
1207 throw new MWException(
1208 "Module '{$module->getModuleName()}' must require POST to use tokens."
1212 if ( !isset( $moduleParams['token'] ) ) {
1213 // Probably can't happen
1214 // @codeCoverageIgnoreStart
1215 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1216 // @codeCoverageIgnoreEnd
1219 $module->requirePostedParameters( [ 'token' ] );
1221 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1222 $module->dieWithError( 'apierror-badtoken' );
1232 private function getMaxLag() {
1233 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1235 'host' => $dbLag[0],
1240 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1241 if ( $jobQueueLagFactor ) {
1242 // Turn total number of jobs into seconds by using the configured value
1243 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1244 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1245 if ( $jobQueueLag > $lagInfo['lag'] ) {
1247 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1248 'lag' => $jobQueueLag,
1249 'type' => 'jobqueue',
1250 'jobs' => $totalJobs,
1255 Hooks
::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1261 * Check the max lag if necessary
1262 * @param ApiBase $module Api module being used
1263 * @param array $params Array an array containing the request parameters.
1264 * @return bool True on success, false should exit immediately
1266 protected function checkMaxLag( $module, $params ) {
1267 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1268 $maxLag = $params['maxlag'];
1269 $lagInfo = $this->getMaxLag();
1270 if ( $lagInfo['lag'] > $maxLag ) {
1271 $response = $this->getRequest()->response();
1273 $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1274 $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1276 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1277 $this->dieWithError(
1278 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1284 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1292 * Check selected RFC 7232 precondition headers
1294 * RFC 7232 envisions a particular model where you send your request to "a
1295 * resource", and for write requests that you can read "the resource" by
1296 * changing the method to GET. When the API receives a GET request, it
1297 * works out even though "the resource" from RFC 7232's perspective might
1298 * be many resources from MediaWiki's perspective. But it totally fails for
1299 * a POST, since what HTTP sees as "the resource" is probably just
1300 * "/api.php" with all the interesting bits in the body.
1302 * Therefore, we only support RFC 7232 precondition headers for GET (and
1303 * HEAD). That means we don't need to bother with If-Match and
1304 * If-Unmodified-Since since they only apply to modification requests.
1306 * And since we don't support Range, If-Range is ignored too.
1309 * @param ApiBase $module Api module being used
1310 * @return bool True on success, false should exit immediately
1312 protected function checkConditionalRequestHeaders( $module ) {
1313 if ( $this->mInternalMode
) {
1314 // No headers to check in internal mode
1318 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1319 // Don't check POSTs
1325 $ifNoneMatch = array_diff(
1326 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1329 if ( $ifNoneMatch ) {
1330 if ( $ifNoneMatch === [ '*' ] ) {
1331 // API responses always "exist"
1334 $etag = $module->getConditionalRequestData( 'etag' );
1337 if ( $ifNoneMatch && $etag !== null ) {
1338 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1339 $match = array_map( function ( $s ) {
1340 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1342 $return304 = in_array( $test, $match, true );
1344 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1346 // Some old browsers sends sizes after the date, like this:
1347 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1349 $i = strpos( $value, ';' );
1350 if ( $i !== false ) {
1351 $value = trim( substr( $value, 0, $i ) );
1354 if ( $value !== '' ) {
1356 $ts = new MWTimestamp( $value );
1358 // RFC 7231 IMF-fixdate
1359 $ts->getTimestamp( TS_RFC2822
) === $value ||
1361 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1362 // asctime (with and without space-padded day)
1363 $ts->format( 'D M j H:i:s Y' ) === $value ||
1364 $ts->format( 'D M j H:i:s Y' ) === $value
1366 $config = $this->getConfig();
1367 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1368 if ( $lastMod !== null ) {
1369 // Mix in some MediaWiki modification times
1372 'user' => $this->getUser()->getTouched(),
1373 'epoch' => $config->get( 'CacheEpoch' ),
1376 if ( $config->get( 'UseCdn' ) ) {
1377 // T46570: the core page itself may not change, but resources might
1378 $modifiedTimes['sepoch'] = wfTimestamp(
1379 TS_MW
, time() - $config->get( 'CdnMaxAge' )
1382 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1383 $lastMod = max( $modifiedTimes );
1384 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1387 } catch ( TimestampException
$e ) {
1388 // Invalid timestamp, ignore it
1394 $this->getRequest()->response()->statusHeader( 304 );
1396 // Avoid outputting the compressed representation of a zero-length body
1397 Wikimedia\
suppressWarnings();
1398 ini_set( 'zlib.output_compression', 0 );
1399 Wikimedia\restoreWarnings
();
1400 wfClearOutputBuffers();
1409 * Check for sufficient permissions to execute
1410 * @param ApiBase $module An Api module
1412 protected function checkExecutePermissions( $module ) {
1413 $user = $this->getUser();
1414 if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1415 !$this->getPermissionManager()->userHasRight( $user, 'read' )
1417 $this->dieWithError( 'apierror-readapidenied' );
1420 if ( $module->isWriteMode() ) {
1421 if ( !$this->mEnableWrite
) {
1422 $this->dieWithError( 'apierror-noapiwrite' );
1423 } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1424 $this->dieWithError( 'apierror-writeapidenied' );
1425 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1426 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1429 $this->checkReadOnly( $module );
1432 // Allow extensions to stop execution for arbitrary reasons.
1433 $message = 'hookaborted';
1434 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1435 $this->dieWithError( $message );
1440 * Check if the DB is read-only for this user
1441 * @param ApiBase $module An Api module
1443 protected function checkReadOnly( $module ) {
1444 if ( wfReadOnly() ) {
1445 $this->dieReadOnly();
1448 if ( $module->isWriteMode()
1449 && $this->getUser()->isBot()
1450 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1452 $this->checkBotReadOnly();
1457 * Check whether we are readonly for bots
1459 private function checkBotReadOnly() {
1460 // Figure out how many servers have passed the lag threshold
1462 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1463 $laggedServers = [];
1464 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1465 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1466 if ( $lag > $lagLimit ) {
1468 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1472 // If a majority of replica DBs are too lagged then disallow writes
1473 $replicaCount = $loadBalancer->getServerCount() - 1;
1474 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1475 $laggedServers = implode( ', ', $laggedServers );
1477 'api-readonly', // Deprecate this channel in favor of api-warning?
1478 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1480 LoggerFactory
::getInstance( 'api-warning' )->warning(
1481 "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1482 'laggeddbs' => $laggedServers,
1486 $this->dieWithError(
1489 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1495 * Check asserts of the user's rights
1496 * @param array $params
1498 protected function checkAsserts( $params ) {
1499 if ( isset( $params['assert'] ) ) {
1500 $user = $this->getUser();
1501 switch ( $params['assert'] ) {
1503 if ( $user->isAnon() ) {
1504 $this->dieWithError( 'apierror-assertuserfailed' );
1508 if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1509 $this->dieWithError( 'apierror-assertbotfailed' );
1514 if ( isset( $params['assertuser'] ) ) {
1515 $assertUser = User
::newFromName( $params['assertuser'], false );
1516 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1517 $this->dieWithError(
1518 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1525 * Check POST for external response and setup result printer
1526 * @param ApiBase $module An Api module
1527 * @param array $params An array with the request parameters
1529 protected function setupExternalResponse( $module, $params ) {
1530 $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1531 $request = $this->getRequest();
1533 if ( !in_array( $request->getMethod(), $validMethods ) ) {
1534 $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1537 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1538 // Module requires POST. GET request might still be allowed
1539 // if $wgDebugApi is true, otherwise fail.
1540 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1543 if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1544 $this->addDeprecation(
1545 'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1549 // See if custom printer is used
1550 $this->mPrinter
= $module->getCustomPrinter();
1551 if ( is_null( $this->mPrinter
) ) {
1552 // Create an appropriate printer
1553 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1556 if ( $request->getProtocol() === 'http' && (
1557 $request->getSession()->shouldForceHTTPS() ||
1558 ( $this->getUser()->isLoggedIn() &&
1559 $this->getUser()->requiresHTTPS() )
1561 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1566 * Execute the actual module, without any error handling
1568 protected function executeAction() {
1569 $params = $this->setupExecuteAction();
1571 // Check asserts early so e.g. errors in parsing a module's parameters due to being
1572 // logged out don't override the client's intended "am I logged in?" check.
1573 $this->checkAsserts( $params );
1575 $module = $this->setupModule();
1576 $this->mModule
= $module;
1578 if ( !$this->mInternalMode
) {
1579 $this->setRequestExpectations( $module );
1582 $this->checkExecutePermissions( $module );
1584 if ( !$this->checkMaxLag( $module, $params ) ) {
1588 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1592 if ( !$this->mInternalMode
) {
1593 $this->setupExternalResponse( $module, $params );
1597 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1599 $this->reportUnusedParams();
1601 if ( !$this->mInternalMode
) {
1602 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1604 $this->printResult();
1609 * Set database connection, query, and write expectations given this module request
1610 * @param ApiBase $module
1612 protected function setRequestExpectations( ApiBase
$module ) {
1613 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1614 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1615 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1616 if ( $this->getRequest()->hasSafeMethod() ) {
1617 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1618 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1619 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1620 $this->getRequest()->markAsSafeRequest();
1622 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1627 * Log the preceding request
1628 * @param float $time Time in seconds
1629 * @param Exception|Throwable|null $e Exception caught while processing the request
1631 protected function logRequest( $time, $e = null ) {
1632 $request = $this->getRequest();
1635 // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1636 '$schema' => '/mediawiki/api/request/0.0.1',
1638 'request_id' => WebRequest
::getRequestId(),
1639 'id' => UIDGenerator
::newUUIDv4(),
1640 'dt' => wfTimestamp( TS_ISO_8601
),
1641 'domain' => $this->getConfig()->get( 'ServerName' ),
1642 // If using the EventBus extension (as intended) with this log channel,
1643 // this stream name will map to a Kafka topic.
1644 'stream' => 'mediawiki.api-request'
1647 'method' => $request->getMethod(),
1648 'client_ip' => $request->getIP()
1650 'database' => WikiMap
::getCurrentWikiDbDomain()->getId(),
1651 'backend_time_ms' => (int)round( $time * 1000 ),
1654 // If set, these headers will be logged in http.request_headers.
1655 $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1656 foreach ( $httpRequestHeadersToLog as $header ) {
1657 if ( $request->getHeader( $header ) ) {
1658 // Set the header in http.request_headers
1659 $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1664 $logCtx['api_error_codes'] = [];
1665 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1666 $logCtx['api_error_codes'][] = $msg->getApiCode();
1670 // Construct space separated message for 'api' log channel
1671 $msg = "API {$request->getMethod()} " .
1672 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1673 " {$logCtx['http']['client_ip']} " .
1674 "T={$logCtx['backend_time_ms']}ms";
1676 $sensitive = array_flip( $this->getSensitiveParams() );
1677 foreach ( $this->getParamsUsed() as $name ) {
1678 $value = $request->getVal( $name );
1679 if ( $value === null ) {
1683 if ( isset( $sensitive[$name] ) ) {
1684 $value = '[redacted]';
1685 $encValue = '[redacted]';
1686 } elseif ( strlen( $value ) > 256 ) {
1687 $value = substr( $value, 0, 256 );
1688 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1690 $encValue = $this->encodeRequestLogValue( $value );
1693 $logCtx['params'][$name] = $value;
1694 $msg .= " {$name}={$encValue}";
1697 // Log an unstructured message to the api channel.
1698 wfDebugLog( 'api', $msg, 'private' );
1700 // The api-request channel a structured data log channel.
1701 wfDebugLog( 'api-request', '', 'private', $logCtx );
1705 * Encode a value in a format suitable for a space-separated log line.
1709 protected function encodeRequestLogValue( $s ) {
1712 $chars = ';@$!*(),/:';
1713 $numChars = strlen( $chars );
1714 for ( $i = 0; $i < $numChars; $i++
) {
1715 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1719 return strtr( rawurlencode( $s ), $table );
1723 * Get the request parameters used in the course of the preceding execute() request
1726 protected function getParamsUsed() {
1727 return array_keys( $this->mParamsUsed
);
1731 * Mark parameters as used
1732 * @param string|string[] $params
1734 public function markParamsUsed( $params ) {
1735 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1739 * Get the request parameters that should be considered sensitive
1743 protected function getSensitiveParams() {
1744 return array_keys( $this->mParamsSensitive
);
1748 * Mark parameters as sensitive
1750 * @param string|string[] $params
1752 public function markParamsSensitive( $params ) {
1753 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1757 * Get a request value, and register the fact that it was used, for logging.
1758 * @param string $name
1759 * @param string|null $default
1760 * @return string|null
1762 public function getVal( $name, $default = null ) {
1763 $this->mParamsUsed
[$name] = true;
1765 $ret = $this->getRequest()->getVal( $name );
1766 if ( $ret === null ) {
1767 if ( $this->getRequest()->getArray( $name ) !== null ) {
1768 // See T12262 for why we don't just implode( '|', ... ) the
1770 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1778 * Get a boolean request value, and register the fact that the parameter
1779 * was used, for logging.
1780 * @param string $name
1783 public function getCheck( $name ) {
1784 return $this->getVal( $name, null ) !== null;
1788 * Get a request upload, and register the fact that it was used, for logging.
1791 * @param string $name Parameter name
1792 * @return WebRequestUpload
1794 public function getUpload( $name ) {
1795 $this->mParamsUsed
[$name] = true;
1797 return $this->getRequest()->getUpload( $name );
1801 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1802 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1804 protected function reportUnusedParams() {
1805 $paramsUsed = $this->getParamsUsed();
1806 $allParams = $this->getRequest()->getValueNames();
1808 if ( !$this->mInternalMode
) {
1809 // Printer has not yet executed; don't warn that its parameters are unused
1810 $printerParams = $this->mPrinter
->encodeParamName(
1811 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1813 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1815 $unusedParams = array_diff( $allParams, $paramsUsed );
1818 if ( count( $unusedParams ) ) {
1819 $this->addWarning( [
1820 'apierror-unrecognizedparams',
1821 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1822 count( $unusedParams )
1828 * Print results using the current printer
1830 * @param int $httpCode HTTP status code, or 0 to not change
1832 protected function printResult( $httpCode = 0 ) {
1833 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1834 $this->addWarning( 'apiwarn-wgdebugapi' );
1837 $printer = $this->mPrinter
;
1838 $printer->initPrinter( false );
1840 $printer->setHttpStatus( $httpCode );
1842 $printer->execute();
1843 $printer->closePrinter();
1849 public function isReadMode() {
1854 * See ApiBase for description.
1858 public function getAllowedParams() {
1861 ApiBase
::PARAM_DFLT
=> 'help',
1862 ApiBase
::PARAM_TYPE
=> 'submodule',
1865 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1866 ApiBase
::PARAM_TYPE
=> 'submodule',
1869 ApiBase
::PARAM_TYPE
=> 'integer'
1872 ApiBase
::PARAM_TYPE
=> 'integer',
1873 ApiBase
::PARAM_DFLT
=> 0
1876 ApiBase
::PARAM_TYPE
=> 'integer',
1877 ApiBase
::PARAM_DFLT
=> 0
1880 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1883 ApiBase
::PARAM_TYPE
=> 'user',
1885 'requestid' => null,
1886 'servedby' => false,
1887 'curtimestamp' => false,
1888 'responselanginfo' => false,
1891 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1894 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1895 ApiBase
::PARAM_DFLT
=> 'bc',
1898 ApiBase
::PARAM_DFLT
=> 'uselang',
1900 'errorsuselocal' => [
1901 ApiBase
::PARAM_DFLT
=> false,
1907 protected function getExamplesMessages() {
1910 => 'apihelp-help-example-main',
1911 'action=help&recursivesubmodules=1'
1912 => 'apihelp-help-example-recursive',
1918 * @phan-param array{nolead?:bool,headerlevel?:int,tocnumber?:int[]} $options
1920 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1921 // Wish PHP had an "array_insert_before". Instead, we have to manually
1922 // reindex the array to get 'permissions' in the right place.
1925 foreach ( $oldHelp as $k => $v ) {
1926 if ( $k === 'submodules' ) {
1927 $help['permissions'] = '';
1931 $help['datatypes'] = '';
1932 $help['templatedparams'] = '';
1933 $help['credits'] = '';
1935 // Fill 'permissions'
1936 $help['permissions'] .= Html
::openElement( 'div',
1937 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1938 $m = $this->msg( 'api-help-permissions' );
1939 if ( !$m->isDisabled() ) {
1940 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1941 $m->numParams( count( self
::$mRights ) )->parse()
1944 $help['permissions'] .= Html
::openElement( 'dl' );
1945 foreach ( self
::$mRights as $right => $rightMsg ) {
1946 $help['permissions'] .= Html
::element( 'dt', null, $right );
1948 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1949 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1951 $groups = array_map( function ( $group ) {
1952 return $group == '*' ?
'all' : $group;
1953 }, $this->getPermissionManager()->getGroupsWithPermission( $right ) );
1955 $help['permissions'] .= Html
::rawElement( 'dd', null,
1956 $this->msg( 'api-help-permissions-granted-to' )
1957 ->numParams( count( $groups ) )
1958 ->params( Message
::listParam( $groups ) )
1962 $help['permissions'] .= Html
::closeElement( 'dl' );
1963 $help['permissions'] .= Html
::closeElement( 'div' );
1965 // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1966 if ( empty( $options['nolead'] ) ) {
1967 $level = $options['headerlevel'];
1968 $tocnumber = &$options['tocnumber'];
1970 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1972 $id = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_PRIMARY
);
1973 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_FALLBACK
);
1974 $headline = Linker
::makeHeadline( min( 6, $level ),
1975 ' class="apihelp-header">',
1981 // Ensure we have a sane anchor
1982 if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1983 $headline = '<div id="main/datatypes"></div>' . $headline;
1985 $help['datatypes'] .= $headline;
1986 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1987 if ( !isset( $tocData['main/datatypes'] ) ) {
1988 $tocnumber[$level]++
;
1989 $tocData['main/datatypes'] = [
1990 'toclevel' => count( $tocnumber ),
1992 'anchor' => 'main/datatypes',
1994 'number' => implode( '.', $tocnumber ),
1999 $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2001 $id = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_PRIMARY
);
2002 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_FALLBACK
);
2003 $headline = Linker
::makeHeadline( min( 6, $level ),
2004 ' class="apihelp-header">',
2010 // Ensure we have a sane anchor
2011 if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2012 $headline = '<div id="main/templatedparams"></div>' . $headline;
2014 $help['templatedparams'] .= $headline;
2015 $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2016 if ( !isset( $tocData['main/templatedparams'] ) ) {
2017 $tocnumber[$level]++
;
2018 $tocData['main/templatedparams'] = [
2019 'toclevel' => count( $tocnumber ),
2021 'anchor' => 'main/templatedparams',
2023 'number' => implode( '.', $tocnumber ),
2028 $header = $this->msg( 'api-credits-header' )->parse();
2029 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
2030 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_FALLBACK
);
2031 $headline = Linker
::makeHeadline( min( 6, $level ),
2032 ' class="apihelp-header">',
2038 // Ensure we have a sane anchor
2039 if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2040 $headline = '<div id="main/credits"></div>' . $headline;
2042 $help['credits'] .= $headline;
2043 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2044 if ( !isset( $tocData['main/credits'] ) ) {
2045 $tocnumber[$level]++
;
2046 $tocData['main/credits'] = [
2047 'toclevel' => count( $tocnumber ),
2049 'anchor' => 'main/credits',
2051 'number' => implode( '.', $tocnumber ),
2058 private $mCanApiHighLimits = null;
2061 * Check whether the current user is allowed to use high limits
2064 public function canApiHighLimits() {
2065 if ( !isset( $this->mCanApiHighLimits
) ) {
2066 $this->mCanApiHighLimits
= $this->getPermissionManager()
2067 ->userHasRight( $this->getUser(), 'apihighlimits' );
2070 return $this->mCanApiHighLimits
;
2074 * Overrides to return this instance's module manager.
2075 * @return ApiModuleManager
2077 public function getModuleManager() {
2078 return $this->mModuleMgr
;
2082 * Fetches the user agent used for this request
2084 * The value will be the combination of the 'Api-User-Agent' header (if
2085 * any) and the standard User-Agent header (if any).
2089 public function getUserAgent() {
2091 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2092 $this->getRequest()->getHeader( 'User-agent' )
2098 * For really cool vim folding this needs to be at the end:
2099 * vim: foldmarker=@{,@} foldmethod=marker