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 wfEscapeWikiText( $e->getMessage() )
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(
1108 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1111 if ( $config->get( 'ShowExceptionDetails' ) ) {
1112 $result->addContentValue(
1115 $this->msg( 'api-exception-trace',
1119 MWExceptionHandler
::getRedactedTraceAsString( $e )
1120 )->inLanguage( $formatter->getLanguage() )->text()
1125 // Add the id and such
1126 $this->addRequestedFields( [ 'servedby' ] );
1128 return array_keys( $errorCodes );
1132 * Add requested fields to the result
1133 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1136 protected function addRequestedFields( $force = [] ) {
1137 $result = $this->getResult();
1139 $requestid = $this->getParameter( 'requestid' );
1140 if ( $requestid !== null ) {
1141 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1144 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1145 in_array( 'servedby', $force, true ) ||
$this->getParameter( 'servedby' )
1147 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1150 if ( $this->getParameter( 'curtimestamp' ) ) {
1151 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1152 ApiResult
::NO_SIZE_CHECK
);
1155 if ( $this->getParameter( 'responselanginfo' ) ) {
1156 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1157 ApiResult
::NO_SIZE_CHECK
);
1158 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1159 ApiResult
::NO_SIZE_CHECK
);
1164 * Set up for the execution.
1167 protected function setupExecuteAction() {
1168 $this->addRequestedFields();
1170 $params = $this->extractRequestParams();
1171 $this->mAction
= $params['action'];
1177 * Set up the module for response
1178 * @return ApiBase The module that will handle this action
1179 * @throws MWException
1180 * @throws ApiUsageException
1182 protected function setupModule() {
1183 // Instantiate the module requested by the user
1184 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1185 if ( $module === null ) {
1186 $this->dieWithError(
1187 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction
) ], 'unknown_action'
1190 $moduleParams = $module->extractRequestParams();
1192 // Check token, if necessary
1193 if ( $module->needsToken() === true ) {
1194 throw new MWException(
1195 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1196 'See documentation for ApiBase::needsToken for details.'
1199 if ( $module->needsToken() ) {
1200 if ( !$module->mustBePosted() ) {
1201 throw new MWException(
1202 "Module '{$module->getModuleName()}' must require POST to use tokens."
1206 if ( !isset( $moduleParams['token'] ) ) {
1207 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1210 $module->requirePostedParameters( [ 'token' ] );
1212 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1213 $module->dieWithError( 'apierror-badtoken' );
1221 * Check the max lag if necessary
1222 * @param ApiBase $module Api module being used
1223 * @param array $params Array an array containing the request parameters.
1224 * @return bool True on success, false should exit immediately
1226 protected function checkMaxLag( $module, $params ) {
1227 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1228 $maxLag = $params['maxlag'];
1229 list( $host, $lag ) = wfGetLB()->getMaxLag();
1230 if ( $lag > $maxLag ) {
1231 $response = $this->getRequest()->response();
1233 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1234 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1236 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1237 $this->dieWithError( [ 'apierror-maxlag', $lag, $host ] );
1240 $this->dieWithError( [ 'apierror-maxlag-generic', $lag ], 'maxlag' );
1248 * Check selected RFC 7232 precondition headers
1250 * RFC 7232 envisions a particular model where you send your request to "a
1251 * resource", and for write requests that you can read "the resource" by
1252 * changing the method to GET. When the API receives a GET request, it
1253 * works out even though "the resource" from RFC 7232's perspective might
1254 * be many resources from MediaWiki's perspective. But it totally fails for
1255 * a POST, since what HTTP sees as "the resource" is probably just
1256 * "/api.php" with all the interesting bits in the body.
1258 * Therefore, we only support RFC 7232 precondition headers for GET (and
1259 * HEAD). That means we don't need to bother with If-Match and
1260 * If-Unmodified-Since since they only apply to modification requests.
1262 * And since we don't support Range, If-Range is ignored too.
1265 * @param ApiBase $module Api module being used
1266 * @return bool True on success, false should exit immediately
1268 protected function checkConditionalRequestHeaders( $module ) {
1269 if ( $this->mInternalMode
) {
1270 // No headers to check in internal mode
1274 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1275 // Don't check POSTs
1281 $ifNoneMatch = array_diff(
1282 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1285 if ( $ifNoneMatch ) {
1286 if ( $ifNoneMatch === [ '*' ] ) {
1287 // API responses always "exist"
1290 $etag = $module->getConditionalRequestData( 'etag' );
1293 if ( $ifNoneMatch && $etag !== null ) {
1294 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1295 $match = array_map( function ( $s ) {
1296 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1298 $return304 = in_array( $test, $match, true );
1300 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1302 // Some old browsers sends sizes after the date, like this:
1303 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1305 $i = strpos( $value, ';' );
1306 if ( $i !== false ) {
1307 $value = trim( substr( $value, 0, $i ) );
1310 if ( $value !== '' ) {
1312 $ts = new MWTimestamp( $value );
1314 // RFC 7231 IMF-fixdate
1315 $ts->getTimestamp( TS_RFC2822
) === $value ||
1317 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1318 // asctime (with and without space-padded day)
1319 $ts->format( 'D M j H:i:s Y' ) === $value ||
1320 $ts->format( 'D M j H:i:s Y' ) === $value
1322 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1323 if ( $lastMod !== null ) {
1324 // Mix in some MediaWiki modification times
1327 'user' => $this->getUser()->getTouched(),
1328 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1330 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1331 // T46570: the core page itself may not change, but resources might
1332 $modifiedTimes['sepoch'] = wfTimestamp(
1333 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1336 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1337 $lastMod = max( $modifiedTimes );
1338 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1341 } catch ( TimestampException
$e ) {
1342 // Invalid timestamp, ignore it
1348 $this->getRequest()->response()->statusHeader( 304 );
1350 // Avoid outputting the compressed representation of a zero-length body
1351 MediaWiki\
suppressWarnings();
1352 ini_set( 'zlib.output_compression', 0 );
1353 MediaWiki\restoreWarnings
();
1354 wfClearOutputBuffers();
1363 * Check for sufficient permissions to execute
1364 * @param ApiBase $module An Api module
1366 protected function checkExecutePermissions( $module ) {
1367 $user = $this->getUser();
1368 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1369 !$user->isAllowed( 'read' )
1371 $this->dieWithError( 'apierror-readapidenied' );
1374 if ( $module->isWriteMode() ) {
1375 if ( !$this->mEnableWrite
) {
1376 $this->dieWithError( 'apierror-noapiwrite' );
1377 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1378 $this->dieWithError( 'apierror-writeapidenied' );
1379 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1380 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1383 $this->checkReadOnly( $module );
1386 // Allow extensions to stop execution for arbitrary reasons.
1388 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1389 $this->dieWithError( $message );
1394 * Check if the DB is read-only for this user
1395 * @param ApiBase $module An Api module
1397 protected function checkReadOnly( $module ) {
1398 if ( wfReadOnly() ) {
1399 $this->dieReadOnly();
1402 if ( $module->isWriteMode()
1403 && $this->getUser()->isBot()
1404 && wfGetLB()->getServerCount() > 1
1406 $this->checkBotReadOnly();
1411 * Check whether we are readonly for bots
1413 private function checkBotReadOnly() {
1414 // Figure out how many servers have passed the lag threshold
1416 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1417 $laggedServers = [];
1418 $loadBalancer = wfGetLB();
1419 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1420 if ( $lag > $lagLimit ) {
1422 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1426 // If a majority of replica DBs are too lagged then disallow writes
1427 $replicaCount = wfGetLB()->getServerCount() - 1;
1428 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1429 $laggedServers = implode( ', ', $laggedServers );
1432 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1435 $this->dieWithError(
1438 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1444 * Check asserts of the user's rights
1445 * @param array $params
1447 protected function checkAsserts( $params ) {
1448 if ( isset( $params['assert'] ) ) {
1449 $user = $this->getUser();
1450 switch ( $params['assert'] ) {
1452 if ( $user->isAnon() ) {
1453 $this->dieWithError( 'apierror-assertuserfailed' );
1457 if ( !$user->isAllowed( 'bot' ) ) {
1458 $this->dieWithError( 'apierror-assertbotfailed' );
1463 if ( isset( $params['assertuser'] ) ) {
1464 $assertUser = User
::newFromName( $params['assertuser'], false );
1465 if ( !$assertUser ||
!$this->getUser()->equals( $assertUser ) ) {
1466 $this->dieWithError(
1467 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1474 * Check POST for external response and setup result printer
1475 * @param ApiBase $module An Api module
1476 * @param array $params An array with the request parameters
1478 protected function setupExternalResponse( $module, $params ) {
1479 $request = $this->getRequest();
1480 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1481 // Module requires POST. GET request might still be allowed
1482 // if $wgDebugApi is true, otherwise fail.
1483 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction
] );
1486 // See if custom printer is used
1487 $this->mPrinter
= $module->getCustomPrinter();
1488 if ( is_null( $this->mPrinter
) ) {
1489 // Create an appropriate printer
1490 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1493 if ( $request->getProtocol() === 'http' && (
1494 $request->getSession()->shouldForceHTTPS() ||
1495 ( $this->getUser()->isLoggedIn() &&
1496 $this->getUser()->requiresHTTPS() )
1498 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1503 * Execute the actual module, without any error handling
1505 protected function executeAction() {
1506 $params = $this->setupExecuteAction();
1507 $module = $this->setupModule();
1508 $this->mModule
= $module;
1510 if ( !$this->mInternalMode
) {
1511 $this->setRequestExpectations( $module );
1514 $this->checkExecutePermissions( $module );
1516 if ( !$this->checkMaxLag( $module, $params ) ) {
1520 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1524 if ( !$this->mInternalMode
) {
1525 $this->setupExternalResponse( $module, $params );
1528 $this->checkAsserts( $params );
1532 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1534 $this->reportUnusedParams();
1536 if ( !$this->mInternalMode
) {
1537 // append Debug information
1538 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1540 // Print result data
1541 $this->printResult();
1546 * Set database connection, query, and write expectations given this module request
1547 * @param ApiBase $module
1549 protected function setRequestExpectations( ApiBase
$module ) {
1550 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1551 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1552 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1553 if ( $this->getRequest()->hasSafeMethod() ) {
1554 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1555 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1556 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1557 $this->getRequest()->markAsSafeRequest();
1559 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1564 * Log the preceding request
1565 * @param float $time Time in seconds
1566 * @param Exception $e Exception caught while processing the request
1568 protected function logRequest( $time, $e = null ) {
1569 $request = $this->getRequest();
1572 'ip' => $request->getIP(),
1573 'userAgent' => $this->getUserAgent(),
1574 'wiki' => wfWikiID(),
1575 'timeSpentBackend' => (int)round( $time * 1000 ),
1576 'hadError' => $e !== null,
1582 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1583 $logCtx['errorCodes'][] = $msg->getApiCode();
1587 // Construct space separated message for 'api' log channel
1588 $msg = "API {$request->getMethod()} " .
1589 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1590 " {$logCtx['ip']} " .
1591 "T={$logCtx['timeSpentBackend']}ms";
1593 foreach ( $this->getParamsUsed() as $name ) {
1594 $value = $request->getVal( $name );
1595 if ( $value === null ) {
1599 if ( strlen( $value ) > 256 ) {
1600 $value = substr( $value, 0, 256 );
1601 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1603 $encValue = $this->encodeRequestLogValue( $value );
1606 $logCtx['params'][$name] = $value;
1607 $msg .= " {$name}={$encValue}";
1610 wfDebugLog( 'api', $msg, 'private' );
1611 // ApiAction channel is for structured data consumers
1612 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1616 * Encode a value in a format suitable for a space-separated log line.
1620 protected function encodeRequestLogValue( $s ) {
1623 $chars = ';@$!*(),/:';
1624 $numChars = strlen( $chars );
1625 for ( $i = 0; $i < $numChars; $i++
) {
1626 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1630 return strtr( rawurlencode( $s ), $table );
1634 * Get the request parameters used in the course of the preceding execute() request
1637 protected function getParamsUsed() {
1638 return array_keys( $this->mParamsUsed
);
1642 * Mark parameters as used
1643 * @param string|string[] $params
1645 public function markParamsUsed( $params ) {
1646 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1650 * Get a request value, and register the fact that it was used, for logging.
1651 * @param string $name
1652 * @param mixed $default
1655 public function getVal( $name, $default = null ) {
1656 $this->mParamsUsed
[$name] = true;
1658 $ret = $this->getRequest()->getVal( $name );
1659 if ( $ret === null ) {
1660 if ( $this->getRequest()->getArray( $name ) !== null ) {
1661 // See bug 10262 for why we don't just implode( '|', ... ) the
1663 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1671 * Get a boolean request value, and register the fact that the parameter
1672 * was used, for logging.
1673 * @param string $name
1676 public function getCheck( $name ) {
1677 return $this->getVal( $name, null ) !== null;
1681 * Get a request upload, and register the fact that it was used, for logging.
1684 * @param string $name Parameter name
1685 * @return WebRequestUpload
1687 public function getUpload( $name ) {
1688 $this->mParamsUsed
[$name] = true;
1690 return $this->getRequest()->getUpload( $name );
1694 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1695 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1697 protected function reportUnusedParams() {
1698 $paramsUsed = $this->getParamsUsed();
1699 $allParams = $this->getRequest()->getValueNames();
1701 if ( !$this->mInternalMode
) {
1702 // Printer has not yet executed; don't warn that its parameters are unused
1703 $printerParams = $this->mPrinter
->encodeParamName(
1704 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1706 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1708 $unusedParams = array_diff( $allParams, $paramsUsed );
1711 if ( count( $unusedParams ) ) {
1712 $this->addWarning( [
1713 'apierror-unrecognizedparams',
1714 Message
::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1715 count( $unusedParams )
1721 * Print results using the current printer
1723 * @param int $httpCode HTTP status code, or 0 to not change
1725 protected function printResult( $httpCode = 0 ) {
1726 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1727 $this->addWarning( 'apiwarn-wgDebugAPI' );
1730 $printer = $this->mPrinter
;
1731 $printer->initPrinter( false );
1733 $printer->setHttpStatus( $httpCode );
1735 $printer->execute();
1736 $printer->closePrinter();
1742 public function isReadMode() {
1747 * See ApiBase for description.
1751 public function getAllowedParams() {
1754 ApiBase
::PARAM_DFLT
=> 'help',
1755 ApiBase
::PARAM_TYPE
=> 'submodule',
1758 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1759 ApiBase
::PARAM_TYPE
=> 'submodule',
1762 ApiBase
::PARAM_TYPE
=> 'integer'
1765 ApiBase
::PARAM_TYPE
=> 'integer',
1766 ApiBase
::PARAM_DFLT
=> 0
1769 ApiBase
::PARAM_TYPE
=> 'integer',
1770 ApiBase
::PARAM_DFLT
=> 0
1773 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1776 ApiBase
::PARAM_TYPE
=> 'user',
1778 'requestid' => null,
1779 'servedby' => false,
1780 'curtimestamp' => false,
1781 'responselanginfo' => false,
1784 ApiBase
::PARAM_DFLT
=> self
::API_DEFAULT_USELANG
,
1787 ApiBase
::PARAM_TYPE
=> [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1788 ApiBase
::PARAM_DFLT
=> 'bc',
1791 ApiBase
::PARAM_DFLT
=> 'uselang',
1793 'errorsuselocal' => [
1794 ApiBase
::PARAM_DFLT
=> false,
1799 /** @see ApiBase::getExamplesMessages() */
1800 protected function getExamplesMessages() {
1803 => 'apihelp-help-example-main',
1804 'action=help&recursivesubmodules=1'
1805 => 'apihelp-help-example-recursive',
1809 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1810 // Wish PHP had an "array_insert_before". Instead, we have to manually
1811 // reindex the array to get 'permissions' in the right place.
1814 foreach ( $oldHelp as $k => $v ) {
1815 if ( $k === 'submodules' ) {
1816 $help['permissions'] = '';
1820 $help['datatypes'] = '';
1821 $help['credits'] = '';
1823 // Fill 'permissions'
1824 $help['permissions'] .= Html
::openElement( 'div',
1825 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1826 $m = $this->msg( 'api-help-permissions' );
1827 if ( !$m->isDisabled() ) {
1828 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1829 $m->numParams( count( self
::$mRights ) )->parse()
1832 $help['permissions'] .= Html
::openElement( 'dl' );
1833 foreach ( self
::$mRights as $right => $rightMsg ) {
1834 $help['permissions'] .= Html
::element( 'dt', null, $right );
1836 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1837 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1839 $groups = array_map( function ( $group ) {
1840 return $group == '*' ?
'all' : $group;
1841 }, User
::getGroupsWithPermission( $right ) );
1843 $help['permissions'] .= Html
::rawElement( 'dd', null,
1844 $this->msg( 'api-help-permissions-granted-to' )
1845 ->numParams( count( $groups ) )
1846 ->params( Message
::listParam( $groups ) )
1850 $help['permissions'] .= Html
::closeElement( 'dl' );
1851 $help['permissions'] .= Html
::closeElement( 'div' );
1853 // Fill 'datatypes' and 'credits', if applicable
1854 if ( empty( $options['nolead'] ) ) {
1855 $level = $options['headerlevel'];
1856 $tocnumber = &$options['tocnumber'];
1858 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1860 // Add an additional span with sanitized ID
1861 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1862 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1865 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1866 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1869 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1870 if ( !isset( $tocData['main/datatypes'] ) ) {
1871 $tocnumber[$level]++
;
1872 $tocData['main/datatypes'] = [
1873 'toclevel' => count( $tocnumber ),
1875 'anchor' => 'main/datatypes',
1877 'number' => implode( '.', $tocnumber ),
1882 // Add an additional span with sanitized ID
1883 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1884 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1887 $header = $this->msg( 'api-credits-header' )->parse();
1888 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1889 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1892 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1893 if ( !isset( $tocData['main/credits'] ) ) {
1894 $tocnumber[$level]++
;
1895 $tocData['main/credits'] = [
1896 'toclevel' => count( $tocnumber ),
1898 'anchor' => 'main/credits',
1900 'number' => implode( '.', $tocnumber ),
1907 private $mCanApiHighLimits = null;
1910 * Check whether the current user is allowed to use high limits
1913 public function canApiHighLimits() {
1914 if ( !isset( $this->mCanApiHighLimits
) ) {
1915 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1918 return $this->mCanApiHighLimits
;
1922 * Overrides to return this instance's module manager.
1923 * @return ApiModuleManager
1925 public function getModuleManager() {
1926 return $this->mModuleMgr
;
1930 * Fetches the user agent used for this request
1932 * The value will be the combination of the 'Api-User-Agent' header (if
1933 * any) and the standard User-Agent header (if any).
1937 public function getUserAgent() {
1939 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1940 $this->getRequest()->getHeader( 'User-agent' )
1946 * For really cool vim folding this needs to be at the end:
1947 * vim: foldmarker=@{,@} foldmethod=marker