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';
156 private $mCacheControl = [];
157 private $mParamsUsed = [];
158 private $mParamsSensitive = [];
160 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
161 private $lacksSameOriginSecurity = null;
164 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
166 * @param IContextSource|WebRequest|null $context If this is an instance of
167 * FauxRequest, errors are thrown and no printing occurs
168 * @param bool $enableWrite Should be set to true if the api may modify data
170 public function __construct( $context = null, $enableWrite = false ) {
171 if ( $context === null ) {
172 $context = RequestContext
::getMain();
173 } elseif ( $context instanceof WebRequest
) {
176 $context = RequestContext
::getMain();
178 // We set a derivative context so we can change stuff later
179 $this->setContext( new DerivativeContext( $context ) );
181 if ( isset( $request ) ) {
182 $this->getContext()->setRequest( $request );
184 $request = $this->getRequest();
187 $this->mInternalMode
= ( $request instanceof FauxRequest
);
189 // Special handling for the main module: $parent === $this
190 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
192 $config = $this->getConfig();
194 if ( !$this->mInternalMode
) {
195 // Log if a request with a non-whitelisted Origin header is seen
196 // with session cookies.
197 $originHeader = $request->getHeader( 'Origin' );
198 if ( $originHeader === false ) {
201 $originHeader = trim( $originHeader );
202 $origins = preg_split( '/\s+/', $originHeader );
204 $sessionCookies = array_intersect(
205 array_keys( $_COOKIE ),
206 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
208 if ( $origins && $sessionCookies && (
209 count( $origins ) !== 1 ||
!self
::matchOrigin(
211 $config->get( 'CrossSiteAJAXdomains' ),
212 $config->get( 'CrossSiteAJAXdomainExceptions' )
215 LoggerFactory
::getInstance( 'cors' )->warning(
216 'Non-whitelisted CORS request with session cookies', [
217 'origin' => $originHeader,
218 'cookies' => $sessionCookies,
219 'ip' => $request->getIP(),
220 'userAgent' => $this->getUserAgent(),
221 'wiki' => WikiMap
::getCurrentWikiDbDomain()->getId(),
226 // If we're in a mode that breaks the same-origin policy, strip
227 // user credentials for security.
228 if ( $this->lacksSameOriginSecurity() ) {
230 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
231 $wgUser = new User();
232 $this->getContext()->setUser( $wgUser );
233 $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
237 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
239 // Setup uselang. This doesn't use $this->getParameter()
240 // because we're not ready to handle errors yet.
241 $uselang = $request->getVal( 'uselang', self
::API_DEFAULT_USELANG
);
242 if ( $uselang === 'user' ) {
243 // Assume the parent context is going to return the user language
244 // for uselang=user (see T85635).
246 if ( $uselang === 'content' ) {
247 $uselang = MediaWikiServices
::getInstance()->getContentLanguage()->getCode();
249 $code = RequestContext
::sanitizeLangCode( $uselang );
250 $this->getContext()->setLanguage( $code );
251 if ( !$this->mInternalMode
) {
253 $wgLang = $this->getContext()->getLanguage();
254 RequestContext
::getMain()->setLanguage( $wgLang );
258 // Set up the error formatter. This doesn't use $this->getParameter()
259 // because we're not ready to handle errors yet.
260 $errorFormat = $request->getVal( 'errorformat', 'bc' );
261 $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
262 $errorsUseDB = $request->getCheck( 'errorsuselocal' );
263 if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
264 if ( $errorLangCode === 'uselang' ) {
265 $errorLang = $this->getLanguage();
266 } elseif ( $errorLangCode === 'content' ) {
267 $errorLang = MediaWikiServices
::getInstance()->getContentLanguage();
269 $errorLangCode = RequestContext
::sanitizeLangCode( $errorLangCode );
270 $errorLang = Language
::factory( $errorLangCode );
272 $this->mErrorFormatter
= new ApiErrorFormatter(
273 $this->mResult
, $errorLang, $errorFormat, $errorsUseDB
276 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
278 $this->mResult
->setErrorFormatter( $this->getErrorFormatter() );
280 $this->mModuleMgr
= new ApiModuleManager( $this );
281 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
282 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
283 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
284 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
286 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
288 $this->mContinuationManager
= null;
289 $this->mEnableWrite
= $enableWrite;
291 $this->mCdnMaxAge
= -1; // flag for executeActionWithErrorHandling()
292 $this->mCommit
= false;
296 * Return true if the API was started by other PHP code using FauxRequest
299 public function isInternalMode() {
300 return $this->mInternalMode
;
304 * Get the ApiResult object associated with current request
308 public function getResult() {
309 return $this->mResult
;
313 * Get the security flag for the current request
316 public function lacksSameOriginSecurity() {
317 if ( $this->lacksSameOriginSecurity
!== null ) {
318 return $this->lacksSameOriginSecurity
;
321 $request = $this->getRequest();
324 if ( $request->getCheck( 'callback' ) ) {
325 $this->lacksSameOriginSecurity
= true;
330 if ( $request->getVal( 'origin' ) === '*' ) {
331 $this->lacksSameOriginSecurity
= true;
335 // Header to be used from XMLHTTPRequest when the request might
336 // otherwise be used for XSS.
337 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
338 $this->lacksSameOriginSecurity
= true;
342 // Allow extensions to override.
343 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
344 return $this->lacksSameOriginSecurity
;
348 * Get the ApiErrorFormatter object associated with current request
349 * @return ApiErrorFormatter
351 public function getErrorFormatter() {
352 return $this->mErrorFormatter
;
356 * Get the continuation manager
357 * @return ApiContinuationManager|null
359 public function getContinuationManager() {
360 return $this->mContinuationManager
;
364 * Set the continuation manager
365 * @param ApiContinuationManager|null $manager
367 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
368 if ( $manager !== null && $this->mContinuationManager
!== null ) {
369 throw new UnexpectedValueException(
370 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
371 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
374 $this->mContinuationManager
= $manager;
378 * Get the API module object. Only works after executeAction()
382 public function getModule() {
383 return $this->mModule
;
387 * Get the result formatter object. Only works after setupExecuteAction()
389 * @return ApiFormatBase
391 public function getPrinter() {
392 return $this->mPrinter
;
396 * Set how long the response should be cached.
400 public function setCacheMaxAge( $maxage ) {
401 $this->setCacheControl( [
402 'max-age' => $maxage,
403 's-maxage' => $maxage
408 * Set the type of caching headers which will be sent.
410 * @param string $mode One of:
411 * - 'public': Cache this object in public caches, if the maxage or smaxage
412 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
413 * not provided by any of these means, the object will be private.
414 * - 'private': Cache this object only in private client-side caches.
415 * - 'anon-public-user-private': Make this object cacheable for logged-out
416 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
417 * set consistently for a given URL, it cannot be set differently depending on
418 * things like the contents of the database, or whether the user is logged in.
420 * If the wiki does not allow anonymous users to read it, the mode set here
421 * will be ignored, and private caching headers will always be sent. In other words,
422 * the "public" mode is equivalent to saying that the data sent is as public as a page
425 * For user-dependent data, the private mode should generally be used. The
426 * anon-public-user-private mode should only be used where there is a particularly
427 * good performance reason for caching the anonymous response, but where the
428 * response to logged-in users may differ, or may contain private data.
430 * If this function is never called, then the default will be the private mode.
432 public function setCacheMode( $mode ) {
433 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
434 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
436 // Ignore for forwards-compatibility
440 if ( !User
::isEveryoneAllowed( 'read' ) ) {
441 // Private wiki, only private headers
442 if ( $mode !== 'private' ) {
443 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
449 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
450 // User language is used for i18n, so we don't want to publicly
451 // cache. Anons are ok, because if they have non-default language
452 // then there's an appropriate Vary header set by whatever set
453 // their non-default language.
454 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
455 "'anon-public-user-private' due to uselang=user\n" );
456 $mode = 'anon-public-user-private';
459 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
460 $this->mCacheMode
= $mode;
464 * Set directives (key/value pairs) for the Cache-Control header.
465 * Boolean values will be formatted as such, by including or omitting
466 * without an equals sign.
468 * Cache control values set here will only be used if the cache mode is not
469 * private, see setCacheMode().
471 * @param array $directives
473 public function setCacheControl( $directives ) {
474 $this->mCacheControl
= $directives +
$this->mCacheControl
;
478 * Create an instance of an output formatter by its name
480 * @param string $format
482 * @return ApiFormatBase
484 public function createPrinterByName( $format ) {
485 $printer = $this->mModuleMgr
->getModule( $format, 'format', /* $ignoreCache */ true );
486 if ( $printer === null ) {
488 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
496 * Execute api request. Any errors will be handled if the API was called by the remote client.
498 public function execute() {
499 if ( $this->mInternalMode
) {
500 $this->executeAction();
502 $this->executeActionWithErrorHandling();
507 * Execute an action, and in case of an error, erase whatever partial results
508 * have been accumulated, and replace it with an error message and a help screen.
510 protected function executeActionWithErrorHandling() {
511 // Verify the CORS header before executing the action
512 if ( !$this->handleCORS() ) {
513 // handleCORS() has sent a 403, abort
517 // Exit here if the request method was OPTIONS
518 // (assume there will be a followup GET or POST)
519 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
523 // In case an error occurs during data output,
524 // clear the output buffer and print just the error information
525 $obLevel = ob_get_level();
528 $t = microtime( true );
531 $this->executeAction();
532 $runTime = microtime( true ) - $t;
533 $this->logRequest( $runTime );
534 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
535 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
537 } catch ( Exception
$e ) { // @todo Remove this block when HHVM is no longer supported
538 $this->handleException( $e );
539 $this->logRequest( microtime( true ) - $t, $e );
541 } catch ( Throwable
$e ) {
542 $this->handleException( $e );
543 $this->logRequest( microtime( true ) - $t, $e );
547 // Commit DBs and send any related cookies and headers
548 MediaWiki
::preOutputCommit( $this->getContext() );
550 // Send cache headers after any code which might generate an error, to
551 // avoid sending public cache headers for errors.
552 $this->sendCacheHeaders( $isError );
554 // Executing the action might have already messed with the output
556 while ( ob_get_level() > $obLevel ) {
562 * Handle an exception as an API response
565 * @param Exception|Throwable $e
567 protected function handleException( $e ) {
568 // T65145: Rollback any open database transactions
569 if ( !$e instanceof ApiUsageException
) {
570 // ApiUsageExceptions are intentional, so don't rollback if that's the case
571 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
574 // Allow extra cleanup and logging
575 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
577 // Handle any kind of exception by outputting properly formatted error message.
578 // If this fails, an unhandled exception should be thrown so that global error
579 // handler will process and log it.
581 $errCodes = $this->substituteResultWithError( $e );
583 // Error results should not be cached
584 $this->setCacheMode( 'private' );
586 $response = $this->getRequest()->response();
587 $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
588 $response->header( $headerStr );
590 // Reset and print just the error message
593 // Printer may not be initialized if the extractRequestParams() fails for the main module
594 $this->createErrorPrinter();
596 // Get desired HTTP code from an ApiUsageException. Don't use codes from other
597 // exception types, as they are unlikely to be intended as an HTTP code.
598 $httpCode = $e instanceof ApiUsageException ?
$e->getCode() : 0;
602 $this->printResult( $httpCode );
603 } catch ( ApiUsageException
$ex ) {
604 // The error printer itself is failing. Try suppressing its request
605 // parameters and redo.
607 $this->addWarning( 'apiwarn-errorprinterfailed' );
608 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
610 $this->mPrinter
->addWarning( $error );
611 } catch ( Exception
$ex2 ) { // @todo Remove this block when HHVM is no longer supported
613 $this->addWarning( $error );
614 } catch ( Throwable
$ex2 ) {
616 $this->addWarning( $error );
621 $this->mPrinter
= null;
622 $this->createErrorPrinter();
623 $this->mPrinter
->forceDefaultParams();
625 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
627 $this->printResult( $httpCode );
632 * Handle an exception from the ApiBeforeMain hook.
634 * This tries to print the exception as an API response, to be more
635 * friendly to clients. If it fails, it will rethrow the exception.
638 * @param Exception|Throwable $e
639 * @throws Exception|Throwable
641 public static function handleApiBeforeMainException( $e ) {
645 $main = new self( RequestContext
::getMain(), false );
646 $main->handleException( $e );
647 $main->logRequest( 0, $e );
648 } catch ( Exception
$e2 ) { // @todo Remove this block when HHVM is no longer supported
649 // Nope, even that didn't work. Punt.
651 } catch ( Throwable
$e2 ) {
652 // Nope, even that didn't work. Punt.
656 // Reset cache headers
657 $main->sendCacheHeaders( true );
663 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
665 * If no origin parameter is present, nothing happens.
666 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
667 * is set and false is returned.
668 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
669 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
671 * https://www.w3.org/TR/cors/#resource-requests
672 * https://www.w3.org/TR/cors/#resource-preflight-requests
674 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
676 protected function handleCORS() {
677 $originParam = $this->getParameter( 'origin' ); // defaults to null
678 if ( $originParam === null ) {
679 // No origin parameter, nothing to do
683 $request = $this->getRequest();
684 $response = $request->response();
686 $matchedOrigin = false;
687 $allowTiming = false;
690 if ( $originParam === '*' ) {
691 // Request for anonymous CORS
692 // Technically we should check for the presence of an Origin header
693 // and not process it as CORS if it's not set, but that would
694 // require us to vary on Origin for all 'origin=*' requests which
695 // we don't want to do.
696 $matchedOrigin = true;
698 $allowCredentials = 'false';
699 $varyOrigin = false; // No need to vary
701 // Non-anonymous CORS, check we allow the domain
703 // Origin: header is a space-separated list of origins, check all of them
704 $originHeader = $request->getHeader( 'Origin' );
705 if ( $originHeader === false ) {
708 $originHeader = trim( $originHeader );
709 $origins = preg_split( '/\s+/', $originHeader );
712 if ( !in_array( $originParam, $origins ) ) {
713 // origin parameter set but incorrect
714 // Send a 403 response
715 $response->statusHeader( 403 );
716 $response->header( 'Cache-Control: no-cache' );
717 echo "'origin' parameter does not match Origin header\n";
722 $config = $this->getConfig();
723 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
725 $config->get( 'CrossSiteAJAXdomains' ),
726 $config->get( 'CrossSiteAJAXdomainExceptions' )
729 $allowOrigin = $originHeader;
730 $allowCredentials = 'true';
731 $allowTiming = $originHeader;
734 if ( $matchedOrigin ) {
735 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
736 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
738 // This is a CORS preflight request
739 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
740 // If method is not a case-sensitive match, do not set any additional headers and terminate.
741 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
744 // We allow the actual request to send the following headers
745 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
746 if ( $requestedHeaders !== false ) {
747 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
748 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
751 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
754 // We only allow the actual request to be GET or POST
755 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
756 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
757 // Unsupported non-preflight method, don't handle it as CORS
759 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
764 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
765 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
766 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
767 if ( $allowTiming !== false ) {
768 $response->header( "Timing-Allow-Origin: $allowTiming" );
773 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
774 . 'MediaWiki-Login-Suppressed'
778 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
782 $this->getOutput()->addVaryHeader( 'Origin' );
789 * Attempt to match an Origin header against a set of rules and a set of exceptions
790 * @param string $value Origin header
791 * @param array $rules Set of wildcard rules
792 * @param array $exceptions Set of wildcard rules
793 * @return bool True if $value matches a rule in $rules and doesn't match
794 * any rules in $exceptions, false otherwise
796 protected static function matchOrigin( $value, $rules, $exceptions ) {
797 foreach ( $rules as $rule ) {
798 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
799 // Rule matches, check exceptions
800 foreach ( $exceptions as $exc ) {
801 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
814 * Attempt to validate the value of Access-Control-Request-Headers against a list
815 * of headers that we allow the follow up request to send.
817 * @param string $requestedHeaders Comma separated list of HTTP headers
818 * @return bool True if all requested headers are in the list of allowed headers
820 protected static function matchRequestedHeaders( $requestedHeaders ) {
821 if ( trim( $requestedHeaders ) === '' ) {
824 $requestedHeaders = explode( ',', $requestedHeaders );
825 $allowedAuthorHeaders = array_flip( [
826 /* simple headers (see spec) */
831 /* non-authorable headers in XHR, which are however requested by some UAs */
835 /* MediaWiki whitelist */
839 foreach ( $requestedHeaders as $rHeader ) {
840 $rHeader = strtolower( trim( $rHeader ) );
841 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
842 LoggerFactory
::getInstance( 'api-warning' )->warning(
843 'CORS preflight failed on requested header: {header}', [
854 * Helper function to convert wildcard string into a regex
858 * @param string $wildcard String with wildcards
859 * @return string Regular expression
861 protected static function wildcardToRegex( $wildcard ) {
862 $wildcard = preg_quote( $wildcard, '/' );
863 $wildcard = str_replace(
869 return "/^https?:\/\/$wildcard$/";
873 * Send caching headers
874 * @param bool $isError Whether an error response is being output
875 * @since 1.26 added $isError parameter
877 protected function sendCacheHeaders( $isError ) {
878 $response = $this->getRequest()->response();
879 $out = $this->getOutput();
881 $out->addVaryHeader( 'Treat-as-Untrusted' );
883 $config = $this->getConfig();
885 if ( $config->get( 'VaryOnXFP' ) ) {
886 $out->addVaryHeader( 'X-Forwarded-Proto' );
889 if ( !$isError && $this->mModule
&&
890 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
892 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
893 if ( $etag !== null ) {
894 $response->header( "ETag: $etag" );
896 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
897 if ( $lastMod !== null ) {
898 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
902 // The logic should be:
903 // $this->mCacheControl['max-age'] is set?
904 // Use it, the module knows better than our guess.
905 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
906 // Use 0 because we can guess caching is probably the wrong thing to do.
907 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
909 if ( isset( $this->mCacheControl
['max-age'] ) ) {
910 $maxage = $this->mCacheControl
['max-age'];
911 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
912 $this->mCacheMode
!== 'private'
914 $maxage = $this->getParameter( 'maxage' );
916 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
918 if ( $this->mCacheMode
== 'private' ) {
919 $response->header( "Cache-Control: $privateCache" );
923 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
924 $out->addVaryHeader( 'Cookie' );
925 $response->header( $out->getVaryHeader() );
926 if ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
927 // Logged in or otherwise has session (e.g. anonymous users who have edited)
928 // Mark request private
929 $response->header( "Cache-Control: $privateCache" );
932 } // else anonymous, send public headers below
935 // Send public headers
936 $response->header( $out->getVaryHeader() );
938 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
939 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
940 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
942 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
943 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
946 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
947 // Public cache not requested
948 // Sending a Vary header in this case is harmless, and protects us
949 // against conditional calls of setCacheMaxAge().
950 $response->header( "Cache-Control: $privateCache" );
955 $this->mCacheControl
['public'] = true;
957 // Send an Expires header
958 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
959 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
960 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
962 // Construct the Cache-Control header
965 foreach ( $this->mCacheControl
as $name => $value ) {
966 if ( is_bool( $value ) ) {
968 $ccHeader .= $separator . $name;
972 $ccHeader .= $separator . "$name=$value";
977 $response->header( "Cache-Control: $ccHeader" );
981 * Create the printer for error output
983 private function createErrorPrinter() {
984 if ( !isset( $this->mPrinter
) ) {
985 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
986 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
987 $value = self
::API_DEFAULT_FORMAT
;
989 $this->mPrinter
= $this->createPrinterByName( $value );
992 // Printer may not be able to handle errors. This is particularly
993 // likely if the module returns something for getCustomPrinter().
994 if ( !$this->mPrinter
->canPrintErrors() ) {
995 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1000 * Create an error message for the given exception.
1002 * If an ApiUsageException, errors/warnings will be extracted from the
1003 * embedded StatusValue.
1005 * Any other exception will be returned with a generic code and wrapper
1006 * text around the exception's (presumably English) message as a single
1007 * error (no warnings).
1009 * @param Exception|Throwable $e
1010 * @param string $type 'error' or 'warning'
1011 * @return ApiMessage[]
1014 protected function errorMessagesFromException( $e, $type = 'error' ) {
1016 if ( $e instanceof ApiUsageException
) {
1017 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1018 $messages[] = ApiMessage
::create( $error );
1020 } elseif ( $type !== 'error' ) {
1021 // None of the rest have any messages for non-error types
1023 // Something is seriously wrong
1024 $config = $this->getConfig();
1025 // TODO: Avoid embedding arbitrary class names in the error code.
1026 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1027 $code = 'internal_api_error_' . $class;
1028 $data = [ 'errorclass' => get_class( $e ) ];
1029 if ( $config->get( 'ShowExceptionDetails' ) ) {
1030 if ( $e instanceof ILocalizedException
) {
1031 $msg = $e->getMessageObject();
1032 } elseif ( $e instanceof MessageSpecifier
) {
1033 $msg = Message
::newFromSpecifier( $e );
1035 $msg = wfEscapeWikiText( $e->getMessage() );
1037 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1039 $params = [ 'apierror-exceptioncaughttype', WebRequest
::getRequestId(), get_class( $e ) ];
1042 $messages[] = ApiMessage
::create( $params, $code, $data );
1048 * Replace the result data with the information about an exception.
1049 * @param Exception|Throwable $e
1050 * @return string[] Error codes
1052 protected function substituteResultWithError( $e ) {
1053 $result = $this->getResult();
1054 $formatter = $this->getErrorFormatter();
1055 $config = $this->getConfig();
1058 // Remember existing warnings and errors across the reset
1059 $errors = $result->getResultData( [ 'errors' ] );
1060 $warnings = $result->getResultData( [ 'warnings' ] );
1062 if ( $warnings !== null ) {
1063 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1065 if ( $errors !== null ) {
1066 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1068 // Collect the copied error codes for the return value
1069 foreach ( $errors as $error ) {
1070 if ( isset( $error['code'] ) ) {
1071 $errorCodes[$error['code']] = true;
1076 // Add errors from the exception
1077 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1078 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1079 if ( ApiErrorFormatter
::isValidApiCode( $msg->getApiCode() ) ) {
1080 $errorCodes[$msg->getApiCode()] = true;
1082 LoggerFactory
::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1083 'code' => $msg->getApiCode(),
1086 $errorCodes['<invalid-code>'] = true;
1088 $formatter->addError( $modulePath, $msg );
1090 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1091 $formatter->addWarning( $modulePath, $msg );
1094 // Add additional data. Path depends on whether we're in BC mode or not.
1095 // Data depends on the type of exception.
1096 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1097 $path = [ 'error' ];
1101 if ( $e instanceof ApiUsageException
) {
1102 $link = wfExpandUrl( wfScript( 'api' ) );
1103 $result->addContentValue(
1107 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1109 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1112 } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1113 $result->addContentValue(
1116 $this->msg( 'api-exception-trace',
1120 MWExceptionHandler
::getRedactedTraceAsString( $e )
1121 )->inLanguage( $formatter->getLanguage() )->text()
1125 // Add the id and such
1126 $this->addRequestedFields( [ 'servedby' ] );
1128 return array_keys( $errorCodes );
1132 * Add requested fields to the result
1133 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1136 protected function addRequestedFields( $force = [] ) {
1137 $result = $this->getResult();
1139 $requestid = $this->getParameter( 'requestid' );
1140 if ( $requestid !== null ) {
1141 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1144 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1145 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1147 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1150 if ( $this->getParameter( 'curtimestamp' ) ) {
1151 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1152 ApiResult
::NO_SIZE_CHECK
);
1155 if ( $this->getParameter( 'responselanginfo' ) ) {
1156 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1157 ApiResult
::NO_SIZE_CHECK
);
1158 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1159 ApiResult
::NO_SIZE_CHECK
);
1164 * Set up for the execution.
1167 protected function setupExecuteAction() {
1168 $this->addRequestedFields();
1170 $params = $this->extractRequestParams();
1171 $this->mAction
= $params['action'];
1177 * Set up the module for response
1178 * @return ApiBase The module that will handle this action
1179 * @throws MWException
1180 * @throws ApiUsageException
1182 protected function setupModule() {
1183 // Instantiate the module requested by the user
1184 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1185 if ( $module === null ) {
1186 // Probably can't happen
1187 // @codeCoverageIgnoreStart
1188 $this->dieWithError(
1189 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1191 // @codeCoverageIgnoreEnd
1193 $moduleParams = $module->extractRequestParams();
1195 // Check token, if necessary
1196 if ( $module->needsToken() === true ) {
1197 throw new MWException(
1198 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1199 'See documentation for ApiBase::needsToken for details.'
1202 if ( $module->needsToken() ) {
1203 if ( !$module->mustBePosted() ) {
1204 throw new MWException(
1205 "Module '{$module->getModuleName()}' must require POST to use tokens."
1209 if ( !isset( $moduleParams['token'] ) ) {
1210 // Probably can't happen
1211 // @codeCoverageIgnoreStart
1212 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1213 // @codeCoverageIgnoreEnd
1216 $module->requirePostedParameters( [ 'token' ] );
1218 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1219 $module->dieWithError( 'apierror-badtoken' );
1229 private function getMaxLag() {
1230 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1232 'host' => $dbLag[0],
1237 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1238 if ( $jobQueueLagFactor ) {
1239 // Turn total number of jobs into seconds by using the configured value
1240 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1241 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1242 if ( $jobQueueLag > $lagInfo['lag'] ) {
1244 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1245 'lag' => $jobQueueLag,
1246 'type' => 'jobqueue',
1247 'jobs' => $totalJobs,
1252 Hooks
::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1258 * Check the max lag if necessary
1259 * @param ApiBase $module Api module being used
1260 * @param array $params Array an array containing the request parameters.
1261 * @return bool True on success, false should exit immediately
1263 protected function checkMaxLag( $module, $params ) {
1264 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1265 $maxLag = $params['maxlag'];
1266 $lagInfo = $this->getMaxLag();
1267 if ( $lagInfo['lag'] > $maxLag ) {
1268 $response = $this->getRequest()->response();
1270 $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1271 $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1273 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1274 $this->dieWithError(
1275 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1281 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1289 * Check selected RFC 7232 precondition headers
1291 * RFC 7232 envisions a particular model where you send your request to "a
1292 * resource", and for write requests that you can read "the resource" by
1293 * changing the method to GET. When the API receives a GET request, it
1294 * works out even though "the resource" from RFC 7232's perspective might
1295 * be many resources from MediaWiki's perspective. But it totally fails for
1296 * a POST, since what HTTP sees as "the resource" is probably just
1297 * "/api.php" with all the interesting bits in the body.
1299 * Therefore, we only support RFC 7232 precondition headers for GET (and
1300 * HEAD). That means we don't need to bother with If-Match and
1301 * If-Unmodified-Since since they only apply to modification requests.
1303 * And since we don't support Range, If-Range is ignored too.
1306 * @param ApiBase $module Api module being used
1307 * @return bool True on success, false should exit immediately
1309 protected function checkConditionalRequestHeaders( $module ) {
1310 if ( $this->mInternalMode
) {
1311 // No headers to check in internal mode
1315 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1316 // Don't check POSTs
1322 $ifNoneMatch = array_diff(
1323 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1326 if ( $ifNoneMatch ) {
1327 if ( $ifNoneMatch === [ '*' ] ) {
1328 // API responses always "exist"
1331 $etag = $module->getConditionalRequestData( 'etag' );
1334 if ( $ifNoneMatch && $etag !== null ) {
1335 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1336 $match = array_map( function ( $s ) {
1337 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1339 $return304 = in_array( $test, $match, true );
1341 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1343 // Some old browsers sends sizes after the date, like this:
1344 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1346 $i = strpos( $value, ';' );
1347 if ( $i !== false ) {
1348 $value = trim( substr( $value, 0, $i ) );
1351 if ( $value !== '' ) {
1353 $ts = new MWTimestamp( $value );
1355 // RFC 7231 IMF-fixdate
1356 $ts->getTimestamp( TS_RFC2822
) === $value ||
1358 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1359 // asctime (with and without space-padded day)
1360 $ts->format( 'D M j H:i:s Y' ) === $value ||
1361 $ts->format( 'D M j H:i:s Y' ) === $value
1363 $config = $this->getConfig();
1364 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1365 if ( $lastMod !== null ) {
1366 // Mix in some MediaWiki modification times
1369 'user' => $this->getUser()->getTouched(),
1370 'epoch' => $config->get( 'CacheEpoch' ),
1373 if ( $config->get( 'UseCdn' ) ) {
1374 // T46570: the core page itself may not change, but resources might
1375 $modifiedTimes['sepoch'] = wfTimestamp(
1376 TS_MW
, time() - $config->get( 'CdnMaxAge' )
1379 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1380 $lastMod = max( $modifiedTimes );
1381 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1384 } catch ( TimestampException
$e ) {
1385 // Invalid timestamp, ignore it
1391 $this->getRequest()->response()->statusHeader( 304 );
1393 // Avoid outputting the compressed representation of a zero-length body
1394 Wikimedia\
suppressWarnings();
1395 ini_set( 'zlib.output_compression', 0 );
1396 Wikimedia\restoreWarnings
();
1397 wfClearOutputBuffers();
1406 * Check for sufficient permissions to execute
1407 * @param ApiBase $module An Api module
1409 protected function checkExecutePermissions( $module ) {
1410 $user = $this->getUser();
1411 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1412 !$user->isAllowed( 'read' )
1414 $this->dieWithError( 'apierror-readapidenied' );
1417 if ( $module->isWriteMode() ) {
1418 if ( !$this->mEnableWrite
) {
1419 $this->dieWithError( 'apierror-noapiwrite' );
1420 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1421 $this->dieWithError( 'apierror-writeapidenied' );
1422 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1423 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1426 $this->checkReadOnly( $module );
1429 // Allow extensions to stop execution for arbitrary reasons.
1430 $message = 'hookaborted';
1431 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1432 $this->dieWithError( $message );
1437 * Check if the DB is read-only for this user
1438 * @param ApiBase $module An Api module
1440 protected function checkReadOnly( $module ) {
1441 if ( wfReadOnly() ) {
1442 $this->dieReadOnly();
1445 if ( $module->isWriteMode()
1446 && $this->getUser()->isBot()
1447 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1449 $this->checkBotReadOnly();
1454 * Check whether we are readonly for bots
1456 private function checkBotReadOnly() {
1457 // Figure out how many servers have passed the lag threshold
1459 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1460 $laggedServers = [];
1461 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1462 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1463 if ( $lag > $lagLimit ) {
1465 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1469 // If a majority of replica DBs are too lagged then disallow writes
1470 $replicaCount = $loadBalancer->getServerCount() - 1;
1471 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1472 $laggedServers = implode( ', ', $laggedServers );
1474 'api-readonly', // Deprecate this channel in favor of api-warning?
1475 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1477 LoggerFactory
::getInstance( 'api-warning' )->warning(
1478 "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1479 'laggeddbs' => $laggedServers,
1483 $this->dieWithError(
1486 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1492 * Check asserts of the user's rights
1493 * @param array $params
1495 protected function checkAsserts( $params ) {
1496 if ( isset( $params['assert'] ) ) {
1497 $user = $this->getUser();
1498 switch ( $params['assert'] ) {
1500 if ( $user->isAnon() ) {
1501 $this->dieWithError( 'apierror-assertuserfailed' );
1505 if ( !$user->isAllowed( 'bot' ) ) {
1506 $this->dieWithError( 'apierror-assertbotfailed' );
1511 if ( isset( $params['assertuser'] ) ) {
1512 $assertUser = User
::newFromName( $params['assertuser'], false );
1513 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1514 $this->dieWithError(
1515 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1522 * Check POST for external response and setup result printer
1523 * @param ApiBase $module An Api module
1524 * @param array $params An array with the request parameters
1526 protected function setupExternalResponse( $module, $params ) {
1527 $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1528 $request = $this->getRequest();
1530 if ( !in_array( $request->getMethod(), $validMethods ) ) {
1531 $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1534 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1535 // Module requires POST. GET request might still be allowed
1536 // if $wgDebugApi is true, otherwise fail.
1537 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1540 // See if custom printer is used
1541 $this->mPrinter
= $module->getCustomPrinter();
1542 if ( is_null( $this->mPrinter
) ) {
1543 // Create an appropriate printer
1544 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1547 if ( $request->getProtocol() === 'http' && (
1548 $request->getSession()->shouldForceHTTPS() ||
1549 ( $this->getUser()->isLoggedIn() &&
1550 $this->getUser()->requiresHTTPS() )
1552 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1557 * Execute the actual module, without any error handling
1559 protected function executeAction() {
1560 $params = $this->setupExecuteAction();
1562 // Check asserts early so e.g. errors in parsing a module's parameters due to being
1563 // logged out don't override the client's intended "am I logged in?" check.
1564 $this->checkAsserts( $params );
1566 $module = $this->setupModule();
1567 $this->mModule
= $module;
1569 if ( !$this->mInternalMode
) {
1570 $this->setRequestExpectations( $module );
1573 $this->checkExecutePermissions( $module );
1575 if ( !$this->checkMaxLag( $module, $params ) ) {
1579 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1583 if ( !$this->mInternalMode
) {
1584 $this->setupExternalResponse( $module, $params );
1588 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1590 $this->reportUnusedParams();
1592 if ( !$this->mInternalMode
) {
1593 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1595 $this->printResult();
1600 * Set database connection, query, and write expectations given this module request
1601 * @param ApiBase $module
1603 protected function setRequestExpectations( ApiBase
$module ) {
1604 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1605 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1606 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1607 if ( $this->getRequest()->hasSafeMethod() ) {
1608 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1609 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1610 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1611 $this->getRequest()->markAsSafeRequest();
1613 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1618 * Log the preceding request
1619 * @param float $time Time in seconds
1620 * @param Exception|Throwable|null $e Exception caught while processing the request
1622 protected function logRequest( $time, $e = null ) {
1623 $request = $this->getRequest();
1626 // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1627 '$schema' => '/mediawiki/api/request/0.0.1',
1629 'request_id' => WebRequest
::getRequestId(),
1630 'id' => UIDGenerator
::newUUIDv4(),
1631 'dt' => wfTimestamp( TS_ISO_8601
),
1632 'domain' => $this->getConfig()->get( 'ServerName' ),
1633 // If using the EventBus extension (as intended) with this log channel,
1634 // this stream name will map to a Kafka topic.
1635 'stream' => 'mediawiki.api-request'
1638 'method' => $request->getMethod(),
1639 'client_ip' => $request->getIP()
1641 'database' => WikiMap
::getCurrentWikiDbDomain()->getId(),
1642 'backend_time_ms' => (int)round( $time * 1000 ),
1645 // If set, these headers will be logged in http.request_headers.
1646 $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1647 foreach ( $httpRequestHeadersToLog as $header ) {
1648 if ( $request->getHeader( $header ) ) {
1649 // Set the header in http.request_headers
1650 $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1655 $logCtx['api_error_codes'] = [];
1656 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1657 $logCtx['api_error_codes'][] = $msg->getApiCode();
1661 // Construct space separated message for 'api' log channel
1662 $msg = "API {$request->getMethod()} " .
1663 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1664 " {$logCtx['http']['client_ip']} " .
1665 "T={$logCtx['backend_time_ms']}ms";
1667 $sensitive = array_flip( $this->getSensitiveParams() );
1668 foreach ( $this->getParamsUsed() as $name ) {
1669 $value = $request->getVal( $name );
1670 if ( $value === null ) {
1674 if ( isset( $sensitive[$name] ) ) {
1675 $value = '[redacted]';
1676 $encValue = '[redacted]';
1677 } elseif ( strlen( $value ) > 256 ) {
1678 $value = substr( $value, 0, 256 );
1679 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1681 $encValue = $this->encodeRequestLogValue( $value );
1684 $logCtx['params'][$name] = $value;
1685 $msg .= " {$name}={$encValue}";
1688 // Log an unstructured message to the api channel.
1689 wfDebugLog( 'api', $msg, 'private' );
1691 // The api-request channel a structured data log channel.
1692 wfDebugLog( 'api-request', '', 'private', $logCtx );
1696 * Encode a value in a format suitable for a space-separated log line.
1700 protected function encodeRequestLogValue( $s ) {
1703 $chars = ';@$!*(),/:';
1704 $numChars = strlen( $chars );
1705 for ( $i = 0; $i < $numChars; $i++
) {
1706 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1710 return strtr( rawurlencode( $s ), $table );
1714 * Get the request parameters used in the course of the preceding execute() request
1717 protected function getParamsUsed() {
1718 return array_keys( $this->mParamsUsed
);
1722 * Mark parameters as used
1723 * @param string|string[] $params
1725 public function markParamsUsed( $params ) {
1726 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1730 * Get the request parameters that should be considered sensitive
1734 protected function getSensitiveParams() {
1735 return array_keys( $this->mParamsSensitive
);
1739 * Mark parameters as sensitive
1741 * @param string|string[] $params
1743 public function markParamsSensitive( $params ) {
1744 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1748 * Get a request value, and register the fact that it was used, for logging.
1749 * @param string $name
1750 * @param string|null $default
1751 * @return string|null
1753 public function getVal( $name, $default = null ) {
1754 $this->mParamsUsed
[$name] = true;
1756 $ret = $this->getRequest()->getVal( $name );
1757 if ( $ret === null ) {
1758 if ( $this->getRequest()->getArray( $name ) !== null ) {
1759 // See T12262 for why we don't just implode( '|', ... ) the
1761 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1769 * Get a boolean request value, and register the fact that the parameter
1770 * was used, for logging.
1771 * @param string $name
1774 public function getCheck( $name ) {
1775 return $this->getVal( $name, null ) !== null;
1779 * Get a request upload, and register the fact that it was used, for logging.
1782 * @param string $name Parameter name
1783 * @return WebRequestUpload
1785 public function getUpload( $name ) {
1786 $this->mParamsUsed
[$name] = true;
1788 return $this->getRequest()->getUpload( $name );
1792 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1793 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1795 protected function reportUnusedParams() {
1796 $paramsUsed = $this->getParamsUsed();
1797 $allParams = $this->getRequest()->getValueNames();
1799 if ( !$this->mInternalMode
) {
1800 // Printer has not yet executed; don't warn that its parameters are unused
1801 $printerParams = $this->mPrinter
->encodeParamName(
1802 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1804 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1806 $unusedParams = array_diff( $allParams, $paramsUsed );
1809 if ( count( $unusedParams ) ) {
1810 $this->addWarning( [
1811 'apierror-unrecognizedparams',
1812 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1813 count( $unusedParams )
1819 * Print results using the current printer
1821 * @param int $httpCode HTTP status code, or 0 to not change
1823 protected function printResult( $httpCode = 0 ) {
1824 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1825 $this->addWarning( 'apiwarn-wgdebugapi' );
1828 $printer = $this->mPrinter
;
1829 $printer->initPrinter( false );
1831 $printer->setHttpStatus( $httpCode );
1833 $printer->execute();
1834 $printer->closePrinter();
1840 public function isReadMode() {
1845 * See ApiBase for description.
1849 public function getAllowedParams() {
1852 ApiBase
::PARAM_DFLT
=> 'help',
1853 ApiBase
::PARAM_TYPE
=> 'submodule',
1856 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1857 ApiBase
::PARAM_TYPE
=> 'submodule',
1860 ApiBase
::PARAM_TYPE
=> 'integer'
1863 ApiBase
::PARAM_TYPE
=> 'integer',
1864 ApiBase
::PARAM_DFLT
=> 0
1867 ApiBase
::PARAM_TYPE
=> 'integer',
1868 ApiBase
::PARAM_DFLT
=> 0
1871 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1874 ApiBase
::PARAM_TYPE
=> 'user',
1876 'requestid' => null,
1877 'servedby' => false,
1878 'curtimestamp' => false,
1879 'responselanginfo' => false,
1882 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1885 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1886 ApiBase
::PARAM_DFLT
=> 'bc',
1889 ApiBase
::PARAM_DFLT
=> 'uselang',
1891 'errorsuselocal' => [
1892 ApiBase
::PARAM_DFLT
=> false,
1898 protected function getExamplesMessages() {
1901 => 'apihelp-help-example-main',
1902 'action=help&recursivesubmodules=1'
1903 => 'apihelp-help-example-recursive',
1907 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1908 // Wish PHP had an "array_insert_before". Instead, we have to manually
1909 // reindex the array to get 'permissions' in the right place.
1912 foreach ( $oldHelp as $k => $v ) {
1913 if ( $k === 'submodules' ) {
1914 $help['permissions'] = '';
1918 $help['datatypes'] = '';
1919 $help['templatedparams'] = '';
1920 $help['credits'] = '';
1922 // Fill 'permissions'
1923 $help['permissions'] .= Html
::openElement( 'div',
1924 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1925 $m = $this->msg( 'api-help-permissions' );
1926 if ( !$m->isDisabled() ) {
1927 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1928 $m->numParams( count( self
::$mRights ) )->parse()
1931 $help['permissions'] .= Html
::openElement( 'dl' );
1932 foreach ( self
::$mRights as $right => $rightMsg ) {
1933 $help['permissions'] .= Html
::element( 'dt', null, $right );
1935 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1936 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1938 $groups = array_map( function ( $group ) {
1939 return $group == '*' ?
'all' : $group;
1940 }, User
::getGroupsWithPermission( $right ) );
1942 $help['permissions'] .= Html
::rawElement( 'dd', null,
1943 $this->msg( 'api-help-permissions-granted-to' )
1944 ->numParams( count( $groups ) )
1945 ->params( Message
::listParam( $groups ) )
1949 $help['permissions'] .= Html
::closeElement( 'dl' );
1950 $help['permissions'] .= Html
::closeElement( 'div' );
1952 // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1953 if ( empty( $options['nolead'] ) ) {
1954 $level = $options['headerlevel'];
1955 $tocnumber = &$options['tocnumber'];
1957 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1959 $id = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_PRIMARY
);
1960 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_FALLBACK
);
1961 $headline = Linker
::makeHeadline( min( 6, $level ),
1962 ' class="apihelp-header">',
1968 // Ensure we have a sane anchor
1969 if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1970 $headline = '<div id="main/datatypes"></div>' . $headline;
1972 $help['datatypes'] .= $headline;
1973 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1974 if ( !isset( $tocData['main/datatypes'] ) ) {
1975 $tocnumber[$level]++
;
1976 $tocData['main/datatypes'] = [
1977 'toclevel' => count( $tocnumber ),
1979 'anchor' => 'main/datatypes',
1981 'number' => implode( '.', $tocnumber ),
1986 $header = $this->msg( 'api-help-templatedparams-header' )->parse();
1988 $id = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_PRIMARY
);
1989 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_FALLBACK
);
1990 $headline = Linker
::makeHeadline( min( 6, $level ),
1991 ' class="apihelp-header">',
1997 // Ensure we have a sane anchor
1998 if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
1999 $headline = '<div id="main/templatedparams"></div>' . $headline;
2001 $help['templatedparams'] .= $headline;
2002 $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2003 if ( !isset( $tocData['main/templatedparams'] ) ) {
2004 $tocnumber[$level]++
;
2005 $tocData['main/templatedparams'] = [
2006 'toclevel' => count( $tocnumber ),
2008 'anchor' => 'main/templatedparams',
2010 'number' => implode( '.', $tocnumber ),
2015 $header = $this->msg( 'api-credits-header' )->parse();
2016 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
2017 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_FALLBACK
);
2018 $headline = Linker
::makeHeadline( min( 6, $level ),
2019 ' class="apihelp-header">',
2025 // Ensure we have a sane anchor
2026 if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2027 $headline = '<div id="main/credits"></div>' . $headline;
2029 $help['credits'] .= $headline;
2030 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2031 if ( !isset( $tocData['main/credits'] ) ) {
2032 $tocnumber[$level]++
;
2033 $tocData['main/credits'] = [
2034 'toclevel' => count( $tocnumber ),
2036 'anchor' => 'main/credits',
2038 'number' => implode( '.', $tocnumber ),
2045 private $mCanApiHighLimits = null;
2048 * Check whether the current user is allowed to use high limits
2051 public function canApiHighLimits() {
2052 if ( !isset( $this->mCanApiHighLimits
) ) {
2053 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
2056 return $this->mCanApiHighLimits
;
2060 * Overrides to return this instance's module manager.
2061 * @return ApiModuleManager
2063 public function getModuleManager() {
2064 return $this->mModuleMgr
;
2068 * Fetches the user agent used for this request
2070 * The value will be the combination of the 'Api-User-Agent' header (if
2071 * any) and the standard User-Agent header (if any).
2075 public function getUserAgent() {
2077 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2078 $this->getRequest()->getHeader( 'User-agent' )
2084 * For really cool vim folding this needs to be at the end:
2085 * vim: foldmarker=@{,@} foldmethod=marker