5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 use MediaWiki\Logger\LoggerFactory
;
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',
59 'clientlogin' => 'ApiClientLogin',
60 'logout' => 'ApiLogout',
61 'createaccount' => 'ApiAMCreateAccount',
62 'linkaccount' => 'ApiLinkAccount',
63 'unlinkaccount' => 'ApiRemoveAuthenticationData',
64 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
65 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
66 'resetpassword' => 'ApiResetPassword',
67 'query' => 'ApiQuery',
68 'expandtemplates' => 'ApiExpandTemplates',
69 'parse' => 'ApiParse',
70 'stashedit' => 'ApiStashEdit',
71 'opensearch' => 'ApiOpenSearch',
72 'feedcontributions' => 'ApiFeedContributions',
73 'feedrecentchanges' => 'ApiFeedRecentChanges',
74 'feedwatchlist' => 'ApiFeedWatchlist',
76 'paraminfo' => 'ApiParamInfo',
78 'compare' => 'ApiComparePages',
79 'tokens' => 'ApiTokens',
80 'checktoken' => 'ApiCheckToken',
81 'cspreport' => 'ApiCSPReport',
84 'purge' => 'ApiPurge',
85 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
86 'rollback' => 'ApiRollback',
87 'delete' => 'ApiDelete',
88 'undelete' => 'ApiUndelete',
89 'protect' => 'ApiProtect',
90 'block' => 'ApiBlock',
91 'unblock' => 'ApiUnblock',
93 'edit' => 'ApiEditPage',
94 'upload' => 'ApiUpload',
95 'filerevert' => 'ApiFileRevert',
96 'emailuser' => 'ApiEmailUser',
97 'watch' => 'ApiWatch',
98 'patrol' => 'ApiPatrol',
99 'import' => 'ApiImport',
100 'clearhasmsg' => 'ApiClearHasMsg',
101 'userrights' => 'ApiUserrights',
102 'options' => 'ApiOptions',
103 'imagerotate' => 'ApiImageRotate',
104 'revisiondelete' => 'ApiRevisionDelete',
105 'managetags' => 'ApiManageTags',
107 'mergehistory' => 'ApiMergeHistory',
111 * List of available formats: format name => format class
113 private static $Formats = [
114 'json' => 'ApiFormatJson',
115 'jsonfm' => 'ApiFormatJson',
116 'php' => 'ApiFormatPhp',
117 'phpfm' => 'ApiFormatPhp',
118 'xml' => 'ApiFormatXml',
119 'xmlfm' => 'ApiFormatXml',
120 'rawfm' => 'ApiFormatJson',
121 'none' => 'ApiFormatNone',
124 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
126 * List of user roles that are specifically relevant to the API.
127 * [ 'right' => [ 'msg' => 'Some message with a $1',
128 * 'params' => [ $someVarToSubst ] ],
131 private static $mRights = [
133 'msg' => 'right-writeapi',
137 'msg' => 'api-help-right-apihighlimits',
138 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
141 // @codingStandardsIgnoreEnd
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 = [];
161 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
162 private $lacksSameOriginSecurity = null;
165 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
167 * @param IContextSource|WebRequest $context If this is an instance of
168 * FauxRequest, errors are thrown and no printing occurs
169 * @param bool $enableWrite Should be set to true if the api may modify data
171 public function __construct( $context = null, $enableWrite = false ) {
172 if ( $context === null ) {
173 $context = RequestContext
::getMain();
174 } elseif ( $context instanceof WebRequest
) {
177 $context = RequestContext
::getMain();
179 // We set a derivative context so we can change stuff later
180 $this->setContext( new DerivativeContext( $context ) );
182 if ( isset( $request ) ) {
183 $this->getContext()->setRequest( $request );
185 $request = $this->getRequest();
188 $this->mInternalMode
= ( $request instanceof FauxRequest
);
190 // Special handling for the main module: $parent === $this
191 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
193 $config = $this->getConfig();
195 if ( !$this->mInternalMode
) {
196 // Log if a request with a non-whitelisted Origin header is seen
197 // with session cookies.
198 $originHeader = $request->getHeader( 'Origin' );
199 if ( $originHeader === false ) {
202 $originHeader = trim( $originHeader );
203 $origins = preg_split( '/\s+/', $originHeader );
205 $sessionCookies = array_intersect(
206 array_keys( $_COOKIE ),
207 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
209 if ( $origins && $sessionCookies && (
210 count( $origins ) !== 1 ||
!self
::matchOrigin(
212 $config->get( 'CrossSiteAJAXdomains' ),
213 $config->get( 'CrossSiteAJAXdomainExceptions' )
216 LoggerFactory
::getInstance( 'cors' )->warning(
217 'Non-whitelisted CORS request with session cookies', [
218 'origin' => $originHeader,
219 'cookies' => $sessionCookies,
220 'ip' => $request->getIP(),
221 'userAgent' => $this->getUserAgent(),
222 'wiki' => wfWikiID(),
227 // If we're in a mode that breaks the same-origin policy, strip
228 // user credentials for security.
229 if ( $this->lacksSameOriginSecurity() ) {
231 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
232 $wgUser = new User();
233 $this->getContext()->setUser( $wgUser );
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
369 public function setContinuationManager( $manager ) {
370 if ( $manager !== null ) {
371 if ( !$manager instanceof ApiContinuationManager
) {
372 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
373 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
376 if ( $this->mContinuationManager
!== null ) {
377 throw new UnexpectedValueException(
378 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
379 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
383 $this->mContinuationManager
= $manager;
387 * Get the API module object. Only works after executeAction()
391 public function getModule() {
392 return $this->mModule
;
396 * Get the result formatter object. Only works after setupExecuteAction()
398 * @return ApiFormatBase
400 public function getPrinter() {
401 return $this->mPrinter
;
405 * Set how long the response should be cached.
409 public function setCacheMaxAge( $maxage ) {
410 $this->setCacheControl( [
411 'max-age' => $maxage,
412 's-maxage' => $maxage
417 * Set the type of caching headers which will be sent.
419 * @param string $mode One of:
420 * - 'public': Cache this object in public caches, if the maxage or smaxage
421 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
422 * not provided by any of these means, the object will be private.
423 * - 'private': Cache this object only in private client-side caches.
424 * - 'anon-public-user-private': Make this object cacheable for logged-out
425 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
426 * set consistently for a given URL, it cannot be set differently depending on
427 * things like the contents of the database, or whether the user is logged in.
429 * If the wiki does not allow anonymous users to read it, the mode set here
430 * will be ignored, and private caching headers will always be sent. In other words,
431 * the "public" mode is equivalent to saying that the data sent is as public as a page
434 * For user-dependent data, the private mode should generally be used. The
435 * anon-public-user-private mode should only be used where there is a particularly
436 * good performance reason for caching the anonymous response, but where the
437 * response to logged-in users may differ, or may contain private data.
439 * If this function is never called, then the default will be the private mode.
441 public function setCacheMode( $mode ) {
442 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
443 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
445 // Ignore for forwards-compatibility
449 if ( !User
::isEveryoneAllowed( 'read' ) ) {
450 // Private wiki, only private headers
451 if ( $mode !== 'private' ) {
452 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
458 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
459 // User language is used for i18n, so we don't want to publicly
460 // cache. Anons are ok, because if they have non-default language
461 // then there's an appropriate Vary header set by whatever set
462 // their non-default language.
463 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
464 "'anon-public-user-private' due to uselang=user\n" );
465 $mode = 'anon-public-user-private';
468 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
469 $this->mCacheMode
= $mode;
473 * Set directives (key/value pairs) for the Cache-Control header.
474 * Boolean values will be formatted as such, by including or omitting
475 * without an equals sign.
477 * Cache control values set here will only be used if the cache mode is not
478 * private, see setCacheMode().
480 * @param array $directives
482 public function setCacheControl( $directives ) {
483 $this->mCacheControl
= $directives +
$this->mCacheControl
;
487 * Create an instance of an output formatter by its name
489 * @param string $format
491 * @return ApiFormatBase
493 public function createPrinterByName( $format ) {
494 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
495 if ( $printer === null ) {
497 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
505 * Execute api request. Any errors will be handled if the API was called by the remote client.
507 public function execute() {
508 if ( $this->mInternalMode
) {
509 $this->executeAction();
511 $this->executeActionWithErrorHandling();
516 * Execute an action, and in case of an error, erase whatever partial results
517 * have been accumulated, and replace it with an error message and a help screen.
519 protected function executeActionWithErrorHandling() {
520 // Verify the CORS header before executing the action
521 if ( !$this->handleCORS() ) {
522 // handleCORS() has sent a 403, abort
526 // Exit here if the request method was OPTIONS
527 // (assume there will be a followup GET or POST)
528 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
532 // In case an error occurs during data output,
533 // clear the output buffer and print just the error information
534 $obLevel = ob_get_level();
537 $t = microtime( true );
540 $this->executeAction();
541 $runTime = microtime( true ) - $t;
542 $this->logRequest( $runTime );
543 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
544 $this->getStats()->timing(
545 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
548 } catch ( Exception
$e ) {
549 $this->handleException( $e );
550 $this->logRequest( microtime( true ) - $t, $e );
554 // Commit DBs and send any related cookies and headers
555 MediaWiki
::preOutputCommit( $this->getContext() );
557 // Send cache headers after any code which might generate an error, to
558 // avoid sending public cache headers for errors.
559 $this->sendCacheHeaders( $isError );
561 // Executing the action might have already messed with the output
563 while ( ob_get_level() > $obLevel ) {
569 * Handle an exception as an API response
572 * @param Exception $e
574 protected function handleException( Exception
$e ) {
575 // Bug 63145: Rollback any open database transactions
576 if ( !( $e instanceof ApiUsageException ||
$e instanceof UsageException
) ) {
577 // UsageExceptions are intentional, so don't rollback if that's the case
579 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
580 } catch ( DBError
$e2 ) {
581 // Rollback threw an exception too. Log it, but don't interrupt
582 // our regularly scheduled exception handling.
583 MWExceptionHandler
::logException( $e2 );
587 // Allow extra cleanup and logging
588 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
591 if ( !( $e instanceof ApiUsageException ||
$e instanceof UsageException
) ) {
592 MWExceptionHandler
::logException( $e );
595 // Handle any kind of exception by outputting properly formatted error message.
596 // If this fails, an unhandled exception should be thrown so that global error
597 // handler will process and log it.
599 $errCodes = $this->substituteResultWithError( $e );
601 // Error results should not be cached
602 $this->setCacheMode( 'private' );
604 $response = $this->getRequest()->response();
605 $headerStr = 'MediaWiki-API-Error: ' . join( ', ', $errCodes );
606 $response->header( $headerStr );
608 // Reset and print just the error message
611 // Printer may not be initialized if the extractRequestParams() fails for the main module
612 $this->createErrorPrinter();
616 $this->printResult( $e->getCode() );
617 } catch ( ApiUsageException
$ex ) {
618 // The error printer itself is failing. Try suppressing its request
619 // parameters and redo.
621 $this->addWarning( 'apiwarn-errorprinterfailed' );
622 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
624 $this->mPrinter
->addWarning( $error );
625 } catch ( Exception
$ex2 ) {
627 $this->addWarning( $error );
630 } catch ( UsageException
$ex ) {
631 // The error printer itself is failing. Try suppressing its request
632 // parameters and redo.
635 [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
639 $this->mPrinter
= null;
640 $this->createErrorPrinter();
641 $this->mPrinter
->forceDefaultParams();
642 if ( $e->getCode() ) {
643 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
645 $this->printResult( $e->getCode() );
650 * Handle an exception from the ApiBeforeMain hook.
652 * This tries to print the exception as an API response, to be more
653 * friendly to clients. If it fails, it will rethrow the exception.
656 * @param Exception $e
659 public static function handleApiBeforeMainException( Exception
$e ) {
663 $main = new self( RequestContext
::getMain(), false );
664 $main->handleException( $e );
665 $main->logRequest( 0, $e );
666 } catch ( Exception
$e2 ) {
667 // Nope, even that didn't work. Punt.
671 // Reset cache headers
672 $main->sendCacheHeaders( true );
678 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
680 * If no origin parameter is present, nothing happens.
681 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
682 * is set and false is returned.
683 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
684 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
686 * https://www.w3.org/TR/cors/#resource-requests
687 * https://www.w3.org/TR/cors/#resource-preflight-requests
689 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
691 protected function handleCORS() {
692 $originParam = $this->getParameter( 'origin' ); // defaults to null
693 if ( $originParam === null ) {
694 // No origin parameter, nothing to do
698 $request = $this->getRequest();
699 $response = $request->response();
701 $matchOrigin = false;
702 $allowTiming = false;
705 if ( $originParam === '*' ) {
706 // Request for anonymous CORS
709 $allowCredentials = 'false';
710 $varyOrigin = false; // No need to vary
712 // Non-anonymous CORS, check we allow the domain
714 // Origin: header is a space-separated list of origins, check all of them
715 $originHeader = $request->getHeader( 'Origin' );
716 if ( $originHeader === false ) {
719 $originHeader = trim( $originHeader );
720 $origins = preg_split( '/\s+/', $originHeader );
723 if ( !in_array( $originParam, $origins ) ) {
724 // origin parameter set but incorrect
725 // Send a 403 response
726 $response->statusHeader( 403 );
727 $response->header( 'Cache-Control: no-cache' );
728 echo "'origin' parameter does not match Origin header\n";
733 $config = $this->getConfig();
734 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
736 $config->get( 'CrossSiteAJAXdomains' ),
737 $config->get( 'CrossSiteAJAXdomainExceptions' )
740 $allowOrigin = $originHeader;
741 $allowCredentials = 'true';
742 $allowTiming = $originHeader;
745 if ( $matchOrigin ) {
746 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
747 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
749 // This is a CORS preflight request
750 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
751 // If method is not a case-sensitive match, do not set any additional headers and terminate.
754 // We allow the actual request to send the following headers
755 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
756 if ( $requestedHeaders !== false ) {
757 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
760 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
763 // We only allow the actual request to be GET or POST
764 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
767 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
768 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
769 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
770 if ( $allowTiming !== false ) {
771 $response->header( "Timing-Allow-Origin: $allowTiming" );
776 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
782 $this->getOutput()->addVaryHeader( 'Origin' );
789 * Attempt to match an Origin header against a set of rules and a set of exceptions
790 * @param string $value Origin header
791 * @param array $rules Set of wildcard rules
792 * @param array $exceptions Set of wildcard rules
793 * @return bool True if $value matches a rule in $rules and doesn't match
794 * any rules in $exceptions, false otherwise
796 protected static function matchOrigin( $value, $rules, $exceptions ) {
797 foreach ( $rules as $rule ) {
798 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
799 // Rule matches, check exceptions
800 foreach ( $exceptions as $exc ) {
801 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
814 * Attempt to validate the value of Access-Control-Request-Headers against a list
815 * of headers that we allow the follow up request to send.
817 * @param string $requestedHeaders Comma seperated list of HTTP headers
818 * @return bool True if all requested headers are in the list of allowed headers
820 protected static function matchRequestedHeaders( $requestedHeaders ) {
821 if ( trim( $requestedHeaders ) === '' ) {
824 $requestedHeaders = explode( ',', $requestedHeaders );
825 $allowedAuthorHeaders = array_flip( [
826 /* simple headers (see spec) */
831 /* non-authorable headers in XHR, which are however requested by some UAs */
835 /* MediaWiki whitelist */
838 foreach ( $requestedHeaders as $rHeader ) {
839 $rHeader = strtolower( trim( $rHeader ) );
840 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
841 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
849 * Helper function to convert wildcard string into a regex
853 * @param string $wildcard String with wildcards
854 * @return string Regular expression
856 protected static function wildcardToRegex( $wildcard ) {
857 $wildcard = preg_quote( $wildcard, '/' );
858 $wildcard = str_replace(
864 return "/^https?:\/\/$wildcard$/";
868 * Send caching headers
869 * @param bool $isError Whether an error response is being output
870 * @since 1.26 added $isError parameter
872 protected function sendCacheHeaders( $isError ) {
873 $response = $this->getRequest()->response();
874 $out = $this->getOutput();
876 $out->addVaryHeader( 'Treat-as-Untrusted' );
878 $config = $this->getConfig();
880 if ( $config->get( 'VaryOnXFP' ) ) {
881 $out->addVaryHeader( 'X-Forwarded-Proto' );
884 if ( !$isError && $this->mModule
&&
885 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
887 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
888 if ( $etag !== null ) {
889 $response->header( "ETag: $etag" );
891 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
892 if ( $lastMod !== null ) {
893 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
897 // The logic should be:
898 // $this->mCacheControl['max-age'] is set?
899 // Use it, the module knows better than our guess.
900 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
901 // Use 0 because we can guess caching is probably the wrong thing to do.
902 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
904 if ( isset( $this->mCacheControl
['max-age'] ) ) {
905 $maxage = $this->mCacheControl
['max-age'];
906 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
907 $this->mCacheMode
!== 'private'
909 $maxage = $this->getParameter( 'maxage' );
911 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
913 if ( $this->mCacheMode
== 'private' ) {
914 $response->header( "Cache-Control: $privateCache" );
918 $useKeyHeader = $config->get( 'UseKeyHeader' );
919 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
920 $out->addVaryHeader( 'Cookie' );
921 $response->header( $out->getVaryHeader() );
922 if ( $useKeyHeader ) {
923 $response->header( $out->getKeyHeader() );
924 if ( $out->haveCacheVaryCookies() ) {
925 // Logged in, mark this request private
926 $response->header( "Cache-Control: $privateCache" );
929 // Logged out, send normal public headers below
930 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
931 // Logged in or otherwise has session (e.g. anonymous users who have edited)
932 // Mark request private
933 $response->header( "Cache-Control: $privateCache" );
936 } // else no Key and anonymous, send public headers below
939 // Send public headers
940 $response->header( $out->getVaryHeader() );
941 if ( $useKeyHeader ) {
942 $response->header( $out->getKeyHeader() );
945 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
946 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
947 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
949 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
950 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
953 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
954 // Public cache not requested
955 // Sending a Vary header in this case is harmless, and protects us
956 // against conditional calls of setCacheMaxAge().
957 $response->header( "Cache-Control: $privateCache" );
962 $this->mCacheControl
['public'] = true;
964 // Send an Expires header
965 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
966 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
967 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
969 // Construct the Cache-Control header
972 foreach ( $this->mCacheControl
as $name => $value ) {
973 if ( is_bool( $value ) ) {
975 $ccHeader .= $separator . $name;
979 $ccHeader .= $separator . "$name=$value";
984 $response->header( "Cache-Control: $ccHeader" );
988 * Create the printer for error output
990 private function createErrorPrinter() {
991 if ( !isset( $this->mPrinter
) ) {
992 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
993 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
994 $value = self
::API_DEFAULT_FORMAT
;
996 $this->mPrinter
= $this->createPrinterByName( $value );
999 // Printer may not be able to handle errors. This is particularly
1000 // likely if the module returns something for getCustomPrinter().
1001 if ( !$this->mPrinter
->canPrintErrors() ) {
1002 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
1007 * Create an error message for the given exception.
1009 * If an ApiUsageException, errors/warnings will be extracted from the
1010 * embedded StatusValue.
1012 * If a base UsageException, the getMessageArray() method will be used to
1013 * extract the code and English message for a single error (no warnings).
1015 * Any other exception will be returned with a generic code and wrapper
1016 * text around the exception's (presumably English) message as a single
1017 * error (no warnings).
1019 * @param Exception $e
1020 * @param string $type 'error' or 'warning'
1021 * @return ApiMessage[]
1024 protected function errorMessagesFromException( $e, $type = 'error' ) {
1026 if ( $e instanceof ApiUsageException
) {
1027 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1028 $messages[] = ApiMessage
::create( $error );
1030 } elseif ( $type !== 'error' ) {
1031 // None of the rest have any messages for non-error types
1032 } elseif ( $e instanceof UsageException
) {
1033 // User entered incorrect parameters - generate error response
1034 $data = $e->getMessageArray();
1035 $code = $data['code'];
1036 $info = $data['info'];
1037 unset( $data['code'], $data['info'] );
1038 $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1040 // Something is seriously wrong
1041 $config = $this->getConfig();
1042 $code = 'internal_api_error_' . get_class( $e );
1043 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
1044 $params = [ 'apierror-databaseerror', WebRequest
::getRequestId() ];
1047 'apierror-exceptioncaught',
1048 WebRequest
::getRequestId(),
1049 $e instanceof ILocalizedException
1050 ?
$e->getMessageObject()
1051 : wfEscapeWikiText( $e->getMessage() )
1054 $messages[] = ApiMessage
::create( $params, $code );
1060 * Replace the result data with the information about an exception.
1061 * @param Exception $e
1062 * @return string[] Error codes
1064 protected function substituteResultWithError( $e ) {
1065 $result = $this->getResult();
1066 $formatter = $this->getErrorFormatter();
1067 $config = $this->getConfig();
1070 // Remember existing warnings and errors across the reset
1071 $errors = $result->getResultData( [ 'errors' ] );
1072 $warnings = $result->getResultData( [ 'warnings' ] );
1074 if ( $warnings !== null ) {
1075 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1077 if ( $errors !== null ) {
1078 $result->addValue( null, 'errors', $errors, ApiResult
::NO_SIZE_CHECK
);
1080 // Collect the copied error codes for the return value
1081 foreach ( $errors as $error ) {
1082 if ( isset( $error['code'] ) ) {
1083 $errorCodes[$error['code']] = true;
1088 // Add errors from the exception
1089 $modulePath = $e instanceof ApiUsageException ?
$e->getModulePath() : null;
1090 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1091 $errorCodes[$msg->getApiCode()] = true;
1092 $formatter->addError( $modulePath, $msg );
1094 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1095 $formatter->addWarning( $modulePath, $msg );
1098 // Add additional data. Path depends on whether we're in BC mode or not.
1099 // Data depends on the type of exception.
1100 if ( $formatter instanceof ApiErrorFormatter_BackCompat
) {
1101 $path = [ 'error' ];
1105 if ( $e instanceof ApiUsageException ||
$e instanceof UsageException
) {
1106 $link = wfExpandUrl( wfScript( 'api' ) );
1107 $result->addContentValue(
1110 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1113 if ( $config->get( 'ShowExceptionDetails' ) ) {
1114 $result->addContentValue(
1117 $this->msg( 'api-exception-trace',
1121 MWExceptionHandler
::getRedactedTraceAsString( $e )
1122 )->inLanguage( $formatter->getLanguage() )->text()
1127 // Add the id and such
1128 $this->addRequestedFields( [ 'servedby' ] );
1130 return array_keys( $errorCodes );
1134 * Add requested fields to the result
1135 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1138 protected function addRequestedFields( $force = [] ) {
1139 $result = $this->getResult();
1141 $requestid = $this->getParameter( 'requestid' );
1142 if ( $requestid !== null ) {
1143 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1146 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1147 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1149 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1152 if ( $this->getParameter( 'curtimestamp' ) ) {
1153 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1154 ApiResult
::NO_SIZE_CHECK
);
1157 if ( $this->getParameter( 'responselanginfo' ) ) {
1158 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1159 ApiResult
::NO_SIZE_CHECK
);
1160 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1161 ApiResult
::NO_SIZE_CHECK
);
1166 * Set up for the execution.
1169 protected function setupExecuteAction() {
1170 $this->addRequestedFields();
1172 $params = $this->extractRequestParams();
1173 $this->mAction
= $params['action'];
1179 * Set up the module for response
1180 * @return ApiBase The module that will handle this action
1181 * @throws MWException
1182 * @throws ApiUsageException
1184 protected function setupModule() {
1185 // Instantiate the module requested by the user
1186 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1187 if ( $module === null ) {
1188 $this->dieWithError(
1189 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1192 $moduleParams = $module->extractRequestParams();
1194 // Check token, if necessary
1195 if ( $module->needsToken() === true ) {
1196 throw new MWException(
1197 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1198 'See documentation for ApiBase::needsToken for details.'
1201 if ( $module->needsToken() ) {
1202 if ( !$module->mustBePosted() ) {
1203 throw new MWException(
1204 "Module '{$module->getModuleName()}' must require POST to use tokens."
1208 if ( !isset( $moduleParams['token'] ) ) {
1209 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1212 $module->requirePostedParameters( [ 'token' ] );
1214 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1215 $module->dieWithError( 'apierror-badtoken' );
1223 * Check the max lag if necessary
1224 * @param ApiBase $module Api module being used
1225 * @param array $params Array an array containing the request parameters.
1226 * @return bool True on success, false should exit immediately
1228 protected function checkMaxLag( $module, $params ) {
1229 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1230 $maxLag = $params['maxlag'];
1231 list( $host, $lag ) = wfGetLB()->getMaxLag();
1232 if ( $lag > $maxLag ) {
1233 $response = $this->getRequest()->response();
1235 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1236 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1238 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1239 $this->dieWithError( [ 'apierror-maxlag', $lag, $host ] );
1242 $this->dieWithError( [ 'apierror-maxlag-generic', $lag ], 'maxlag' );
1250 * Check selected RFC 7232 precondition headers
1252 * RFC 7232 envisions a particular model where you send your request to "a
1253 * resource", and for write requests that you can read "the resource" by
1254 * changing the method to GET. When the API receives a GET request, it
1255 * works out even though "the resource" from RFC 7232's perspective might
1256 * be many resources from MediaWiki's perspective. But it totally fails for
1257 * a POST, since what HTTP sees as "the resource" is probably just
1258 * "/api.php" with all the interesting bits in the body.
1260 * Therefore, we only support RFC 7232 precondition headers for GET (and
1261 * HEAD). That means we don't need to bother with If-Match and
1262 * If-Unmodified-Since since they only apply to modification requests.
1264 * And since we don't support Range, If-Range is ignored too.
1267 * @param ApiBase $module Api module being used
1268 * @return bool True on success, false should exit immediately
1270 protected function checkConditionalRequestHeaders( $module ) {
1271 if ( $this->mInternalMode
) {
1272 // No headers to check in internal mode
1276 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1277 // Don't check POSTs
1283 $ifNoneMatch = array_diff(
1284 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1287 if ( $ifNoneMatch ) {
1288 if ( $ifNoneMatch === [ '*' ] ) {
1289 // API responses always "exist"
1292 $etag = $module->getConditionalRequestData( 'etag' );
1295 if ( $ifNoneMatch && $etag !== null ) {
1296 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1297 $match = array_map( function ( $s ) {
1298 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1300 $return304 = in_array( $test, $match, true );
1302 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1304 // Some old browsers sends sizes after the date, like this:
1305 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1307 $i = strpos( $value, ';' );
1308 if ( $i !== false ) {
1309 $value = trim( substr( $value, 0, $i ) );
1312 if ( $value !== '' ) {
1314 $ts = new MWTimestamp( $value );
1316 // RFC 7231 IMF-fixdate
1317 $ts->getTimestamp( TS_RFC2822
) === $value ||
1319 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1320 // asctime (with and without space-padded day)
1321 $ts->format( 'D M j H:i:s Y' ) === $value ||
1322 $ts->format( 'D M j H:i:s Y' ) === $value
1324 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1325 if ( $lastMod !== null ) {
1326 // Mix in some MediaWiki modification times
1329 'user' => $this->getUser()->getTouched(),
1330 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1332 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1333 // T46570: the core page itself may not change, but resources might
1334 $modifiedTimes['sepoch'] = wfTimestamp(
1335 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1338 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1339 $lastMod = max( $modifiedTimes );
1340 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1343 } catch ( TimestampException
$e ) {
1344 // Invalid timestamp, ignore it
1350 $this->getRequest()->response()->statusHeader( 304 );
1352 // Avoid outputting the compressed representation of a zero-length body
1353 MediaWiki\
suppressWarnings();
1354 ini_set( 'zlib.output_compression', 0 );
1355 MediaWiki\restoreWarnings
();
1356 wfClearOutputBuffers();
1365 * Check for sufficient permissions to execute
1366 * @param ApiBase $module An Api module
1368 protected function checkExecutePermissions( $module ) {
1369 $user = $this->getUser();
1370 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1371 !$user->isAllowed( 'read' )
1373 $this->dieWithError( 'apierror-readapidenied' );
1376 if ( $module->isWriteMode() ) {
1377 if ( !$this->mEnableWrite
) {
1378 $this->dieWithError( 'apierror-noapiwrite' );
1379 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1380 $this->dieWithError( 'apierror-writeapidenied' );
1381 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1382 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1385 $this->checkReadOnly( $module );
1388 // Allow extensions to stop execution for arbitrary reasons.
1390 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1391 $this->dieWithError( $message );
1396 * Check if the DB is read-only for this user
1397 * @param ApiBase $module An Api module
1399 protected function checkReadOnly( $module ) {
1400 if ( wfReadOnly() ) {
1401 $this->dieReadOnly();
1404 if ( $module->isWriteMode()
1405 && $this->getUser()->isBot()
1406 && wfGetLB()->getServerCount() > 1
1408 $this->checkBotReadOnly();
1413 * Check whether we are readonly for bots
1415 private function checkBotReadOnly() {
1416 // Figure out how many servers have passed the lag threshold
1418 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1419 $laggedServers = [];
1420 $loadBalancer = wfGetLB();
1421 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1422 if ( $lag > $lagLimit ) {
1424 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1428 // If a majority of replica DBs are too lagged then disallow writes
1429 $replicaCount = wfGetLB()->getServerCount() - 1;
1430 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1431 $laggedServers = implode( ', ', $laggedServers );
1434 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1437 $this->dieWithError(
1440 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1446 * Check asserts of the user's rights
1447 * @param array $params
1449 protected function checkAsserts( $params ) {
1450 if ( isset( $params['assert'] ) ) {
1451 $user = $this->getUser();
1452 switch ( $params['assert'] ) {
1454 if ( $user->isAnon() ) {
1455 $this->dieWithError( 'apierror-assertuserfailed' );
1459 if ( !$user->isAllowed( 'bot' ) ) {
1460 $this->dieWithError( 'apierror-assertbotfailed' );
1465 if ( isset( $params['assertuser'] ) ) {
1466 $assertUser = User
::newFromName( $params['assertuser'], false );
1467 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1468 $this->dieWithError(
1469 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1476 * Check POST for external response and setup result printer
1477 * @param ApiBase $module An Api module
1478 * @param array $params An array with the request parameters
1480 protected function setupExternalResponse( $module, $params ) {
1481 $request = $this->getRequest();
1482 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1483 // Module requires POST. GET request might still be allowed
1484 // if $wgDebugApi is true, otherwise fail.
1485 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1488 // See if custom printer is used
1489 $this->mPrinter
= $module->getCustomPrinter();
1490 if ( is_null( $this->mPrinter
) ) {
1491 // Create an appropriate printer
1492 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1495 if ( $request->getProtocol() === 'http' && (
1496 $request->getSession()->shouldForceHTTPS() ||
1497 ( $this->getUser()->isLoggedIn() &&
1498 $this->getUser()->requiresHTTPS() )
1500 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1505 * Execute the actual module, without any error handling
1507 protected function executeAction() {
1508 $params = $this->setupExecuteAction();
1509 $module = $this->setupModule();
1510 $this->mModule
= $module;
1512 if ( !$this->mInternalMode
) {
1513 $this->setRequestExpectations( $module );
1516 $this->checkExecutePermissions( $module );
1518 if ( !$this->checkMaxLag( $module, $params ) ) {
1522 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1526 if ( !$this->mInternalMode
) {
1527 $this->setupExternalResponse( $module, $params );
1530 $this->checkAsserts( $params );
1534 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1536 $this->reportUnusedParams();
1538 if ( !$this->mInternalMode
) {
1539 // append Debug information
1540 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1542 // Print result data
1543 $this->printResult();
1548 * Set database connection, query, and write expectations given this module request
1549 * @param ApiBase $module
1551 protected function setRequestExpectations( ApiBase
$module ) {
1552 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1553 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1554 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1555 if ( $this->getRequest()->hasSafeMethod() ) {
1556 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1557 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1558 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1559 $this->getRequest()->markAsSafeRequest();
1561 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1566 * Log the preceding request
1567 * @param float $time Time in seconds
1568 * @param Exception $e Exception caught while processing the request
1570 protected function logRequest( $time, $e = null ) {
1571 $request = $this->getRequest();
1574 'ip' => $request->getIP(),
1575 'userAgent' => $this->getUserAgent(),
1576 'wiki' => wfWikiID(),
1577 'timeSpentBackend' => (int)round( $time * 1000 ),
1578 'hadError' => $e !== null,
1584 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1585 $logCtx['errorCodes'][] = $msg->getApiCode();
1589 // Construct space separated message for 'api' log channel
1590 $msg = "API {$request->getMethod()} " .
1591 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1592 " {$logCtx['ip']} " .
1593 "T={$logCtx['timeSpentBackend']}ms";
1595 foreach ( $this->getParamsUsed() as $name ) {
1596 $value = $request->getVal( $name );
1597 if ( $value === null ) {
1601 if ( strlen( $value ) > 256 ) {
1602 $value = substr( $value, 0, 256 );
1603 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1605 $encValue = $this->encodeRequestLogValue( $value );
1608 $logCtx['params'][$name] = $value;
1609 $msg .= " {$name}={$encValue}";
1612 wfDebugLog( 'api', $msg, 'private' );
1613 // ApiAction channel is for structured data consumers
1614 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1618 * Encode a value in a format suitable for a space-separated log line.
1622 protected function encodeRequestLogValue( $s ) {
1625 $chars = ';@$!*(),/:';
1626 $numChars = strlen( $chars );
1627 for ( $i = 0; $i < $numChars; $i++
) {
1628 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1632 return strtr( rawurlencode( $s ), $table );
1636 * Get the request parameters used in the course of the preceding execute() request
1639 protected function getParamsUsed() {
1640 return array_keys( $this->mParamsUsed
);
1644 * Mark parameters as used
1645 * @param string|string[] $params
1647 public function markParamsUsed( $params ) {
1648 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1652 * Get a request value, and register the fact that it was used, for logging.
1653 * @param string $name
1654 * @param mixed $default
1657 public function getVal( $name, $default = null ) {
1658 $this->mParamsUsed
[$name] = true;
1660 $ret = $this->getRequest()->getVal( $name );
1661 if ( $ret === null ) {
1662 if ( $this->getRequest()->getArray( $name ) !== null ) {
1663 // See bug 10262 for why we don't just implode( '|', ... ) the
1665 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1673 * Get a boolean request value, and register the fact that the parameter
1674 * was used, for logging.
1675 * @param string $name
1678 public function getCheck( $name ) {
1679 return $this->getVal( $name, null ) !== null;
1683 * Get a request upload, and register the fact that it was used, for logging.
1686 * @param string $name Parameter name
1687 * @return WebRequestUpload
1689 public function getUpload( $name ) {
1690 $this->mParamsUsed
[$name] = true;
1692 return $this->getRequest()->getUpload( $name );
1696 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1697 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1699 protected function reportUnusedParams() {
1700 $paramsUsed = $this->getParamsUsed();
1701 $allParams = $this->getRequest()->getValueNames();
1703 if ( !$this->mInternalMode
) {
1704 // Printer has not yet executed; don't warn that its parameters are unused
1705 $printerParams = $this->mPrinter
->encodeParamName(
1706 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1708 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1710 $unusedParams = array_diff( $allParams, $paramsUsed );
1713 if ( count( $unusedParams ) ) {
1714 $this->addWarning( [
1715 'apierror-unrecognizedparams',
1716 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1717 count( $unusedParams )
1723 * Print results using the current printer
1725 * @param int $httpCode HTTP status code, or 0 to not change
1727 protected function printResult( $httpCode = 0 ) {
1728 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1729 $this->addWarning( 'apiwarn-wgDebugAPI' );
1732 $printer = $this->mPrinter
;
1733 $printer->initPrinter( false );
1735 $printer->setHttpStatus( $httpCode );
1737 $printer->execute();
1738 $printer->closePrinter();
1744 public function isReadMode() {
1749 * See ApiBase for description.
1753 public function getAllowedParams() {
1756 ApiBase
::PARAM_DFLT
=> 'help',
1757 ApiBase
::PARAM_TYPE
=> 'submodule',
1760 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1761 ApiBase
::PARAM_TYPE
=> 'submodule',
1764 ApiBase
::PARAM_TYPE
=> 'integer'
1767 ApiBase
::PARAM_TYPE
=> 'integer',
1768 ApiBase
::PARAM_DFLT
=> 0
1771 ApiBase
::PARAM_TYPE
=> 'integer',
1772 ApiBase
::PARAM_DFLT
=> 0
1775 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1778 ApiBase
::PARAM_TYPE
=> 'user',
1780 'requestid' => null,
1781 'servedby' => false,
1782 'curtimestamp' => false,
1783 'responselanginfo' => false,
1786 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1789 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1790 ApiBase
::PARAM_DFLT
=> 'bc',
1793 ApiBase
::PARAM_DFLT
=> 'uselang',
1795 'errorsuselocal' => [
1796 ApiBase
::PARAM_DFLT
=> false,
1801 /** @see ApiBase::getExamplesMessages() */
1802 protected function getExamplesMessages() {
1805 => 'apihelp-help-example-main',
1806 'action=help&recursivesubmodules=1'
1807 => 'apihelp-help-example-recursive',
1811 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1812 // Wish PHP had an "array_insert_before". Instead, we have to manually
1813 // reindex the array to get 'permissions' in the right place.
1816 foreach ( $oldHelp as $k => $v ) {
1817 if ( $k === 'submodules' ) {
1818 $help['permissions'] = '';
1822 $help['datatypes'] = '';
1823 $help['credits'] = '';
1825 // Fill 'permissions'
1826 $help['permissions'] .= Html
::openElement( 'div',
1827 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1828 $m = $this->msg( 'api-help-permissions' );
1829 if ( !$m->isDisabled() ) {
1830 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1831 $m->numParams( count( self
::$mRights ) )->parse()
1834 $help['permissions'] .= Html
::openElement( 'dl' );
1835 foreach ( self
::$mRights as $right => $rightMsg ) {
1836 $help['permissions'] .= Html
::element( 'dt', null, $right );
1838 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1839 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1841 $groups = array_map( function ( $group ) {
1842 return $group == '*' ?
'all' : $group;
1843 }, User
::getGroupsWithPermission( $right ) );
1845 $help['permissions'] .= Html
::rawElement( 'dd', null,
1846 $this->msg( 'api-help-permissions-granted-to' )
1847 ->numParams( count( $groups ) )
1848 ->params( Message
::listParam( $groups ) )
1852 $help['permissions'] .= Html
::closeElement( 'dl' );
1853 $help['permissions'] .= Html
::closeElement( 'div' );
1855 // Fill 'datatypes' and 'credits', if applicable
1856 if ( empty( $options['nolead'] ) ) {
1857 $level = $options['headerlevel'];
1858 $tocnumber = &$options['tocnumber'];
1860 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1862 // Add an additional span with sanitized ID
1863 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1864 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1867 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1868 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1871 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1872 if ( !isset( $tocData['main/datatypes'] ) ) {
1873 $tocnumber[$level]++
;
1874 $tocData['main/datatypes'] = [
1875 'toclevel' => count( $tocnumber ),
1877 'anchor' => 'main/datatypes',
1879 'number' => implode( '.', $tocnumber ),
1884 // Add an additional span with sanitized ID
1885 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1886 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1889 $header = $this->msg( 'api-credits-header' )->parse();
1890 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1891 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1894 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1895 if ( !isset( $tocData['main/credits'] ) ) {
1896 $tocnumber[$level]++
;
1897 $tocData['main/credits'] = [
1898 'toclevel' => count( $tocnumber ),
1900 'anchor' => 'main/credits',
1902 'number' => implode( '.', $tocnumber ),
1909 private $mCanApiHighLimits = null;
1912 * Check whether the current user is allowed to use high limits
1915 public function canApiHighLimits() {
1916 if ( !isset( $this->mCanApiHighLimits
) ) {
1917 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1920 return $this->mCanApiHighLimits
;
1924 * Overrides to return this instance's module manager.
1925 * @return ApiModuleManager
1927 public function getModuleManager() {
1928 return $this->mModuleMgr
;
1932 * Fetches the user agent used for this request
1934 * The value will be the combination of the 'Api-User-Agent' header (if
1935 * any) and the standard User-Agent header (if any).
1939 public function getUserAgent() {
1941 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1942 $this->getRequest()->getHeader( 'User-agent' )
1948 * For really cool vim folding this needs to be at the end:
1949 * vim: foldmarker=@{,@} foldmethod=marker