3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Timestamp\TimestampException
;
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * When no uselang parameter is given, this language will be used
50 const API_DEFAULT_USELANG
= 'user';
53 * List of available modules: action name => module class
55 private static $Modules = [
56 'login' => ApiLogin
::class,
57 'clientlogin' => ApiClientLogin
::class,
58 'logout' => ApiLogout
::class,
59 'createaccount' => ApiAMCreateAccount
::class,
60 'linkaccount' => ApiLinkAccount
::class,
61 'unlinkaccount' => ApiRemoveAuthenticationData
::class,
62 'changeauthenticationdata' => ApiChangeAuthenticationData
::class,
63 'removeauthenticationdata' => ApiRemoveAuthenticationData
::class,
64 'resetpassword' => ApiResetPassword
::class,
65 'query' => ApiQuery
::class,
66 'expandtemplates' => ApiExpandTemplates
::class,
67 'parse' => ApiParse
::class,
68 'stashedit' => ApiStashEdit
::class,
69 'opensearch' => ApiOpenSearch
::class,
70 'feedcontributions' => ApiFeedContributions
::class,
71 'feedrecentchanges' => ApiFeedRecentChanges
::class,
72 'feedwatchlist' => ApiFeedWatchlist
::class,
73 'help' => ApiHelp
::class,
74 'paraminfo' => ApiParamInfo
::class,
75 'rsd' => ApiRsd
::class,
76 'compare' => ApiComparePages
::class,
77 'tokens' => ApiTokens
::class,
78 'checktoken' => ApiCheckToken
::class,
79 'cspreport' => ApiCSPReport
::class,
80 'validatepassword' => ApiValidatePassword
::class,
83 'purge' => ApiPurge
::class,
84 'setnotificationtimestamp' => ApiSetNotificationTimestamp
::class,
85 'rollback' => ApiRollback
::class,
86 'delete' => ApiDelete
::class,
87 'undelete' => ApiUndelete
::class,
88 'protect' => ApiProtect
::class,
89 'block' => ApiBlock
::class,
90 'unblock' => ApiUnblock
::class,
91 'move' => ApiMove
::class,
92 'edit' => ApiEditPage
::class,
93 'upload' => ApiUpload
::class,
94 'filerevert' => ApiFileRevert
::class,
95 'emailuser' => ApiEmailUser
::class,
96 'watch' => ApiWatch
::class,
97 'patrol' => ApiPatrol
::class,
98 'import' => ApiImport
::class,
99 'clearhasmsg' => ApiClearHasMsg
::class,
100 'userrights' => ApiUserrights
::class,
101 'options' => ApiOptions
::class,
102 'imagerotate' => ApiImageRotate
::class,
103 'revisiondelete' => ApiRevisionDelete
::class,
104 'managetags' => ApiManageTags
::class,
105 'tag' => ApiTag
::class,
106 'mergehistory' => ApiMergeHistory
::class,
107 'setpagelanguage' => ApiSetPageLanguage
::class,
111 * List of available formats: format name => format class
113 private static $Formats = [
114 'json' => ApiFormatJson
::class,
115 'jsonfm' => ApiFormatJson
::class,
116 'php' => ApiFormatPhp
::class,
117 'phpfm' => ApiFormatPhp
::class,
118 'xml' => ApiFormatXml
::class,
119 'xmlfm' => ApiFormatXml
::class,
120 'rawfm' => ApiFormatJson
::class,
121 'none' => ApiFormatNone
::class,
125 * List of user roles that are specifically relevant to the API.
126 * [ 'right' => [ 'msg' => 'Some message with a $1',
127 * 'params' => [ $someVarToSubst ] ],
130 private static $mRights = [
132 'msg' => 'right-writeapi',
136 'msg' => 'api-help-right-apihighlimits',
137 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
146 private $mModuleMgr, $mResult, $mErrorFormatter = null;
147 /** @var ApiContinuationManager|null */
148 private $mContinuationManager;
150 private $mEnableWrite;
151 private $mInternalMode, $mSquidMaxage;
155 private $mCacheMode = 'private';
156 private $mCacheControl = [];
157 private $mParamsUsed = [];
158 private $mParamsSensitive = [];
160 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
161 private $lacksSameOriginSecurity = null;
164 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
166 * @param IContextSource|WebRequest|null $context If this is an instance of
167 * FauxRequest, errors are thrown and no printing occurs
168 * @param bool $enableWrite Should be set to true if the api may modify data
170 public function __construct( $context = null, $enableWrite = false ) {
171 if ( $context === null ) {
172 $context = RequestContext
::getMain();
173 } elseif ( $context instanceof WebRequest
) {
176 $context = RequestContext
::getMain();
178 // We set a derivative context so we can change stuff later
179 $this->setContext( new DerivativeContext( $context ) );
181 if ( isset( $request ) ) {
182 $this->getContext()->setRequest( $request );
184 $request = $this->getRequest();
187 $this->mInternalMode
= ( $request instanceof FauxRequest
);
189 // Special handling for the main module: $parent === $this
190 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
192 $config = $this->getConfig();
194 if ( !$this->mInternalMode
) {
195 // Log if a request with a non-whitelisted Origin header is seen
196 // with session cookies.
197 $originHeader = $request->getHeader( 'Origin' );
198 if ( $originHeader === false ) {
201 $originHeader = trim( $originHeader );
202 $origins = preg_split( '/\s+/', $originHeader );
204 $sessionCookies = array_intersect(
205 array_keys( $_COOKIE ),
206 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
208 if ( $origins && $sessionCookies && (
209 count( $origins ) !== 1 ||
!self
::matchOrigin(
211 $config->get( 'CrossSiteAJAXdomains' ),
212 $config->get( 'CrossSiteAJAXdomainExceptions' )
215 LoggerFactory
::getInstance( 'cors' )->warning(
216 'Non-whitelisted CORS request with session cookies', [
217 'origin' => $originHeader,
218 'cookies' => $sessionCookies,
219 'ip' => $request->getIP(),
220 'userAgent' => $this->getUserAgent(),
221 'wiki' => wfWikiID(),
226 // If we're in a mode that breaks the same-origin policy, strip
227 // user credentials for security.
228 if ( $this->lacksSameOriginSecurity() ) {
230 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
231 $wgUser = new User();
232 $this->getContext()->setUser( $wgUser );
233 $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
237 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
239 // Setup uselang. This doesn't use $this->getParameter()
240 // because we're not ready to handle errors yet.
241 $uselang = $request->getVal( 'uselang', self
::API_DEFAULT_USELANG
);
242 if ( $uselang === 'user' ) {
243 // Assume the parent context is going to return the user language
244 // for uselang=user (see T85635).
246 if ( $uselang === 'content' ) {
248 $uselang = $wgContLang->getCode();
250 $code = RequestContext
::sanitizeLangCode( $uselang );
251 $this->getContext()->setLanguage( $code );
252 if ( !$this->mInternalMode
) {
254 $wgLang = $this->getContext()->getLanguage();
255 RequestContext
::getMain()->setLanguage( $wgLang );
259 // Set up the error formatter. This doesn't use $this->getParameter()
260 // because we're not ready to handle errors yet.
261 $errorFormat = $request->getVal( 'errorformat', 'bc' );
262 $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
263 $errorsUseDB = $request->getCheck( 'errorsuselocal' );
264 if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
265 if ( $errorLangCode === 'uselang' ) {
266 $errorLang = $this->getLanguage();
267 } elseif ( $errorLangCode === 'content' ) {
269 $errorLang = $wgContLang;
271 $errorLangCode = RequestContext
::sanitizeLangCode( $errorLangCode );
272 $errorLang = Language
::factory( $errorLangCode );
274 $this->mErrorFormatter
= new ApiErrorFormatter(
275 $this->mResult
, $errorLang, $errorFormat, $errorsUseDB
278 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
280 $this->mResult
->setErrorFormatter( $this->getErrorFormatter() );
282 $this->mModuleMgr
= new ApiModuleManager( $this );
283 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
284 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
285 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
286 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
288 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
290 $this->mContinuationManager
= null;
291 $this->mEnableWrite
= $enableWrite;
293 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
294 $this->mCommit
= false;
298 * Return true if the API was started by other PHP code using FauxRequest
301 public function isInternalMode() {
302 return $this->mInternalMode
;
306 * Get the ApiResult object associated with current request
310 public function getResult() {
311 return $this->mResult
;
315 * Get the security flag for the current request
318 public function lacksSameOriginSecurity() {
319 if ( $this->lacksSameOriginSecurity
!== null ) {
320 return $this->lacksSameOriginSecurity
;
323 $request = $this->getRequest();
326 if ( $request->getVal( 'callback' ) !== null ) {
327 $this->lacksSameOriginSecurity
= true;
332 if ( $request->getVal( 'origin' ) === '*' ) {
333 $this->lacksSameOriginSecurity
= true;
337 // Header to be used from XMLHTTPRequest when the request might
338 // otherwise be used for XSS.
339 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
340 $this->lacksSameOriginSecurity
= true;
344 // Allow extensions to override.
345 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
346 return $this->lacksSameOriginSecurity
;
350 * Get the ApiErrorFormatter object associated with current request
351 * @return ApiErrorFormatter
353 public function getErrorFormatter() {
354 return $this->mErrorFormatter
;
358 * Get the continuation manager
359 * @return ApiContinuationManager|null
361 public function getContinuationManager() {
362 return $this->mContinuationManager
;
366 * Set the continuation manager
367 * @param ApiContinuationManager|null $manager
369 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
370 if ( $manager !== null && $this->mContinuationManager
!== null ) {
371 throw new UnexpectedValueException(
372 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
373 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
376 $this->mContinuationManager
= $manager;
380 * Get the API module object. Only works after executeAction()
384 public function getModule() {
385 return $this->mModule
;
389 * Get the result formatter object. Only works after setupExecuteAction()
391 * @return ApiFormatBase
393 public function getPrinter() {
394 return $this->mPrinter
;
398 * Set how long the response should be cached.
402 public function setCacheMaxAge( $maxage ) {
403 $this->setCacheControl( [
404 'max-age' => $maxage,
405 's-maxage' => $maxage
410 * Set the type of caching headers which will be sent.
412 * @param string $mode One of:
413 * - 'public': Cache this object in public caches, if the maxage or smaxage
414 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
415 * not provided by any of these means, the object will be private.
416 * - 'private': Cache this object only in private client-side caches.
417 * - 'anon-public-user-private': Make this object cacheable for logged-out
418 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
419 * set consistently for a given URL, it cannot be set differently depending on
420 * things like the contents of the database, or whether the user is logged in.
422 * If the wiki does not allow anonymous users to read it, the mode set here
423 * will be ignored, and private caching headers will always be sent. In other words,
424 * the "public" mode is equivalent to saying that the data sent is as public as a page
427 * For user-dependent data, the private mode should generally be used. The
428 * anon-public-user-private mode should only be used where there is a particularly
429 * good performance reason for caching the anonymous response, but where the
430 * response to logged-in users may differ, or may contain private data.
432 * If this function is never called, then the default will be the private mode.
434 public function setCacheMode( $mode ) {
435 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
436 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
438 // Ignore for forwards-compatibility
442 if ( !User
::isEveryoneAllowed( 'read' ) ) {
443 // Private wiki, only private headers
444 if ( $mode !== 'private' ) {
445 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
451 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
452 // User language is used for i18n, so we don't want to publicly
453 // cache. Anons are ok, because if they have non-default language
454 // then there's an appropriate Vary header set by whatever set
455 // their non-default language.
456 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
457 "'anon-public-user-private' due to uselang=user\n" );
458 $mode = 'anon-public-user-private';
461 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
462 $this->mCacheMode
= $mode;
466 * Set directives (key/value pairs) for the Cache-Control header.
467 * Boolean values will be formatted as such, by including or omitting
468 * without an equals sign.
470 * Cache control values set here will only be used if the cache mode is not
471 * private, see setCacheMode().
473 * @param array $directives
475 public function setCacheControl( $directives ) {
476 $this->mCacheControl
= $directives +
$this->mCacheControl
;
480 * Create an instance of an output formatter by its name
482 * @param string $format
484 * @return ApiFormatBase
486 public function createPrinterByName( $format ) {
487 $printer = $this->mModuleMgr
->getModule( $format, 'format', /* $ignoreCache */ true );
488 if ( $printer === null ) {
490 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
498 * Execute api request. Any errors will be handled if the API was called by the remote client.
500 public function execute() {
501 if ( $this->mInternalMode
) {
502 $this->executeAction();
504 $this->executeActionWithErrorHandling();
509 * Execute an action, and in case of an error, erase whatever partial results
510 * have been accumulated, and replace it with an error message and a help screen.
512 protected function executeActionWithErrorHandling() {
513 // Verify the CORS header before executing the action
514 if ( !$this->handleCORS() ) {
515 // handleCORS() has sent a 403, abort
519 // Exit here if the request method was OPTIONS
520 // (assume there will be a followup GET or POST)
521 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
525 // In case an error occurs during data output,
526 // clear the output buffer and print just the error information
527 $obLevel = ob_get_level();
530 $t = microtime( true );
533 $this->executeAction();
534 $runTime = microtime( true ) - $t;
535 $this->logRequest( $runTime );
536 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
537 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
539 } catch ( Exception
$e ) {
540 $this->handleException( $e );
541 $this->logRequest( microtime( true ) - $t, $e );
545 // Commit DBs and send any related cookies and headers
546 MediaWiki
::preOutputCommit( $this->getContext() );
548 // Send cache headers after any code which might generate an error, to
549 // avoid sending public cache headers for errors.
550 $this->sendCacheHeaders( $isError );
552 // Executing the action might have already messed with the output
554 while ( ob_get_level() > $obLevel ) {
560 * Handle an exception as an API response
563 * @param Exception $e
565 protected function handleException( Exception
$e ) {
566 // T65145: Rollback any open database transactions
567 if ( !( $e instanceof ApiUsageException ||
$e instanceof UsageException
) ) {
568 // UsageExceptions are intentional, so don't rollback if that's the case
569 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
572 // Allow extra cleanup and logging
573 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
575 // Handle any kind of exception by outputting properly formatted error message.
576 // If this fails, an unhandled exception should be thrown so that global error
577 // handler will process and log it.
579 $errCodes = $this->substituteResultWithError( $e );
581 // Error results should not be cached
582 $this->setCacheMode( 'private' );
584 $response = $this->getRequest()->response();
585 $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
586 $response->header( $headerStr );
588 // Reset and print just the error message
591 // Printer may not be initialized if the extractRequestParams() fails for the main module
592 $this->createErrorPrinter();
596 $this->printResult( $e->getCode() );
597 } catch ( ApiUsageException
$ex ) {
598 // The error printer itself is failing. Try suppressing its request
599 // parameters and redo.
601 $this->addWarning( 'apiwarn-errorprinterfailed' );
602 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
604 $this->mPrinter
->addWarning( $error );
605 } catch ( Exception
$ex2 ) {
607 $this->addWarning( $error );
610 } catch ( UsageException
$ex ) {
611 // The error printer itself is failing. Try suppressing its request
612 // parameters and redo.
615 [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
619 $this->mPrinter
= null;
620 $this->createErrorPrinter();
621 $this->mPrinter
->forceDefaultParams();
622 if ( $e->getCode() ) {
623 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
625 $this->printResult( $e->getCode() );
630 * Handle an exception from the ApiBeforeMain hook.
632 * This tries to print the exception as an API response, to be more
633 * friendly to clients. If it fails, it will rethrow the exception.
636 * @param Exception $e
639 public static function handleApiBeforeMainException( Exception
$e ) {
643 $main = new self( RequestContext
::getMain(), false );
644 $main->handleException( $e );
645 $main->logRequest( 0, $e );
646 } catch ( Exception
$e2 ) {
647 // Nope, even that didn't work. Punt.
651 // Reset cache headers
652 $main->sendCacheHeaders( true );
658 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
660 * If no origin parameter is present, nothing happens.
661 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
662 * is set and false is returned.
663 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
664 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
666 * https://www.w3.org/TR/cors/#resource-requests
667 * https://www.w3.org/TR/cors/#resource-preflight-requests
669 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
671 protected function handleCORS() {
672 $originParam = $this->getParameter( 'origin' ); // defaults to null
673 if ( $originParam === null ) {
674 // No origin parameter, nothing to do
678 $request = $this->getRequest();
679 $response = $request->response();
681 $matchedOrigin = false;
682 $allowTiming = false;
685 if ( $originParam === '*' ) {
686 // Request for anonymous CORS
687 // Technically we should check for the presence of an Origin header
688 // and not process it as CORS if it's not set, but that would
689 // require us to vary on Origin for all 'origin=*' requests which
690 // we don't want to do.
691 $matchedOrigin = true;
693 $allowCredentials = 'false';
694 $varyOrigin = false; // No need to vary
696 // Non-anonymous CORS, check we allow the domain
698 // Origin: header is a space-separated list of origins, check all of them
699 $originHeader = $request->getHeader( 'Origin' );
700 if ( $originHeader === false ) {
703 $originHeader = trim( $originHeader );
704 $origins = preg_split( '/\s+/', $originHeader );
707 if ( !in_array( $originParam, $origins ) ) {
708 // origin parameter set but incorrect
709 // Send a 403 response
710 $response->statusHeader( 403 );
711 $response->header( 'Cache-Control: no-cache' );
712 echo "'origin' parameter does not match Origin header\n";
717 $config = $this->getConfig();
718 $matchedOrigin = count( $origins ) === 1 && self
::matchOrigin(
720 $config->get( 'CrossSiteAJAXdomains' ),
721 $config->get( 'CrossSiteAJAXdomainExceptions' )
724 $allowOrigin = $originHeader;
725 $allowCredentials = 'true';
726 $allowTiming = $originHeader;
729 if ( $matchedOrigin ) {
730 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
731 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
733 // This is a CORS preflight request
734 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
735 // If method is not a case-sensitive match, do not set any additional headers and terminate.
736 $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
739 // We allow the actual request to send the following headers
740 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
741 if ( $requestedHeaders !== false ) {
742 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
743 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
746 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
749 // We only allow the actual request to be GET or POST
750 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
751 } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
752 // Unsupported non-preflight method, don't handle it as CORS
754 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
759 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
760 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
761 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
762 if ( $allowTiming !== false ) {
763 $response->header( "Timing-Allow-Origin: $allowTiming" );
768 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
769 . 'MediaWiki-Login-Suppressed'
773 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
777 $this->getOutput()->addVaryHeader( 'Origin' );
784 * Attempt to match an Origin header against a set of rules and a set of exceptions
785 * @param string $value Origin header
786 * @param array $rules Set of wildcard rules
787 * @param array $exceptions Set of wildcard rules
788 * @return bool True if $value matches a rule in $rules and doesn't match
789 * any rules in $exceptions, false otherwise
791 protected static function matchOrigin( $value, $rules, $exceptions ) {
792 foreach ( $rules as $rule ) {
793 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
794 // Rule matches, check exceptions
795 foreach ( $exceptions as $exc ) {
796 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
809 * Attempt to validate the value of Access-Control-Request-Headers against a list
810 * of headers that we allow the follow up request to send.
812 * @param string $requestedHeaders Comma seperated list of HTTP headers
813 * @return bool True if all requested headers are in the list of allowed headers
815 protected static function matchRequestedHeaders( $requestedHeaders ) {
816 if ( trim( $requestedHeaders ) === '' ) {
819 $requestedHeaders = explode( ',', $requestedHeaders );
820 $allowedAuthorHeaders = array_flip( [
821 /* simple headers (see spec) */
826 /* non-authorable headers in XHR, which are however requested by some UAs */
830 /* MediaWiki whitelist */
833 foreach ( $requestedHeaders as $rHeader ) {
834 $rHeader = strtolower( trim( $rHeader ) );
835 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
836 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
844 * Helper function to convert wildcard string into a regex
848 * @param string $wildcard String with wildcards
849 * @return string Regular expression
851 protected static function wildcardToRegex( $wildcard ) {
852 $wildcard = preg_quote( $wildcard, '/' );
853 $wildcard = str_replace(
859 return "/^https?:\/\/$wildcard$/";
863 * Send caching headers
864 * @param bool $isError Whether an error response is being output
865 * @since 1.26 added $isError parameter
867 protected function sendCacheHeaders( $isError ) {
868 $response = $this->getRequest()->response();
869 $out = $this->getOutput();
871 $out->addVaryHeader( 'Treat-as-Untrusted' );
873 $config = $this->getConfig();
875 if ( $config->get( 'VaryOnXFP' ) ) {
876 $out->addVaryHeader( 'X-Forwarded-Proto' );
879 if ( !$isError && $this->mModule
&&
880 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
882 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
883 if ( $etag !== null ) {
884 $response->header( "ETag: $etag" );
886 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
887 if ( $lastMod !== null ) {
888 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
892 // The logic should be:
893 // $this->mCacheControl['max-age'] is set?
894 // Use it, the module knows better than our guess.
895 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
896 // Use 0 because we can guess caching is probably the wrong thing to do.
897 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
899 if ( isset( $this->mCacheControl
['max-age'] ) ) {
900 $maxage = $this->mCacheControl
['max-age'];
901 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
902 $this->mCacheMode
!== 'private'
904 $maxage = $this->getParameter( 'maxage' );
906 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
908 if ( $this->mCacheMode
== 'private' ) {
909 $response->header( "Cache-Control: $privateCache" );
913 $useKeyHeader = $config->get( 'UseKeyHeader' );
914 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
915 $out->addVaryHeader( 'Cookie' );
916 $response->header( $out->getVaryHeader() );
917 if ( $useKeyHeader ) {
918 $response->header( $out->getKeyHeader() );
919 if ( $out->haveCacheVaryCookies() ) {
920 // Logged in, mark this request private
921 $response->header( "Cache-Control: $privateCache" );
924 // Logged out, send normal public headers below
925 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
926 // Logged in or otherwise has session (e.g. anonymous users who have edited)
927 // Mark request private
928 $response->header( "Cache-Control: $privateCache" );
931 } // else no Key and anonymous, send public headers below
934 // Send public headers
935 $response->header( $out->getVaryHeader() );
936 if ( $useKeyHeader ) {
937 $response->header( $out->getKeyHeader() );
940 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
941 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
942 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
944 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
945 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
948 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
949 // Public cache not requested
950 // Sending a Vary header in this case is harmless, and protects us
951 // against conditional calls of setCacheMaxAge().
952 $response->header( "Cache-Control: $privateCache" );
957 $this->mCacheControl
['public'] = true;
959 // Send an Expires header
960 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
961 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
962 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
964 // Construct the Cache-Control header
967 foreach ( $this->mCacheControl
as $name => $value ) {
968 if ( is_bool( $value ) ) {
970 $ccHeader .= $separator . $name;
974 $ccHeader .= $separator . "$name=$value";
979 $response->header( "Cache-Control: $ccHeader" );
983 * Create the printer for error output
985 private function createErrorPrinter() {
986 if ( !isset( $this->mPrinter
) ) {
987 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
988 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
989 $value = self
::API_DEFAULT_FORMAT
;
991 $this->mPrinter
= $this->createPrinterByName( $value );
994 // Printer may not be able to handle errors. This is particularly
995 // likely if the module returns something for getCustomPrinter().
996 if ( !$this->mPrinter
->canPrintErrors() ) {
997 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1002 * Create an error message for the given exception.
1004 * If an ApiUsageException, errors/warnings will be extracted from the
1005 * embedded StatusValue.
1007 * If a base UsageException, the getMessageArray() method will be used to
1008 * extract the code and English message for a single error (no warnings).
1010 * Any other exception will be returned with a generic code and wrapper
1011 * text around the exception's (presumably English) message as a single
1012 * error (no warnings).
1014 * @param Exception $e
1015 * @param string $type 'error' or 'warning'
1016 * @return ApiMessage[]
1019 protected function errorMessagesFromException( $e, $type = 'error' ) {
1021 if ( $e instanceof ApiUsageException
) {
1022 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1023 $messages[] = ApiMessage
::create( $error );
1025 } elseif ( $type !== 'error' ) {
1026 // None of the rest have any messages for non-error types
1027 } elseif ( $e instanceof UsageException
) {
1028 // User entered incorrect parameters - generate error response
1029 $data = Wikimedia\
quietCall( [ $e, 'getMessageArray' ] );
1030 $code = $data['code'];
1031 $info = $data['info'];
1032 unset( $data['code'], $data['info'] );
1033 $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1035 // Something is seriously wrong
1036 $config = $this->getConfig();
1037 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1038 $code = 'internal_api_error_' . $class;
1039 if ( $config->get( 'ShowExceptionDetails' ) ) {
1040 if ( $e instanceof ILocalizedException
) {
1041 $msg = $e->getMessageObject();
1042 } elseif ( $e instanceof MessageSpecifier
) {
1043 $msg = Message
::newFromSpecifier( $e );
1045 $msg = wfEscapeWikiText( $e->getMessage() );
1047 $params = [ 'apierror-exceptioncaught', WebRequest
::getRequestId(), $msg ];
1049 $params = [ 'apierror-exceptioncaughttype', WebRequest
::getRequestId(), get_class( $e ) ];
1052 $messages[] = ApiMessage
::create( $params, $code );
1058 * Replace the result data with the information about an exception.
1059 * @param Exception $e
1060 * @return string[] Error codes
1062 protected function substituteResultWithError( $e ) {
1063 $result = $this->getResult();
1064 $formatter = $this->getErrorFormatter();
1065 $config = $this->getConfig();
1068 // Remember existing warnings and errors across the reset
1069 $errors = $result->getResultData( [ 'errors' ] );
1070 $warnings = $result->getResultData( [ 'warnings' ] );
1072 if ( $warnings !== null ) {
1073 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1075 if ( $errors !== null ) {
1076 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1078 // Collect the copied error codes for the return value
1079 foreach ( $errors as $error ) {
1080 if ( isset( $error['code'] ) ) {
1081 $errorCodes[$error['code']] = true;
1086 // Add errors from the exception
1087 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1088 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1089 $errorCodes[$msg->getApiCode()] = true;
1090 $formatter->addError( $modulePath, $msg );
1092 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1093 $formatter->addWarning( $modulePath, $msg );
1096 // Add additional data. Path depends on whether we're in BC mode or not.
1097 // Data depends on the type of exception.
1098 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1099 $path = [ 'error' ];
1103 if ( $e instanceof ApiUsageException ||
$e instanceof UsageException
) {
1104 $link = wfExpandUrl( wfScript( 'api' ) );
1105 $result->addContentValue(
1109 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1111 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1115 if ( $config->get( 'ShowExceptionDetails' ) ) {
1116 $result->addContentValue(
1119 $this->msg( 'api-exception-trace',
1123 MWExceptionHandler
::getRedactedTraceAsString( $e )
1124 )->inLanguage( $formatter->getLanguage() )->text()
1129 // Add the id and such
1130 $this->addRequestedFields( [ 'servedby' ] );
1132 return array_keys( $errorCodes );
1136 * Add requested fields to the result
1137 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1140 protected function addRequestedFields( $force = [] ) {
1141 $result = $this->getResult();
1143 $requestid = $this->getParameter( 'requestid' );
1144 if ( $requestid !== null ) {
1145 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1148 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1149 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1151 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1154 if ( $this->getParameter( 'curtimestamp' ) ) {
1155 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1156 ApiResult
::NO_SIZE_CHECK
);
1159 if ( $this->getParameter( 'responselanginfo' ) ) {
1160 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1161 ApiResult
::NO_SIZE_CHECK
);
1162 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1163 ApiResult
::NO_SIZE_CHECK
);
1168 * Set up for the execution.
1171 protected function setupExecuteAction() {
1172 $this->addRequestedFields();
1174 $params = $this->extractRequestParams();
1175 $this->mAction
= $params['action'];
1181 * Set up the module for response
1182 * @return ApiBase The module that will handle this action
1183 * @throws MWException
1184 * @throws ApiUsageException
1186 protected function setupModule() {
1187 // Instantiate the module requested by the user
1188 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1189 if ( $module === null ) {
1190 // Probably can't happen
1191 // @codeCoverageIgnoreStart
1192 $this->dieWithError(
1193 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1195 // @codeCoverageIgnoreEnd
1197 $moduleParams = $module->extractRequestParams();
1199 // Check token, if necessary
1200 if ( $module->needsToken() === true ) {
1201 throw new MWException(
1202 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1203 'See documentation for ApiBase::needsToken for details.'
1206 if ( $module->needsToken() ) {
1207 if ( !$module->mustBePosted() ) {
1208 throw new MWException(
1209 "Module '{$module->getModuleName()}' must require POST to use tokens."
1213 if ( !isset( $moduleParams['token'] ) ) {
1214 // Probably can't happen
1215 // @codeCoverageIgnoreStart
1216 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1217 // @codeCoverageIgnoreEnd
1220 $module->requirePostedParameters( [ 'token' ] );
1222 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1223 $module->dieWithError( 'apierror-badtoken' );
1233 private function getMaxLag() {
1234 $dbLag = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getMaxLag();
1236 'host' => $dbLag[0],
1241 $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1242 if ( $jobQueueLagFactor ) {
1243 // Turn total number of jobs into seconds by using the configured value
1244 $totalJobs = array_sum( JobQueueGroup
::singleton()->getQueueSizes() );
1245 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1246 if ( $jobQueueLag > $lagInfo['lag'] ) {
1248 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1249 'lag' => $jobQueueLag,
1250 'type' => 'jobqueue',
1251 'jobs' => $totalJobs,
1256 Hooks
::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1262 * Check the max lag if necessary
1263 * @param ApiBase $module Api module being used
1264 * @param array $params Array an array containing the request parameters.
1265 * @return bool True on success, false should exit immediately
1267 protected function checkMaxLag( $module, $params ) {
1268 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1269 $maxLag = $params['maxlag'];
1270 $lagInfo = $this->getMaxLag();
1271 if ( $lagInfo['lag'] > $maxLag ) {
1272 $response = $this->getRequest()->response();
1274 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1275 $response->header( 'X-Database-Lag: ' . intval( $lagInfo['lag'] ) );
1277 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1278 $this->dieWithError(
1279 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1285 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1293 * Check selected RFC 7232 precondition headers
1295 * RFC 7232 envisions a particular model where you send your request to "a
1296 * resource", and for write requests that you can read "the resource" by
1297 * changing the method to GET. When the API receives a GET request, it
1298 * works out even though "the resource" from RFC 7232's perspective might
1299 * be many resources from MediaWiki's perspective. But it totally fails for
1300 * a POST, since what HTTP sees as "the resource" is probably just
1301 * "/api.php" with all the interesting bits in the body.
1303 * Therefore, we only support RFC 7232 precondition headers for GET (and
1304 * HEAD). That means we don't need to bother with If-Match and
1305 * If-Unmodified-Since since they only apply to modification requests.
1307 * And since we don't support Range, If-Range is ignored too.
1310 * @param ApiBase $module Api module being used
1311 * @return bool True on success, false should exit immediately
1313 protected function checkConditionalRequestHeaders( $module ) {
1314 if ( $this->mInternalMode
) {
1315 // No headers to check in internal mode
1319 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1320 // Don't check POSTs
1326 $ifNoneMatch = array_diff(
1327 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1330 if ( $ifNoneMatch ) {
1331 if ( $ifNoneMatch === [ '*' ] ) {
1332 // API responses always "exist"
1335 $etag = $module->getConditionalRequestData( 'etag' );
1338 if ( $ifNoneMatch && $etag !== null ) {
1339 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1340 $match = array_map( function ( $s ) {
1341 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1343 $return304 = in_array( $test, $match, true );
1345 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1347 // Some old browsers sends sizes after the date, like this:
1348 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1350 $i = strpos( $value, ';' );
1351 if ( $i !== false ) {
1352 $value = trim( substr( $value, 0, $i ) );
1355 if ( $value !== '' ) {
1357 $ts = new MWTimestamp( $value );
1359 // RFC 7231 IMF-fixdate
1360 $ts->getTimestamp( TS_RFC2822
) === $value ||
1362 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1363 // asctime (with and without space-padded day)
1364 $ts->format( 'D M j H:i:s Y' ) === $value ||
1365 $ts->format( 'D M j H:i:s Y' ) === $value
1367 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1368 if ( $lastMod !== null ) {
1369 // Mix in some MediaWiki modification times
1372 'user' => $this->getUser()->getTouched(),
1373 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1375 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1376 // T46570: the core page itself may not change, but resources might
1377 $modifiedTimes['sepoch'] = wfTimestamp(
1378 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1381 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1382 $lastMod = max( $modifiedTimes );
1383 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1386 } catch ( TimestampException
$e ) {
1387 // Invalid timestamp, ignore it
1393 $this->getRequest()->response()->statusHeader( 304 );
1395 // Avoid outputting the compressed representation of a zero-length body
1396 Wikimedia\
suppressWarnings();
1397 ini_set( 'zlib.output_compression', 0 );
1398 Wikimedia\restoreWarnings
();
1399 wfClearOutputBuffers();
1408 * Check for sufficient permissions to execute
1409 * @param ApiBase $module An Api module
1411 protected function checkExecutePermissions( $module ) {
1412 $user = $this->getUser();
1413 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1414 !$user->isAllowed( 'read' )
1416 $this->dieWithError( 'apierror-readapidenied' );
1419 if ( $module->isWriteMode() ) {
1420 if ( !$this->mEnableWrite
) {
1421 $this->dieWithError( 'apierror-noapiwrite' );
1422 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1423 $this->dieWithError( 'apierror-writeapidenied' );
1424 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1425 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1428 $this->checkReadOnly( $module );
1431 // Allow extensions to stop execution for arbitrary reasons.
1432 $message = 'hookaborted';
1433 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1434 $this->dieWithError( $message );
1439 * Check if the DB is read-only for this user
1440 * @param ApiBase $module An Api module
1442 protected function checkReadOnly( $module ) {
1443 if ( wfReadOnly() ) {
1444 $this->dieReadOnly();
1447 if ( $module->isWriteMode()
1448 && $this->getUser()->isBot()
1449 && MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1451 $this->checkBotReadOnly();
1456 * Check whether we are readonly for bots
1458 private function checkBotReadOnly() {
1459 // Figure out how many servers have passed the lag threshold
1461 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1462 $laggedServers = [];
1463 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1464 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1465 if ( $lag > $lagLimit ) {
1467 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1471 // If a majority of replica DBs are too lagged then disallow writes
1472 $replicaCount = $loadBalancer->getServerCount() - 1;
1473 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1474 $laggedServers = implode( ', ', $laggedServers );
1477 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1480 $this->dieWithError(
1483 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1489 * Check asserts of the user's rights
1490 * @param array $params
1492 protected function checkAsserts( $params ) {
1493 if ( isset( $params['assert'] ) ) {
1494 $user = $this->getUser();
1495 switch ( $params['assert'] ) {
1497 if ( $user->isAnon() ) {
1498 $this->dieWithError( 'apierror-assertuserfailed' );
1502 if ( !$user->isAllowed( 'bot' ) ) {
1503 $this->dieWithError( 'apierror-assertbotfailed' );
1508 if ( isset( $params['assertuser'] ) ) {
1509 $assertUser = User
::newFromName( $params['assertuser'], false );
1510 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1511 $this->dieWithError(
1512 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1519 * Check POST for external response and setup result printer
1520 * @param ApiBase $module An Api module
1521 * @param array $params An array with the request parameters
1523 protected function setupExternalResponse( $module, $params ) {
1524 $request = $this->getRequest();
1525 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1526 // Module requires POST. GET request might still be allowed
1527 // if $wgDebugApi is true, otherwise fail.
1528 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1531 // See if custom printer is used
1532 $this->mPrinter
= $module->getCustomPrinter();
1533 if ( is_null( $this->mPrinter
) ) {
1534 // Create an appropriate printer
1535 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1538 if ( $request->getProtocol() === 'http' && (
1539 $request->getSession()->shouldForceHTTPS() ||
1540 ( $this->getUser()->isLoggedIn() &&
1541 $this->getUser()->requiresHTTPS() )
1543 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1548 * Execute the actual module, without any error handling
1550 protected function executeAction() {
1551 $params = $this->setupExecuteAction();
1553 // Check asserts early so e.g. errors in parsing a module's parameters due to being
1554 // logged out don't override the client's intended "am I logged in?" check.
1555 $this->checkAsserts( $params );
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 );
1580 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1582 $this->reportUnusedParams();
1584 if ( !$this->mInternalMode
) {
1585 // append Debug information
1586 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1588 // Print result data
1589 $this->printResult();
1594 * Set database connection, query, and write expectations given this module request
1595 * @param ApiBase $module
1597 protected function setRequestExpectations( ApiBase
$module ) {
1598 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1599 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1600 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1601 if ( $this->getRequest()->hasSafeMethod() ) {
1602 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1603 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1604 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1605 $this->getRequest()->markAsSafeRequest();
1607 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1612 * Log the preceding request
1613 * @param float $time Time in seconds
1614 * @param Exception|null $e Exception caught while processing the request
1616 protected function logRequest( $time, $e = null ) {
1617 $request = $this->getRequest();
1620 'ip' => $request->getIP(),
1621 'userAgent' => $this->getUserAgent(),
1622 'wiki' => wfWikiID(),
1623 'timeSpentBackend' => (int)round( $time * 1000 ),
1624 'hadError' => $e !== null,
1630 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1631 $logCtx['errorCodes'][] = $msg->getApiCode();
1635 // Construct space separated message for 'api' log channel
1636 $msg = "API {$request->getMethod()} " .
1637 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1638 " {$logCtx['ip']} " .
1639 "T={$logCtx['timeSpentBackend']}ms";
1641 $sensitive = array_flip( $this->getSensitiveParams() );
1642 foreach ( $this->getParamsUsed() as $name ) {
1643 $value = $request->getVal( $name );
1644 if ( $value === null ) {
1648 if ( isset( $sensitive[$name] ) ) {
1649 $value = '[redacted]';
1650 $encValue = '[redacted]';
1651 } elseif ( strlen( $value ) > 256 ) {
1652 $value = substr( $value, 0, 256 );
1653 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1655 $encValue = $this->encodeRequestLogValue( $value );
1658 $logCtx['params'][$name] = $value;
1659 $msg .= " {$name}={$encValue}";
1662 wfDebugLog( 'api', $msg, 'private' );
1663 // ApiAction channel is for structured data consumers
1664 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1668 * Encode a value in a format suitable for a space-separated log line.
1672 protected function encodeRequestLogValue( $s ) {
1675 $chars = ';@$!*(),/:';
1676 $numChars = strlen( $chars );
1677 for ( $i = 0; $i < $numChars; $i++
) {
1678 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1682 return strtr( rawurlencode( $s ), $table );
1686 * Get the request parameters used in the course of the preceding execute() request
1689 protected function getParamsUsed() {
1690 return array_keys( $this->mParamsUsed
);
1694 * Mark parameters as used
1695 * @param string|string[] $params
1697 public function markParamsUsed( $params ) {
1698 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1702 * Get the request parameters that should be considered sensitive
1706 protected function getSensitiveParams() {
1707 return array_keys( $this->mParamsSensitive
);
1711 * Mark parameters as sensitive
1713 * @param string|string[] $params
1715 public function markParamsSensitive( $params ) {
1716 $this->mParamsSensitive +
= array_fill_keys( (array)$params, true );
1720 * Get a request value, and register the fact that it was used, for logging.
1721 * @param string $name
1722 * @param string|null $default
1723 * @return string|null
1725 public function getVal( $name, $default = null ) {
1726 $this->mParamsUsed
[$name] = true;
1728 $ret = $this->getRequest()->getVal( $name );
1729 if ( $ret === null ) {
1730 if ( $this->getRequest()->getArray( $name ) !== null ) {
1731 // See T12262 for why we don't just implode( '|', ... ) the
1733 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1741 * Get a boolean request value, and register the fact that the parameter
1742 * was used, for logging.
1743 * @param string $name
1746 public function getCheck( $name ) {
1747 return $this->getVal( $name, null ) !== null;
1751 * Get a request upload, and register the fact that it was used, for logging.
1754 * @param string $name Parameter name
1755 * @return WebRequestUpload
1757 public function getUpload( $name ) {
1758 $this->mParamsUsed
[$name] = true;
1760 return $this->getRequest()->getUpload( $name );
1764 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1765 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1767 protected function reportUnusedParams() {
1768 $paramsUsed = $this->getParamsUsed();
1769 $allParams = $this->getRequest()->getValueNames();
1771 if ( !$this->mInternalMode
) {
1772 // Printer has not yet executed; don't warn that its parameters are unused
1773 $printerParams = $this->mPrinter
->encodeParamName(
1774 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1776 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1778 $unusedParams = array_diff( $allParams, $paramsUsed );
1781 if ( count( $unusedParams ) ) {
1782 $this->addWarning( [
1783 'apierror-unrecognizedparams',
1784 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1785 count( $unusedParams )
1791 * Print results using the current printer
1793 * @param int $httpCode HTTP status code, or 0 to not change
1795 protected function printResult( $httpCode = 0 ) {
1796 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1797 $this->addWarning( 'apiwarn-wgDebugAPI' );
1800 $printer = $this->mPrinter
;
1801 $printer->initPrinter( false );
1803 $printer->setHttpStatus( $httpCode );
1805 $printer->execute();
1806 $printer->closePrinter();
1812 public function isReadMode() {
1817 * See ApiBase for description.
1821 public function getAllowedParams() {
1824 ApiBase
::PARAM_DFLT
=> 'help',
1825 ApiBase
::PARAM_TYPE
=> 'submodule',
1828 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_FORMAT
,
1829 ApiBase
::PARAM_TYPE
=> 'submodule',
1832 ApiBase
::PARAM_TYPE
=> 'integer'
1835 ApiBase
::PARAM_TYPE
=> 'integer',
1836 ApiBase
::PARAM_DFLT
=> 0
1839 ApiBase
::PARAM_TYPE
=> 'integer',
1840 ApiBase
::PARAM_DFLT
=> 0
1843 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1846 ApiBase
::PARAM_TYPE
=> 'user',
1848 'requestid' => null,
1849 'servedby' => false,
1850 'curtimestamp' => false,
1851 'responselanginfo' => false,
1854 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1857 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1858 ApiBase
::PARAM_DFLT
=> 'bc',
1861 ApiBase
::PARAM_DFLT
=> 'uselang',
1863 'errorsuselocal' => [
1864 ApiBase
::PARAM_DFLT
=> false,
1870 protected function getExamplesMessages() {
1873 => 'apihelp-help-example-main',
1874 'action=help&recursivesubmodules=1'
1875 => 'apihelp-help-example-recursive',
1879 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1880 // Wish PHP had an "array_insert_before". Instead, we have to manually
1881 // reindex the array to get 'permissions' in the right place.
1884 foreach ( $oldHelp as $k => $v ) {
1885 if ( $k === 'submodules' ) {
1886 $help['permissions'] = '';
1890 $help['datatypes'] = '';
1891 $help['templatedparams'] = '';
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', 'templatedparams', 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-help-templatedparams-header' )->parse();
1960 $id = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_PRIMARY
);
1961 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/templatedparams', Sanitizer
::ID_FALLBACK
);
1962 $headline = Linker
::makeHeadline( min( 6, $level ),
1963 ' class="apihelp-header">',
1969 // Ensure we have a sane anchor
1970 if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
1971 $headline = '<div id="main/templatedparams"></div>' . $headline;
1973 $help['templatedparams'] .= $headline;
1974 $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
1975 if ( !isset( $tocData['main/templatedparams'] ) ) {
1976 $tocnumber[$level]++
;
1977 $tocData['main/templatedparams'] = [
1978 'toclevel' => count( $tocnumber ),
1980 'anchor' => 'main/templatedparams',
1982 'number' => implode( '.', $tocnumber ),
1987 $header = $this->msg( 'api-credits-header' )->parse();
1988 $id = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_PRIMARY
);
1989 $idFallback = Sanitizer
::escapeIdForAttribute( 'main/credits', Sanitizer
::ID_FALLBACK
);
1990 $headline = Linker
::makeHeadline( min( 6, $level ),
1991 ' class="apihelp-header">',
1997 // Ensure we have a sane anchor
1998 if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
1999 $headline = '<div id="main/credits"></div>' . $headline;
2001 $help['credits'] .= $headline;
2002 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2003 if ( !isset( $tocData['main/credits'] ) ) {
2004 $tocnumber[$level]++
;
2005 $tocData['main/credits'] = [
2006 'toclevel' => count( $tocnumber ),
2008 'anchor' => 'main/credits',
2010 'number' => implode( '.', $tocnumber ),
2017 private $mCanApiHighLimits = null;
2020 * Check whether the current user is allowed to use high limits
2023 public function canApiHighLimits() {
2024 if ( !isset( $this->mCanApiHighLimits
) ) {
2025 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
2028 return $this->mCanApiHighLimits
;
2032 * Overrides to return this instance's module manager.
2033 * @return ApiModuleManager
2035 public function getModuleManager() {
2036 return $this->mModuleMgr
;
2040 * Fetches the user agent used for this request
2042 * The value will be the combination of the 'Api-User-Agent' header (if
2043 * any) and the standard User-Agent header (if any).
2047 public function getUserAgent() {
2049 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2050 $this->getRequest()->getHeader( 'User-agent' )
2056 * For really cool vim folding this needs to be at the end:
2057 * vim: foldmarker=@{,@} foldmethod=marker