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( ApiContinuationManager
$manager = null ) {
372 if ( $manager !== null && $this->mContinuationManager
!== null ) {
373 throw new UnexpectedValueException(
374 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
375 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
378 $this->mContinuationManager
= $manager;
382 * Get the API module object. Only works after executeAction()
386 public function getModule() {
387 return $this->mModule
;
391 * Get the result formatter object. Only works after setupExecuteAction()
393 * @return ApiFormatBase
395 public function getPrinter() {
396 return $this->mPrinter
;
400 * Set how long the response should be cached.
404 public function setCacheMaxAge( $maxage ) {
405 $this->setCacheControl( [
406 'max-age' => $maxage,
407 's-maxage' => $maxage
412 * Set the type of caching headers which will be sent.
414 * @param string $mode One of:
415 * - 'public': Cache this object in public caches, if the maxage or smaxage
416 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
417 * not provided by any of these means, the object will be private.
418 * - 'private': Cache this object only in private client-side caches.
419 * - 'anon-public-user-private': Make this object cacheable for logged-out
420 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
421 * set consistently for a given URL, it cannot be set differently depending on
422 * things like the contents of the database, or whether the user is logged in.
424 * If the wiki does not allow anonymous users to read it, the mode set here
425 * will be ignored, and private caching headers will always be sent. In other words,
426 * the "public" mode is equivalent to saying that the data sent is as public as a page
429 * For user-dependent data, the private mode should generally be used. The
430 * anon-public-user-private mode should only be used where there is a particularly
431 * good performance reason for caching the anonymous response, but where the
432 * response to logged-in users may differ, or may contain private data.
434 * If this function is never called, then the default will be the private mode.
436 public function setCacheMode( $mode ) {
437 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
438 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
440 // Ignore for forwards-compatibility
444 if ( !User
::isEveryoneAllowed( 'read' ) ) {
445 // Private wiki, only private headers
446 if ( $mode !== 'private' ) {
447 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
453 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
454 // User language is used for i18n, so we don't want to publicly
455 // cache. Anons are ok, because if they have non-default language
456 // then there's an appropriate Vary header set by whatever set
457 // their non-default language.
458 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
459 "'anon-public-user-private' due to uselang=user\n" );
460 $mode = 'anon-public-user-private';
463 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
464 $this->mCacheMode
= $mode;
468 * Set directives (key/value pairs) for the Cache-Control header.
469 * Boolean values will be formatted as such, by including or omitting
470 * without an equals sign.
472 * Cache control values set here will only be used if the cache mode is not
473 * private, see setCacheMode().
475 * @param array $directives
477 public function setCacheControl( $directives ) {
478 $this->mCacheControl
= $directives +
$this->mCacheControl
;
482 * Create an instance of an output formatter by its name
484 * @param string $format
486 * @return ApiFormatBase
488 public function createPrinterByName( $format ) {
489 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
490 if ( $printer === null ) {
492 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
500 * Execute api request. Any errors will be handled if the API was called by the remote client.
502 public function execute() {
503 if ( $this->mInternalMode
) {
504 $this->executeAction();
506 $this->executeActionWithErrorHandling();
511 * Execute an action, and in case of an error, erase whatever partial results
512 * have been accumulated, and replace it with an error message and a help screen.
514 protected function executeActionWithErrorHandling() {
515 // Verify the CORS header before executing the action
516 if ( !$this->handleCORS() ) {
517 // handleCORS() has sent a 403, abort
521 // Exit here if the request method was OPTIONS
522 // (assume there will be a followup GET or POST)
523 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
527 // In case an error occurs during data output,
528 // clear the output buffer and print just the error information
529 $obLevel = ob_get_level();
532 $t = microtime( true );
535 $this->executeAction();
536 $runTime = microtime( true ) - $t;
537 $this->logRequest( $runTime );
538 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
539 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
540 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
543 } catch ( Exception
$e ) {
544 $this->handleException( $e );
545 $this->logRequest( microtime( true ) - $t, $e );
549 // Commit DBs and send any related cookies and headers
550 MediaWiki
::preOutputCommit( $this->getContext() );
552 // Send cache headers after any code which might generate an error, to
553 // avoid sending public cache headers for errors.
554 $this->sendCacheHeaders( $isError );
556 // Executing the action might have already messed with the output
558 while ( ob_get_level() > $obLevel ) {
564 * Handle an exception as an API response
567 * @param Exception $e
569 protected function handleException( Exception
$e ) {
570 // T65145: Rollback any open database transactions
571 if ( !( $e instanceof ApiUsageException ||
$e instanceof UsageException
) ) {
572 // UsageExceptions are intentional, so don't rollback if that's the case
573 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
576 // Allow extra cleanup and logging
577 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
579 // Handle any kind of exception by outputting properly formatted error message.
580 // If this fails, an unhandled exception should be thrown so that global error
581 // handler will process and log it.
583 $errCodes = $this->substituteResultWithError( $e );
585 // Error results should not be cached
586 $this->setCacheMode( 'private' );
588 $response = $this->getRequest()->response();
589 $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
590 $response->header( $headerStr );
592 // Reset and print just the error message
595 // Printer may not be initialized if the extractRequestParams() fails for the main module
596 $this->createErrorPrinter();
600 $this->printResult( $e->getCode() );
601 } catch ( ApiUsageException
$ex ) {
602 // The error printer itself is failing. Try suppressing its request
603 // parameters and redo.
605 $this->addWarning( 'apiwarn-errorprinterfailed' );
606 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
608 $this->mPrinter
->addWarning( $error );
609 } catch ( Exception
$ex2 ) {
611 $this->addWarning( $error );
614 } catch ( UsageException
$ex ) {
615 // The error printer itself is failing. Try suppressing its request
616 // parameters and redo.
619 [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
623 $this->mPrinter
= null;
624 $this->createErrorPrinter();
625 $this->mPrinter
->forceDefaultParams();
626 if ( $e->getCode() ) {
627 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
629 $this->printResult( $e->getCode() );
634 * Handle an exception from the ApiBeforeMain hook.
636 * This tries to print the exception as an API response, to be more
637 * friendly to clients. If it fails, it will rethrow the exception.
640 * @param Exception $e
643 public static function handleApiBeforeMainException( Exception
$e ) {
647 $main = new self( RequestContext
::getMain(), false );
648 $main->handleException( $e );
649 $main->logRequest( 0, $e );
650 } catch ( Exception
$e2 ) {
651 // Nope, even that didn't work. Punt.
655 // Reset cache headers
656 $main->sendCacheHeaders( true );
662 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
664 * If no origin parameter is present, nothing happens.
665 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
666 * is set and false is returned.
667 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
668 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
670 * https://www.w3.org/TR/cors/#resource-requests
671 * https://www.w3.org/TR/cors/#resource-preflight-requests
673 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
675 protected function handleCORS() {
676 $originParam = $this->getParameter( 'origin' ); // defaults to null
677 if ( $originParam === null ) {
678 // No origin parameter, nothing to do
682 $request = $this->getRequest();
683 $response = $request->response();
685 $matchedOrigin = false;
686 $allowTiming = false;
689 if ( $originParam === '*' ) {
690 // Request for anonymous CORS
691 // Technically we should check for the presence of an Origin header
692 // and not process it as CORS if it's not set, but that would
693 // require us to vary on Origin for all 'origin=*' requests which
694 // we don't want to do.
695 $matchedOrigin = true;
697 $allowCredentials = 'false';
698 $varyOrigin = false; // No need to vary
700 // Non-anonymous CORS, check we allow the domain
702 // Origin: header is a space-separated list of origins, check all of them
703 $originHeader = $request->getHeader( 'Origin' );
704 if ( $originHeader === false ) {
707 $originHeader = trim( $originHeader );
708 $origins = preg_split( '/\s+/', $originHeader );
711 if ( !in_array( $originParam, $origins ) ) {
712 // origin parameter set but incorrect
713 // Send a 403 response
714 $response->statusHeader( 403 );
715 $response->header( 'Cache-Control: no-cache' );
716 echo "'origin' parameter does not match Origin header\n";
721 $config = $this->getConfig();
722 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
724 $config->get( 'CrossSiteAJAXdomains' ),
725 $config->get( 'CrossSiteAJAXdomainExceptions' )
728 $allowOrigin = $originHeader;
729 $allowCredentials = 'true';
730 $allowTiming = $originHeader;
733 if ( $matchedOrigin ) {
734 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
735 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
737 // This is a CORS preflight request
738 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
739 // If method is not a case-sensitive match, do not set any additional headers and terminate.
740 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
743 // We allow the actual request to send the following headers
744 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
745 if ( $requestedHeaders !== false ) {
746 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
747 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
750 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
753 // We only allow the actual request to be GET or POST
754 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
755 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
756 // Unsupported non-preflight method, don't handle it as CORS
758 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
763 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
764 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
765 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
766 if ( $allowTiming !== false ) {
767 $response->header( "Timing-Allow-Origin: $allowTiming" );
772 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
773 . 'MediaWiki-Login-Suppressed'
777 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
781 $this->getOutput()->addVaryHeader( 'Origin' );
788 * Attempt to match an Origin header against a set of rules and a set of exceptions
789 * @param string $value Origin header
790 * @param array $rules Set of wildcard rules
791 * @param array $exceptions Set of wildcard rules
792 * @return bool True if $value matches a rule in $rules and doesn't match
793 * any rules in $exceptions, false otherwise
795 protected static function matchOrigin( $value, $rules, $exceptions ) {
796 foreach ( $rules as $rule ) {
797 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
798 // Rule matches, check exceptions
799 foreach ( $exceptions as $exc ) {
800 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
813 * Attempt to validate the value of Access-Control-Request-Headers against a list
814 * of headers that we allow the follow up request to send.
816 * @param string $requestedHeaders Comma seperated list of HTTP headers
817 * @return bool True if all requested headers are in the list of allowed headers
819 protected static function matchRequestedHeaders( $requestedHeaders ) {
820 if ( trim( $requestedHeaders ) === '' ) {
823 $requestedHeaders = explode( ',', $requestedHeaders );
824 $allowedAuthorHeaders = array_flip( [
825 /* simple headers (see spec) */
830 /* non-authorable headers in XHR, which are however requested by some UAs */
834 /* MediaWiki whitelist */
837 foreach ( $requestedHeaders as $rHeader ) {
838 $rHeader = strtolower( trim( $rHeader ) );
839 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
840 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
848 * Helper function to convert wildcard string into a regex
852 * @param string $wildcard String with wildcards
853 * @return string Regular expression
855 protected static function wildcardToRegex( $wildcard ) {
856 $wildcard = preg_quote( $wildcard, '/' );
857 $wildcard = str_replace(
863 return "/^https?:\/\/$wildcard$/";
867 * Send caching headers
868 * @param bool $isError Whether an error response is being output
869 * @since 1.26 added $isError parameter
871 protected function sendCacheHeaders( $isError ) {
872 $response = $this->getRequest()->response();
873 $out = $this->getOutput();
875 $out->addVaryHeader( 'Treat-as-Untrusted' );
877 $config = $this->getConfig();
879 if ( $config->get( 'VaryOnXFP' ) ) {
880 $out->addVaryHeader( 'X-Forwarded-Proto' );
883 if ( !$isError && $this->mModule
&&
884 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
886 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
887 if ( $etag !== null ) {
888 $response->header( "ETag: $etag" );
890 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
891 if ( $lastMod !== null ) {
892 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
896 // The logic should be:
897 // $this->mCacheControl['max-age'] is set?
898 // Use it, the module knows better than our guess.
899 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
900 // Use 0 because we can guess caching is probably the wrong thing to do.
901 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
903 if ( isset( $this->mCacheControl
['max-age'] ) ) {
904 $maxage = $this->mCacheControl
['max-age'];
905 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
906 $this->mCacheMode
!== 'private'
908 $maxage = $this->getParameter( 'maxage' );
910 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
912 if ( $this->mCacheMode
== 'private' ) {
913 $response->header( "Cache-Control: $privateCache" );
917 $useKeyHeader = $config->get( 'UseKeyHeader' );
918 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
919 $out->addVaryHeader( 'Cookie' );
920 $response->header( $out->getVaryHeader() );
921 if ( $useKeyHeader ) {
922 $response->header( $out->getKeyHeader() );
923 if ( $out->haveCacheVaryCookies() ) {
924 // Logged in, mark this request private
925 $response->header( "Cache-Control: $privateCache" );
928 // Logged out, send normal public headers below
929 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
930 // Logged in or otherwise has session (e.g. anonymous users who have edited)
931 // Mark request private
932 $response->header( "Cache-Control: $privateCache" );
935 } // else no Key and anonymous, send public headers below
938 // Send public headers
939 $response->header( $out->getVaryHeader() );
940 if ( $useKeyHeader ) {
941 $response->header( $out->getKeyHeader() );
944 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
945 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
946 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
948 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
949 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
952 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
953 // Public cache not requested
954 // Sending a Vary header in this case is harmless, and protects us
955 // against conditional calls of setCacheMaxAge().
956 $response->header( "Cache-Control: $privateCache" );
961 $this->mCacheControl
['public'] = true;
963 // Send an Expires header
964 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
965 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
966 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
968 // Construct the Cache-Control header
971 foreach ( $this->mCacheControl
as $name => $value ) {
972 if ( is_bool( $value ) ) {
974 $ccHeader .= $separator . $name;
978 $ccHeader .= $separator . "$name=$value";
983 $response->header( "Cache-Control: $ccHeader" );
987 * Create the printer for error output
989 private function createErrorPrinter() {
990 if ( !isset( $this->mPrinter
) ) {
991 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
992 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
993 $value = self
::API_DEFAULT_FORMAT
;
995 $this->mPrinter
= $this->createPrinterByName( $value );
998 // Printer may not be able to handle errors. This is particularly
999 // likely if the module returns something for getCustomPrinter().
1000 if ( !$this->mPrinter
->canPrintErrors() ) {
1001 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1006 * Create an error message for the given exception.
1008 * If an ApiUsageException, errors/warnings will be extracted from the
1009 * embedded StatusValue.
1011 * If a base UsageException, the getMessageArray() method will be used to
1012 * extract the code and English message for a single error (no warnings).
1014 * Any other exception will be returned with a generic code and wrapper
1015 * text around the exception's (presumably English) message as a single
1016 * error (no warnings).
1018 * @param Exception $e
1019 * @param string $type 'error' or 'warning'
1020 * @return ApiMessage[]
1023 protected function errorMessagesFromException( $e, $type = 'error' ) {
1025 if ( $e instanceof ApiUsageException
) {
1026 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1027 $messages[] = ApiMessage
::create( $error );
1029 } elseif ( $type !== 'error' ) {
1030 // None of the rest have any messages for non-error types
1031 } elseif ( $e instanceof UsageException
) {
1032 // User entered incorrect parameters - generate error response
1033 $data = Wikimedia\
quietCall( [ $e, 'getMessageArray' ] );
1034 $code = $data['code'];
1035 $info = $data['info'];
1036 unset( $data['code'], $data['info'] );
1037 $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1039 // Something is seriously wrong
1040 $config = $this->getConfig();
1041 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1042 $code = 'internal_api_error_' . $class;
1043 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
1044 $params = [ 'apierror-databaseerror', WebRequest
::getRequestId() ];
1046 if ( $e instanceof ILocalizedException
) {
1047 $msg = $e->getMessageObject();
1048 } elseif ( $e instanceof MessageSpecifier
) {
1049 $msg = Message
::newFromSpecifier( $e );
1051 $msg = wfEscapeWikiText( $e->getMessage() );
1053 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1055 $messages[] = ApiMessage
::create( $params, $code );
1061 * Replace the result data with the information about an exception.
1062 * @param Exception $e
1063 * @return string[] Error codes
1065 protected function substituteResultWithError( $e ) {
1066 $result = $this->getResult();
1067 $formatter = $this->getErrorFormatter();
1068 $config = $this->getConfig();
1071 // Remember existing warnings and errors across the reset
1072 $errors = $result->getResultData( [ 'errors' ] );
1073 $warnings = $result->getResultData( [ 'warnings' ] );
1075 if ( $warnings !== null ) {
1076 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1078 if ( $errors !== null ) {
1079 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1081 // Collect the copied error codes for the return value
1082 foreach ( $errors as $error ) {
1083 if ( isset( $error['code'] ) ) {
1084 $errorCodes[$error['code']] = true;
1089 // Add errors from the exception
1090 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1091 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1092 $errorCodes[$msg->getApiCode()] = true;
1093 $formatter->addError( $modulePath, $msg );
1095 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1096 $formatter->addWarning( $modulePath, $msg );
1099 // Add additional data. Path depends on whether we're in BC mode or not.
1100 // Data depends on the type of exception.
1101 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1102 $path = [ 'error' ];
1106 if ( $e instanceof ApiUsageException ||
$e instanceof UsageException
) {
1107 $link = wfExpandUrl( wfScript( 'api' ) );
1108 $result->addContentValue(
1112 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1114 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1118 if ( $config->get( 'ShowExceptionDetails' ) &&
1119 ( !$e instanceof DBError ||
$config->get( 'ShowDBErrorBacktrace' ) )
1121 $result->addContentValue(
1124 $this->msg( 'api-exception-trace',
1128 MWExceptionHandler
::getRedactedTraceAsString( $e )
1129 )->inLanguage( $formatter->getLanguage() )->text()
1134 // Add the id and such
1135 $this->addRequestedFields( [ 'servedby' ] );
1137 return array_keys( $errorCodes );
1141 * Add requested fields to the result
1142 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1145 protected function addRequestedFields( $force = [] ) {
1146 $result = $this->getResult();
1148 $requestid = $this->getParameter( 'requestid' );
1149 if ( $requestid !== null ) {
1150 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1153 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1154 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1156 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1159 if ( $this->getParameter( 'curtimestamp' ) ) {
1160 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1161 ApiResult
::NO_SIZE_CHECK
);
1164 if ( $this->getParameter( 'responselanginfo' ) ) {
1165 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1166 ApiResult
::NO_SIZE_CHECK
);
1167 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1168 ApiResult
::NO_SIZE_CHECK
);
1173 * Set up for the execution.
1176 protected function setupExecuteAction() {
1177 $this->addRequestedFields();
1179 $params = $this->extractRequestParams();
1180 $this->mAction
= $params['action'];
1186 * Set up the module for response
1187 * @return ApiBase The module that will handle this action
1188 * @throws MWException
1189 * @throws ApiUsageException
1191 protected function setupModule() {
1192 // Instantiate the module requested by the user
1193 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1194 if ( $module === null ) {
1195 // Probably can't happen
1196 // @codeCoverageIgnoreStart
1197 $this->dieWithError(
1198 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1200 // @codeCoverageIgnoreEnd
1202 $moduleParams = $module->extractRequestParams();
1204 // Check token, if necessary
1205 if ( $module->needsToken() === true ) {
1206 throw new MWException(
1207 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1208 'See documentation for ApiBase::needsToken for details.'
1211 if ( $module->needsToken() ) {
1212 if ( !$module->mustBePosted() ) {
1213 throw new MWException(
1214 "Module '{$module->getModuleName()}' must require POST to use tokens."
1218 if ( !isset( $moduleParams['token'] ) ) {
1219 // Probably can't happen
1220 // @codeCoverageIgnoreStart
1221 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1222 // @codeCoverageIgnoreEnd
1225 $module->requirePostedParameters( [ 'token' ] );
1227 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1228 $module->dieWithError( 'apierror-badtoken' );
1238 private function getMaxLag() {
1239 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1241 'host' => $dbLag[0],
1246 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1247 if ( $jobQueueLagFactor ) {
1248 // Turn total number of jobs into seconds by using the configured value
1249 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1250 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1251 if ( $jobQueueLag > $lagInfo['lag'] ) {
1253 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1254 'lag' => $jobQueueLag,
1255 'type' => 'jobqueue',
1256 'jobs' => $totalJobs,
1261 Hooks
::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1267 * Check the max lag if necessary
1268 * @param ApiBase $module Api module being used
1269 * @param array $params Array an array containing the request parameters.
1270 * @return bool True on success, false should exit immediately
1272 protected function checkMaxLag( $module, $params ) {
1273 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1274 $maxLag = $params['maxlag'];
1275 $lagInfo = $this->getMaxLag();
1276 if ( $lagInfo['lag'] > $maxLag ) {
1277 $response = $this->getRequest()->response();
1279 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1280 $response->header( 'X-Database-Lag: ' . intval( $lagInfo['lag'] ) );
1282 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1283 $this->dieWithError(
1284 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1290 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1298 * Check selected RFC 7232 precondition headers
1300 * RFC 7232 envisions a particular model where you send your request to "a
1301 * resource", and for write requests that you can read "the resource" by
1302 * changing the method to GET. When the API receives a GET request, it
1303 * works out even though "the resource" from RFC 7232's perspective might
1304 * be many resources from MediaWiki's perspective. But it totally fails for
1305 * a POST, since what HTTP sees as "the resource" is probably just
1306 * "/api.php" with all the interesting bits in the body.
1308 * Therefore, we only support RFC 7232 precondition headers for GET (and
1309 * HEAD). That means we don't need to bother with If-Match and
1310 * If-Unmodified-Since since they only apply to modification requests.
1312 * And since we don't support Range, If-Range is ignored too.
1315 * @param ApiBase $module Api module being used
1316 * @return bool True on success, false should exit immediately
1318 protected function checkConditionalRequestHeaders( $module ) {
1319 if ( $this->mInternalMode
) {
1320 // No headers to check in internal mode
1324 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1325 // Don't check POSTs
1331 $ifNoneMatch = array_diff(
1332 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1335 if ( $ifNoneMatch ) {
1336 if ( $ifNoneMatch === [ '*' ] ) {
1337 // API responses always "exist"
1340 $etag = $module->getConditionalRequestData( 'etag' );
1343 if ( $ifNoneMatch && $etag !== null ) {
1344 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1345 $match = array_map( function ( $s ) {
1346 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1348 $return304 = in_array( $test, $match, true );
1350 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1352 // Some old browsers sends sizes after the date, like this:
1353 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1355 $i = strpos( $value, ';' );
1356 if ( $i !== false ) {
1357 $value = trim( substr( $value, 0, $i ) );
1360 if ( $value !== '' ) {
1362 $ts = new MWTimestamp( $value );
1364 // RFC 7231 IMF-fixdate
1365 $ts->getTimestamp( TS_RFC2822
) === $value ||
1367 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1368 // asctime (with and without space-padded day)
1369 $ts->format( 'D M j H:i:s Y' ) === $value ||
1370 $ts->format( 'D M j H:i:s Y' ) === $value
1372 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1373 if ( $lastMod !== null ) {
1374 // Mix in some MediaWiki modification times
1377 'user' => $this->getUser()->getTouched(),
1378 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1380 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1381 // T46570: the core page itself may not change, but resources might
1382 $modifiedTimes['sepoch'] = wfTimestamp(
1383 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1386 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1387 $lastMod = max( $modifiedTimes );
1388 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1391 } catch ( TimestampException
$e ) {
1392 // Invalid timestamp, ignore it
1398 $this->getRequest()->response()->statusHeader( 304 );
1400 // Avoid outputting the compressed representation of a zero-length body
1401 Wikimedia\
suppressWarnings();
1402 ini_set( 'zlib.output_compression', 0 );
1403 Wikimedia\restoreWarnings
();
1404 wfClearOutputBuffers();
1413 * Check for sufficient permissions to execute
1414 * @param ApiBase $module An Api module
1416 protected function checkExecutePermissions( $module ) {
1417 $user = $this->getUser();
1418 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1419 !$user->isAllowed( 'read' )
1421 $this->dieWithError( 'apierror-readapidenied' );
1424 if ( $module->isWriteMode() ) {
1425 if ( !$this->mEnableWrite
) {
1426 $this->dieWithError( 'apierror-noapiwrite' );
1427 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1428 $this->dieWithError( 'apierror-writeapidenied' );
1429 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1430 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1433 $this->checkReadOnly( $module );
1436 // Allow extensions to stop execution for arbitrary reasons.
1437 $message = 'hookaborted';
1438 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1439 $this->dieWithError( $message );
1444 * Check if the DB is read-only for this user
1445 * @param ApiBase $module An Api module
1447 protected function checkReadOnly( $module ) {
1448 if ( wfReadOnly() ) {
1449 $this->dieReadOnly();
1452 if ( $module->isWriteMode()
1453 && $this->getUser()->isBot()
1454 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1456 $this->checkBotReadOnly();
1461 * Check whether we are readonly for bots
1463 private function checkBotReadOnly() {
1464 // Figure out how many servers have passed the lag threshold
1466 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1467 $laggedServers = [];
1468 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1469 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1470 if ( $lag > $lagLimit ) {
1472 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1476 // If a majority of replica DBs are too lagged then disallow writes
1477 $replicaCount = $loadBalancer->getServerCount() - 1;
1478 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1479 $laggedServers = implode( ', ', $laggedServers );
1482 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1485 $this->dieWithError(
1488 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1494 * Check asserts of the user's rights
1495 * @param array $params
1497 protected function checkAsserts( $params ) {
1498 if ( isset( $params['assert'] ) ) {
1499 $user = $this->getUser();
1500 switch ( $params['assert'] ) {
1502 if ( $user->isAnon() ) {
1503 $this->dieWithError( 'apierror-assertuserfailed' );
1507 if ( !$user->isAllowed( 'bot' ) ) {
1508 $this->dieWithError( 'apierror-assertbotfailed' );
1513 if ( isset( $params['assertuser'] ) ) {
1514 $assertUser = User
::newFromName( $params['assertuser'], false );
1515 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1516 $this->dieWithError(
1517 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1524 * Check POST for external response and setup result printer
1525 * @param ApiBase $module An Api module
1526 * @param array $params An array with the request parameters
1528 protected function setupExternalResponse( $module, $params ) {
1529 $request = $this->getRequest();
1530 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1531 // Module requires POST. GET request might still be allowed
1532 // if $wgDebugApi is true, otherwise fail.
1533 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1536 // See if custom printer is used
1537 $this->mPrinter
= $module->getCustomPrinter();
1538 if ( is_null( $this->mPrinter
) ) {
1539 // Create an appropriate printer
1540 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1543 if ( $request->getProtocol() === 'http' && (
1544 $request->getSession()->shouldForceHTTPS() ||
1545 ( $this->getUser()->isLoggedIn() &&
1546 $this->getUser()->requiresHTTPS() )
1548 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1553 * Execute the actual module, without any error handling
1555 protected function executeAction() {
1556 $params = $this->setupExecuteAction();
1557 $module = $this->setupModule();
1558 $this->mModule
= $module;
1560 if ( !$this->mInternalMode
) {
1561 $this->setRequestExpectations( $module );
1564 $this->checkExecutePermissions( $module );
1566 if ( !$this->checkMaxLag( $module, $params ) ) {
1570 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1574 if ( !$this->mInternalMode
) {
1575 $this->setupExternalResponse( $module, $params );
1578 $this->checkAsserts( $params );
1582 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1584 $this->reportUnusedParams();
1586 if ( !$this->mInternalMode
) {
1587 // append Debug information
1588 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1590 // Print result data
1591 $this->printResult();
1596 * Set database connection, query, and write expectations given this module request
1597 * @param ApiBase $module
1599 protected function setRequestExpectations( ApiBase
$module ) {
1600 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1601 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1602 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1603 if ( $this->getRequest()->hasSafeMethod() ) {
1604 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1605 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1606 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1607 $this->getRequest()->markAsSafeRequest();
1609 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1614 * Log the preceding request
1615 * @param float $time Time in seconds
1616 * @param Exception $e Exception caught while processing the request
1618 protected function logRequest( $time, $e = null ) {
1619 $request = $this->getRequest();
1622 'ip' => $request->getIP(),
1623 'userAgent' => $this->getUserAgent(),
1624 'wiki' => wfWikiID(),
1625 'timeSpentBackend' => (int)round( $time * 1000 ),
1626 'hadError' => $e !== null,
1632 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1633 $logCtx['errorCodes'][] = $msg->getApiCode();
1637 // Construct space separated message for 'api' log channel
1638 $msg = "API {$request->getMethod()} " .
1639 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1640 " {$logCtx['ip']} " .
1641 "T={$logCtx['timeSpentBackend']}ms";
1643 $sensitive = array_flip( $this->getSensitiveParams() );
1644 foreach ( $this->getParamsUsed() as $name ) {
1645 $value = $request->getVal( $name );
1646 if ( $value === null ) {
1650 if ( isset( $sensitive[$name] ) ) {
1651 $value = '[redacted]';
1652 $encValue = '[redacted]';
1653 } elseif ( strlen( $value ) > 256 ) {
1654 $value = substr( $value, 0, 256 );
1655 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1657 $encValue = $this->encodeRequestLogValue( $value );
1660 $logCtx['params'][$name] = $value;
1661 $msg .= " {$name}={$encValue}";
1664 wfDebugLog( 'api', $msg, 'private' );
1665 // ApiAction channel is for structured data consumers
1666 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1670 * Encode a value in a format suitable for a space-separated log line.
1674 protected function encodeRequestLogValue( $s ) {
1677 $chars = ';@$!*(),/:';
1678 $numChars = strlen( $chars );
1679 for ( $i = 0; $i < $numChars; $i++
) {
1680 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1684 return strtr( rawurlencode( $s ), $table );
1688 * Get the request parameters used in the course of the preceding execute() request
1691 protected function getParamsUsed() {
1692 return array_keys( $this->mParamsUsed
);
1696 * Mark parameters as used
1697 * @param string|string[] $params
1699 public function markParamsUsed( $params ) {
1700 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1704 * Get the request parameters that should be considered sensitive
1708 protected function getSensitiveParams() {
1709 return array_keys( $this->mParamsSensitive
);
1713 * Mark parameters as sensitive
1715 * @param string|string[] $params
1717 public function markParamsSensitive( $params ) {
1718 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1722 * Get a request value, and register the fact that it was used, for logging.
1723 * @param string $name
1724 * @param string|null $default
1725 * @return string|null
1727 public function getVal( $name, $default = null ) {
1728 $this->mParamsUsed
[$name] = true;
1730 $ret = $this->getRequest()->getVal( $name );
1731 if ( $ret === null ) {
1732 if ( $this->getRequest()->getArray( $name ) !== null ) {
1733 // See T12262 for why we don't just implode( '|', ... ) the
1735 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1743 * Get a boolean request value, and register the fact that the parameter
1744 * was used, for logging.
1745 * @param string $name
1748 public function getCheck( $name ) {
1749 return $this->getVal( $name, null ) !== null;
1753 * Get a request upload, and register the fact that it was used, for logging.
1756 * @param string $name Parameter name
1757 * @return WebRequestUpload
1759 public function getUpload( $name ) {
1760 $this->mParamsUsed
[$name] = true;
1762 return $this->getRequest()->getUpload( $name );
1766 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1767 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1769 protected function reportUnusedParams() {
1770 $paramsUsed = $this->getParamsUsed();
1771 $allParams = $this->getRequest()->getValueNames();
1773 if ( !$this->mInternalMode
) {
1774 // Printer has not yet executed; don't warn that its parameters are unused
1775 $printerParams = $this->mPrinter
->encodeParamName(
1776 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1778 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1780 $unusedParams = array_diff( $allParams, $paramsUsed );
1783 if ( count( $unusedParams ) ) {
1784 $this->addWarning( [
1785 'apierror-unrecognizedparams',
1786 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1787 count( $unusedParams )
1793 * Print results using the current printer
1795 * @param int $httpCode HTTP status code, or 0 to not change
1797 protected function printResult( $httpCode = 0 ) {
1798 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1799 $this->addWarning( 'apiwarn-wgDebugAPI' );
1802 $printer = $this->mPrinter
;
1803 $printer->initPrinter( false );
1805 $printer->setHttpStatus( $httpCode );
1807 $printer->execute();
1808 $printer->closePrinter();
1814 public function isReadMode() {
1819 * See ApiBase for description.
1823 public function getAllowedParams() {
1826 ApiBase
::PARAM_DFLT
=> 'help',
1827 ApiBase
::PARAM_TYPE
=> 'submodule',
1830 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1831 ApiBase
::PARAM_TYPE
=> 'submodule',
1834 ApiBase
::PARAM_TYPE
=> 'integer'
1837 ApiBase
::PARAM_TYPE
=> 'integer',
1838 ApiBase
::PARAM_DFLT
=> 0
1841 ApiBase
::PARAM_TYPE
=> 'integer',
1842 ApiBase
::PARAM_DFLT
=> 0
1845 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1848 ApiBase
::PARAM_TYPE
=> 'user',
1850 'requestid' => null,
1851 'servedby' => false,
1852 'curtimestamp' => false,
1853 'responselanginfo' => false,
1856 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1859 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1860 ApiBase
::PARAM_DFLT
=> 'bc',
1863 ApiBase
::PARAM_DFLT
=> 'uselang',
1865 'errorsuselocal' => [
1866 ApiBase
::PARAM_DFLT
=> false,
1872 protected function getExamplesMessages() {
1875 => 'apihelp-help-example-main',
1876 'action=help&recursivesubmodules=1'
1877 => 'apihelp-help-example-recursive',
1881 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1882 // Wish PHP had an "array_insert_before". Instead, we have to manually
1883 // reindex the array to get 'permissions' in the right place.
1886 foreach ( $oldHelp as $k => $v ) {
1887 if ( $k === 'submodules' ) {
1888 $help['permissions'] = '';
1892 $help['datatypes'] = '';
1893 $help['templatedparams'] = '';
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', 'templatedparams', 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-help-templatedparams-header' )->parse();
1962 $id = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_PRIMARY
);
1963 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_FALLBACK
);
1964 $headline = Linker
::makeHeadline( min( 6, $level ),
1965 ' class="apihelp-header">',
1971 // Ensure we have a sane anchor
1972 if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
1973 $headline = '<div id="main/templatedparams"></div>' . $headline;
1975 $help['templatedparams'] .= $headline;
1976 $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
1977 if ( !isset( $tocData['main/templatedparams'] ) ) {
1978 $tocnumber[$level]++
;
1979 $tocData['main/templatedparams'] = [
1980 'toclevel' => count( $tocnumber ),
1982 'anchor' => 'main/templatedparams',
1984 'number' => implode( '.', $tocnumber ),
1989 $header = $this->msg( 'api-credits-header' )->parse();
1990 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
1991 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_FALLBACK
);
1992 $headline = Linker
::makeHeadline( min( 6, $level ),
1993 ' class="apihelp-header">',
1999 // Ensure we have a sane anchor
2000 if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2001 $headline = '<div id="main/credits"></div>' . $headline;
2003 $help['credits'] .= $headline;
2004 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2005 if ( !isset( $tocData['main/credits'] ) ) {
2006 $tocnumber[$level]++
;
2007 $tocData['main/credits'] = [
2008 'toclevel' => count( $tocnumber ),
2010 'anchor' => 'main/credits',
2012 'number' => implode( '.', $tocnumber ),
2019 private $mCanApiHighLimits = null;
2022 * Check whether the current user is allowed to use high limits
2025 public function canApiHighLimits() {
2026 if ( !isset( $this->mCanApiHighLimits
) ) {
2027 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
2030 return $this->mCanApiHighLimits
;
2034 * Overrides to return this instance's module manager.
2035 * @return ApiModuleManager
2037 public function getModuleManager() {
2038 return $this->mModuleMgr
;
2042 * Fetches the user agent used for this request
2044 * The value will be the combination of the 'Api-User-Agent' header (if
2045 * any) and the standard User-Agent header (if any).
2049 public function getUserAgent() {
2051 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2052 $this->getRequest()->getHeader( 'User-agent' )
2058 * For really cool vim folding this needs to be at the end:
2059 * vim: foldmarker=@{,@} foldmethod=marker