3 * Created on Sep 4, 2006
5 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
26 use MediaWiki\Logger\LoggerFactory
;
27 use MediaWiki\MediaWikiServices
;
28 use Wikimedia\Timestamp\TimestampException
;
29 use Wikimedia\Rdbms\DBQueryError
;
30 use Wikimedia\Rdbms\DBError
;
33 * This is the main API class, used for both external and internal processing.
34 * When executed, it will create the requested formatter object,
35 * instantiate and execute an object associated with the needed action,
36 * and use formatter to print results.
37 * In case of an exception, an error message will be printed using the same formatter.
39 * To use API from another application, run it using FauxRequest object, in which
40 * case any internal exceptions will not be handled but passed up to the caller.
41 * After successful execution, use getResult() for the resulting data.
45 class ApiMain
extends ApiBase
{
47 * When no format parameter is given, this format will be used
49 const API_DEFAULT_FORMAT
= 'jsonfm';
52 * When no uselang parameter is given, this language will be used
54 const API_DEFAULT_USELANG
= 'user';
57 * List of available modules: action name => module class
59 private static $Modules = [
60 'login' => 'ApiLogin',
61 'clientlogin' => 'ApiClientLogin',
62 'logout' => 'ApiLogout',
63 'createaccount' => 'ApiAMCreateAccount',
64 'linkaccount' => 'ApiLinkAccount',
65 'unlinkaccount' => 'ApiRemoveAuthenticationData',
66 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
67 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
68 'resetpassword' => 'ApiResetPassword',
69 'query' => 'ApiQuery',
70 'expandtemplates' => 'ApiExpandTemplates',
71 'parse' => 'ApiParse',
72 'stashedit' => 'ApiStashEdit',
73 'opensearch' => 'ApiOpenSearch',
74 'feedcontributions' => 'ApiFeedContributions',
75 'feedrecentchanges' => 'ApiFeedRecentChanges',
76 'feedwatchlist' => 'ApiFeedWatchlist',
78 'paraminfo' => 'ApiParamInfo',
80 'compare' => 'ApiComparePages',
81 'tokens' => 'ApiTokens',
82 'checktoken' => 'ApiCheckToken',
83 'cspreport' => 'ApiCSPReport',
84 'validatepassword' => 'ApiValidatePassword',
87 'purge' => 'ApiPurge',
88 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
89 'rollback' => 'ApiRollback',
90 'delete' => 'ApiDelete',
91 'undelete' => 'ApiUndelete',
92 'protect' => 'ApiProtect',
93 'block' => 'ApiBlock',
94 'unblock' => 'ApiUnblock',
96 'edit' => 'ApiEditPage',
97 'upload' => 'ApiUpload',
98 'filerevert' => 'ApiFileRevert',
99 'emailuser' => 'ApiEmailUser',
100 'watch' => 'ApiWatch',
101 'patrol' => 'ApiPatrol',
102 'import' => 'ApiImport',
103 'clearhasmsg' => 'ApiClearHasMsg',
104 'userrights' => 'ApiUserrights',
105 'options' => 'ApiOptions',
106 'imagerotate' => 'ApiImageRotate',
107 'revisiondelete' => 'ApiRevisionDelete',
108 'managetags' => 'ApiManageTags',
110 'mergehistory' => 'ApiMergeHistory',
111 'setpagelanguage' => 'ApiSetPageLanguage',
115 * List of available formats: format name => format class
117 private static $Formats = [
118 'json' => 'ApiFormatJson',
119 'jsonfm' => 'ApiFormatJson',
120 'php' => 'ApiFormatPhp',
121 'phpfm' => 'ApiFormatPhp',
122 'xml' => 'ApiFormatXml',
123 'xmlfm' => 'ApiFormatXml',
124 'rawfm' => 'ApiFormatJson',
125 'none' => 'ApiFormatNone',
129 * List of user roles that are specifically relevant to the API.
130 * [ 'right' => [ 'msg' => 'Some message with a $1',
131 * 'params' => [ $someVarToSubst ] ],
134 private static $mRights = [
136 'msg' => 'right-writeapi',
140 'msg' => 'api-help-right-apihighlimits',
141 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
150 private $mModuleMgr, $mResult, $mErrorFormatter = null;
151 /** @var ApiContinuationManager|null */
152 private $mContinuationManager;
154 private $mEnableWrite;
155 private $mInternalMode, $mSquidMaxage;
159 private $mCacheMode = 'private';
160 private $mCacheControl = [];
161 private $mParamsUsed = [];
162 private $mParamsSensitive = [];
164 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
165 private $lacksSameOriginSecurity = null;
168 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
170 * @param IContextSource|WebRequest $context If this is an instance of
171 * FauxRequest, errors are thrown and no printing occurs
172 * @param bool $enableWrite Should be set to true if the api may modify data
174 public function __construct( $context = null, $enableWrite = false ) {
175 if ( $context === null ) {
176 $context = RequestContext
::getMain();
177 } elseif ( $context instanceof WebRequest
) {
180 $context = RequestContext
::getMain();
182 // We set a derivative context so we can change stuff later
183 $this->setContext( new DerivativeContext( $context ) );
185 if ( isset( $request ) ) {
186 $this->getContext()->setRequest( $request );
188 $request = $this->getRequest();
191 $this->mInternalMode
= ( $request instanceof FauxRequest
);
193 // Special handling for the main module: $parent === $this
194 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
196 $config = $this->getConfig();
198 if ( !$this->mInternalMode
) {
199 // Log if a request with a non-whitelisted Origin header is seen
200 // with session cookies.
201 $originHeader = $request->getHeader( 'Origin' );
202 if ( $originHeader === false ) {
205 $originHeader = trim( $originHeader );
206 $origins = preg_split( '/\s+/', $originHeader );
208 $sessionCookies = array_intersect(
209 array_keys( $_COOKIE ),
210 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
212 if ( $origins && $sessionCookies && (
213 count( $origins ) !== 1 ||
!self
::matchOrigin(
215 $config->get( 'CrossSiteAJAXdomains' ),
216 $config->get( 'CrossSiteAJAXdomainExceptions' )
219 LoggerFactory
::getInstance( 'cors' )->warning(
220 'Non-whitelisted CORS request with session cookies', [
221 'origin' => $originHeader,
222 'cookies' => $sessionCookies,
223 'ip' => $request->getIP(),
224 'userAgent' => $this->getUserAgent(),
225 'wiki' => wfWikiID(),
230 // If we're in a mode that breaks the same-origin policy, strip
231 // user credentials for security.
232 if ( $this->lacksSameOriginSecurity() ) {
234 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
235 $wgUser = new User();
236 $this->getContext()->setUser( $wgUser );
237 $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
241 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
243 // Setup uselang. This doesn't use $this->getParameter()
244 // because we're not ready to handle errors yet.
245 $uselang = $request->getVal( 'uselang', self
::API_DEFAULT_USELANG
);
246 if ( $uselang === 'user' ) {
247 // Assume the parent context is going to return the user language
248 // for uselang=user (see T85635).
250 if ( $uselang === 'content' ) {
252 $uselang = $wgContLang->getCode();
254 $code = RequestContext
::sanitizeLangCode( $uselang );
255 $this->getContext()->setLanguage( $code );
256 if ( !$this->mInternalMode
) {
258 $wgLang = $this->getContext()->getLanguage();
259 RequestContext
::getMain()->setLanguage( $wgLang );
263 // Set up the error formatter. This doesn't use $this->getParameter()
264 // because we're not ready to handle errors yet.
265 $errorFormat = $request->getVal( 'errorformat', 'bc' );
266 $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
267 $errorsUseDB = $request->getCheck( 'errorsuselocal' );
268 if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
269 if ( $errorLangCode === 'uselang' ) {
270 $errorLang = $this->getLanguage();
271 } elseif ( $errorLangCode === 'content' ) {
273 $errorLang = $wgContLang;
275 $errorLangCode = RequestContext
::sanitizeLangCode( $errorLangCode );
276 $errorLang = Language
::factory( $errorLangCode );
278 $this->mErrorFormatter
= new ApiErrorFormatter(
279 $this->mResult
, $errorLang, $errorFormat, $errorsUseDB
282 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
284 $this->mResult
->setErrorFormatter( $this->getErrorFormatter() );
286 $this->mModuleMgr
= new ApiModuleManager( $this );
287 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
288 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
289 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
290 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
292 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
294 $this->mContinuationManager
= null;
295 $this->mEnableWrite
= $enableWrite;
297 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
298 $this->mCommit
= false;
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->getVal( 'callback' ) !== null ) {
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( $manager ) {
374 if ( $manager !== null ) {
375 if ( !$manager instanceof ApiContinuationManager
) {
376 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
377 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
380 if ( $this->mContinuationManager
!== null ) {
381 throw new UnexpectedValueException(
382 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
383 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
387 $this->mContinuationManager
= $manager;
391 * Get the API module object. Only works after executeAction()
395 public function getModule() {
396 return $this->mModule
;
400 * Get the result formatter object. Only works after setupExecuteAction()
402 * @return ApiFormatBase
404 public function getPrinter() {
405 return $this->mPrinter
;
409 * Set how long the response should be cached.
413 public function setCacheMaxAge( $maxage ) {
414 $this->setCacheControl( [
415 'max-age' => $maxage,
416 's-maxage' => $maxage
421 * Set the type of caching headers which will be sent.
423 * @param string $mode One of:
424 * - 'public': Cache this object in public caches, if the maxage or smaxage
425 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
426 * not provided by any of these means, the object will be private.
427 * - 'private': Cache this object only in private client-side caches.
428 * - 'anon-public-user-private': Make this object cacheable for logged-out
429 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
430 * set consistently for a given URL, it cannot be set differently depending on
431 * things like the contents of the database, or whether the user is logged in.
433 * If the wiki does not allow anonymous users to read it, the mode set here
434 * will be ignored, and private caching headers will always be sent. In other words,
435 * the "public" mode is equivalent to saying that the data sent is as public as a page
438 * For user-dependent data, the private mode should generally be used. The
439 * anon-public-user-private mode should only be used where there is a particularly
440 * good performance reason for caching the anonymous response, but where the
441 * response to logged-in users may differ, or may contain private data.
443 * If this function is never called, then the default will be the private mode.
445 public function setCacheMode( $mode ) {
446 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
447 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
449 // Ignore for forwards-compatibility
453 if ( !User
::isEveryoneAllowed( 'read' ) ) {
454 // Private wiki, only private headers
455 if ( $mode !== 'private' ) {
456 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
462 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
463 // User language is used for i18n, so we don't want to publicly
464 // cache. Anons are ok, because if they have non-default language
465 // then there's an appropriate Vary header set by whatever set
466 // their non-default language.
467 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
468 "'anon-public-user-private' due to uselang=user\n" );
469 $mode = 'anon-public-user-private';
472 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
473 $this->mCacheMode
= $mode;
477 * Set directives (key/value pairs) for the Cache-Control header.
478 * Boolean values will be formatted as such, by including or omitting
479 * without an equals sign.
481 * Cache control values set here will only be used if the cache mode is not
482 * private, see setCacheMode().
484 * @param array $directives
486 public function setCacheControl( $directives ) {
487 $this->mCacheControl
= $directives +
$this->mCacheControl
;
491 * Create an instance of an output formatter by its name
493 * @param string $format
495 * @return ApiFormatBase
497 public function createPrinterByName( $format ) {
498 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
499 if ( $printer === null ) {
501 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
509 * Execute api request. Any errors will be handled if the API was called by the remote client.
511 public function execute() {
512 if ( $this->mInternalMode
) {
513 $this->executeAction();
515 $this->executeActionWithErrorHandling();
520 * Execute an action, and in case of an error, erase whatever partial results
521 * have been accumulated, and replace it with an error message and a help screen.
523 protected function executeActionWithErrorHandling() {
524 // Verify the CORS header before executing the action
525 if ( !$this->handleCORS() ) {
526 // handleCORS() has sent a 403, abort
530 // Exit here if the request method was OPTIONS
531 // (assume there will be a followup GET or POST)
532 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
536 // In case an error occurs during data output,
537 // clear the output buffer and print just the error information
538 $obLevel = ob_get_level();
541 $t = microtime( true );
544 $this->executeAction();
545 $runTime = microtime( true ) - $t;
546 $this->logRequest( $runTime );
547 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
548 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
549 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
552 } catch ( Exception
$e ) {
553 $this->handleException( $e );
554 $this->logRequest( microtime( true ) - $t, $e );
558 // Commit DBs and send any related cookies and headers
559 MediaWiki
::preOutputCommit( $this->getContext() );
561 // Send cache headers after any code which might generate an error, to
562 // avoid sending public cache headers for errors.
563 $this->sendCacheHeaders( $isError );
565 // Executing the action might have already messed with the output
567 while ( ob_get_level() > $obLevel ) {
573 * Handle an exception as an API response
576 * @param Exception $e
578 protected function handleException( Exception
$e ) {
579 // T65145: Rollback any open database transactions
580 if ( !( $e instanceof ApiUsageException ||
$e instanceof UsageException
) ) {
581 // UsageExceptions are intentional, so don't rollback if that's the case
582 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
585 // Allow extra cleanup and logging
586 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
588 // Handle any kind of exception by outputting properly formatted error message.
589 // If this fails, an unhandled exception should be thrown so that global error
590 // handler will process and log it.
592 $errCodes = $this->substituteResultWithError( $e );
594 // Error results should not be cached
595 $this->setCacheMode( 'private' );
597 $response = $this->getRequest()->response();
598 $headerStr = 'MediaWiki-API-Error: ' . join( ', ', $errCodes );
599 $response->header( $headerStr );
601 // Reset and print just the error message
604 // Printer may not be initialized if the extractRequestParams() fails for the main module
605 $this->createErrorPrinter();
609 $this->printResult( $e->getCode() );
610 } catch ( ApiUsageException
$ex ) {
611 // The error printer itself is failing. Try suppressing its request
612 // parameters and redo.
614 $this->addWarning( 'apiwarn-errorprinterfailed' );
615 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
617 $this->mPrinter
->addWarning( $error );
618 } catch ( Exception
$ex2 ) {
620 $this->addWarning( $error );
623 } catch ( UsageException
$ex ) {
624 // The error printer itself is failing. Try suppressing its request
625 // parameters and redo.
628 [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
632 $this->mPrinter
= null;
633 $this->createErrorPrinter();
634 $this->mPrinter
->forceDefaultParams();
635 if ( $e->getCode() ) {
636 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
638 $this->printResult( $e->getCode() );
643 * Handle an exception from the ApiBeforeMain hook.
645 * This tries to print the exception as an API response, to be more
646 * friendly to clients. If it fails, it will rethrow the exception.
649 * @param Exception $e
652 public static function handleApiBeforeMainException( Exception
$e ) {
656 $main = new self( RequestContext
::getMain(), false );
657 $main->handleException( $e );
658 $main->logRequest( 0, $e );
659 } catch ( Exception
$e2 ) {
660 // Nope, even that didn't work. Punt.
664 // Reset cache headers
665 $main->sendCacheHeaders( true );
671 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
673 * If no origin parameter is present, nothing happens.
674 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
675 * is set and false is returned.
676 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
677 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
679 * https://www.w3.org/TR/cors/#resource-requests
680 * https://www.w3.org/TR/cors/#resource-preflight-requests
682 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
684 protected function handleCORS() {
685 $originParam = $this->getParameter( 'origin' ); // defaults to null
686 if ( $originParam === null ) {
687 // No origin parameter, nothing to do
691 $request = $this->getRequest();
692 $response = $request->response();
694 $matchedOrigin = false;
695 $allowTiming = false;
698 if ( $originParam === '*' ) {
699 // Request for anonymous CORS
700 // Technically we should check for the presence of an Origin header
701 // and not process it as CORS if it's not set, but that would
702 // require us to vary on Origin for all 'origin=*' requests which
703 // we don't want to do.
704 $matchedOrigin = true;
706 $allowCredentials = 'false';
707 $varyOrigin = false; // No need to vary
709 // Non-anonymous CORS, check we allow the domain
711 // Origin: header is a space-separated list of origins, check all of them
712 $originHeader = $request->getHeader( 'Origin' );
713 if ( $originHeader === false ) {
716 $originHeader = trim( $originHeader );
717 $origins = preg_split( '/\s+/', $originHeader );
720 if ( !in_array( $originParam, $origins ) ) {
721 // origin parameter set but incorrect
722 // Send a 403 response
723 $response->statusHeader( 403 );
724 $response->header( 'Cache-Control: no-cache' );
725 echo "'origin' parameter does not match Origin header\n";
730 $config = $this->getConfig();
731 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
733 $config->get( 'CrossSiteAJAXdomains' ),
734 $config->get( 'CrossSiteAJAXdomainExceptions' )
737 $allowOrigin = $originHeader;
738 $allowCredentials = 'true';
739 $allowTiming = $originHeader;
742 if ( $matchedOrigin ) {
743 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
744 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
746 // This is a CORS preflight request
747 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
748 // If method is not a case-sensitive match, do not set any additional headers and terminate.
749 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
752 // We allow the actual request to send the following headers
753 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
754 if ( $requestedHeaders !== false ) {
755 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
756 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
759 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
762 // We only allow the actual request to be GET or POST
763 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
764 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
765 // Unsupported non-preflight method, don't handle it as CORS
767 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
772 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
773 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
774 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
775 if ( $allowTiming !== false ) {
776 $response->header( "Timing-Allow-Origin: $allowTiming" );
781 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
782 . 'MediaWiki-Login-Suppressed'
786 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
790 $this->getOutput()->addVaryHeader( 'Origin' );
797 * Attempt to match an Origin header against a set of rules and a set of exceptions
798 * @param string $value Origin header
799 * @param array $rules Set of wildcard rules
800 * @param array $exceptions Set of wildcard rules
801 * @return bool True if $value matches a rule in $rules and doesn't match
802 * any rules in $exceptions, false otherwise
804 protected static function matchOrigin( $value, $rules, $exceptions ) {
805 foreach ( $rules as $rule ) {
806 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
807 // Rule matches, check exceptions
808 foreach ( $exceptions as $exc ) {
809 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
822 * Attempt to validate the value of Access-Control-Request-Headers against a list
823 * of headers that we allow the follow up request to send.
825 * @param string $requestedHeaders Comma seperated list of HTTP headers
826 * @return bool True if all requested headers are in the list of allowed headers
828 protected static function matchRequestedHeaders( $requestedHeaders ) {
829 if ( trim( $requestedHeaders ) === '' ) {
832 $requestedHeaders = explode( ',', $requestedHeaders );
833 $allowedAuthorHeaders = array_flip( [
834 /* simple headers (see spec) */
839 /* non-authorable headers in XHR, which are however requested by some UAs */
843 /* MediaWiki whitelist */
846 foreach ( $requestedHeaders as $rHeader ) {
847 $rHeader = strtolower( trim( $rHeader ) );
848 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
849 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
857 * Helper function to convert wildcard string into a regex
861 * @param string $wildcard String with wildcards
862 * @return string Regular expression
864 protected static function wildcardToRegex( $wildcard ) {
865 $wildcard = preg_quote( $wildcard, '/' );
866 $wildcard = str_replace(
872 return "/^https?:\/\/$wildcard$/";
876 * Send caching headers
877 * @param bool $isError Whether an error response is being output
878 * @since 1.26 added $isError parameter
880 protected function sendCacheHeaders( $isError ) {
881 $response = $this->getRequest()->response();
882 $out = $this->getOutput();
884 $out->addVaryHeader( 'Treat-as-Untrusted' );
886 $config = $this->getConfig();
888 if ( $config->get( 'VaryOnXFP' ) ) {
889 $out->addVaryHeader( 'X-Forwarded-Proto' );
892 if ( !$isError && $this->mModule
&&
893 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
895 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
896 if ( $etag !== null ) {
897 $response->header( "ETag: $etag" );
899 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
900 if ( $lastMod !== null ) {
901 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
905 // The logic should be:
906 // $this->mCacheControl['max-age'] is set?
907 // Use it, the module knows better than our guess.
908 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
909 // Use 0 because we can guess caching is probably the wrong thing to do.
910 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
912 if ( isset( $this->mCacheControl
['max-age'] ) ) {
913 $maxage = $this->mCacheControl
['max-age'];
914 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
915 $this->mCacheMode
!== 'private'
917 $maxage = $this->getParameter( 'maxage' );
919 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
921 if ( $this->mCacheMode
== 'private' ) {
922 $response->header( "Cache-Control: $privateCache" );
926 $useKeyHeader = $config->get( 'UseKeyHeader' );
927 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
928 $out->addVaryHeader( 'Cookie' );
929 $response->header( $out->getVaryHeader() );
930 if ( $useKeyHeader ) {
931 $response->header( $out->getKeyHeader() );
932 if ( $out->haveCacheVaryCookies() ) {
933 // Logged in, mark this request private
934 $response->header( "Cache-Control: $privateCache" );
937 // Logged out, send normal public headers below
938 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
939 // Logged in or otherwise has session (e.g. anonymous users who have edited)
940 // Mark request private
941 $response->header( "Cache-Control: $privateCache" );
944 } // else no Key and anonymous, send public headers below
947 // Send public headers
948 $response->header( $out->getVaryHeader() );
949 if ( $useKeyHeader ) {
950 $response->header( $out->getKeyHeader() );
953 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
954 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
955 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
957 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
958 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
961 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
962 // Public cache not requested
963 // Sending a Vary header in this case is harmless, and protects us
964 // against conditional calls of setCacheMaxAge().
965 $response->header( "Cache-Control: $privateCache" );
970 $this->mCacheControl
['public'] = true;
972 // Send an Expires header
973 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
974 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
975 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
977 // Construct the Cache-Control header
980 foreach ( $this->mCacheControl
as $name => $value ) {
981 if ( is_bool( $value ) ) {
983 $ccHeader .= $separator . $name;
987 $ccHeader .= $separator . "$name=$value";
992 $response->header( "Cache-Control: $ccHeader" );
996 * Create the printer for error output
998 private function createErrorPrinter() {
999 if ( !isset( $this->mPrinter
) ) {
1000 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
1001 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
1002 $value = self
::API_DEFAULT_FORMAT
;
1004 $this->mPrinter
= $this->createPrinterByName( $value );
1007 // Printer may not be able to handle errors. This is particularly
1008 // likely if the module returns something for getCustomPrinter().
1009 if ( !$this->mPrinter
->canPrintErrors() ) {
1010 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1015 * Create an error message for the given exception.
1017 * If an ApiUsageException, errors/warnings will be extracted from the
1018 * embedded StatusValue.
1020 * If a base UsageException, the getMessageArray() method will be used to
1021 * extract the code and English message for a single error (no warnings).
1023 * Any other exception will be returned with a generic code and wrapper
1024 * text around the exception's (presumably English) message as a single
1025 * error (no warnings).
1027 * @param Exception $e
1028 * @param string $type 'error' or 'warning'
1029 * @return ApiMessage[]
1032 protected function errorMessagesFromException( $e, $type = 'error' ) {
1034 if ( $e instanceof ApiUsageException
) {
1035 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1036 $messages[] = ApiMessage
::create( $error );
1038 } elseif ( $type !== 'error' ) {
1039 // None of the rest have any messages for non-error types
1040 } elseif ( $e instanceof UsageException
) {
1041 // User entered incorrect parameters - generate error response
1042 $data = MediaWiki\
quietCall( [ $e, 'getMessageArray' ] );
1043 $code = $data['code'];
1044 $info = $data['info'];
1045 unset( $data['code'], $data['info'] );
1046 $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1048 // Something is seriously wrong
1049 $config = $this->getConfig();
1050 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1051 $code = 'internal_api_error_' . $class;
1052 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
1053 $params = [ 'apierror-databaseerror', WebRequest
::getRequestId() ];
1055 if ( $e instanceof ILocalizedException
) {
1056 $msg = $e->getMessageObject();
1057 } elseif ( $e instanceof MessageSpecifier
) {
1058 $msg = Message
::newFromSpecifier( $e );
1060 $msg = wfEscapeWikiText( $e->getMessage() );
1062 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1064 $messages[] = ApiMessage
::create( $params, $code );
1070 * Replace the result data with the information about an exception.
1071 * @param Exception $e
1072 * @return string[] Error codes
1074 protected function substituteResultWithError( $e ) {
1075 $result = $this->getResult();
1076 $formatter = $this->getErrorFormatter();
1077 $config = $this->getConfig();
1080 // Remember existing warnings and errors across the reset
1081 $errors = $result->getResultData( [ 'errors' ] );
1082 $warnings = $result->getResultData( [ 'warnings' ] );
1084 if ( $warnings !== null ) {
1085 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1087 if ( $errors !== null ) {
1088 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1090 // Collect the copied error codes for the return value
1091 foreach ( $errors as $error ) {
1092 if ( isset( $error['code'] ) ) {
1093 $errorCodes[$error['code']] = true;
1098 // Add errors from the exception
1099 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1100 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1101 $errorCodes[$msg->getApiCode()] = true;
1102 $formatter->addError( $modulePath, $msg );
1104 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1105 $formatter->addWarning( $modulePath, $msg );
1108 // Add additional data. Path depends on whether we're in BC mode or not.
1109 // Data depends on the type of exception.
1110 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1111 $path = [ 'error' ];
1115 if ( $e instanceof ApiUsageException ||
$e instanceof UsageException
) {
1116 $link = wfExpandUrl( wfScript( 'api' ) );
1117 $result->addContentValue(
1121 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1123 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1127 if ( $config->get( 'ShowExceptionDetails' ) &&
1128 ( !$e instanceof DBError ||
$config->get( 'ShowDBErrorBacktrace' ) )
1130 $result->addContentValue(
1133 $this->msg( 'api-exception-trace',
1137 MWExceptionHandler
::getRedactedTraceAsString( $e )
1138 )->inLanguage( $formatter->getLanguage() )->text()
1143 // Add the id and such
1144 $this->addRequestedFields( [ 'servedby' ] );
1146 return array_keys( $errorCodes );
1150 * Add requested fields to the result
1151 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1154 protected function addRequestedFields( $force = [] ) {
1155 $result = $this->getResult();
1157 $requestid = $this->getParameter( 'requestid' );
1158 if ( $requestid !== null ) {
1159 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1162 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1163 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1165 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1168 if ( $this->getParameter( 'curtimestamp' ) ) {
1169 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1170 ApiResult
::NO_SIZE_CHECK
);
1173 if ( $this->getParameter( 'responselanginfo' ) ) {
1174 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1175 ApiResult
::NO_SIZE_CHECK
);
1176 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1177 ApiResult
::NO_SIZE_CHECK
);
1182 * Set up for the execution.
1185 protected function setupExecuteAction() {
1186 $this->addRequestedFields();
1188 $params = $this->extractRequestParams();
1189 $this->mAction
= $params['action'];
1195 * Set up the module for response
1196 * @return ApiBase The module that will handle this action
1197 * @throws MWException
1198 * @throws ApiUsageException
1200 protected function setupModule() {
1201 // Instantiate the module requested by the user
1202 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1203 if ( $module === null ) {
1204 $this->dieWithError(
1205 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1208 $moduleParams = $module->extractRequestParams();
1210 // Check token, if necessary
1211 if ( $module->needsToken() === true ) {
1212 throw new MWException(
1213 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1214 'See documentation for ApiBase::needsToken for details.'
1217 if ( $module->needsToken() ) {
1218 if ( !$module->mustBePosted() ) {
1219 throw new MWException(
1220 "Module '{$module->getModuleName()}' must require POST to use tokens."
1224 if ( !isset( $moduleParams['token'] ) ) {
1225 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1228 $module->requirePostedParameters( [ 'token' ] );
1230 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1231 $module->dieWithError( 'apierror-badtoken' );
1241 private function getMaxLag() {
1242 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1244 'host' => $dbLag[0],
1249 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1250 if ( $jobQueueLagFactor ) {
1251 // Turn total number of jobs into seconds by using the configured value
1252 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1253 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1254 if ( $jobQueueLag > $lagInfo['lag'] ) {
1256 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1257 'lag' => $jobQueueLag,
1258 'type' => 'jobqueue',
1259 'jobs' => $totalJobs,
1268 * Check the max lag if necessary
1269 * @param ApiBase $module Api module being used
1270 * @param array $params Array an array containing the request parameters.
1271 * @return bool True on success, false should exit immediately
1273 protected function checkMaxLag( $module, $params ) {
1274 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1275 $maxLag = $params['maxlag'];
1276 $lagInfo = $this->getMaxLag();
1277 if ( $lagInfo['lag'] > $maxLag ) {
1278 $response = $this->getRequest()->response();
1280 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1281 $response->header( 'X-Database-Lag: ' . intval( $lagInfo['lag'] ) );
1283 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1284 $this->dieWithError(
1285 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1291 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1299 * Check selected RFC 7232 precondition headers
1301 * RFC 7232 envisions a particular model where you send your request to "a
1302 * resource", and for write requests that you can read "the resource" by
1303 * changing the method to GET. When the API receives a GET request, it
1304 * works out even though "the resource" from RFC 7232's perspective might
1305 * be many resources from MediaWiki's perspective. But it totally fails for
1306 * a POST, since what HTTP sees as "the resource" is probably just
1307 * "/api.php" with all the interesting bits in the body.
1309 * Therefore, we only support RFC 7232 precondition headers for GET (and
1310 * HEAD). That means we don't need to bother with If-Match and
1311 * If-Unmodified-Since since they only apply to modification requests.
1313 * And since we don't support Range, If-Range is ignored too.
1316 * @param ApiBase $module Api module being used
1317 * @return bool True on success, false should exit immediately
1319 protected function checkConditionalRequestHeaders( $module ) {
1320 if ( $this->mInternalMode
) {
1321 // No headers to check in internal mode
1325 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1326 // Don't check POSTs
1332 $ifNoneMatch = array_diff(
1333 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1336 if ( $ifNoneMatch ) {
1337 if ( $ifNoneMatch === [ '*' ] ) {
1338 // API responses always "exist"
1341 $etag = $module->getConditionalRequestData( 'etag' );
1344 if ( $ifNoneMatch && $etag !== null ) {
1345 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1346 $match = array_map( function ( $s ) {
1347 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1349 $return304 = in_array( $test, $match, true );
1351 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1353 // Some old browsers sends sizes after the date, like this:
1354 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1356 $i = strpos( $value, ';' );
1357 if ( $i !== false ) {
1358 $value = trim( substr( $value, 0, $i ) );
1361 if ( $value !== '' ) {
1363 $ts = new MWTimestamp( $value );
1365 // RFC 7231 IMF-fixdate
1366 $ts->getTimestamp( TS_RFC2822
) === $value ||
1368 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1369 // asctime (with and without space-padded day)
1370 $ts->format( 'D M j H:i:s Y' ) === $value ||
1371 $ts->format( 'D M j H:i:s Y' ) === $value
1373 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1374 if ( $lastMod !== null ) {
1375 // Mix in some MediaWiki modification times
1378 'user' => $this->getUser()->getTouched(),
1379 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1381 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1382 // T46570: the core page itself may not change, but resources might
1383 $modifiedTimes['sepoch'] = wfTimestamp(
1384 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1387 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1388 $lastMod = max( $modifiedTimes );
1389 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1392 } catch ( TimestampException
$e ) {
1393 // Invalid timestamp, ignore it
1399 $this->getRequest()->response()->statusHeader( 304 );
1401 // Avoid outputting the compressed representation of a zero-length body
1402 MediaWiki\
suppressWarnings();
1403 ini_set( 'zlib.output_compression', 0 );
1404 MediaWiki\restoreWarnings
();
1405 wfClearOutputBuffers();
1414 * Check for sufficient permissions to execute
1415 * @param ApiBase $module An Api module
1417 protected function checkExecutePermissions( $module ) {
1418 $user = $this->getUser();
1419 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1420 !$user->isAllowed( 'read' )
1422 $this->dieWithError( 'apierror-readapidenied' );
1425 if ( $module->isWriteMode() ) {
1426 if ( !$this->mEnableWrite
) {
1427 $this->dieWithError( 'apierror-noapiwrite' );
1428 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1429 $this->dieWithError( 'apierror-writeapidenied' );
1430 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1431 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1434 $this->checkReadOnly( $module );
1437 // Allow extensions to stop execution for arbitrary reasons.
1439 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1440 $this->dieWithError( $message );
1445 * Check if the DB is read-only for this user
1446 * @param ApiBase $module An Api module
1448 protected function checkReadOnly( $module ) {
1449 if ( wfReadOnly() ) {
1450 $this->dieReadOnly();
1453 if ( $module->isWriteMode()
1454 && $this->getUser()->isBot()
1455 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1457 $this->checkBotReadOnly();
1462 * Check whether we are readonly for bots
1464 private function checkBotReadOnly() {
1465 // Figure out how many servers have passed the lag threshold
1467 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1468 $laggedServers = [];
1469 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1470 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1471 if ( $lag > $lagLimit ) {
1473 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1477 // If a majority of replica DBs are too lagged then disallow writes
1478 $replicaCount = $loadBalancer->getServerCount() - 1;
1479 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1480 $laggedServers = implode( ', ', $laggedServers );
1483 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1486 $this->dieWithError(
1489 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1495 * Check asserts of the user's rights
1496 * @param array $params
1498 protected function checkAsserts( $params ) {
1499 if ( isset( $params['assert'] ) ) {
1500 $user = $this->getUser();
1501 switch ( $params['assert'] ) {
1503 if ( $user->isAnon() ) {
1504 $this->dieWithError( 'apierror-assertuserfailed' );
1508 if ( !$user->isAllowed( 'bot' ) ) {
1509 $this->dieWithError( 'apierror-assertbotfailed' );
1514 if ( isset( $params['assertuser'] ) ) {
1515 $assertUser = User
::newFromName( $params['assertuser'], false );
1516 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1517 $this->dieWithError(
1518 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1525 * Check POST for external response and setup result printer
1526 * @param ApiBase $module An Api module
1527 * @param array $params An array with the request parameters
1529 protected function setupExternalResponse( $module, $params ) {
1530 $request = $this->getRequest();
1531 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1532 // Module requires POST. GET request might still be allowed
1533 // if $wgDebugApi is true, otherwise fail.
1534 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1537 // See if custom printer is used
1538 $this->mPrinter
= $module->getCustomPrinter();
1539 if ( is_null( $this->mPrinter
) ) {
1540 // Create an appropriate printer
1541 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1544 if ( $request->getProtocol() === 'http' && (
1545 $request->getSession()->shouldForceHTTPS() ||
1546 ( $this->getUser()->isLoggedIn() &&
1547 $this->getUser()->requiresHTTPS() )
1549 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1554 * Execute the actual module, without any error handling
1556 protected function executeAction() {
1557 $params = $this->setupExecuteAction();
1558 $module = $this->setupModule();
1559 $this->mModule
= $module;
1561 if ( !$this->mInternalMode
) {
1562 $this->setRequestExpectations( $module );
1565 $this->checkExecutePermissions( $module );
1567 if ( !$this->checkMaxLag( $module, $params ) ) {
1571 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1575 if ( !$this->mInternalMode
) {
1576 $this->setupExternalResponse( $module, $params );
1579 $this->checkAsserts( $params );
1583 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1585 $this->reportUnusedParams();
1587 if ( !$this->mInternalMode
) {
1588 // append Debug information
1589 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1591 // Print result data
1592 $this->printResult();
1597 * Set database connection, query, and write expectations given this module request
1598 * @param ApiBase $module
1600 protected function setRequestExpectations( ApiBase
$module ) {
1601 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1602 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1603 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1604 if ( $this->getRequest()->hasSafeMethod() ) {
1605 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1606 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1607 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1608 $this->getRequest()->markAsSafeRequest();
1610 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1615 * Log the preceding request
1616 * @param float $time Time in seconds
1617 * @param Exception $e Exception caught while processing the request
1619 protected function logRequest( $time, $e = null ) {
1620 $request = $this->getRequest();
1623 'ip' => $request->getIP(),
1624 'userAgent' => $this->getUserAgent(),
1625 'wiki' => wfWikiID(),
1626 'timeSpentBackend' => (int)round( $time * 1000 ),
1627 'hadError' => $e !== null,
1633 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1634 $logCtx['errorCodes'][] = $msg->getApiCode();
1638 // Construct space separated message for 'api' log channel
1639 $msg = "API {$request->getMethod()} " .
1640 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1641 " {$logCtx['ip']} " .
1642 "T={$logCtx['timeSpentBackend']}ms";
1644 $sensitive = array_flip( $this->getSensitiveParams() );
1645 foreach ( $this->getParamsUsed() as $name ) {
1646 $value = $request->getVal( $name );
1647 if ( $value === null ) {
1651 if ( isset( $sensitive[$name] ) ) {
1652 $value = '[redacted]';
1653 $encValue = '[redacted]';
1654 } elseif ( strlen( $value ) > 256 ) {
1655 $value = substr( $value, 0, 256 );
1656 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1658 $encValue = $this->encodeRequestLogValue( $value );
1661 $logCtx['params'][$name] = $value;
1662 $msg .= " {$name}={$encValue}";
1665 wfDebugLog( 'api', $msg, 'private' );
1666 // ApiAction channel is for structured data consumers
1667 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1671 * Encode a value in a format suitable for a space-separated log line.
1675 protected function encodeRequestLogValue( $s ) {
1678 $chars = ';@$!*(),/:';
1679 $numChars = strlen( $chars );
1680 for ( $i = 0; $i < $numChars; $i++
) {
1681 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1685 return strtr( rawurlencode( $s ), $table );
1689 * Get the request parameters used in the course of the preceding execute() request
1692 protected function getParamsUsed() {
1693 return array_keys( $this->mParamsUsed
);
1697 * Mark parameters as used
1698 * @param string|string[] $params
1700 public function markParamsUsed( $params ) {
1701 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1705 * Get the request parameters that should be considered sensitive
1709 protected function getSensitiveParams() {
1710 return array_keys( $this->mParamsSensitive
);
1714 * Mark parameters as sensitive
1716 * @param string|string[] $params
1718 public function markParamsSensitive( $params ) {
1719 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1723 * Get a request value, and register the fact that it was used, for logging.
1724 * @param string $name
1725 * @param mixed $default
1728 public function getVal( $name, $default = null ) {
1729 $this->mParamsUsed
[$name] = true;
1731 $ret = $this->getRequest()->getVal( $name );
1732 if ( $ret === null ) {
1733 if ( $this->getRequest()->getArray( $name ) !== null ) {
1734 // See T12262 for why we don't just implode( '|', ... ) the
1736 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1744 * Get a boolean request value, and register the fact that the parameter
1745 * was used, for logging.
1746 * @param string $name
1749 public function getCheck( $name ) {
1750 return $this->getVal( $name, null ) !== null;
1754 * Get a request upload, and register the fact that it was used, for logging.
1757 * @param string $name Parameter name
1758 * @return WebRequestUpload
1760 public function getUpload( $name ) {
1761 $this->mParamsUsed
[$name] = true;
1763 return $this->getRequest()->getUpload( $name );
1767 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1768 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1770 protected function reportUnusedParams() {
1771 $paramsUsed = $this->getParamsUsed();
1772 $allParams = $this->getRequest()->getValueNames();
1774 if ( !$this->mInternalMode
) {
1775 // Printer has not yet executed; don't warn that its parameters are unused
1776 $printerParams = $this->mPrinter
->encodeParamName(
1777 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1779 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1781 $unusedParams = array_diff( $allParams, $paramsUsed );
1784 if ( count( $unusedParams ) ) {
1785 $this->addWarning( [
1786 'apierror-unrecognizedparams',
1787 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1788 count( $unusedParams )
1794 * Print results using the current printer
1796 * @param int $httpCode HTTP status code, or 0 to not change
1798 protected function printResult( $httpCode = 0 ) {
1799 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1800 $this->addWarning( 'apiwarn-wgDebugAPI' );
1803 $printer = $this->mPrinter
;
1804 $printer->initPrinter( false );
1806 $printer->setHttpStatus( $httpCode );
1808 $printer->execute();
1809 $printer->closePrinter();
1815 public function isReadMode() {
1820 * See ApiBase for description.
1824 public function getAllowedParams() {
1827 ApiBase
::PARAM_DFLT
=> 'help',
1828 ApiBase
::PARAM_TYPE
=> 'submodule',
1831 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1832 ApiBase
::PARAM_TYPE
=> 'submodule',
1835 ApiBase
::PARAM_TYPE
=> 'integer'
1838 ApiBase
::PARAM_TYPE
=> 'integer',
1839 ApiBase
::PARAM_DFLT
=> 0
1842 ApiBase
::PARAM_TYPE
=> 'integer',
1843 ApiBase
::PARAM_DFLT
=> 0
1846 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1849 ApiBase
::PARAM_TYPE
=> 'user',
1851 'requestid' => null,
1852 'servedby' => false,
1853 'curtimestamp' => false,
1854 'responselanginfo' => false,
1857 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1860 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1861 ApiBase
::PARAM_DFLT
=> 'bc',
1864 ApiBase
::PARAM_DFLT
=> 'uselang',
1866 'errorsuselocal' => [
1867 ApiBase
::PARAM_DFLT
=> false,
1873 protected function getExamplesMessages() {
1876 => 'apihelp-help-example-main',
1877 'action=help&recursivesubmodules=1'
1878 => 'apihelp-help-example-recursive',
1882 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1883 // Wish PHP had an "array_insert_before". Instead, we have to manually
1884 // reindex the array to get 'permissions' in the right place.
1887 foreach ( $oldHelp as $k => $v ) {
1888 if ( $k === 'submodules' ) {
1889 $help['permissions'] = '';
1893 $help['datatypes'] = '';
1894 $help['credits'] = '';
1896 // Fill 'permissions'
1897 $help['permissions'] .= Html
::openElement( 'div',
1898 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1899 $m = $this->msg( 'api-help-permissions' );
1900 if ( !$m->isDisabled() ) {
1901 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1902 $m->numParams( count( self
::$mRights ) )->parse()
1905 $help['permissions'] .= Html
::openElement( 'dl' );
1906 foreach ( self
::$mRights as $right => $rightMsg ) {
1907 $help['permissions'] .= Html
::element( 'dt', null, $right );
1909 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1910 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1912 $groups = array_map( function ( $group ) {
1913 return $group == '*' ?
'all' : $group;
1914 }, User
::getGroupsWithPermission( $right ) );
1916 $help['permissions'] .= Html
::rawElement( 'dd', null,
1917 $this->msg( 'api-help-permissions-granted-to' )
1918 ->numParams( count( $groups ) )
1919 ->params( Message
::listParam( $groups ) )
1923 $help['permissions'] .= Html
::closeElement( 'dl' );
1924 $help['permissions'] .= Html
::closeElement( 'div' );
1926 // Fill 'datatypes' and 'credits', if applicable
1927 if ( empty( $options['nolead'] ) ) {
1928 $level = $options['headerlevel'];
1929 $tocnumber = &$options['tocnumber'];
1931 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1933 $id = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_PRIMARY
);
1934 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_FALLBACK
);
1935 $headline = Linker
::makeHeadline( min( 6, $level ),
1936 ' class="apihelp-header">',
1942 // Ensure we have a sane anchor
1943 if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1944 $headline = '<div id="main/datatypes"></div>' . $headline;
1946 $help['datatypes'] .= $headline;
1947 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1948 if ( !isset( $tocData['main/datatypes'] ) ) {
1949 $tocnumber[$level]++
;
1950 $tocData['main/datatypes'] = [
1951 'toclevel' => count( $tocnumber ),
1953 'anchor' => 'main/datatypes',
1955 'number' => implode( '.', $tocnumber ),
1960 $header = $this->msg( 'api-credits-header' )->parse();
1961 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
1962 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_FALLBACK
);
1963 $headline = Linker
::makeHeadline( min( 6, $level ),
1964 ' class="apihelp-header">',
1970 // Ensure we have a sane anchor
1971 if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
1972 $headline = '<div id="main/credits"></div>' . $headline;
1974 $help['credits'] .= $headline;
1975 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1976 if ( !isset( $tocData['main/credits'] ) ) {
1977 $tocnumber[$level]++
;
1978 $tocData['main/credits'] = [
1979 'toclevel' => count( $tocnumber ),
1981 'anchor' => 'main/credits',
1983 'number' => implode( '.', $tocnumber ),
1990 private $mCanApiHighLimits = null;
1993 * Check whether the current user is allowed to use high limits
1996 public function canApiHighLimits() {
1997 if ( !isset( $this->mCanApiHighLimits
) ) {
1998 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
2001 return $this->mCanApiHighLimits
;
2005 * Overrides to return this instance's module manager.
2006 * @return ApiModuleManager
2008 public function getModuleManager() {
2009 return $this->mModuleMgr
;
2013 * Fetches the user agent used for this request
2015 * The value will be the combination of the 'Api-User-Agent' header (if
2016 * any) and the standard User-Agent header (if any).
2020 public function getUserAgent() {
2022 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2023 $this->getRequest()->getHeader( 'User-agent' )
2029 * For really cool vim folding this needs to be at the end:
2030 * vim: foldmarker=@{,@} foldmethod=marker