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
;
27 use Wikimedia\Rdbms\DBQueryError
;
28 use Wikimedia\Rdbms\DBError
;
31 * This is the main API class, used for both external and internal processing.
32 * When executed, it will create the requested formatter object,
33 * instantiate and execute an object associated with the needed action,
34 * and use formatter to print results.
35 * In case of an exception, an error message will be printed using the same formatter.
37 * To use API from another application, run it using FauxRequest object, in which
38 * case any internal exceptions will not be handled but passed up to the caller.
39 * After successful execution, use getResult() for the resulting data.
43 class ApiMain
extends ApiBase
{
45 * When no format parameter is given, this format will be used
47 const API_DEFAULT_FORMAT
= 'jsonfm';
50 * When no uselang parameter is given, this language will be used
52 const API_DEFAULT_USELANG
= 'user';
55 * List of available modules: action name => module class
57 private static $Modules = [
58 'login' => ApiLogin
::class,
59 'clientlogin' => ApiClientLogin
::class,
60 'logout' => ApiLogout
::class,
61 'createaccount' => ApiAMCreateAccount
::class,
62 'linkaccount' => ApiLinkAccount
::class,
63 'unlinkaccount' => ApiRemoveAuthenticationData
::class,
64 'changeauthenticationdata' => ApiChangeAuthenticationData
::class,
65 'removeauthenticationdata' => ApiRemoveAuthenticationData
::class,
66 'resetpassword' => ApiResetPassword
::class,
67 'query' => ApiQuery
::class,
68 'expandtemplates' => ApiExpandTemplates
::class,
69 'parse' => ApiParse
::class,
70 'stashedit' => ApiStashEdit
::class,
71 'opensearch' => ApiOpenSearch
::class,
72 'feedcontributions' => ApiFeedContributions
::class,
73 'feedrecentchanges' => ApiFeedRecentChanges
::class,
74 'feedwatchlist' => ApiFeedWatchlist
::class,
75 'help' => ApiHelp
::class,
76 'paraminfo' => ApiParamInfo
::class,
77 'rsd' => ApiRsd
::class,
78 'compare' => ApiComparePages
::class,
79 'tokens' => ApiTokens
::class,
80 'checktoken' => ApiCheckToken
::class,
81 'cspreport' => ApiCSPReport
::class,
82 'validatepassword' => ApiValidatePassword
::class,
85 'purge' => ApiPurge
::class,
86 'setnotificationtimestamp' => ApiSetNotificationTimestamp
::class,
87 'rollback' => ApiRollback
::class,
88 'delete' => ApiDelete
::class,
89 'undelete' => ApiUndelete
::class,
90 'protect' => ApiProtect
::class,
91 'block' => ApiBlock
::class,
92 'unblock' => ApiUnblock
::class,
93 'move' => ApiMove
::class,
94 'edit' => ApiEditPage
::class,
95 'upload' => ApiUpload
::class,
96 'filerevert' => ApiFileRevert
::class,
97 'emailuser' => ApiEmailUser
::class,
98 'watch' => ApiWatch
::class,
99 'patrol' => ApiPatrol
::class,
100 'import' => ApiImport
::class,
101 'clearhasmsg' => ApiClearHasMsg
::class,
102 'userrights' => ApiUserrights
::class,
103 'options' => ApiOptions
::class,
104 'imagerotate' => ApiImageRotate
::class,
105 'revisiondelete' => ApiRevisionDelete
::class,
106 'managetags' => ApiManageTags
::class,
107 'tag' => ApiTag
::class,
108 'mergehistory' => ApiMergeHistory
::class,
109 'setpagelanguage' => ApiSetPageLanguage
::class,
113 * List of available formats: format name => format class
115 private static $Formats = [
116 'json' => ApiFormatJson
::class,
117 'jsonfm' => ApiFormatJson
::class,
118 'php' => ApiFormatPhp
::class,
119 'phpfm' => ApiFormatPhp
::class,
120 'xml' => ApiFormatXml
::class,
121 'xmlfm' => ApiFormatXml
::class,
122 'rawfm' => ApiFormatJson
::class,
123 'none' => ApiFormatNone
::class,
127 * List of user roles that are specifically relevant to the API.
128 * [ 'right' => [ 'msg' => 'Some message with a $1',
129 * 'params' => [ $someVarToSubst ] ],
132 private static $mRights = [
134 'msg' => 'right-writeapi',
138 'msg' => 'api-help-right-apihighlimits',
139 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
148 private $mModuleMgr, $mResult, $mErrorFormatter = null;
149 /** @var ApiContinuationManager|null */
150 private $mContinuationManager;
152 private $mEnableWrite;
153 private $mInternalMode, $mSquidMaxage;
157 private $mCacheMode = 'private';
158 private $mCacheControl = [];
159 private $mParamsUsed = [];
160 private $mParamsSensitive = [];
162 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
163 private $lacksSameOriginSecurity = null;
166 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
168 * @param IContextSource|WebRequest $context If this is an instance of
169 * FauxRequest, errors are thrown and no printing occurs
170 * @param bool $enableWrite Should be set to true if the api may modify data
172 public function __construct( $context = null, $enableWrite = false ) {
173 if ( $context === null ) {
174 $context = RequestContext
::getMain();
175 } elseif ( $context instanceof WebRequest
) {
178 $context = RequestContext
::getMain();
180 // We set a derivative context so we can change stuff later
181 $this->setContext( new DerivativeContext( $context ) );
183 if ( isset( $request ) ) {
184 $this->getContext()->setRequest( $request );
186 $request = $this->getRequest();
189 $this->mInternalMode
= ( $request instanceof FauxRequest
);
191 // Special handling for the main module: $parent === $this
192 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
194 $config = $this->getConfig();
196 if ( !$this->mInternalMode
) {
197 // Log if a request with a non-whitelisted Origin header is seen
198 // with session cookies.
199 $originHeader = $request->getHeader( 'Origin' );
200 if ( $originHeader === false ) {
203 $originHeader = trim( $originHeader );
204 $origins = preg_split( '/\s+/', $originHeader );
206 $sessionCookies = array_intersect(
207 array_keys( $_COOKIE ),
208 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
210 if ( $origins && $sessionCookies && (
211 count( $origins ) !== 1 ||
!self
::matchOrigin(
213 $config->get( 'CrossSiteAJAXdomains' ),
214 $config->get( 'CrossSiteAJAXdomainExceptions' )
217 LoggerFactory
::getInstance( 'cors' )->warning(
218 'Non-whitelisted CORS request with session cookies', [
219 'origin' => $originHeader,
220 'cookies' => $sessionCookies,
221 'ip' => $request->getIP(),
222 'userAgent' => $this->getUserAgent(),
223 'wiki' => wfWikiID(),
228 // If we're in a mode that breaks the same-origin policy, strip
229 // user credentials for security.
230 if ( $this->lacksSameOriginSecurity() ) {
232 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
233 $wgUser = new User();
234 $this->getContext()->setUser( $wgUser );
235 $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
239 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
241 // Setup uselang. This doesn't use $this->getParameter()
242 // because we're not ready to handle errors yet.
243 $uselang = $request->getVal( 'uselang', self
::API_DEFAULT_USELANG
);
244 if ( $uselang === 'user' ) {
245 // Assume the parent context is going to return the user language
246 // for uselang=user (see T85635).
248 if ( $uselang === 'content' ) {
250 $uselang = $wgContLang->getCode();
252 $code = RequestContext
::sanitizeLangCode( $uselang );
253 $this->getContext()->setLanguage( $code );
254 if ( !$this->mInternalMode
) {
256 $wgLang = $this->getContext()->getLanguage();
257 RequestContext
::getMain()->setLanguage( $wgLang );
261 // Set up the error formatter. This doesn't use $this->getParameter()
262 // because we're not ready to handle errors yet.
263 $errorFormat = $request->getVal( 'errorformat', 'bc' );
264 $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
265 $errorsUseDB = $request->getCheck( 'errorsuselocal' );
266 if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
267 if ( $errorLangCode === 'uselang' ) {
268 $errorLang = $this->getLanguage();
269 } elseif ( $errorLangCode === 'content' ) {
271 $errorLang = $wgContLang;
273 $errorLangCode = RequestContext
::sanitizeLangCode( $errorLangCode );
274 $errorLang = Language
::factory( $errorLangCode );
276 $this->mErrorFormatter
= new ApiErrorFormatter(
277 $this->mResult
, $errorLang, $errorFormat, $errorsUseDB
280 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
282 $this->mResult
->setErrorFormatter( $this->getErrorFormatter() );
284 $this->mModuleMgr
= new ApiModuleManager( $this );
285 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
286 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
287 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
288 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
290 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
292 $this->mContinuationManager
= null;
293 $this->mEnableWrite
= $enableWrite;
295 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
296 $this->mCommit
= false;
300 * Return true if the API was started by other PHP code using FauxRequest
303 public function isInternalMode() {
304 return $this->mInternalMode
;
308 * Get the ApiResult object associated with current request
312 public function getResult() {
313 return $this->mResult
;
317 * Get the security flag for the current request
320 public function lacksSameOriginSecurity() {
321 if ( $this->lacksSameOriginSecurity
!== null ) {
322 return $this->lacksSameOriginSecurity
;
325 $request = $this->getRequest();
328 if ( $request->getVal( 'callback' ) !== null ) {
329 $this->lacksSameOriginSecurity
= true;
334 if ( $request->getVal( 'origin' ) === '*' ) {
335 $this->lacksSameOriginSecurity
= true;
339 // Header to be used from XMLHTTPRequest when the request might
340 // otherwise be used for XSS.
341 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
342 $this->lacksSameOriginSecurity
= true;
346 // Allow extensions to override.
347 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
348 return $this->lacksSameOriginSecurity
;
352 * Get the ApiErrorFormatter object associated with current request
353 * @return ApiErrorFormatter
355 public function getErrorFormatter() {
356 return $this->mErrorFormatter
;
360 * Get the continuation manager
361 * @return ApiContinuationManager|null
363 public function getContinuationManager() {
364 return $this->mContinuationManager
;
368 * Set the continuation manager
369 * @param ApiContinuationManager|null $manager
371 public function setContinuationManager( $manager ) {
372 if ( $manager !== null ) {
373 if ( !$manager instanceof ApiContinuationManager
) {
374 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
375 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
378 if ( $this->mContinuationManager
!== null ) {
379 throw new UnexpectedValueException(
380 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
381 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
385 $this->mContinuationManager
= $manager;
389 * Get the API module object. Only works after executeAction()
393 public function getModule() {
394 return $this->mModule
;
398 * Get the result formatter object. Only works after setupExecuteAction()
400 * @return ApiFormatBase
402 public function getPrinter() {
403 return $this->mPrinter
;
407 * Set how long the response should be cached.
411 public function setCacheMaxAge( $maxage ) {
412 $this->setCacheControl( [
413 'max-age' => $maxage,
414 's-maxage' => $maxage
419 * Set the type of caching headers which will be sent.
421 * @param string $mode One of:
422 * - 'public': Cache this object in public caches, if the maxage or smaxage
423 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
424 * not provided by any of these means, the object will be private.
425 * - 'private': Cache this object only in private client-side caches.
426 * - 'anon-public-user-private': Make this object cacheable for logged-out
427 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
428 * set consistently for a given URL, it cannot be set differently depending on
429 * things like the contents of the database, or whether the user is logged in.
431 * If the wiki does not allow anonymous users to read it, the mode set here
432 * will be ignored, and private caching headers will always be sent. In other words,
433 * the "public" mode is equivalent to saying that the data sent is as public as a page
436 * For user-dependent data, the private mode should generally be used. The
437 * anon-public-user-private mode should only be used where there is a particularly
438 * good performance reason for caching the anonymous response, but where the
439 * response to logged-in users may differ, or may contain private data.
441 * If this function is never called, then the default will be the private mode.
443 public function setCacheMode( $mode ) {
444 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
445 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
447 // Ignore for forwards-compatibility
451 if ( !User
::isEveryoneAllowed( 'read' ) ) {
452 // Private wiki, only private headers
453 if ( $mode !== 'private' ) {
454 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
460 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
461 // User language is used for i18n, so we don't want to publicly
462 // cache. Anons are ok, because if they have non-default language
463 // then there's an appropriate Vary header set by whatever set
464 // their non-default language.
465 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
466 "'anon-public-user-private' due to uselang=user\n" );
467 $mode = 'anon-public-user-private';
470 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
471 $this->mCacheMode
= $mode;
475 * Set directives (key/value pairs) for the Cache-Control header.
476 * Boolean values will be formatted as such, by including or omitting
477 * without an equals sign.
479 * Cache control values set here will only be used if the cache mode is not
480 * private, see setCacheMode().
482 * @param array $directives
484 public function setCacheControl( $directives ) {
485 $this->mCacheControl
= $directives +
$this->mCacheControl
;
489 * Create an instance of an output formatter by its name
491 * @param string $format
493 * @return ApiFormatBase
495 public function createPrinterByName( $format ) {
496 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
497 if ( $printer === null ) {
499 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
507 * Execute api request. Any errors will be handled if the API was called by the remote client.
509 public function execute() {
510 if ( $this->mInternalMode
) {
511 $this->executeAction();
513 $this->executeActionWithErrorHandling();
518 * Execute an action, and in case of an error, erase whatever partial results
519 * have been accumulated, and replace it with an error message and a help screen.
521 protected function executeActionWithErrorHandling() {
522 // Verify the CORS header before executing the action
523 if ( !$this->handleCORS() ) {
524 // handleCORS() has sent a 403, abort
528 // Exit here if the request method was OPTIONS
529 // (assume there will be a followup GET or POST)
530 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
534 // In case an error occurs during data output,
535 // clear the output buffer and print just the error information
536 $obLevel = ob_get_level();
539 $t = microtime( true );
542 $this->executeAction();
543 $runTime = microtime( true ) - $t;
544 $this->logRequest( $runTime );
545 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
546 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
547 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
550 } catch ( Exception
$e ) {
551 $this->handleException( $e );
552 $this->logRequest( microtime( true ) - $t, $e );
556 // Commit DBs and send any related cookies and headers
557 MediaWiki
::preOutputCommit( $this->getContext() );
559 // Send cache headers after any code which might generate an error, to
560 // avoid sending public cache headers for errors.
561 $this->sendCacheHeaders( $isError );
563 // Executing the action might have already messed with the output
565 while ( ob_get_level() > $obLevel ) {
571 * Handle an exception as an API response
574 * @param Exception $e
576 protected function handleException( Exception
$e ) {
577 // T65145: Rollback any open database transactions
578 if ( !( $e instanceof ApiUsageException ||
$e instanceof UsageException
) ) {
579 // UsageExceptions are intentional, so don't rollback if that's the case
580 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
583 // Allow extra cleanup and logging
584 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
586 // Handle any kind of exception by outputting properly formatted error message.
587 // If this fails, an unhandled exception should be thrown so that global error
588 // handler will process and log it.
590 $errCodes = $this->substituteResultWithError( $e );
592 // Error results should not be cached
593 $this->setCacheMode( 'private' );
595 $response = $this->getRequest()->response();
596 $headerStr = 'MediaWiki-API-Error: ' . join( ', ', $errCodes );
597 $response->header( $headerStr );
599 // Reset and print just the error message
602 // Printer may not be initialized if the extractRequestParams() fails for the main module
603 $this->createErrorPrinter();
607 $this->printResult( $e->getCode() );
608 } catch ( ApiUsageException
$ex ) {
609 // The error printer itself is failing. Try suppressing its request
610 // parameters and redo.
612 $this->addWarning( 'apiwarn-errorprinterfailed' );
613 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
615 $this->mPrinter
->addWarning( $error );
616 } catch ( Exception
$ex2 ) {
618 $this->addWarning( $error );
621 } catch ( UsageException
$ex ) {
622 // The error printer itself is failing. Try suppressing its request
623 // parameters and redo.
626 [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
630 $this->mPrinter
= null;
631 $this->createErrorPrinter();
632 $this->mPrinter
->forceDefaultParams();
633 if ( $e->getCode() ) {
634 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
636 $this->printResult( $e->getCode() );
641 * Handle an exception from the ApiBeforeMain hook.
643 * This tries to print the exception as an API response, to be more
644 * friendly to clients. If it fails, it will rethrow the exception.
647 * @param Exception $e
650 public static function handleApiBeforeMainException( Exception
$e ) {
654 $main = new self( RequestContext
::getMain(), false );
655 $main->handleException( $e );
656 $main->logRequest( 0, $e );
657 } catch ( Exception
$e2 ) {
658 // Nope, even that didn't work. Punt.
662 // Reset cache headers
663 $main->sendCacheHeaders( true );
669 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
671 * If no origin parameter is present, nothing happens.
672 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
673 * is set and false is returned.
674 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
675 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
677 * https://www.w3.org/TR/cors/#resource-requests
678 * https://www.w3.org/TR/cors/#resource-preflight-requests
680 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
682 protected function handleCORS() {
683 $originParam = $this->getParameter( 'origin' ); // defaults to null
684 if ( $originParam === null ) {
685 // No origin parameter, nothing to do
689 $request = $this->getRequest();
690 $response = $request->response();
692 $matchedOrigin = false;
693 $allowTiming = false;
696 if ( $originParam === '*' ) {
697 // Request for anonymous CORS
698 // Technically we should check for the presence of an Origin header
699 // and not process it as CORS if it's not set, but that would
700 // require us to vary on Origin for all 'origin=*' requests which
701 // we don't want to do.
702 $matchedOrigin = true;
704 $allowCredentials = 'false';
705 $varyOrigin = false; // No need to vary
707 // Non-anonymous CORS, check we allow the domain
709 // Origin: header is a space-separated list of origins, check all of them
710 $originHeader = $request->getHeader( 'Origin' );
711 if ( $originHeader === false ) {
714 $originHeader = trim( $originHeader );
715 $origins = preg_split( '/\s+/', $originHeader );
718 if ( !in_array( $originParam, $origins ) ) {
719 // origin parameter set but incorrect
720 // Send a 403 response
721 $response->statusHeader( 403 );
722 $response->header( 'Cache-Control: no-cache' );
723 echo "'origin' parameter does not match Origin header\n";
728 $config = $this->getConfig();
729 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
731 $config->get( 'CrossSiteAJAXdomains' ),
732 $config->get( 'CrossSiteAJAXdomainExceptions' )
735 $allowOrigin = $originHeader;
736 $allowCredentials = 'true';
737 $allowTiming = $originHeader;
740 if ( $matchedOrigin ) {
741 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
742 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
744 // This is a CORS preflight request
745 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
746 // If method is not a case-sensitive match, do not set any additional headers and terminate.
747 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
750 // We allow the actual request to send the following headers
751 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
752 if ( $requestedHeaders !== false ) {
753 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
754 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
757 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
760 // We only allow the actual request to be GET or POST
761 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
762 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
763 // Unsupported non-preflight method, don't handle it as CORS
765 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
770 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
771 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
772 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
773 if ( $allowTiming !== false ) {
774 $response->header( "Timing-Allow-Origin: $allowTiming" );
779 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
780 . 'MediaWiki-Login-Suppressed'
784 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
788 $this->getOutput()->addVaryHeader( 'Origin' );
795 * Attempt to match an Origin header against a set of rules and a set of exceptions
796 * @param string $value Origin header
797 * @param array $rules Set of wildcard rules
798 * @param array $exceptions Set of wildcard rules
799 * @return bool True if $value matches a rule in $rules and doesn't match
800 * any rules in $exceptions, false otherwise
802 protected static function matchOrigin( $value, $rules, $exceptions ) {
803 foreach ( $rules as $rule ) {
804 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
805 // Rule matches, check exceptions
806 foreach ( $exceptions as $exc ) {
807 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
820 * Attempt to validate the value of Access-Control-Request-Headers against a list
821 * of headers that we allow the follow up request to send.
823 * @param string $requestedHeaders Comma seperated list of HTTP headers
824 * @return bool True if all requested headers are in the list of allowed headers
826 protected static function matchRequestedHeaders( $requestedHeaders ) {
827 if ( trim( $requestedHeaders ) === '' ) {
830 $requestedHeaders = explode( ',', $requestedHeaders );
831 $allowedAuthorHeaders = array_flip( [
832 /* simple headers (see spec) */
837 /* non-authorable headers in XHR, which are however requested by some UAs */
841 /* MediaWiki whitelist */
844 foreach ( $requestedHeaders as $rHeader ) {
845 $rHeader = strtolower( trim( $rHeader ) );
846 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
847 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
855 * Helper function to convert wildcard string into a regex
859 * @param string $wildcard String with wildcards
860 * @return string Regular expression
862 protected static function wildcardToRegex( $wildcard ) {
863 $wildcard = preg_quote( $wildcard, '/' );
864 $wildcard = str_replace(
870 return "/^https?:\/\/$wildcard$/";
874 * Send caching headers
875 * @param bool $isError Whether an error response is being output
876 * @since 1.26 added $isError parameter
878 protected function sendCacheHeaders( $isError ) {
879 $response = $this->getRequest()->response();
880 $out = $this->getOutput();
882 $out->addVaryHeader( 'Treat-as-Untrusted' );
884 $config = $this->getConfig();
886 if ( $config->get( 'VaryOnXFP' ) ) {
887 $out->addVaryHeader( 'X-Forwarded-Proto' );
890 if ( !$isError && $this->mModule
&&
891 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
893 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
894 if ( $etag !== null ) {
895 $response->header( "ETag: $etag" );
897 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
898 if ( $lastMod !== null ) {
899 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
903 // The logic should be:
904 // $this->mCacheControl['max-age'] is set?
905 // Use it, the module knows better than our guess.
906 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
907 // Use 0 because we can guess caching is probably the wrong thing to do.
908 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
910 if ( isset( $this->mCacheControl
['max-age'] ) ) {
911 $maxage = $this->mCacheControl
['max-age'];
912 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
913 $this->mCacheMode
!== 'private'
915 $maxage = $this->getParameter( 'maxage' );
917 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
919 if ( $this->mCacheMode
== 'private' ) {
920 $response->header( "Cache-Control: $privateCache" );
924 $useKeyHeader = $config->get( 'UseKeyHeader' );
925 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
926 $out->addVaryHeader( 'Cookie' );
927 $response->header( $out->getVaryHeader() );
928 if ( $useKeyHeader ) {
929 $response->header( $out->getKeyHeader() );
930 if ( $out->haveCacheVaryCookies() ) {
931 // Logged in, mark this request private
932 $response->header( "Cache-Control: $privateCache" );
935 // Logged out, send normal public headers below
936 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
937 // Logged in or otherwise has session (e.g. anonymous users who have edited)
938 // Mark request private
939 $response->header( "Cache-Control: $privateCache" );
942 } // else no Key and anonymous, send public headers below
945 // Send public headers
946 $response->header( $out->getVaryHeader() );
947 if ( $useKeyHeader ) {
948 $response->header( $out->getKeyHeader() );
951 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
952 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
953 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
955 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
956 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
959 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
960 // Public cache not requested
961 // Sending a Vary header in this case is harmless, and protects us
962 // against conditional calls of setCacheMaxAge().
963 $response->header( "Cache-Control: $privateCache" );
968 $this->mCacheControl
['public'] = true;
970 // Send an Expires header
971 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
972 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
973 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
975 // Construct the Cache-Control header
978 foreach ( $this->mCacheControl
as $name => $value ) {
979 if ( is_bool( $value ) ) {
981 $ccHeader .= $separator . $name;
985 $ccHeader .= $separator . "$name=$value";
990 $response->header( "Cache-Control: $ccHeader" );
994 * Create the printer for error output
996 private function createErrorPrinter() {
997 if ( !isset( $this->mPrinter
) ) {
998 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
999 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
1000 $value = self
::API_DEFAULT_FORMAT
;
1002 $this->mPrinter
= $this->createPrinterByName( $value );
1005 // Printer may not be able to handle errors. This is particularly
1006 // likely if the module returns something for getCustomPrinter().
1007 if ( !$this->mPrinter
->canPrintErrors() ) {
1008 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1013 * Create an error message for the given exception.
1015 * If an ApiUsageException, errors/warnings will be extracted from the
1016 * embedded StatusValue.
1018 * If a base UsageException, the getMessageArray() method will be used to
1019 * extract the code and English message for a single error (no warnings).
1021 * Any other exception will be returned with a generic code and wrapper
1022 * text around the exception's (presumably English) message as a single
1023 * error (no warnings).
1025 * @param Exception $e
1026 * @param string $type 'error' or 'warning'
1027 * @return ApiMessage[]
1030 protected function errorMessagesFromException( $e, $type = 'error' ) {
1032 if ( $e instanceof ApiUsageException
) {
1033 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1034 $messages[] = ApiMessage
::create( $error );
1036 } elseif ( $type !== 'error' ) {
1037 // None of the rest have any messages for non-error types
1038 } elseif ( $e instanceof UsageException
) {
1039 // User entered incorrect parameters - generate error response
1040 $data = MediaWiki\
quietCall( [ $e, 'getMessageArray' ] );
1041 $code = $data['code'];
1042 $info = $data['info'];
1043 unset( $data['code'], $data['info'] );
1044 $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1046 // Something is seriously wrong
1047 $config = $this->getConfig();
1048 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1049 $code = 'internal_api_error_' . $class;
1050 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
1051 $params = [ 'apierror-databaseerror', WebRequest
::getRequestId() ];
1053 if ( $e instanceof ILocalizedException
) {
1054 $msg = $e->getMessageObject();
1055 } elseif ( $e instanceof MessageSpecifier
) {
1056 $msg = Message
::newFromSpecifier( $e );
1058 $msg = wfEscapeWikiText( $e->getMessage() );
1060 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1062 $messages[] = ApiMessage
::create( $params, $code );
1068 * Replace the result data with the information about an exception.
1069 * @param Exception $e
1070 * @return string[] Error codes
1072 protected function substituteResultWithError( $e ) {
1073 $result = $this->getResult();
1074 $formatter = $this->getErrorFormatter();
1075 $config = $this->getConfig();
1078 // Remember existing warnings and errors across the reset
1079 $errors = $result->getResultData( [ 'errors' ] );
1080 $warnings = $result->getResultData( [ 'warnings' ] );
1082 if ( $warnings !== null ) {
1083 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1085 if ( $errors !== null ) {
1086 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1088 // Collect the copied error codes for the return value
1089 foreach ( $errors as $error ) {
1090 if ( isset( $error['code'] ) ) {
1091 $errorCodes[$error['code']] = true;
1096 // Add errors from the exception
1097 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1098 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1099 $errorCodes[$msg->getApiCode()] = true;
1100 $formatter->addError( $modulePath, $msg );
1102 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1103 $formatter->addWarning( $modulePath, $msg );
1106 // Add additional data. Path depends on whether we're in BC mode or not.
1107 // Data depends on the type of exception.
1108 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1109 $path = [ 'error' ];
1113 if ( $e instanceof ApiUsageException ||
$e instanceof UsageException
) {
1114 $link = wfExpandUrl( wfScript( 'api' ) );
1115 $result->addContentValue(
1119 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1121 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1125 if ( $config->get( 'ShowExceptionDetails' ) &&
1126 ( !$e instanceof DBError ||
$config->get( 'ShowDBErrorBacktrace' ) )
1128 $result->addContentValue(
1131 $this->msg( 'api-exception-trace',
1135 MWExceptionHandler
::getRedactedTraceAsString( $e )
1136 )->inLanguage( $formatter->getLanguage() )->text()
1141 // Add the id and such
1142 $this->addRequestedFields( [ 'servedby' ] );
1144 return array_keys( $errorCodes );
1148 * Add requested fields to the result
1149 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1152 protected function addRequestedFields( $force = [] ) {
1153 $result = $this->getResult();
1155 $requestid = $this->getParameter( 'requestid' );
1156 if ( $requestid !== null ) {
1157 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1160 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1161 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1163 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1166 if ( $this->getParameter( 'curtimestamp' ) ) {
1167 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1168 ApiResult
::NO_SIZE_CHECK
);
1171 if ( $this->getParameter( 'responselanginfo' ) ) {
1172 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1173 ApiResult
::NO_SIZE_CHECK
);
1174 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1175 ApiResult
::NO_SIZE_CHECK
);
1180 * Set up for the execution.
1183 protected function setupExecuteAction() {
1184 $this->addRequestedFields();
1186 $params = $this->extractRequestParams();
1187 $this->mAction
= $params['action'];
1193 * Set up the module for response
1194 * @return ApiBase The module that will handle this action
1195 * @throws MWException
1196 * @throws ApiUsageException
1198 protected function setupModule() {
1199 // Instantiate the module requested by the user
1200 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1201 if ( $module === null ) {
1202 $this->dieWithError(
1203 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1206 $moduleParams = $module->extractRequestParams();
1208 // Check token, if necessary
1209 if ( $module->needsToken() === true ) {
1210 throw new MWException(
1211 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1212 'See documentation for ApiBase::needsToken for details.'
1215 if ( $module->needsToken() ) {
1216 if ( !$module->mustBePosted() ) {
1217 throw new MWException(
1218 "Module '{$module->getModuleName()}' must require POST to use tokens."
1222 if ( !isset( $moduleParams['token'] ) ) {
1223 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1226 $module->requirePostedParameters( [ 'token' ] );
1228 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1229 $module->dieWithError( 'apierror-badtoken' );
1239 private function getMaxLag() {
1240 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1242 'host' => $dbLag[0],
1247 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1248 if ( $jobQueueLagFactor ) {
1249 // Turn total number of jobs into seconds by using the configured value
1250 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1251 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1252 if ( $jobQueueLag > $lagInfo['lag'] ) {
1254 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1255 'lag' => $jobQueueLag,
1256 'type' => 'jobqueue',
1257 'jobs' => $totalJobs,
1266 * Check the max lag if necessary
1267 * @param ApiBase $module Api module being used
1268 * @param array $params Array an array containing the request parameters.
1269 * @return bool True on success, false should exit immediately
1271 protected function checkMaxLag( $module, $params ) {
1272 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1273 $maxLag = $params['maxlag'];
1274 $lagInfo = $this->getMaxLag();
1275 if ( $lagInfo['lag'] > $maxLag ) {
1276 $response = $this->getRequest()->response();
1278 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1279 $response->header( 'X-Database-Lag: ' . intval( $lagInfo['lag'] ) );
1281 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1282 $this->dieWithError(
1283 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1289 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1297 * Check selected RFC 7232 precondition headers
1299 * RFC 7232 envisions a particular model where you send your request to "a
1300 * resource", and for write requests that you can read "the resource" by
1301 * changing the method to GET. When the API receives a GET request, it
1302 * works out even though "the resource" from RFC 7232's perspective might
1303 * be many resources from MediaWiki's perspective. But it totally fails for
1304 * a POST, since what HTTP sees as "the resource" is probably just
1305 * "/api.php" with all the interesting bits in the body.
1307 * Therefore, we only support RFC 7232 precondition headers for GET (and
1308 * HEAD). That means we don't need to bother with If-Match and
1309 * If-Unmodified-Since since they only apply to modification requests.
1311 * And since we don't support Range, If-Range is ignored too.
1314 * @param ApiBase $module Api module being used
1315 * @return bool True on success, false should exit immediately
1317 protected function checkConditionalRequestHeaders( $module ) {
1318 if ( $this->mInternalMode
) {
1319 // No headers to check in internal mode
1323 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1324 // Don't check POSTs
1330 $ifNoneMatch = array_diff(
1331 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1334 if ( $ifNoneMatch ) {
1335 if ( $ifNoneMatch === [ '*' ] ) {
1336 // API responses always "exist"
1339 $etag = $module->getConditionalRequestData( 'etag' );
1342 if ( $ifNoneMatch && $etag !== null ) {
1343 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1344 $match = array_map( function ( $s ) {
1345 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1347 $return304 = in_array( $test, $match, true );
1349 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1351 // Some old browsers sends sizes after the date, like this:
1352 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1354 $i = strpos( $value, ';' );
1355 if ( $i !== false ) {
1356 $value = trim( substr( $value, 0, $i ) );
1359 if ( $value !== '' ) {
1361 $ts = new MWTimestamp( $value );
1363 // RFC 7231 IMF-fixdate
1364 $ts->getTimestamp( TS_RFC2822
) === $value ||
1366 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1367 // asctime (with and without space-padded day)
1368 $ts->format( 'D M j H:i:s Y' ) === $value ||
1369 $ts->format( 'D M j H:i:s Y' ) === $value
1371 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1372 if ( $lastMod !== null ) {
1373 // Mix in some MediaWiki modification times
1376 'user' => $this->getUser()->getTouched(),
1377 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1379 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1380 // T46570: the core page itself may not change, but resources might
1381 $modifiedTimes['sepoch'] = wfTimestamp(
1382 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1385 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1386 $lastMod = max( $modifiedTimes );
1387 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1390 } catch ( TimestampException
$e ) {
1391 // Invalid timestamp, ignore it
1397 $this->getRequest()->response()->statusHeader( 304 );
1399 // Avoid outputting the compressed representation of a zero-length body
1400 MediaWiki\
suppressWarnings();
1401 ini_set( 'zlib.output_compression', 0 );
1402 MediaWiki\restoreWarnings
();
1403 wfClearOutputBuffers();
1412 * Check for sufficient permissions to execute
1413 * @param ApiBase $module An Api module
1415 protected function checkExecutePermissions( $module ) {
1416 $user = $this->getUser();
1417 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1418 !$user->isAllowed( 'read' )
1420 $this->dieWithError( 'apierror-readapidenied' );
1423 if ( $module->isWriteMode() ) {
1424 if ( !$this->mEnableWrite
) {
1425 $this->dieWithError( 'apierror-noapiwrite' );
1426 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1427 $this->dieWithError( 'apierror-writeapidenied' );
1428 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1429 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1432 $this->checkReadOnly( $module );
1435 // Allow extensions to stop execution for arbitrary reasons.
1437 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1438 $this->dieWithError( $message );
1443 * Check if the DB is read-only for this user
1444 * @param ApiBase $module An Api module
1446 protected function checkReadOnly( $module ) {
1447 if ( wfReadOnly() ) {
1448 $this->dieReadOnly();
1451 if ( $module->isWriteMode()
1452 && $this->getUser()->isBot()
1453 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1455 $this->checkBotReadOnly();
1460 * Check whether we are readonly for bots
1462 private function checkBotReadOnly() {
1463 // Figure out how many servers have passed the lag threshold
1465 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1466 $laggedServers = [];
1467 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1468 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1469 if ( $lag > $lagLimit ) {
1471 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1475 // If a majority of replica DBs are too lagged then disallow writes
1476 $replicaCount = $loadBalancer->getServerCount() - 1;
1477 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1478 $laggedServers = implode( ', ', $laggedServers );
1481 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1484 $this->dieWithError(
1487 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1493 * Check asserts of the user's rights
1494 * @param array $params
1496 protected function checkAsserts( $params ) {
1497 if ( isset( $params['assert'] ) ) {
1498 $user = $this->getUser();
1499 switch ( $params['assert'] ) {
1501 if ( $user->isAnon() ) {
1502 $this->dieWithError( 'apierror-assertuserfailed' );
1506 if ( !$user->isAllowed( 'bot' ) ) {
1507 $this->dieWithError( 'apierror-assertbotfailed' );
1512 if ( isset( $params['assertuser'] ) ) {
1513 $assertUser = User
::newFromName( $params['assertuser'], false );
1514 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1515 $this->dieWithError(
1516 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1523 * Check POST for external response and setup result printer
1524 * @param ApiBase $module An Api module
1525 * @param array $params An array with the request parameters
1527 protected function setupExternalResponse( $module, $params ) {
1528 $request = $this->getRequest();
1529 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1530 // Module requires POST. GET request might still be allowed
1531 // if $wgDebugApi is true, otherwise fail.
1532 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1535 // See if custom printer is used
1536 $this->mPrinter
= $module->getCustomPrinter();
1537 if ( is_null( $this->mPrinter
) ) {
1538 // Create an appropriate printer
1539 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1542 if ( $request->getProtocol() === 'http' && (
1543 $request->getSession()->shouldForceHTTPS() ||
1544 ( $this->getUser()->isLoggedIn() &&
1545 $this->getUser()->requiresHTTPS() )
1547 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1552 * Execute the actual module, without any error handling
1554 protected function executeAction() {
1555 $params = $this->setupExecuteAction();
1556 $module = $this->setupModule();
1557 $this->mModule
= $module;
1559 if ( !$this->mInternalMode
) {
1560 $this->setRequestExpectations( $module );
1563 $this->checkExecutePermissions( $module );
1565 if ( !$this->checkMaxLag( $module, $params ) ) {
1569 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1573 if ( !$this->mInternalMode
) {
1574 $this->setupExternalResponse( $module, $params );
1577 $this->checkAsserts( $params );
1581 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1583 $this->reportUnusedParams();
1585 if ( !$this->mInternalMode
) {
1586 // append Debug information
1587 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1589 // Print result data
1590 $this->printResult();
1595 * Set database connection, query, and write expectations given this module request
1596 * @param ApiBase $module
1598 protected function setRequestExpectations( ApiBase
$module ) {
1599 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1600 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1601 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1602 if ( $this->getRequest()->hasSafeMethod() ) {
1603 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1604 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1605 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1606 $this->getRequest()->markAsSafeRequest();
1608 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1613 * Log the preceding request
1614 * @param float $time Time in seconds
1615 * @param Exception $e Exception caught while processing the request
1617 protected function logRequest( $time, $e = null ) {
1618 $request = $this->getRequest();
1621 'ip' => $request->getIP(),
1622 'userAgent' => $this->getUserAgent(),
1623 'wiki' => wfWikiID(),
1624 'timeSpentBackend' => (int)round( $time * 1000 ),
1625 'hadError' => $e !== null,
1631 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1632 $logCtx['errorCodes'][] = $msg->getApiCode();
1636 // Construct space separated message for 'api' log channel
1637 $msg = "API {$request->getMethod()} " .
1638 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1639 " {$logCtx['ip']} " .
1640 "T={$logCtx['timeSpentBackend']}ms";
1642 $sensitive = array_flip( $this->getSensitiveParams() );
1643 foreach ( $this->getParamsUsed() as $name ) {
1644 $value = $request->getVal( $name );
1645 if ( $value === null ) {
1649 if ( isset( $sensitive[$name] ) ) {
1650 $value = '[redacted]';
1651 $encValue = '[redacted]';
1652 } elseif ( strlen( $value ) > 256 ) {
1653 $value = substr( $value, 0, 256 );
1654 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1656 $encValue = $this->encodeRequestLogValue( $value );
1659 $logCtx['params'][$name] = $value;
1660 $msg .= " {$name}={$encValue}";
1663 wfDebugLog( 'api', $msg, 'private' );
1664 // ApiAction channel is for structured data consumers
1665 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1669 * Encode a value in a format suitable for a space-separated log line.
1673 protected function encodeRequestLogValue( $s ) {
1676 $chars = ';@$!*(),/:';
1677 $numChars = strlen( $chars );
1678 for ( $i = 0; $i < $numChars; $i++
) {
1679 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1683 return strtr( rawurlencode( $s ), $table );
1687 * Get the request parameters used in the course of the preceding execute() request
1690 protected function getParamsUsed() {
1691 return array_keys( $this->mParamsUsed
);
1695 * Mark parameters as used
1696 * @param string|string[] $params
1698 public function markParamsUsed( $params ) {
1699 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1703 * Get the request parameters that should be considered sensitive
1707 protected function getSensitiveParams() {
1708 return array_keys( $this->mParamsSensitive
);
1712 * Mark parameters as sensitive
1714 * @param string|string[] $params
1716 public function markParamsSensitive( $params ) {
1717 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1721 * Get a request value, and register the fact that it was used, for logging.
1722 * @param string $name
1723 * @param mixed $default
1726 public function getVal( $name, $default = null ) {
1727 $this->mParamsUsed
[$name] = true;
1729 $ret = $this->getRequest()->getVal( $name );
1730 if ( $ret === null ) {
1731 if ( $this->getRequest()->getArray( $name ) !== null ) {
1732 // See T12262 for why we don't just implode( '|', ... ) the
1734 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1742 * Get a boolean request value, and register the fact that the parameter
1743 * was used, for logging.
1744 * @param string $name
1747 public function getCheck( $name ) {
1748 return $this->getVal( $name, null ) !== null;
1752 * Get a request upload, and register the fact that it was used, for logging.
1755 * @param string $name Parameter name
1756 * @return WebRequestUpload
1758 public function getUpload( $name ) {
1759 $this->mParamsUsed
[$name] = true;
1761 return $this->getRequest()->getUpload( $name );
1765 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1766 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1768 protected function reportUnusedParams() {
1769 $paramsUsed = $this->getParamsUsed();
1770 $allParams = $this->getRequest()->getValueNames();
1772 if ( !$this->mInternalMode
) {
1773 // Printer has not yet executed; don't warn that its parameters are unused
1774 $printerParams = $this->mPrinter
->encodeParamName(
1775 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1777 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1779 $unusedParams = array_diff( $allParams, $paramsUsed );
1782 if ( count( $unusedParams ) ) {
1783 $this->addWarning( [
1784 'apierror-unrecognizedparams',
1785 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1786 count( $unusedParams )
1792 * Print results using the current printer
1794 * @param int $httpCode HTTP status code, or 0 to not change
1796 protected function printResult( $httpCode = 0 ) {
1797 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1798 $this->addWarning( 'apiwarn-wgDebugAPI' );
1801 $printer = $this->mPrinter
;
1802 $printer->initPrinter( false );
1804 $printer->setHttpStatus( $httpCode );
1806 $printer->execute();
1807 $printer->closePrinter();
1813 public function isReadMode() {
1818 * See ApiBase for description.
1822 public function getAllowedParams() {
1825 ApiBase
::PARAM_DFLT
=> 'help',
1826 ApiBase
::PARAM_TYPE
=> 'submodule',
1829 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1830 ApiBase
::PARAM_TYPE
=> 'submodule',
1833 ApiBase
::PARAM_TYPE
=> 'integer'
1836 ApiBase
::PARAM_TYPE
=> 'integer',
1837 ApiBase
::PARAM_DFLT
=> 0
1840 ApiBase
::PARAM_TYPE
=> 'integer',
1841 ApiBase
::PARAM_DFLT
=> 0
1844 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1847 ApiBase
::PARAM_TYPE
=> 'user',
1849 'requestid' => null,
1850 'servedby' => false,
1851 'curtimestamp' => false,
1852 'responselanginfo' => false,
1855 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1858 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1859 ApiBase
::PARAM_DFLT
=> 'bc',
1862 ApiBase
::PARAM_DFLT
=> 'uselang',
1864 'errorsuselocal' => [
1865 ApiBase
::PARAM_DFLT
=> false,
1871 protected function getExamplesMessages() {
1874 => 'apihelp-help-example-main',
1875 'action=help&recursivesubmodules=1'
1876 => 'apihelp-help-example-recursive',
1880 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1881 // Wish PHP had an "array_insert_before". Instead, we have to manually
1882 // reindex the array to get 'permissions' in the right place.
1885 foreach ( $oldHelp as $k => $v ) {
1886 if ( $k === 'submodules' ) {
1887 $help['permissions'] = '';
1891 $help['datatypes'] = '';
1892 $help['credits'] = '';
1894 // Fill 'permissions'
1895 $help['permissions'] .= Html
::openElement( 'div',
1896 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1897 $m = $this->msg( 'api-help-permissions' );
1898 if ( !$m->isDisabled() ) {
1899 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1900 $m->numParams( count( self
::$mRights ) )->parse()
1903 $help['permissions'] .= Html
::openElement( 'dl' );
1904 foreach ( self
::$mRights as $right => $rightMsg ) {
1905 $help['permissions'] .= Html
::element( 'dt', null, $right );
1907 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1908 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1910 $groups = array_map( function ( $group ) {
1911 return $group == '*' ?
'all' : $group;
1912 }, User
::getGroupsWithPermission( $right ) );
1914 $help['permissions'] .= Html
::rawElement( 'dd', null,
1915 $this->msg( 'api-help-permissions-granted-to' )
1916 ->numParams( count( $groups ) )
1917 ->params( Message
::listParam( $groups ) )
1921 $help['permissions'] .= Html
::closeElement( 'dl' );
1922 $help['permissions'] .= Html
::closeElement( 'div' );
1924 // Fill 'datatypes' and 'credits', if applicable
1925 if ( empty( $options['nolead'] ) ) {
1926 $level = $options['headerlevel'];
1927 $tocnumber = &$options['tocnumber'];
1929 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1931 $id = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_PRIMARY
);
1932 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/datatypes', Sanitizer
::ID_FALLBACK
);
1933 $headline = Linker
::makeHeadline( min( 6, $level ),
1934 ' class="apihelp-header">',
1940 // Ensure we have a sane anchor
1941 if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1942 $headline = '<div id="main/datatypes"></div>' . $headline;
1944 $help['datatypes'] .= $headline;
1945 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1946 if ( !isset( $tocData['main/datatypes'] ) ) {
1947 $tocnumber[$level]++
;
1948 $tocData['main/datatypes'] = [
1949 'toclevel' => count( $tocnumber ),
1951 'anchor' => 'main/datatypes',
1953 'number' => implode( '.', $tocnumber ),
1958 $header = $this->msg( 'api-credits-header' )->parse();
1959 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
1960 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', 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/credits' && $idFallback !== 'main/credits' ) {
1970 $headline = '<div id="main/credits"></div>' . $headline;
1972 $help['credits'] .= $headline;
1973 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1974 if ( !isset( $tocData['main/credits'] ) ) {
1975 $tocnumber[$level]++
;
1976 $tocData['main/credits'] = [
1977 'toclevel' => count( $tocnumber ),
1979 'anchor' => 'main/credits',
1981 'number' => implode( '.', $tocnumber ),
1988 private $mCanApiHighLimits = null;
1991 * Check whether the current user is allowed to use high limits
1994 public function canApiHighLimits() {
1995 if ( !isset( $this->mCanApiHighLimits
) ) {
1996 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1999 return $this->mCanApiHighLimits
;
2003 * Overrides to return this instance's module manager.
2004 * @return ApiModuleManager
2006 public function getModuleManager() {
2007 return $this->mModuleMgr
;
2011 * Fetches the user agent used for this request
2013 * The value will be the combination of the 'Api-User-Agent' header (if
2014 * any) and the standard User-Agent header (if any).
2018 public function getUserAgent() {
2020 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2021 $this->getRequest()->getHeader( 'User-agent' )
2027 * For really cool vim folding this needs to be at the end:
2028 * vim: foldmarker=@{,@} foldmethod=marker