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()
296 $this->mCommit
= false;
300 * Return true if the API was started by other PHP code using FauxRequest
303 public function isInternalMode() {
304 return $this->mInternalMode
;
308 * Get the ApiResult object associated with current request
312 public function getResult() {
313 return $this->mResult
;
317 * Get the security flag for the current request
320 public function lacksSameOriginSecurity() {
321 if ( $this->lacksSameOriginSecurity
!== null ) {
322 return $this->lacksSameOriginSecurity
;
325 $request = $this->getRequest();
328 if ( $request->getCheck( 'callback' ) ) {
329 $this->lacksSameOriginSecurity
= true;
334 if ( $request->getVal( 'origin' ) === '*' ) {
335 $this->lacksSameOriginSecurity
= true;
339 // Header to be used from XMLHTTPRequest when the request might
340 // otherwise be used for XSS.
341 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
342 $this->lacksSameOriginSecurity
= true;
346 // Allow extensions to override.
347 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
348 return $this->lacksSameOriginSecurity
;
352 * Get the ApiErrorFormatter object associated with current request
353 * @return ApiErrorFormatter
355 public function getErrorFormatter() {
356 return $this->mErrorFormatter
;
360 * Get the continuation manager
361 * @return ApiContinuationManager|null
363 public function getContinuationManager() {
364 return $this->mContinuationManager
;
368 * Set the continuation manager
369 * @param ApiContinuationManager|null $manager
371 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
372 if ( $manager !== null && $this->mContinuationManager
!== null ) {
373 throw new UnexpectedValueException(
374 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
375 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
378 $this->mContinuationManager
= $manager;
382 * Get the API module object. Only works after executeAction()
386 public function getModule() {
387 return $this->mModule
;
391 * Get the result formatter object. Only works after setupExecuteAction()
393 * @return ApiFormatBase
395 public function getPrinter() {
396 return $this->mPrinter
;
400 * Set how long the response should be cached.
404 public function setCacheMaxAge( $maxage ) {
405 $this->setCacheControl( [
406 'max-age' => $maxage,
407 's-maxage' => $maxage
412 * Set the type of caching headers which will be sent.
414 * @param string $mode One of:
415 * - 'public': Cache this object in public caches, if the maxage or smaxage
416 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
417 * not provided by any of these means, the object will be private.
418 * - 'private': Cache this object only in private client-side caches.
419 * - 'anon-public-user-private': Make this object cacheable for logged-out
420 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
421 * set consistently for a given URL, it cannot be set differently depending on
422 * things like the contents of the database, or whether the user is logged in.
424 * If the wiki does not allow anonymous users to read it, the mode set here
425 * will be ignored, and private caching headers will always be sent. In other words,
426 * the "public" mode is equivalent to saying that the data sent is as public as a page
429 * For user-dependent data, the private mode should generally be used. The
430 * anon-public-user-private mode should only be used where there is a particularly
431 * good performance reason for caching the anonymous response, but where the
432 * response to logged-in users may differ, or may contain private data.
434 * If this function is never called, then the default will be the private mode.
436 public function setCacheMode( $mode ) {
437 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
438 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
440 // Ignore for forwards-compatibility
444 if ( !User
::isEveryoneAllowed( 'read' ) ) {
445 // Private wiki, only private headers
446 if ( $mode !== 'private' ) {
447 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
453 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
454 // User language is used for i18n, so we don't want to publicly
455 // cache. Anons are ok, because if they have non-default language
456 // then there's an appropriate Vary header set by whatever set
457 // their non-default language.
458 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
459 "'anon-public-user-private' due to uselang=user\n" );
460 $mode = 'anon-public-user-private';
463 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
464 $this->mCacheMode
= $mode;
468 * Set directives (key/value pairs) for the Cache-Control header.
469 * Boolean values will be formatted as such, by including or omitting
470 * without an equals sign.
472 * Cache control values set here will only be used if the cache mode is not
473 * private, see setCacheMode().
475 * @param array $directives
477 public function setCacheControl( $directives ) {
478 $this->mCacheControl
= $directives +
$this->mCacheControl
;
482 * Create an instance of an output formatter by its name
484 * @param string $format
486 * @return ApiFormatBase
488 public function createPrinterByName( $format ) {
489 $printer = $this->mModuleMgr
->getModule( $format, 'format', /* $ignoreCache */ true );
490 if ( $printer === null ) {
492 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
500 * Execute api request. Any errors will be handled if the API was called by the remote client.
502 public function execute() {
503 if ( $this->mInternalMode
) {
504 $this->executeAction();
506 $this->executeActionWithErrorHandling();
511 * Execute an action, and in case of an error, erase whatever partial results
512 * have been accumulated, and replace it with an error message and a help screen.
514 protected function executeActionWithErrorHandling() {
515 // Verify the CORS header before executing the action
516 if ( !$this->handleCORS() ) {
517 // handleCORS() has sent a 403, abort
521 // Exit here if the request method was OPTIONS
522 // (assume there will be a followup GET or POST)
523 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
527 // In case an error occurs during data output,
528 // clear the output buffer and print just the error information
529 $obLevel = ob_get_level();
532 $t = microtime( true );
535 $this->executeAction();
536 $runTime = microtime( true ) - $t;
537 $this->logRequest( $runTime );
538 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
539 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
541 } catch ( Exception
$e ) { // @todo Remove this block when HHVM is no longer supported
542 $this->handleException( $e );
543 $this->logRequest( microtime( true ) - $t, $e );
545 } catch ( Throwable
$e ) {
546 $this->handleException( $e );
547 $this->logRequest( microtime( true ) - $t, $e );
551 // Commit DBs and send any related cookies and headers
552 MediaWiki
::preOutputCommit( $this->getContext() );
554 // Send cache headers after any code which might generate an error, to
555 // avoid sending public cache headers for errors.
556 $this->sendCacheHeaders( $isError );
558 // Executing the action might have already messed with the output
560 while ( ob_get_level() > $obLevel ) {
566 * Handle an exception as an API response
569 * @param Exception|Throwable $e
571 protected function handleException( $e ) {
572 // T65145: Rollback any open database transactions
573 if ( !$e instanceof ApiUsageException
) {
574 // ApiUsageExceptions are intentional, so don't rollback if that's the case
575 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
578 // Allow extra cleanup and logging
579 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
581 // Handle any kind of exception by outputting properly formatted error message.
582 // If this fails, an unhandled exception should be thrown so that global error
583 // handler will process and log it.
585 $errCodes = $this->substituteResultWithError( $e );
587 // Error results should not be cached
588 $this->setCacheMode( 'private' );
590 $response = $this->getRequest()->response();
591 $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
592 $response->header( $headerStr );
594 // Reset and print just the error message
597 // Printer may not be initialized if the extractRequestParams() fails for the main module
598 $this->createErrorPrinter();
600 // Get desired HTTP code from an ApiUsageException. Don't use codes from other
601 // exception types, as they are unlikely to be intended as an HTTP code.
602 $httpCode = $e instanceof ApiUsageException ?
$e->getCode() : 0;
606 $this->printResult( $httpCode );
607 } catch ( ApiUsageException
$ex ) {
608 // The error printer itself is failing. Try suppressing its request
609 // parameters and redo.
611 $this->addWarning( 'apiwarn-errorprinterfailed' );
612 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
614 $this->mPrinter
->addWarning( $error );
615 } catch ( Exception
$ex2 ) { // @todo Remove this block when HHVM is no longer supported
617 $this->addWarning( $error );
618 } catch ( Throwable
$ex2 ) {
620 $this->addWarning( $error );
625 $this->mPrinter
= null;
626 $this->createErrorPrinter();
627 $this->mPrinter
->forceDefaultParams();
629 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
631 $this->printResult( $httpCode );
636 * Handle an exception from the ApiBeforeMain hook.
638 * This tries to print the exception as an API response, to be more
639 * friendly to clients. If it fails, it will rethrow the exception.
642 * @param Exception|Throwable $e
643 * @throws Exception|Throwable
645 public static function handleApiBeforeMainException( $e ) {
649 $main = new self( RequestContext
::getMain(), false );
650 $main->handleException( $e );
651 $main->logRequest( 0, $e );
652 } catch ( Exception
$e2 ) { // @todo Remove this block when HHVM is no longer supported
653 // Nope, even that didn't work. Punt.
655 } catch ( Throwable
$e2 ) {
656 // Nope, even that didn't work. Punt.
660 // Reset cache headers
661 $main->sendCacheHeaders( true );
667 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
669 * If no origin parameter is present, nothing happens.
670 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
671 * is set and false is returned.
672 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
673 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
675 * https://www.w3.org/TR/cors/#resource-requests
676 * https://www.w3.org/TR/cors/#resource-preflight-requests
678 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
680 protected function handleCORS() {
681 $originParam = $this->getParameter( 'origin' ); // defaults to null
682 if ( $originParam === null ) {
683 // No origin parameter, nothing to do
687 $request = $this->getRequest();
688 $response = $request->response();
690 $matchedOrigin = false;
691 $allowTiming = false;
694 if ( $originParam === '*' ) {
695 // Request for anonymous CORS
696 // Technically we should check for the presence of an Origin header
697 // and not process it as CORS if it's not set, but that would
698 // require us to vary on Origin for all 'origin=*' requests which
699 // we don't want to do.
700 $matchedOrigin = true;
702 $allowCredentials = 'false';
703 $varyOrigin = false; // No need to vary
705 // Non-anonymous CORS, check we allow the domain
707 // Origin: header is a space-separated list of origins, check all of them
708 $originHeader = $request->getHeader( 'Origin' );
709 if ( $originHeader === false ) {
712 $originHeader = trim( $originHeader );
713 $origins = preg_split( '/\s+/', $originHeader );
716 if ( !in_array( $originParam, $origins ) ) {
717 // origin parameter set but incorrect
718 // Send a 403 response
719 $response->statusHeader( 403 );
720 $response->header( 'Cache-Control: no-cache' );
721 echo "'origin' parameter does not match Origin header\n";
726 $config = $this->getConfig();
727 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
729 $config->get( 'CrossSiteAJAXdomains' ),
730 $config->get( 'CrossSiteAJAXdomainExceptions' )
733 $allowOrigin = $originHeader;
734 $allowCredentials = 'true';
735 $allowTiming = $originHeader;
738 if ( $matchedOrigin ) {
739 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
740 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
742 // This is a CORS preflight request
743 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
744 // If method is not a case-sensitive match, do not set any additional headers and terminate.
745 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
748 // We allow the actual request to send the following headers
749 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
750 if ( $requestedHeaders !== false ) {
751 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
752 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
755 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
758 // We only allow the actual request to be GET or POST
759 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
760 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
761 // Unsupported non-preflight method, don't handle it as CORS
763 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
768 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
769 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
770 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
771 if ( $allowTiming !== false ) {
772 $response->header( "Timing-Allow-Origin: $allowTiming" );
777 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
778 . 'MediaWiki-Login-Suppressed'
782 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
786 $this->getOutput()->addVaryHeader( 'Origin' );
793 * Attempt to match an Origin header against a set of rules and a set of exceptions
794 * @param string $value Origin header
795 * @param array $rules Set of wildcard rules
796 * @param array $exceptions Set of wildcard rules
797 * @return bool True if $value matches a rule in $rules and doesn't match
798 * any rules in $exceptions, false otherwise
800 protected static function matchOrigin( $value, $rules, $exceptions ) {
801 foreach ( $rules as $rule ) {
802 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
803 // Rule matches, check exceptions
804 foreach ( $exceptions as $exc ) {
805 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
818 * Attempt to validate the value of Access-Control-Request-Headers against a list
819 * of headers that we allow the follow up request to send.
821 * @param string $requestedHeaders Comma separated list of HTTP headers
822 * @return bool True if all requested headers are in the list of allowed headers
824 protected static function matchRequestedHeaders( $requestedHeaders ) {
825 if ( trim( $requestedHeaders ) === '' ) {
828 $requestedHeaders = explode( ',', $requestedHeaders );
829 $allowedAuthorHeaders = array_flip( [
830 /* simple headers (see spec) */
835 /* non-authorable headers in XHR, which are however requested by some UAs */
839 /* MediaWiki whitelist */
843 foreach ( $requestedHeaders as $rHeader ) {
844 $rHeader = strtolower( trim( $rHeader ) );
845 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
846 LoggerFactory
::getInstance( 'api-warning' )->warning(
847 'CORS preflight failed on requested header: {header}', [
858 * Helper function to convert wildcard string into a regex
862 * @param string $wildcard String with wildcards
863 * @return string Regular expression
865 protected static function wildcardToRegex( $wildcard ) {
866 $wildcard = preg_quote( $wildcard, '/' );
867 $wildcard = str_replace(
873 return "/^https?:\/\/$wildcard$/";
877 * Send caching headers
878 * @param bool $isError Whether an error response is being output
879 * @since 1.26 added $isError parameter
881 protected function sendCacheHeaders( $isError ) {
882 $response = $this->getRequest()->response();
883 $out = $this->getOutput();
885 $out->addVaryHeader( 'Treat-as-Untrusted' );
887 $config = $this->getConfig();
889 if ( $config->get( 'VaryOnXFP' ) ) {
890 $out->addVaryHeader( 'X-Forwarded-Proto' );
893 if ( !$isError && $this->mModule
&&
894 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
896 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
897 if ( $etag !== null ) {
898 $response->header( "ETag: $etag" );
900 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
901 if ( $lastMod !== null ) {
902 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
906 // The logic should be:
907 // $this->mCacheControl['max-age'] is set?
908 // Use it, the module knows better than our guess.
909 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
910 // Use 0 because we can guess caching is probably the wrong thing to do.
911 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
913 if ( isset( $this->mCacheControl
['max-age'] ) ) {
914 $maxage = $this->mCacheControl
['max-age'];
915 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
916 $this->mCacheMode
!== 'private'
918 $maxage = $this->getParameter( 'maxage' );
920 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
922 if ( $this->mCacheMode
== 'private' ) {
923 $response->header( "Cache-Control: $privateCache" );
927 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
928 $out->addVaryHeader( 'Cookie' );
929 $response->header( $out->getVaryHeader() );
930 if ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
931 // Logged in or otherwise has session (e.g. anonymous users who have edited)
932 // Mark request private
933 $response->header( "Cache-Control: $privateCache" );
936 } // else anonymous, send public headers below
939 // Send public headers
940 $response->header( $out->getVaryHeader() );
942 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
943 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
944 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
946 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
947 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
950 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
951 // Public cache not requested
952 // Sending a Vary header in this case is harmless, and protects us
953 // against conditional calls of setCacheMaxAge().
954 $response->header( "Cache-Control: $privateCache" );
959 $this->mCacheControl
['public'] = true;
961 // Send an Expires header
962 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
963 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
964 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
966 // Construct the Cache-Control header
969 foreach ( $this->mCacheControl
as $name => $value ) {
970 if ( is_bool( $value ) ) {
972 $ccHeader .= $separator . $name;
976 $ccHeader .= $separator . "$name=$value";
981 $response->header( "Cache-Control: $ccHeader" );
985 * Create the printer for error output
987 private function createErrorPrinter() {
988 if ( !isset( $this->mPrinter
) ) {
989 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
990 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
991 $value = self
::API_DEFAULT_FORMAT
;
993 $this->mPrinter
= $this->createPrinterByName( $value );
996 // Printer may not be able to handle errors. This is particularly
997 // likely if the module returns something for getCustomPrinter().
998 if ( !$this->mPrinter
->canPrintErrors() ) {
999 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1004 * Create an error message for the given exception.
1006 * If an ApiUsageException, errors/warnings will be extracted from the
1007 * embedded StatusValue.
1009 * Any other exception will be returned with a generic code and wrapper
1010 * text around the exception's (presumably English) message as a single
1011 * error (no warnings).
1013 * @param Exception|Throwable $e
1014 * @param string $type 'error' or 'warning'
1015 * @return ApiMessage[]
1018 protected function errorMessagesFromException( $e, $type = 'error' ) {
1020 if ( $e instanceof ApiUsageException
) {
1021 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1022 $messages[] = ApiMessage
::create( $error );
1024 } elseif ( $type !== 'error' ) {
1025 // None of the rest have any messages for non-error types
1027 // Something is seriously wrong
1028 $config = $this->getConfig();
1029 // TODO: Avoid embedding arbitrary class names in the error code.
1030 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1031 $code = 'internal_api_error_' . $class;
1032 $data = [ 'errorclass' => get_class( $e ) ];
1033 if ( $config->get( 'ShowExceptionDetails' ) ) {
1034 if ( $e instanceof ILocalizedException
) {
1035 $msg = $e->getMessageObject();
1036 } elseif ( $e instanceof MessageSpecifier
) {
1037 $msg = Message
::newFromSpecifier( $e );
1039 $msg = wfEscapeWikiText( $e->getMessage() );
1041 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1043 $params = [ 'apierror-exceptioncaughttype', WebRequest
::getRequestId(), get_class( $e ) ];
1046 $messages[] = ApiMessage
::create( $params, $code, $data );
1052 * Replace the result data with the information about an exception.
1053 * @param Exception|Throwable $e
1054 * @return string[] Error codes
1056 protected function substituteResultWithError( $e ) {
1057 $result = $this->getResult();
1058 $formatter = $this->getErrorFormatter();
1059 $config = $this->getConfig();
1062 // Remember existing warnings and errors across the reset
1063 $errors = $result->getResultData( [ 'errors' ] );
1064 $warnings = $result->getResultData( [ 'warnings' ] );
1066 if ( $warnings !== null ) {
1067 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1069 if ( $errors !== null ) {
1070 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1072 // Collect the copied error codes for the return value
1073 foreach ( $errors as $error ) {
1074 if ( isset( $error['code'] ) ) {
1075 $errorCodes[$error['code']] = true;
1080 // Add errors from the exception
1081 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1082 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1083 if ( ApiErrorFormatter
::isValidApiCode( $msg->getApiCode() ) ) {
1084 $errorCodes[$msg->getApiCode()] = true;
1086 LoggerFactory
::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1087 'code' => $msg->getApiCode(),
1090 $errorCodes['<invalid-code>'] = true;
1092 $formatter->addError( $modulePath, $msg );
1094 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1095 $formatter->addWarning( $modulePath, $msg );
1098 // Add additional data. Path depends on whether we're in BC mode or not.
1099 // Data depends on the type of exception.
1100 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1101 $path = [ 'error' ];
1105 if ( $e instanceof ApiUsageException
) {
1106 $link = wfExpandUrl( wfScript( 'api' ) );
1107 $result->addContentValue(
1111 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1113 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1116 } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1117 $result->addContentValue(
1120 $this->msg( 'api-exception-trace',
1124 MWExceptionHandler
::getRedactedTraceAsString( $e )
1125 )->inLanguage( $formatter->getLanguage() )->text()
1129 // Add the id and such
1130 $this->addRequestedFields( [ 'servedby' ] );
1132 return array_keys( $errorCodes );
1136 * Add requested fields to the result
1137 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1140 protected function addRequestedFields( $force = [] ) {
1141 $result = $this->getResult();
1143 $requestid = $this->getParameter( 'requestid' );
1144 if ( $requestid !== null ) {
1145 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1148 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1149 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1151 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1154 if ( $this->getParameter( 'curtimestamp' ) ) {
1155 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1156 ApiResult
::NO_SIZE_CHECK
);
1159 if ( $this->getParameter( 'responselanginfo' ) ) {
1160 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1161 ApiResult
::NO_SIZE_CHECK
);
1162 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1163 ApiResult
::NO_SIZE_CHECK
);
1168 * Set up for the execution.
1171 protected function setupExecuteAction() {
1172 $this->addRequestedFields();
1174 $params = $this->extractRequestParams();
1175 $this->mAction
= $params['action'];
1181 * Set up the module for response
1182 * @return ApiBase The module that will handle this action
1183 * @throws MWException
1184 * @throws ApiUsageException
1186 protected function setupModule() {
1187 // Instantiate the module requested by the user
1188 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1189 if ( $module === null ) {
1190 // Probably can't happen
1191 // @codeCoverageIgnoreStart
1192 $this->dieWithError(
1193 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1195 // @codeCoverageIgnoreEnd
1197 $moduleParams = $module->extractRequestParams();
1199 // Check token, if necessary
1200 if ( $module->needsToken() === true ) {
1201 throw new MWException(
1202 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1203 'See documentation for ApiBase::needsToken for details.'
1206 if ( $module->needsToken() ) {
1207 if ( !$module->mustBePosted() ) {
1208 throw new MWException(
1209 "Module '{$module->getModuleName()}' must require POST to use tokens."
1213 if ( !isset( $moduleParams['token'] ) ) {
1214 // Probably can't happen
1215 // @codeCoverageIgnoreStart
1216 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1217 // @codeCoverageIgnoreEnd
1220 $module->requirePostedParameters( [ 'token' ] );
1222 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1223 $module->dieWithError( 'apierror-badtoken' );
1233 private function getMaxLag() {
1234 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1236 'host' => $dbLag[0],
1241 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1242 if ( $jobQueueLagFactor ) {
1243 // Turn total number of jobs into seconds by using the configured value
1244 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1245 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1246 if ( $jobQueueLag > $lagInfo['lag'] ) {
1248 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1249 'lag' => $jobQueueLag,
1250 'type' => 'jobqueue',
1251 'jobs' => $totalJobs,
1256 Hooks
::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1262 * Check the max lag if necessary
1263 * @param ApiBase $module Api module being used
1264 * @param array $params Array an array containing the request parameters.
1265 * @return bool True on success, false should exit immediately
1267 protected function checkMaxLag( $module, $params ) {
1268 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1269 $maxLag = $params['maxlag'];
1270 $lagInfo = $this->getMaxLag();
1271 if ( $lagInfo['lag'] > $maxLag ) {
1272 $response = $this->getRequest()->response();
1274 $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1275 $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1277 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1278 $this->dieWithError(
1279 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1285 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1293 * Check selected RFC 7232 precondition headers
1295 * RFC 7232 envisions a particular model where you send your request to "a
1296 * resource", and for write requests that you can read "the resource" by
1297 * changing the method to GET. When the API receives a GET request, it
1298 * works out even though "the resource" from RFC 7232's perspective might
1299 * be many resources from MediaWiki's perspective. But it totally fails for
1300 * a POST, since what HTTP sees as "the resource" is probably just
1301 * "/api.php" with all the interesting bits in the body.
1303 * Therefore, we only support RFC 7232 precondition headers for GET (and
1304 * HEAD). That means we don't need to bother with If-Match and
1305 * If-Unmodified-Since since they only apply to modification requests.
1307 * And since we don't support Range, If-Range is ignored too.
1310 * @param ApiBase $module Api module being used
1311 * @return bool True on success, false should exit immediately
1313 protected function checkConditionalRequestHeaders( $module ) {
1314 if ( $this->mInternalMode
) {
1315 // No headers to check in internal mode
1319 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1320 // Don't check POSTs
1326 $ifNoneMatch = array_diff(
1327 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1330 if ( $ifNoneMatch ) {
1331 if ( $ifNoneMatch === [ '*' ] ) {
1332 // API responses always "exist"
1335 $etag = $module->getConditionalRequestData( 'etag' );
1338 if ( $ifNoneMatch && $etag !== null ) {
1339 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1340 $match = array_map( function ( $s ) {
1341 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1343 $return304 = in_array( $test, $match, true );
1345 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1347 // Some old browsers sends sizes after the date, like this:
1348 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1350 $i = strpos( $value, ';' );
1351 if ( $i !== false ) {
1352 $value = trim( substr( $value, 0, $i ) );
1355 if ( $value !== '' ) {
1357 $ts = new MWTimestamp( $value );
1359 // RFC 7231 IMF-fixdate
1360 $ts->getTimestamp( TS_RFC2822
) === $value ||
1362 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1363 // asctime (with and without space-padded day)
1364 $ts->format( 'D M j H:i:s Y' ) === $value ||
1365 $ts->format( 'D M j H:i:s Y' ) === $value
1367 $config = $this->getConfig();
1368 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1369 if ( $lastMod !== null ) {
1370 // Mix in some MediaWiki modification times
1373 'user' => $this->getUser()->getTouched(),
1374 'epoch' => $config->get( 'CacheEpoch' ),
1377 if ( $config->get( 'UseCdn' ) ) {
1378 // T46570: the core page itself may not change, but resources might
1379 $modifiedTimes['sepoch'] = wfTimestamp(
1380 TS_MW
, time() - $config->get( 'CdnMaxAge' )
1383 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1384 $lastMod = max( $modifiedTimes );
1385 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1388 } catch ( TimestampException
$e ) {
1389 // Invalid timestamp, ignore it
1395 $this->getRequest()->response()->statusHeader( 304 );
1397 // Avoid outputting the compressed representation of a zero-length body
1398 Wikimedia\
suppressWarnings();
1399 ini_set( 'zlib.output_compression', 0 );
1400 Wikimedia\restoreWarnings
();
1401 wfClearOutputBuffers();
1410 * Check for sufficient permissions to execute
1411 * @param ApiBase $module An Api module
1413 protected function checkExecutePermissions( $module ) {
1414 $user = $this->getUser();
1415 if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1416 !$this->getPermissionManager()->userHasRight( $user, 'read' )
1418 $this->dieWithError( 'apierror-readapidenied' );
1421 if ( $module->isWriteMode() ) {
1422 if ( !$this->mEnableWrite
) {
1423 $this->dieWithError( 'apierror-noapiwrite' );
1424 } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1425 $this->dieWithError( 'apierror-writeapidenied' );
1426 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1427 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1430 $this->checkReadOnly( $module );
1433 // Allow extensions to stop execution for arbitrary reasons.
1434 $message = 'hookaborted';
1435 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1436 $this->dieWithError( $message );
1441 * Check if the DB is read-only for this user
1442 * @param ApiBase $module An Api module
1444 protected function checkReadOnly( $module ) {
1445 if ( wfReadOnly() ) {
1446 $this->dieReadOnly();
1449 if ( $module->isWriteMode()
1450 && $this->getUser()->isBot()
1451 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1453 $this->checkBotReadOnly();
1458 * Check whether we are readonly for bots
1460 private function checkBotReadOnly() {
1461 // Figure out how many servers have passed the lag threshold
1463 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1464 $laggedServers = [];
1465 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1466 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1467 if ( $lag > $lagLimit ) {
1469 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1473 // If a majority of replica DBs are too lagged then disallow writes
1474 $replicaCount = $loadBalancer->getServerCount() - 1;
1475 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1476 $laggedServers = implode( ', ', $laggedServers );
1478 'api-readonly', // Deprecate this channel in favor of api-warning?
1479 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1481 LoggerFactory
::getInstance( 'api-warning' )->warning(
1482 "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1483 'laggeddbs' => $laggedServers,
1487 $this->dieWithError(
1490 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1496 * Check asserts of the user's rights
1497 * @param array $params
1499 protected function checkAsserts( $params ) {
1500 if ( isset( $params['assert'] ) ) {
1501 $user = $this->getUser();
1502 switch ( $params['assert'] ) {
1504 if ( $user->isAnon() ) {
1505 $this->dieWithError( 'apierror-assertuserfailed' );
1509 if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1510 $this->dieWithError( 'apierror-assertbotfailed' );
1515 if ( isset( $params['assertuser'] ) ) {
1516 $assertUser = User
::newFromName( $params['assertuser'], false );
1517 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1518 $this->dieWithError(
1519 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1526 * Check POST for external response and setup result printer
1527 * @param ApiBase $module An Api module
1528 * @param array $params An array with the request parameters
1530 protected function setupExternalResponse( $module, $params ) {
1531 $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1532 $request = $this->getRequest();
1534 if ( !in_array( $request->getMethod(), $validMethods ) ) {
1535 $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1538 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1539 // Module requires POST. GET request might still be allowed
1540 // if $wgDebugApi is true, otherwise fail.
1541 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1544 if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1545 $this->addDeprecation(
1546 'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1550 // See if custom printer is used
1551 $this->mPrinter
= $module->getCustomPrinter();
1552 if ( is_null( $this->mPrinter
) ) {
1553 // Create an appropriate printer
1554 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1557 if ( $request->getProtocol() === 'http' && (
1558 $request->getSession()->shouldForceHTTPS() ||
1559 ( $this->getUser()->isLoggedIn() &&
1560 $this->getUser()->requiresHTTPS() )
1562 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1567 * Execute the actual module, without any error handling
1569 protected function executeAction() {
1570 $params = $this->setupExecuteAction();
1572 // Check asserts early so e.g. errors in parsing a module's parameters due to being
1573 // logged out don't override the client's intended "am I logged in?" check.
1574 $this->checkAsserts( $params );
1576 $module = $this->setupModule();
1577 $this->mModule
= $module;
1579 if ( !$this->mInternalMode
) {
1580 $this->setRequestExpectations( $module );
1583 $this->checkExecutePermissions( $module );
1585 if ( !$this->checkMaxLag( $module, $params ) ) {
1589 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1593 if ( !$this->mInternalMode
) {
1594 $this->setupExternalResponse( $module, $params );
1598 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1600 $this->reportUnusedParams();
1602 if ( !$this->mInternalMode
) {
1603 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1605 $this->printResult();
1610 * Set database connection, query, and write expectations given this module request
1611 * @param ApiBase $module
1613 protected function setRequestExpectations( ApiBase
$module ) {
1614 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1615 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1616 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1617 if ( $this->getRequest()->hasSafeMethod() ) {
1618 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1619 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1620 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1621 $this->getRequest()->markAsSafeRequest();
1623 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1628 * Log the preceding request
1629 * @param float $time Time in seconds
1630 * @param Exception|Throwable|null $e Exception caught while processing the request
1632 protected function logRequest( $time, $e = null ) {
1633 $request = $this->getRequest();
1636 // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1637 '$schema' => '/mediawiki/api/request/0.0.1',
1639 'request_id' => WebRequest
::getRequestId(),
1640 'id' => UIDGenerator
::newUUIDv4(),
1641 'dt' => wfTimestamp( TS_ISO_8601
),
1642 'domain' => $this->getConfig()->get( 'ServerName' ),
1643 // If using the EventBus extension (as intended) with this log channel,
1644 // this stream name will map to a Kafka topic.
1645 'stream' => 'mediawiki.api-request'
1648 'method' => $request->getMethod(),
1649 'client_ip' => $request->getIP()
1651 'database' => WikiMap
::getCurrentWikiDbDomain()->getId(),
1652 'backend_time_ms' => (int)round( $time * 1000 ),
1655 // If set, these headers will be logged in http.request_headers.
1656 $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1657 foreach ( $httpRequestHeadersToLog as $header ) {
1658 if ( $request->getHeader( $header ) ) {
1659 // Set the header in http.request_headers
1660 $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1665 $logCtx['api_error_codes'] = [];
1666 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1667 $logCtx['api_error_codes'][] = $msg->getApiCode();
1671 // Construct space separated message for 'api' log channel
1672 $msg = "API {$request->getMethod()} " .
1673 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1674 " {$logCtx['http']['client_ip']} " .
1675 "T={$logCtx['backend_time_ms']}ms";
1677 $sensitive = array_flip( $this->getSensitiveParams() );
1678 foreach ( $this->getParamsUsed() as $name ) {
1679 $value = $request->getVal( $name );
1680 if ( $value === null ) {
1684 if ( isset( $sensitive[$name] ) ) {
1685 $value = '[redacted]';
1686 $encValue = '[redacted]';
1687 } elseif ( strlen( $value ) > 256 ) {
1688 $value = substr( $value, 0, 256 );
1689 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1691 $encValue = $this->encodeRequestLogValue( $value );
1694 $logCtx['params'][$name] = $value;
1695 $msg .= " {$name}={$encValue}";
1698 // Log an unstructured message to the api channel.
1699 wfDebugLog( 'api', $msg, 'private' );
1701 // The api-request channel a structured data log channel.
1702 wfDebugLog( 'api-request', '', 'private', $logCtx );
1706 * Encode a value in a format suitable for a space-separated log line.
1710 protected function encodeRequestLogValue( $s ) {
1713 $chars = ';@$!*(),/:';
1714 $numChars = strlen( $chars );
1715 for ( $i = 0; $i < $numChars; $i++
) {
1716 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1720 return strtr( rawurlencode( $s ), $table );
1724 * Get the request parameters used in the course of the preceding execute() request
1727 protected function getParamsUsed() {
1728 return array_keys( $this->mParamsUsed
);
1732 * Mark parameters as used
1733 * @param string|string[] $params
1735 public function markParamsUsed( $params ) {
1736 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1740 * Get the request parameters that should be considered sensitive
1744 protected function getSensitiveParams() {
1745 return array_keys( $this->mParamsSensitive
);
1749 * Mark parameters as sensitive
1751 * @param string|string[] $params
1753 public function markParamsSensitive( $params ) {
1754 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1758 * Get a request value, and register the fact that it was used, for logging.
1759 * @param string $name
1760 * @param string|null $default
1761 * @return string|null
1763 public function getVal( $name, $default = null ) {
1764 $this->mParamsUsed
[$name] = true;
1766 $ret = $this->getRequest()->getVal( $name );
1767 if ( $ret === null ) {
1768 if ( $this->getRequest()->getArray( $name ) !== null ) {
1769 // See T12262 for why we don't just implode( '|', ... ) the
1771 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1779 * Get a boolean request value, and register the fact that the parameter
1780 * was used, for logging.
1781 * @param string $name
1784 public function getCheck( $name ) {
1785 return $this->getVal( $name, null ) !== null;
1789 * Get a request upload, and register the fact that it was used, for logging.
1792 * @param string $name Parameter name
1793 * @return WebRequestUpload
1795 public function getUpload( $name ) {
1796 $this->mParamsUsed
[$name] = true;
1798 return $this->getRequest()->getUpload( $name );
1802 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1803 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1805 protected function reportUnusedParams() {
1806 $paramsUsed = $this->getParamsUsed();
1807 $allParams = $this->getRequest()->getValueNames();
1809 if ( !$this->mInternalMode
) {
1810 // Printer has not yet executed; don't warn that its parameters are unused
1811 $printerParams = $this->mPrinter
->encodeParamName(
1812 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1814 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1816 $unusedParams = array_diff( $allParams, $paramsUsed );
1819 if ( count( $unusedParams ) ) {
1820 $this->addWarning( [
1821 'apierror-unrecognizedparams',
1822 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1823 count( $unusedParams )
1829 * Print results using the current printer
1831 * @param int $httpCode HTTP status code, or 0 to not change
1833 protected function printResult( $httpCode = 0 ) {
1834 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1835 $this->addWarning( 'apiwarn-wgdebugapi' );
1838 $printer = $this->mPrinter
;
1839 $printer->initPrinter( false );
1841 $printer->setHttpStatus( $httpCode );
1843 $printer->execute();
1844 $printer->closePrinter();
1850 public function isReadMode() {
1855 * See ApiBase for description.
1859 public function getAllowedParams() {
1862 ApiBase
::PARAM_DFLT
=> 'help',
1863 ApiBase
::PARAM_TYPE
=> 'submodule',
1866 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1867 ApiBase
::PARAM_TYPE
=> 'submodule',
1870 ApiBase
::PARAM_TYPE
=> 'integer'
1873 ApiBase
::PARAM_TYPE
=> 'integer',
1874 ApiBase
::PARAM_DFLT
=> 0
1877 ApiBase
::PARAM_TYPE
=> 'integer',
1878 ApiBase
::PARAM_DFLT
=> 0
1881 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1884 ApiBase
::PARAM_TYPE
=> 'user',
1886 'requestid' => null,
1887 'servedby' => false,
1888 'curtimestamp' => false,
1889 'responselanginfo' => false,
1892 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1895 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1896 ApiBase
::PARAM_DFLT
=> 'bc',
1899 ApiBase
::PARAM_DFLT
=> 'uselang',
1901 'errorsuselocal' => [
1902 ApiBase
::PARAM_DFLT
=> false,
1908 protected function getExamplesMessages() {
1911 => 'apihelp-help-example-main',
1912 'action=help&recursivesubmodules=1'
1913 => 'apihelp-help-example-recursive',
1917 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1918 // Wish PHP had an "array_insert_before". Instead, we have to manually
1919 // reindex the array to get 'permissions' in the right place.
1922 foreach ( $oldHelp as $k => $v ) {
1923 if ( $k === 'submodules' ) {
1924 $help['permissions'] = '';
1928 $help['datatypes'] = '';
1929 $help['templatedparams'] = '';
1930 $help['credits'] = '';
1932 // Fill 'permissions'
1933 $help['permissions'] .= Html
::openElement( 'div',
1934 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1935 $m = $this->msg( 'api-help-permissions' );
1936 if ( !$m->isDisabled() ) {
1937 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1938 $m->numParams( count( self
::$mRights ) )->parse()
1941 $help['permissions'] .= Html
::openElement( 'dl' );
1942 foreach ( self
::$mRights as $right => $rightMsg ) {
1943 $help['permissions'] .= Html
::element( 'dt', null, $right );
1945 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1946 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1948 $groups = array_map( function ( $group ) {
1949 return $group == '*' ?
'all' : $group;
1950 }, $this->getPermissionManager()->getGroupsWithPermission( $right ) );
1952 $help['permissions'] .= Html
::rawElement( 'dd', null,
1953 $this->msg( 'api-help-permissions-granted-to' )
1954 ->numParams( count( $groups ) )
1955 ->params( Message
::listParam( $groups ) )
1959 $help['permissions'] .= Html
::closeElement( 'dl' );
1960 $help['permissions'] .= Html
::closeElement( 'div' );
1962 // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1963 if ( empty( $options['nolead'] ) ) {
1964 $level = $options['headerlevel'];
1965 $tocnumber = &$options['tocnumber'];
1967 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1969 $id = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_PRIMARY
);
1970 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_FALLBACK
);
1971 $headline = Linker
::makeHeadline( min( 6, $level ),
1972 ' class="apihelp-header">',
1978 // Ensure we have a sane anchor
1979 if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1980 $headline = '<div id="main/datatypes"></div>' . $headline;
1982 $help['datatypes'] .= $headline;
1983 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1984 if ( !isset( $tocData['main/datatypes'] ) ) {
1985 $tocnumber[$level]++
;
1986 $tocData['main/datatypes'] = [
1987 'toclevel' => count( $tocnumber ),
1989 'anchor' => 'main/datatypes',
1991 'number' => implode( '.', $tocnumber ),
1996 $header = $this->msg( 'api-help-templatedparams-header' )->parse();
1998 $id = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_PRIMARY
);
1999 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_FALLBACK
);
2000 $headline = Linker
::makeHeadline( min( 6, $level ),
2001 ' class="apihelp-header">',
2007 // Ensure we have a sane anchor
2008 if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2009 $headline = '<div id="main/templatedparams"></div>' . $headline;
2011 $help['templatedparams'] .= $headline;
2012 $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2013 if ( !isset( $tocData['main/templatedparams'] ) ) {
2014 $tocnumber[$level]++
;
2015 $tocData['main/templatedparams'] = [
2016 'toclevel' => count( $tocnumber ),
2018 'anchor' => 'main/templatedparams',
2020 'number' => implode( '.', $tocnumber ),
2025 $header = $this->msg( 'api-credits-header' )->parse();
2026 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
2027 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_FALLBACK
);
2028 $headline = Linker
::makeHeadline( min( 6, $level ),
2029 ' class="apihelp-header">',
2035 // Ensure we have a sane anchor
2036 if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2037 $headline = '<div id="main/credits"></div>' . $headline;
2039 $help['credits'] .= $headline;
2040 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2041 if ( !isset( $tocData['main/credits'] ) ) {
2042 $tocnumber[$level]++
;
2043 $tocData['main/credits'] = [
2044 'toclevel' => count( $tocnumber ),
2046 'anchor' => 'main/credits',
2048 'number' => implode( '.', $tocnumber ),
2055 private $mCanApiHighLimits = null;
2058 * Check whether the current user is allowed to use high limits
2061 public function canApiHighLimits() {
2062 if ( !isset( $this->mCanApiHighLimits
) ) {
2063 $this->mCanApiHighLimits
= $this->getPermissionManager()
2064 ->userHasRight( $this->getUser(), 'apihighlimits' );
2067 return $this->mCanApiHighLimits
;
2071 * Overrides to return this instance's module manager.
2072 * @return ApiModuleManager
2074 public function getModuleManager() {
2075 return $this->mModuleMgr
;
2079 * Fetches the user agent used for this request
2081 * The value will be the combination of the 'Api-User-Agent' header (if
2082 * any) and the standard User-Agent header (if any).
2086 public function getUserAgent() {
2088 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2089 $this->getRequest()->getHeader( 'User-agent' )
2095 * For really cool vim folding this needs to be at the end:
2096 * vim: foldmarker=@{,@} foldmethod=marker