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(
286 MediaWikiServices
::getInstance()->getObjectFactory()
288 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
289 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
290 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
291 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
293 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
295 $this->mContinuationManager
= null;
296 $this->mEnableWrite
= $enableWrite;
298 $this->mCdnMaxAge
= -1; // flag for executeActionWithErrorHandling()
302 * Return true if the API was started by other PHP code using FauxRequest
305 public function isInternalMode() {
306 return $this->mInternalMode
;
310 * Get the ApiResult object associated with current request
314 public function getResult() {
315 return $this->mResult
;
319 * Get the security flag for the current request
322 public function lacksSameOriginSecurity() {
323 if ( $this->lacksSameOriginSecurity
!== null ) {
324 return $this->lacksSameOriginSecurity
;
327 $request = $this->getRequest();
330 if ( $request->getCheck( 'callback' ) ) {
331 $this->lacksSameOriginSecurity
= true;
336 if ( $request->getVal( 'origin' ) === '*' ) {
337 $this->lacksSameOriginSecurity
= true;
341 // Header to be used from XMLHTTPRequest when the request might
342 // otherwise be used for XSS.
343 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
344 $this->lacksSameOriginSecurity
= true;
348 // Allow extensions to override.
349 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
350 return $this->lacksSameOriginSecurity
;
354 * Get the ApiErrorFormatter object associated with current request
355 * @return ApiErrorFormatter
357 public function getErrorFormatter() {
358 return $this->mErrorFormatter
;
362 * Get the continuation manager
363 * @return ApiContinuationManager|null
365 public function getContinuationManager() {
366 return $this->mContinuationManager
;
370 * Set the continuation manager
371 * @param ApiContinuationManager|null $manager
373 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
374 if ( $manager !== null && $this->mContinuationManager
!== null ) {
375 throw new UnexpectedValueException(
376 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
377 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
380 $this->mContinuationManager
= $manager;
384 * Get the API module object. Only works after executeAction()
388 public function getModule() {
389 return $this->mModule
;
393 * Get the result formatter object. Only works after setupExecuteAction()
395 * @return ApiFormatBase
397 public function getPrinter() {
398 return $this->mPrinter
;
402 * Set how long the response should be cached.
406 public function setCacheMaxAge( $maxage ) {
407 $this->setCacheControl( [
408 'max-age' => $maxage,
409 's-maxage' => $maxage
414 * Set the type of caching headers which will be sent.
416 * @param string $mode One of:
417 * - 'public': Cache this object in public caches, if the maxage or smaxage
418 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
419 * not provided by any of these means, the object will be private.
420 * - 'private': Cache this object only in private client-side caches.
421 * - 'anon-public-user-private': Make this object cacheable for logged-out
422 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
423 * set consistently for a given URL, it cannot be set differently depending on
424 * things like the contents of the database, or whether the user is logged in.
426 * If the wiki does not allow anonymous users to read it, the mode set here
427 * will be ignored, and private caching headers will always be sent. In other words,
428 * the "public" mode is equivalent to saying that the data sent is as public as a page
431 * For user-dependent data, the private mode should generally be used. The
432 * anon-public-user-private mode should only be used where there is a particularly
433 * good performance reason for caching the anonymous response, but where the
434 * response to logged-in users may differ, or may contain private data.
436 * If this function is never called, then the default will be the private mode.
438 public function setCacheMode( $mode ) {
439 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
440 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
442 // Ignore for forwards-compatibility
446 if ( !User
::isEveryoneAllowed( 'read' ) ) {
447 // Private wiki, only private headers
448 if ( $mode !== 'private' ) {
449 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
455 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
456 // User language is used for i18n, so we don't want to publicly
457 // cache. Anons are ok, because if they have non-default language
458 // then there's an appropriate Vary header set by whatever set
459 // their non-default language.
460 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
461 "'anon-public-user-private' due to uselang=user\n" );
462 $mode = 'anon-public-user-private';
465 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
466 $this->mCacheMode
= $mode;
470 * Set directives (key/value pairs) for the Cache-Control header.
471 * Boolean values will be formatted as such, by including or omitting
472 * without an equals sign.
474 * Cache control values set here will only be used if the cache mode is not
475 * private, see setCacheMode().
477 * @param array $directives
479 public function setCacheControl( $directives ) {
480 $this->mCacheControl
= $directives +
$this->mCacheControl
;
484 * Create an instance of an output formatter by its name
486 * @param string $format
488 * @return ApiFormatBase
490 public function createPrinterByName( $format ) {
491 $printer = $this->mModuleMgr
->getModule( $format, 'format', /* $ignoreCache */ true );
492 if ( $printer === null ) {
494 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
502 * Execute api request. Any errors will be handled if the API was called by the remote client.
504 public function execute() {
505 if ( $this->mInternalMode
) {
506 $this->executeAction();
508 $this->executeActionWithErrorHandling();
513 * Execute an action, and in case of an error, erase whatever partial results
514 * have been accumulated, and replace it with an error message and a help screen.
516 protected function executeActionWithErrorHandling() {
517 // Verify the CORS header before executing the action
518 if ( !$this->handleCORS() ) {
519 // handleCORS() has sent a 403, abort
523 // Exit here if the request method was OPTIONS
524 // (assume there will be a followup GET or POST)
525 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
529 // In case an error occurs during data output,
530 // clear the output buffer and print just the error information
531 $obLevel = ob_get_level();
534 $t = microtime( true );
537 $this->executeAction();
538 $runTime = microtime( true ) - $t;
539 $this->logRequest( $runTime );
540 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
541 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
543 } catch ( Exception
$e ) { // @todo Remove this block when HHVM is no longer supported
544 $this->handleException( $e );
545 $this->logRequest( microtime( true ) - $t, $e );
547 } catch ( Throwable
$e ) {
548 $this->handleException( $e );
549 $this->logRequest( microtime( true ) - $t, $e );
553 // Commit DBs and send any related cookies and headers
554 MediaWiki
::preOutputCommit( $this->getContext() );
556 // Send cache headers after any code which might generate an error, to
557 // avoid sending public cache headers for errors.
558 $this->sendCacheHeaders( $isError );
560 // Executing the action might have already messed with the output
562 while ( ob_get_level() > $obLevel ) {
568 * Handle an exception as an API response
571 * @param Exception|Throwable $e
573 protected function handleException( $e ) {
574 // T65145: Rollback any open database transactions
575 if ( !$e instanceof ApiUsageException
) {
576 // ApiUsageExceptions are intentional, so don't rollback if that's the case
577 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
580 // Allow extra cleanup and logging
581 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
583 // Handle any kind of exception by outputting properly formatted error message.
584 // If this fails, an unhandled exception should be thrown so that global error
585 // handler will process and log it.
587 $errCodes = $this->substituteResultWithError( $e );
589 // Error results should not be cached
590 $this->setCacheMode( 'private' );
592 $response = $this->getRequest()->response();
593 $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
594 $response->header( $headerStr );
596 // Reset and print just the error message
599 // Printer may not be initialized if the extractRequestParams() fails for the main module
600 $this->createErrorPrinter();
602 // Get desired HTTP code from an ApiUsageException. Don't use codes from other
603 // exception types, as they are unlikely to be intended as an HTTP code.
604 $httpCode = $e instanceof ApiUsageException ?
$e->getCode() : 0;
608 $this->printResult( $httpCode );
609 } catch ( ApiUsageException
$ex ) {
610 // The error printer itself is failing. Try suppressing its request
611 // parameters and redo.
613 $this->addWarning( 'apiwarn-errorprinterfailed' );
614 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
616 $this->mPrinter
->addWarning( $error );
617 } catch ( Exception
$ex2 ) { // @todo Remove this block when HHVM is no longer supported
619 $this->addWarning( $error );
620 } catch ( Throwable
$ex2 ) {
622 $this->addWarning( $error );
627 $this->mPrinter
= null;
628 $this->createErrorPrinter();
629 $this->mPrinter
->forceDefaultParams();
631 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
633 $this->printResult( $httpCode );
638 * Handle an exception from the ApiBeforeMain hook.
640 * This tries to print the exception as an API response, to be more
641 * friendly to clients. If it fails, it will rethrow the exception.
644 * @param Exception|Throwable $e
645 * @throws Exception|Throwable
647 public static function handleApiBeforeMainException( $e ) {
651 $main = new self( RequestContext
::getMain(), false );
652 $main->handleException( $e );
653 $main->logRequest( 0, $e );
654 } catch ( Exception
$e2 ) { // @todo Remove this block when HHVM is no longer supported
655 // Nope, even that didn't work. Punt.
657 } catch ( Throwable
$e2 ) {
658 // Nope, even that didn't work. Punt.
662 // Reset cache headers
663 $main->sendCacheHeaders( true );
669 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
671 * If no origin parameter is present, nothing happens.
672 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
673 * is set and false is returned.
674 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
675 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
677 * https://www.w3.org/TR/cors/#resource-requests
678 * https://www.w3.org/TR/cors/#resource-preflight-requests
680 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
682 protected function handleCORS() {
683 $originParam = $this->getParameter( 'origin' ); // defaults to null
684 if ( $originParam === null ) {
685 // No origin parameter, nothing to do
689 $request = $this->getRequest();
690 $response = $request->response();
692 $matchedOrigin = false;
693 $allowTiming = false;
696 if ( $originParam === '*' ) {
697 // Request for anonymous CORS
698 // Technically we should check for the presence of an Origin header
699 // and not process it as CORS if it's not set, but that would
700 // require us to vary on Origin for all 'origin=*' requests which
701 // we don't want to do.
702 $matchedOrigin = true;
704 $allowCredentials = 'false';
705 $varyOrigin = false; // No need to vary
707 // Non-anonymous CORS, check we allow the domain
709 // Origin: header is a space-separated list of origins, check all of them
710 $originHeader = $request->getHeader( 'Origin' );
711 if ( $originHeader === false ) {
714 $originHeader = trim( $originHeader );
715 $origins = preg_split( '/\s+/', $originHeader );
718 if ( !in_array( $originParam, $origins ) ) {
719 // origin parameter set but incorrect
720 // Send a 403 response
721 $response->statusHeader( 403 );
722 $response->header( 'Cache-Control: no-cache' );
723 echo "'origin' parameter does not match Origin header\n";
728 $config = $this->getConfig();
729 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
731 $config->get( 'CrossSiteAJAXdomains' ),
732 $config->get( 'CrossSiteAJAXdomainExceptions' )
735 $allowOrigin = $originHeader;
736 $allowCredentials = 'true';
737 $allowTiming = $originHeader;
740 if ( $matchedOrigin ) {
741 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
742 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
744 // This is a CORS preflight request
745 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
746 // If method is not a case-sensitive match, do not set any additional headers and terminate.
747 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
750 // We allow the actual request to send the following headers
751 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
752 if ( $requestedHeaders !== false ) {
753 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
754 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
757 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
760 // We only allow the actual request to be GET or POST
761 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
762 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
763 // Unsupported non-preflight method, don't handle it as CORS
765 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
770 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
771 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
772 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
773 if ( $allowTiming !== false ) {
774 $response->header( "Timing-Allow-Origin: $allowTiming" );
779 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
780 . 'MediaWiki-Login-Suppressed'
784 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
788 $this->getOutput()->addVaryHeader( 'Origin' );
795 * Attempt to match an Origin header against a set of rules and a set of exceptions
796 * @param string $value Origin header
797 * @param array $rules Set of wildcard rules
798 * @param array $exceptions Set of wildcard rules
799 * @return bool True if $value matches a rule in $rules and doesn't match
800 * any rules in $exceptions, false otherwise
802 protected static function matchOrigin( $value, $rules, $exceptions ) {
803 foreach ( $rules as $rule ) {
804 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
805 // Rule matches, check exceptions
806 foreach ( $exceptions as $exc ) {
807 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
820 * Attempt to validate the value of Access-Control-Request-Headers against a list
821 * of headers that we allow the follow up request to send.
823 * @param string $requestedHeaders Comma separated list of HTTP headers
824 * @return bool True if all requested headers are in the list of allowed headers
826 protected static function matchRequestedHeaders( $requestedHeaders ) {
827 if ( trim( $requestedHeaders ) === '' ) {
830 $requestedHeaders = explode( ',', $requestedHeaders );
831 $allowedAuthorHeaders = array_flip( [
832 /* simple headers (see spec) */
837 /* non-authorable headers in XHR, which are however requested by some UAs */
841 /* MediaWiki whitelist */
845 foreach ( $requestedHeaders as $rHeader ) {
846 $rHeader = strtolower( trim( $rHeader ) );
847 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
848 LoggerFactory
::getInstance( 'api-warning' )->warning(
849 'CORS preflight failed on requested header: {header}', [
860 * Helper function to convert wildcard string into a regex
864 * @param string $wildcard String with wildcards
865 * @return string Regular expression
867 protected static function wildcardToRegex( $wildcard ) {
868 $wildcard = preg_quote( $wildcard, '/' );
869 $wildcard = str_replace(
875 return "/^https?:\/\/$wildcard$/";
879 * Send caching headers
880 * @param bool $isError Whether an error response is being output
881 * @since 1.26 added $isError parameter
883 protected function sendCacheHeaders( $isError ) {
884 $response = $this->getRequest()->response();
885 $out = $this->getOutput();
887 $out->addVaryHeader( 'Treat-as-Untrusted' );
889 $config = $this->getConfig();
891 if ( $config->get( 'VaryOnXFP' ) ) {
892 $out->addVaryHeader( 'X-Forwarded-Proto' );
895 if ( !$isError && $this->mModule
&&
896 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
898 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
899 if ( $etag !== null ) {
900 $response->header( "ETag: $etag" );
902 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
903 if ( $lastMod !== null ) {
904 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
908 // The logic should be:
909 // $this->mCacheControl['max-age'] is set?
910 // Use it, the module knows better than our guess.
911 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
912 // Use 0 because we can guess caching is probably the wrong thing to do.
913 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
915 if ( isset( $this->mCacheControl
['max-age'] ) ) {
916 $maxage = $this->mCacheControl
['max-age'];
917 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
918 $this->mCacheMode
!== 'private'
920 $maxage = $this->getParameter( 'maxage' );
922 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
924 if ( $this->mCacheMode
== 'private' ) {
925 $response->header( "Cache-Control: $privateCache" );
929 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
930 $out->addVaryHeader( 'Cookie' );
931 $response->header( $out->getVaryHeader() );
932 if ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
933 // Logged in or otherwise has session (e.g. anonymous users who have edited)
934 // Mark request private
935 $response->header( "Cache-Control: $privateCache" );
938 } // else anonymous, send public headers below
941 // Send public headers
942 $response->header( $out->getVaryHeader() );
944 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
945 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
946 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
948 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
949 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
952 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
953 // Public cache not requested
954 // Sending a Vary header in this case is harmless, and protects us
955 // against conditional calls of setCacheMaxAge().
956 $response->header( "Cache-Control: $privateCache" );
961 $this->mCacheControl
['public'] = true;
963 // Send an Expires header
964 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
965 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
966 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
968 // Construct the Cache-Control header
971 foreach ( $this->mCacheControl
as $name => $value ) {
972 if ( is_bool( $value ) ) {
974 $ccHeader .= $separator . $name;
978 $ccHeader .= $separator . "$name=$value";
983 $response->header( "Cache-Control: $ccHeader" );
987 * Create the printer for error output
989 private function createErrorPrinter() {
990 if ( !isset( $this->mPrinter
) ) {
991 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
992 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
993 $value = self
::API_DEFAULT_FORMAT
;
995 $this->mPrinter
= $this->createPrinterByName( $value );
998 // Printer may not be able to handle errors. This is particularly
999 // likely if the module returns something for getCustomPrinter().
1000 if ( !$this->mPrinter
->canPrintErrors() ) {
1001 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1006 * Create an error message for the given exception.
1008 * If an ApiUsageException, errors/warnings will be extracted from the
1009 * embedded StatusValue.
1011 * Any other exception will be returned with a generic code and wrapper
1012 * text around the exception's (presumably English) message as a single
1013 * error (no warnings).
1015 * @param Exception|Throwable $e
1016 * @param string $type 'error' or 'warning'
1017 * @return ApiMessage[]
1020 protected function errorMessagesFromException( $e, $type = 'error' ) {
1022 if ( $e instanceof ApiUsageException
) {
1023 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1024 $messages[] = ApiMessage
::create( $error );
1026 } elseif ( $type !== 'error' ) {
1027 // None of the rest have any messages for non-error types
1029 // Something is seriously wrong
1030 $config = $this->getConfig();
1031 // TODO: Avoid embedding arbitrary class names in the error code.
1032 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1033 $code = 'internal_api_error_' . $class;
1034 $data = [ 'errorclass' => get_class( $e ) ];
1035 if ( $config->get( 'ShowExceptionDetails' ) ) {
1036 if ( $e instanceof ILocalizedException
) {
1037 $msg = $e->getMessageObject();
1038 } elseif ( $e instanceof MessageSpecifier
) {
1039 $msg = Message
::newFromSpecifier( $e );
1041 $msg = wfEscapeWikiText( $e->getMessage() );
1043 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1045 $params = [ 'apierror-exceptioncaughttype', WebRequest
::getRequestId(), get_class( $e ) ];
1048 $messages[] = ApiMessage
::create( $params, $code, $data );
1054 * Replace the result data with the information about an exception.
1055 * @param Exception|Throwable $e
1056 * @return string[] Error codes
1058 protected function substituteResultWithError( $e ) {
1059 $result = $this->getResult();
1060 $formatter = $this->getErrorFormatter();
1061 $config = $this->getConfig();
1064 // Remember existing warnings and errors across the reset
1065 $errors = $result->getResultData( [ 'errors' ] );
1066 $warnings = $result->getResultData( [ 'warnings' ] );
1068 if ( $warnings !== null ) {
1069 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1071 if ( $errors !== null ) {
1072 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1074 // Collect the copied error codes for the return value
1075 foreach ( $errors as $error ) {
1076 if ( isset( $error['code'] ) ) {
1077 $errorCodes[$error['code']] = true;
1082 // Add errors from the exception
1083 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1084 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1085 if ( ApiErrorFormatter
::isValidApiCode( $msg->getApiCode() ) ) {
1086 $errorCodes[$msg->getApiCode()] = true;
1088 LoggerFactory
::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1089 'code' => $msg->getApiCode(),
1092 $errorCodes['<invalid-code>'] = true;
1094 $formatter->addError( $modulePath, $msg );
1096 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1097 $formatter->addWarning( $modulePath, $msg );
1100 // Add additional data. Path depends on whether we're in BC mode or not.
1101 // Data depends on the type of exception.
1102 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1103 $path = [ 'error' ];
1107 if ( $e instanceof ApiUsageException
) {
1108 $link = wfExpandUrl( wfScript( 'api' ) );
1109 $result->addContentValue(
1113 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1115 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1118 } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1119 $result->addContentValue(
1122 $this->msg( 'api-exception-trace',
1126 MWExceptionHandler
::getRedactedTraceAsString( $e )
1127 )->inLanguage( $formatter->getLanguage() )->text()
1131 // Add the id and such
1132 $this->addRequestedFields( [ 'servedby' ] );
1134 return array_keys( $errorCodes );
1138 * Add requested fields to the result
1139 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1142 protected function addRequestedFields( $force = [] ) {
1143 $result = $this->getResult();
1145 $requestid = $this->getParameter( 'requestid' );
1146 if ( $requestid !== null ) {
1147 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1150 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1151 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1153 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1156 if ( $this->getParameter( 'curtimestamp' ) ) {
1157 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
), ApiResult
::NO_SIZE_CHECK
);
1160 if ( $this->getParameter( 'responselanginfo' ) ) {
1161 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1162 ApiResult
::NO_SIZE_CHECK
);
1163 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1164 ApiResult
::NO_SIZE_CHECK
);
1169 * Set up for the execution.
1172 protected function setupExecuteAction() {
1173 $this->addRequestedFields();
1175 $params = $this->extractRequestParams();
1176 $this->mAction
= $params['action'];
1182 * Set up the module for response
1183 * @return ApiBase The module that will handle this action
1184 * @throws MWException
1185 * @throws ApiUsageException
1187 protected function setupModule() {
1188 // Instantiate the module requested by the user
1189 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1190 if ( $module === null ) {
1191 // Probably can't happen
1192 // @codeCoverageIgnoreStart
1193 $this->dieWithError(
1194 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1196 // @codeCoverageIgnoreEnd
1198 $moduleParams = $module->extractRequestParams();
1200 // Check token, if necessary
1201 if ( $module->needsToken() === true ) {
1202 throw new MWException(
1203 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1204 'See documentation for ApiBase::needsToken for details.'
1207 if ( $module->needsToken() ) {
1208 if ( !$module->mustBePosted() ) {
1209 throw new MWException(
1210 "Module '{$module->getModuleName()}' must require POST to use tokens."
1214 if ( !isset( $moduleParams['token'] ) ) {
1215 // Probably can't happen
1216 // @codeCoverageIgnoreStart
1217 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1218 // @codeCoverageIgnoreEnd
1221 $module->requirePostedParameters( [ 'token' ] );
1223 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1224 $module->dieWithError( 'apierror-badtoken' );
1234 private function getMaxLag() {
1235 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1237 'host' => $dbLag[0],
1242 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1243 if ( $jobQueueLagFactor ) {
1244 // Turn total number of jobs into seconds by using the configured value
1245 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1246 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1247 if ( $jobQueueLag > $lagInfo['lag'] ) {
1249 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1250 'lag' => $jobQueueLag,
1251 'type' => 'jobqueue',
1252 'jobs' => $totalJobs,
1257 Hooks
::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1263 * Check the max lag if necessary
1264 * @param ApiBase $module Api module being used
1265 * @param array $params Array an array containing the request parameters.
1266 * @return bool True on success, false should exit immediately
1268 protected function checkMaxLag( $module, $params ) {
1269 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1270 $maxLag = $params['maxlag'];
1271 $lagInfo = $this->getMaxLag();
1272 if ( $lagInfo['lag'] > $maxLag ) {
1273 $response = $this->getRequest()->response();
1275 $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1276 $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1278 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1279 $this->dieWithError(
1280 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1286 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1294 * Check selected RFC 7232 precondition headers
1296 * RFC 7232 envisions a particular model where you send your request to "a
1297 * resource", and for write requests that you can read "the resource" by
1298 * changing the method to GET. When the API receives a GET request, it
1299 * works out even though "the resource" from RFC 7232's perspective might
1300 * be many resources from MediaWiki's perspective. But it totally fails for
1301 * a POST, since what HTTP sees as "the resource" is probably just
1302 * "/api.php" with all the interesting bits in the body.
1304 * Therefore, we only support RFC 7232 precondition headers for GET (and
1305 * HEAD). That means we don't need to bother with If-Match and
1306 * If-Unmodified-Since since they only apply to modification requests.
1308 * And since we don't support Range, If-Range is ignored too.
1311 * @param ApiBase $module Api module being used
1312 * @return bool True on success, false should exit immediately
1314 protected function checkConditionalRequestHeaders( $module ) {
1315 if ( $this->mInternalMode
) {
1316 // No headers to check in internal mode
1320 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1321 // Don't check POSTs
1327 $ifNoneMatch = array_diff(
1328 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1331 if ( $ifNoneMatch ) {
1332 if ( $ifNoneMatch === [ '*' ] ) {
1333 // API responses always "exist"
1336 $etag = $module->getConditionalRequestData( 'etag' );
1339 if ( $ifNoneMatch && $etag !== null ) {
1340 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1341 $match = array_map( function ( $s ) {
1342 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1344 $return304 = in_array( $test, $match, true );
1346 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1348 // Some old browsers sends sizes after the date, like this:
1349 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1351 $i = strpos( $value, ';' );
1352 if ( $i !== false ) {
1353 $value = trim( substr( $value, 0, $i ) );
1356 if ( $value !== '' ) {
1358 $ts = new MWTimestamp( $value );
1360 // RFC 7231 IMF-fixdate
1361 $ts->getTimestamp( TS_RFC2822
) === $value ||
1363 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1364 // asctime (with and without space-padded day)
1365 $ts->format( 'D M j H:i:s Y' ) === $value ||
1366 $ts->format( 'D M j H:i:s Y' ) === $value
1368 $config = $this->getConfig();
1369 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1370 if ( $lastMod !== null ) {
1371 // Mix in some MediaWiki modification times
1374 'user' => $this->getUser()->getTouched(),
1375 'epoch' => $config->get( 'CacheEpoch' ),
1378 if ( $config->get( 'UseCdn' ) ) {
1379 // T46570: the core page itself may not change, but resources might
1380 $modifiedTimes['sepoch'] = wfTimestamp(
1381 TS_MW
, time() - $config->get( 'CdnMaxAge' )
1384 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1385 $lastMod = max( $modifiedTimes );
1386 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1389 } catch ( TimestampException
$e ) {
1390 // Invalid timestamp, ignore it
1396 $this->getRequest()->response()->statusHeader( 304 );
1398 // Avoid outputting the compressed representation of a zero-length body
1399 Wikimedia\
suppressWarnings();
1400 ini_set( 'zlib.output_compression', 0 );
1401 Wikimedia\restoreWarnings
();
1402 wfClearOutputBuffers();
1411 * Check for sufficient permissions to execute
1412 * @param ApiBase $module An Api module
1414 protected function checkExecutePermissions( $module ) {
1415 $user = $this->getUser();
1416 if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1417 !$this->getPermissionManager()->userHasRight( $user, 'read' )
1419 $this->dieWithError( 'apierror-readapidenied' );
1422 if ( $module->isWriteMode() ) {
1423 if ( !$this->mEnableWrite
) {
1424 $this->dieWithError( 'apierror-noapiwrite' );
1425 } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1426 $this->dieWithError( 'apierror-writeapidenied' );
1427 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1428 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1431 $this->checkReadOnly( $module );
1434 // Allow extensions to stop execution for arbitrary reasons.
1435 $message = 'hookaborted';
1436 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1437 $this->dieWithError( $message );
1442 * Check if the DB is read-only for this user
1443 * @param ApiBase $module An Api module
1445 protected function checkReadOnly( $module ) {
1446 if ( wfReadOnly() ) {
1447 $this->dieReadOnly();
1450 if ( $module->isWriteMode()
1451 && $this->getUser()->isBot()
1452 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1454 $this->checkBotReadOnly();
1459 * Check whether we are readonly for bots
1461 private function checkBotReadOnly() {
1462 // Figure out how many servers have passed the lag threshold
1464 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1465 $laggedServers = [];
1466 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1467 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1468 if ( $lag > $lagLimit ) {
1470 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1474 // If a majority of replica DBs are too lagged then disallow writes
1475 $replicaCount = $loadBalancer->getServerCount() - 1;
1476 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1477 $laggedServers = implode( ', ', $laggedServers );
1479 'api-readonly', // Deprecate this channel in favor of api-warning?
1480 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1482 LoggerFactory
::getInstance( 'api-warning' )->warning(
1483 "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1484 'laggeddbs' => $laggedServers,
1488 $this->dieWithError(
1491 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1497 * Check asserts of the user's rights
1498 * @param array $params
1500 protected function checkAsserts( $params ) {
1501 if ( isset( $params['assert'] ) ) {
1502 $user = $this->getUser();
1503 switch ( $params['assert'] ) {
1505 if ( $user->isAnon() ) {
1506 $this->dieWithError( 'apierror-assertuserfailed' );
1510 if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1511 $this->dieWithError( 'apierror-assertbotfailed' );
1516 if ( isset( $params['assertuser'] ) ) {
1517 $assertUser = User
::newFromName( $params['assertuser'], false );
1518 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1519 $this->dieWithError(
1520 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1527 * Check POST for external response and setup result printer
1528 * @param ApiBase $module An Api module
1529 * @param array $params An array with the request parameters
1531 protected function setupExternalResponse( $module, $params ) {
1532 $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1533 $request = $this->getRequest();
1535 if ( !in_array( $request->getMethod(), $validMethods ) ) {
1536 $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1539 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1540 // Module requires POST. GET request might still be allowed
1541 // if $wgDebugApi is true, otherwise fail.
1542 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1545 if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1546 $this->addDeprecation(
1547 'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1551 // See if custom printer is used
1552 $this->mPrinter
= $module->getCustomPrinter();
1553 if ( is_null( $this->mPrinter
) ) {
1554 // Create an appropriate printer
1555 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1558 if ( $request->getProtocol() === 'http' && (
1559 $request->getSession()->shouldForceHTTPS() ||
1560 ( $this->getUser()->isLoggedIn() &&
1561 $this->getUser()->requiresHTTPS() )
1563 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1568 * Execute the actual module, without any error handling
1570 protected function executeAction() {
1571 $params = $this->setupExecuteAction();
1573 // Check asserts early so e.g. errors in parsing a module's parameters due to being
1574 // logged out don't override the client's intended "am I logged in?" check.
1575 $this->checkAsserts( $params );
1577 $module = $this->setupModule();
1578 $this->mModule
= $module;
1580 if ( !$this->mInternalMode
) {
1581 $this->setRequestExpectations( $module );
1584 $this->checkExecutePermissions( $module );
1586 if ( !$this->checkMaxLag( $module, $params ) ) {
1590 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1594 if ( !$this->mInternalMode
) {
1595 $this->setupExternalResponse( $module, $params );
1599 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1601 $this->reportUnusedParams();
1603 if ( !$this->mInternalMode
) {
1604 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1606 $this->printResult();
1611 * Set database connection, query, and write expectations given this module request
1612 * @param ApiBase $module
1614 protected function setRequestExpectations( ApiBase
$module ) {
1615 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1616 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1617 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1618 if ( $this->getRequest()->hasSafeMethod() ) {
1619 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1620 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1621 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1622 $this->getRequest()->markAsSafeRequest();
1624 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1629 * Log the preceding request
1630 * @param float $time Time in seconds
1631 * @param Exception|Throwable|null $e Exception caught while processing the request
1633 protected function logRequest( $time, $e = null ) {
1634 $request = $this->getRequest();
1637 // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1638 '$schema' => '/mediawiki/api/request/0.0.1',
1640 'request_id' => WebRequest
::getRequestId(),
1641 'id' => UIDGenerator
::newUUIDv4(),
1642 'dt' => wfTimestamp( TS_ISO_8601
),
1643 'domain' => $this->getConfig()->get( 'ServerName' ),
1644 // If using the EventBus extension (as intended) with this log channel,
1645 // this stream name will map to a Kafka topic.
1646 'stream' => 'mediawiki.api-request'
1649 'method' => $request->getMethod(),
1650 'client_ip' => $request->getIP()
1652 'database' => WikiMap
::getCurrentWikiDbDomain()->getId(),
1653 'backend_time_ms' => (int)round( $time * 1000 ),
1656 // If set, these headers will be logged in http.request_headers.
1657 $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1658 foreach ( $httpRequestHeadersToLog as $header ) {
1659 if ( $request->getHeader( $header ) ) {
1660 // Set the header in http.request_headers
1661 $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1666 $logCtx['api_error_codes'] = [];
1667 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1668 $logCtx['api_error_codes'][] = $msg->getApiCode();
1672 // Construct space separated message for 'api' log channel
1673 $msg = "API {$request->getMethod()} " .
1674 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1675 " {$logCtx['http']['client_ip']} " .
1676 "T={$logCtx['backend_time_ms']}ms";
1678 $sensitive = array_flip( $this->getSensitiveParams() );
1679 foreach ( $this->getParamsUsed() as $name ) {
1680 $value = $request->getVal( $name );
1681 if ( $value === null ) {
1685 if ( isset( $sensitive[$name] ) ) {
1686 $value = '[redacted]';
1687 $encValue = '[redacted]';
1688 } elseif ( strlen( $value ) > 256 ) {
1689 $value = substr( $value, 0, 256 );
1690 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1692 $encValue = $this->encodeRequestLogValue( $value );
1695 $logCtx['params'][$name] = $value;
1696 $msg .= " {$name}={$encValue}";
1699 // Log an unstructured message to the api channel.
1700 wfDebugLog( 'api', $msg, 'private' );
1702 // The api-request channel a structured data log channel.
1703 wfDebugLog( 'api-request', '', 'private', $logCtx );
1707 * Encode a value in a format suitable for a space-separated log line.
1711 protected function encodeRequestLogValue( $s ) {
1714 $chars = ';@$!*(),/:';
1715 $numChars = strlen( $chars );
1716 for ( $i = 0; $i < $numChars; $i++
) {
1717 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1721 return strtr( rawurlencode( $s ), $table );
1725 * Get the request parameters used in the course of the preceding execute() request
1728 protected function getParamsUsed() {
1729 return array_keys( $this->mParamsUsed
);
1733 * Mark parameters as used
1734 * @param string|string[] $params
1736 public function markParamsUsed( $params ) {
1737 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1741 * Get the request parameters that should be considered sensitive
1745 protected function getSensitiveParams() {
1746 return array_keys( $this->mParamsSensitive
);
1750 * Mark parameters as sensitive
1752 * @param string|string[] $params
1754 public function markParamsSensitive( $params ) {
1755 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1759 * Get a request value, and register the fact that it was used, for logging.
1760 * @param string $name
1761 * @param string|null $default
1762 * @return string|null
1764 public function getVal( $name, $default = null ) {
1765 $this->mParamsUsed
[$name] = true;
1767 $ret = $this->getRequest()->getVal( $name );
1768 if ( $ret === null ) {
1769 if ( $this->getRequest()->getArray( $name ) !== null ) {
1770 // See T12262 for why we don't just implode( '|', ... ) the
1772 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1780 * Get a boolean request value, and register the fact that the parameter
1781 * was used, for logging.
1782 * @param string $name
1785 public function getCheck( $name ) {
1786 return $this->getVal( $name, null ) !== null;
1790 * Get a request upload, and register the fact that it was used, for logging.
1793 * @param string $name Parameter name
1794 * @return WebRequestUpload
1796 public function getUpload( $name ) {
1797 $this->mParamsUsed
[$name] = true;
1799 return $this->getRequest()->getUpload( $name );
1803 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1804 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1806 protected function reportUnusedParams() {
1807 $paramsUsed = $this->getParamsUsed();
1808 $allParams = $this->getRequest()->getValueNames();
1810 if ( !$this->mInternalMode
) {
1811 // Printer has not yet executed; don't warn that its parameters are unused
1812 $printerParams = $this->mPrinter
->encodeParamName(
1813 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1815 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1817 $unusedParams = array_diff( $allParams, $paramsUsed );
1820 if ( count( $unusedParams ) ) {
1821 $this->addWarning( [
1822 'apierror-unrecognizedparams',
1823 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1824 count( $unusedParams )
1830 * Print results using the current printer
1832 * @param int $httpCode HTTP status code, or 0 to not change
1834 protected function printResult( $httpCode = 0 ) {
1835 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1836 $this->addWarning( 'apiwarn-wgdebugapi' );
1839 $printer = $this->mPrinter
;
1840 $printer->initPrinter( false );
1842 $printer->setHttpStatus( $httpCode );
1844 $printer->execute();
1845 $printer->closePrinter();
1851 public function isReadMode() {
1856 * See ApiBase for description.
1860 public function getAllowedParams() {
1863 ApiBase
::PARAM_DFLT
=> 'help',
1864 ApiBase
::PARAM_TYPE
=> 'submodule',
1867 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1868 ApiBase
::PARAM_TYPE
=> 'submodule',
1871 ApiBase
::PARAM_TYPE
=> 'integer'
1874 ApiBase
::PARAM_TYPE
=> 'integer',
1875 ApiBase
::PARAM_DFLT
=> 0
1878 ApiBase
::PARAM_TYPE
=> 'integer',
1879 ApiBase
::PARAM_DFLT
=> 0
1882 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1885 ApiBase
::PARAM_TYPE
=> 'user',
1887 'requestid' => null,
1888 'servedby' => false,
1889 'curtimestamp' => false,
1890 'responselanginfo' => false,
1893 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1896 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1897 ApiBase
::PARAM_DFLT
=> 'bc',
1900 ApiBase
::PARAM_DFLT
=> 'uselang',
1902 'errorsuselocal' => [
1903 ApiBase
::PARAM_DFLT
=> false,
1909 protected function getExamplesMessages() {
1912 => 'apihelp-help-example-main',
1913 'action=help&recursivesubmodules=1'
1914 => 'apihelp-help-example-recursive',
1920 * @phan-param array{nolead?:bool,headerlevel?:int,tocnumber?:int[]} $options
1922 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1923 // Wish PHP had an "array_insert_before". Instead, we have to manually
1924 // reindex the array to get 'permissions' in the right place.
1927 foreach ( $oldHelp as $k => $v ) {
1928 if ( $k === 'submodules' ) {
1929 $help['permissions'] = '';
1933 $help['datatypes'] = '';
1934 $help['templatedparams'] = '';
1935 $help['credits'] = '';
1937 // Fill 'permissions'
1938 $help['permissions'] .= Html
::openElement( 'div',
1939 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1940 $m = $this->msg( 'api-help-permissions' );
1941 if ( !$m->isDisabled() ) {
1942 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1943 $m->numParams( count( self
::$mRights ) )->parse()
1946 $help['permissions'] .= Html
::openElement( 'dl' );
1947 foreach ( self
::$mRights as $right => $rightMsg ) {
1948 $help['permissions'] .= Html
::element( 'dt', null, $right );
1950 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1951 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1953 $groups = array_map( function ( $group ) {
1954 return $group == '*' ?
'all' : $group;
1955 }, $this->getPermissionManager()->getGroupsWithPermission( $right ) );
1957 $help['permissions'] .= Html
::rawElement( 'dd', null,
1958 $this->msg( 'api-help-permissions-granted-to' )
1959 ->numParams( count( $groups ) )
1960 ->params( Message
::listParam( $groups ) )
1964 $help['permissions'] .= Html
::closeElement( 'dl' );
1965 $help['permissions'] .= Html
::closeElement( 'div' );
1967 // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1968 if ( empty( $options['nolead'] ) ) {
1969 $level = $options['headerlevel'];
1970 $tocnumber = &$options['tocnumber'];
1972 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1974 $id = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_PRIMARY
);
1975 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_FALLBACK
);
1976 $headline = Linker
::makeHeadline( min( 6, $level ),
1977 ' class="apihelp-header">',
1983 // Ensure we have a sane anchor
1984 if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1985 $headline = '<div id="main/datatypes"></div>' . $headline;
1987 $help['datatypes'] .= $headline;
1988 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1989 if ( !isset( $tocData['main/datatypes'] ) ) {
1990 $tocnumber[$level]++
;
1991 $tocData['main/datatypes'] = [
1992 'toclevel' => count( $tocnumber ),
1994 'anchor' => 'main/datatypes',
1996 'number' => implode( '.', $tocnumber ),
2001 $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2003 $id = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_PRIMARY
);
2004 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_FALLBACK
);
2005 $headline = Linker
::makeHeadline( min( 6, $level ),
2006 ' class="apihelp-header">',
2012 // Ensure we have a sane anchor
2013 if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2014 $headline = '<div id="main/templatedparams"></div>' . $headline;
2016 $help['templatedparams'] .= $headline;
2017 $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2018 if ( !isset( $tocData['main/templatedparams'] ) ) {
2019 $tocnumber[$level]++
;
2020 $tocData['main/templatedparams'] = [
2021 'toclevel' => count( $tocnumber ),
2023 'anchor' => 'main/templatedparams',
2025 'number' => implode( '.', $tocnumber ),
2030 $header = $this->msg( 'api-credits-header' )->parse();
2031 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
2032 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_FALLBACK
);
2033 $headline = Linker
::makeHeadline( min( 6, $level ),
2034 ' class="apihelp-header">',
2040 // Ensure we have a sane anchor
2041 if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2042 $headline = '<div id="main/credits"></div>' . $headline;
2044 $help['credits'] .= $headline;
2045 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2046 if ( !isset( $tocData['main/credits'] ) ) {
2047 $tocnumber[$level]++
;
2048 $tocData['main/credits'] = [
2049 'toclevel' => count( $tocnumber ),
2051 'anchor' => 'main/credits',
2053 'number' => implode( '.', $tocnumber ),
2060 private $mCanApiHighLimits = null;
2063 * Check whether the current user is allowed to use high limits
2066 public function canApiHighLimits() {
2067 if ( !isset( $this->mCanApiHighLimits
) ) {
2068 $this->mCanApiHighLimits
= $this->getPermissionManager()
2069 ->userHasRight( $this->getUser(), 'apihighlimits' );
2072 return $this->mCanApiHighLimits
;
2076 * Overrides to return this instance's module manager.
2077 * @return ApiModuleManager
2079 public function getModuleManager() {
2080 return $this->mModuleMgr
;
2084 * Fetches the user agent used for this request
2086 * The value will be the combination of the 'Api-User-Agent' header (if
2087 * any) and the standard User-Agent header (if any).
2091 public function getUserAgent() {
2093 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2094 $this->getRequest()->getHeader( 'User-agent' )
2100 * For really cool vim folding this needs to be at the end:
2101 * vim: foldmarker=@{,@} foldmethod=marker