Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / api / ApiMain.php
blob52f1d95830ffda43a43242e8251463b1a95bdc4c
1 <?php
2 /**
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
24 * @file
25 * @defgroup API API
28 use MediaWiki\Logger\LoggerFactory;
30 /**
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.
41 * @ingroup API
43 class ApiMain extends ApiBase {
44 /**
45 * When no format parameter is given, this format will be used
47 const API_DEFAULT_FORMAT = 'jsonfm';
49 /**
50 * When no uselang parameter is given, this language will be used
52 const API_DEFAULT_USELANG = 'user';
54 /**
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',
75 'help' => 'ApiHelp',
76 'paraminfo' => 'ApiParamInfo',
77 'rsd' => 'ApiRsd',
78 'compare' => 'ApiComparePages',
79 'tokens' => 'ApiTokens',
80 'checktoken' => 'ApiCheckToken',
81 'cspreport' => 'ApiCSPReport',
82 'validatepassword' => 'ApiValidatePassword',
84 // Write modules
85 'purge' => 'ApiPurge',
86 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
87 'rollback' => 'ApiRollback',
88 'delete' => 'ApiDelete',
89 'undelete' => 'ApiUndelete',
90 'protect' => 'ApiProtect',
91 'block' => 'ApiBlock',
92 'unblock' => 'ApiUnblock',
93 'move' => 'ApiMove',
94 'edit' => 'ApiEditPage',
95 'upload' => 'ApiUpload',
96 'filerevert' => 'ApiFileRevert',
97 'emailuser' => 'ApiEmailUser',
98 'watch' => 'ApiWatch',
99 'patrol' => 'ApiPatrol',
100 'import' => 'ApiImport',
101 'clearhasmsg' => 'ApiClearHasMsg',
102 'userrights' => 'ApiUserrights',
103 'options' => 'ApiOptions',
104 'imagerotate' => 'ApiImageRotate',
105 'revisiondelete' => 'ApiRevisionDelete',
106 'managetags' => 'ApiManageTags',
107 'tag' => 'ApiTag',
108 'mergehistory' => 'ApiMergeHistory',
109 'setpagelanguage' => 'ApiSetPageLanguage',
113 * List of available formats: format name => format class
115 private static $Formats = [
116 'json' => 'ApiFormatJson',
117 'jsonfm' => 'ApiFormatJson',
118 'php' => 'ApiFormatPhp',
119 'phpfm' => 'ApiFormatPhp',
120 'xml' => 'ApiFormatXml',
121 'xmlfm' => 'ApiFormatXml',
122 'rawfm' => 'ApiFormatJson',
123 'none' => 'ApiFormatNone',
126 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
128 * List of user roles that are specifically relevant to the API.
129 * [ 'right' => [ 'msg' => 'Some message with a $1',
130 * 'params' => [ $someVarToSubst ] ],
131 * ];
133 private static $mRights = [
134 'writeapi' => [
135 'msg' => 'right-writeapi',
136 'params' => []
138 'apihighlimits' => [
139 'msg' => 'api-help-right-apihighlimits',
140 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ]
143 // @codingStandardsIgnoreEnd
146 * @var ApiFormatBase
148 private $mPrinter;
150 private $mModuleMgr, $mResult, $mErrorFormatter = null;
151 /** @var ApiContinuationManager|null */
152 private $mContinuationManager;
153 private $mAction;
154 private $mEnableWrite;
155 private $mInternalMode, $mSquidMaxage;
156 /** @var ApiBase */
157 private $mModule;
159 private $mCacheMode = 'private';
160 private $mCacheControl = [];
161 private $mParamsUsed = [];
163 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
164 private $lacksSameOriginSecurity = null;
167 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
169 * @param IContextSource|WebRequest $context If this is an instance of
170 * FauxRequest, errors are thrown and no printing occurs
171 * @param bool $enableWrite Should be set to true if the api may modify data
173 public function __construct( $context = null, $enableWrite = false ) {
174 if ( $context === null ) {
175 $context = RequestContext::getMain();
176 } elseif ( $context instanceof WebRequest ) {
177 // BC for pre-1.19
178 $request = $context;
179 $context = RequestContext::getMain();
181 // We set a derivative context so we can change stuff later
182 $this->setContext( new DerivativeContext( $context ) );
184 if ( isset( $request ) ) {
185 $this->getContext()->setRequest( $request );
186 } else {
187 $request = $this->getRequest();
190 $this->mInternalMode = ( $request instanceof FauxRequest );
192 // Special handling for the main module: $parent === $this
193 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
195 $config = $this->getConfig();
197 if ( !$this->mInternalMode ) {
198 // Log if a request with a non-whitelisted Origin header is seen
199 // with session cookies.
200 $originHeader = $request->getHeader( 'Origin' );
201 if ( $originHeader === false ) {
202 $origins = [];
203 } else {
204 $originHeader = trim( $originHeader );
205 $origins = preg_split( '/\s+/', $originHeader );
207 $sessionCookies = array_intersect(
208 array_keys( $_COOKIE ),
209 MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
211 if ( $origins && $sessionCookies && (
212 count( $origins ) !== 1 || !self::matchOrigin(
213 $origins[0],
214 $config->get( 'CrossSiteAJAXdomains' ),
215 $config->get( 'CrossSiteAJAXdomainExceptions' )
217 ) ) {
218 LoggerFactory::getInstance( 'cors' )->warning(
219 'Non-whitelisted CORS request with session cookies', [
220 'origin' => $originHeader,
221 'cookies' => $sessionCookies,
222 'ip' => $request->getIP(),
223 'userAgent' => $this->getUserAgent(),
224 'wiki' => wfWikiID(),
229 // If we're in a mode that breaks the same-origin policy, strip
230 // user credentials for security.
231 if ( $this->lacksSameOriginSecurity() ) {
232 global $wgUser;
233 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
234 $wgUser = new User();
235 $this->getContext()->setUser( $wgUser );
239 $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
241 // Setup uselang. This doesn't use $this->getParameter()
242 // because we're not ready to handle errors yet.
243 $uselang = $request->getVal( 'uselang', self::API_DEFAULT_USELANG );
244 if ( $uselang === 'user' ) {
245 // Assume the parent context is going to return the user language
246 // for uselang=user (see T85635).
247 } else {
248 if ( $uselang === 'content' ) {
249 global $wgContLang;
250 $uselang = $wgContLang->getCode();
252 $code = RequestContext::sanitizeLangCode( $uselang );
253 $this->getContext()->setLanguage( $code );
254 if ( !$this->mInternalMode ) {
255 global $wgLang;
256 $wgLang = $this->getContext()->getLanguage();
257 RequestContext::getMain()->setLanguage( $wgLang );
261 // Set up the error formatter. This doesn't use $this->getParameter()
262 // because we're not ready to handle errors yet.
263 $errorFormat = $request->getVal( 'errorformat', 'bc' );
264 $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
265 $errorsUseDB = $request->getCheck( 'errorsuselocal' );
266 if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
267 if ( $errorLangCode === 'uselang' ) {
268 $errorLang = $this->getLanguage();
269 } elseif ( $errorLangCode === 'content' ) {
270 global $wgContLang;
271 $errorLang = $wgContLang;
272 } else {
273 $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
274 $errorLang = Language::factory( $errorLangCode );
276 $this->mErrorFormatter = new ApiErrorFormatter(
277 $this->mResult, $errorLang, $errorFormat, $errorsUseDB
279 } else {
280 $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
282 $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
284 $this->mModuleMgr = new ApiModuleManager( $this );
285 $this->mModuleMgr->addModules( self::$Modules, 'action' );
286 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
287 $this->mModuleMgr->addModules( self::$Formats, 'format' );
288 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
290 Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
292 $this->mContinuationManager = null;
293 $this->mEnableWrite = $enableWrite;
295 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
296 $this->mCommit = false;
300 * Return true if the API was started by other PHP code using FauxRequest
301 * @return bool
303 public function isInternalMode() {
304 return $this->mInternalMode;
308 * Get the ApiResult object associated with current request
310 * @return ApiResult
312 public function getResult() {
313 return $this->mResult;
317 * Get the security flag for the current request
318 * @return bool
320 public function lacksSameOriginSecurity() {
321 if ( $this->lacksSameOriginSecurity !== null ) {
322 return $this->lacksSameOriginSecurity;
325 $request = $this->getRequest();
327 // JSONP mode
328 if ( $request->getVal( 'callback' ) !== null ) {
329 $this->lacksSameOriginSecurity = true;
330 return true;
333 // Anonymous CORS
334 if ( $request->getVal( 'origin' ) === '*' ) {
335 $this->lacksSameOriginSecurity = true;
336 return true;
339 // Header to be used from XMLHTTPRequest when the request might
340 // otherwise be used for XSS.
341 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
342 $this->lacksSameOriginSecurity = true;
343 return true;
346 // Allow extensions to override.
347 $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
348 return $this->lacksSameOriginSecurity;
352 * Get the ApiErrorFormatter object associated with current request
353 * @return ApiErrorFormatter
355 public function getErrorFormatter() {
356 return $this->mErrorFormatter;
360 * Get the continuation manager
361 * @return ApiContinuationManager|null
363 public function getContinuationManager() {
364 return $this->mContinuationManager;
368 * Set the continuation manager
369 * @param ApiContinuationManager|null
371 public function setContinuationManager( $manager ) {
372 if ( $manager !== null ) {
373 if ( !$manager instanceof ApiContinuationManager ) {
374 throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
375 is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
378 if ( $this->mContinuationManager !== null ) {
379 throw new UnexpectedValueException(
380 __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
381 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
385 $this->mContinuationManager = $manager;
389 * Get the API module object. Only works after executeAction()
391 * @return ApiBase
393 public function getModule() {
394 return $this->mModule;
398 * Get the result formatter object. Only works after setupExecuteAction()
400 * @return ApiFormatBase
402 public function getPrinter() {
403 return $this->mPrinter;
407 * Set how long the response should be cached.
409 * @param int $maxage
411 public function setCacheMaxAge( $maxage ) {
412 $this->setCacheControl( [
413 'max-age' => $maxage,
414 's-maxage' => $maxage
415 ] );
419 * Set the type of caching headers which will be sent.
421 * @param string $mode One of:
422 * - 'public': Cache this object in public caches, if the maxage or smaxage
423 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
424 * not provided by any of these means, the object will be private.
425 * - 'private': Cache this object only in private client-side caches.
426 * - 'anon-public-user-private': Make this object cacheable for logged-out
427 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
428 * set consistently for a given URL, it cannot be set differently depending on
429 * things like the contents of the database, or whether the user is logged in.
431 * If the wiki does not allow anonymous users to read it, the mode set here
432 * will be ignored, and private caching headers will always be sent. In other words,
433 * the "public" mode is equivalent to saying that the data sent is as public as a page
434 * view.
436 * For user-dependent data, the private mode should generally be used. The
437 * anon-public-user-private mode should only be used where there is a particularly
438 * good performance reason for caching the anonymous response, but where the
439 * response to logged-in users may differ, or may contain private data.
441 * If this function is never called, then the default will be the private mode.
443 public function setCacheMode( $mode ) {
444 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
445 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
447 // Ignore for forwards-compatibility
448 return;
451 if ( !User::isEveryoneAllowed( 'read' ) ) {
452 // Private wiki, only private headers
453 if ( $mode !== 'private' ) {
454 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
456 return;
460 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
461 // User language is used for i18n, so we don't want to publicly
462 // cache. Anons are ok, because if they have non-default language
463 // then there's an appropriate Vary header set by whatever set
464 // their non-default language.
465 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
466 "'anon-public-user-private' due to uselang=user\n" );
467 $mode = 'anon-public-user-private';
470 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
471 $this->mCacheMode = $mode;
475 * Set directives (key/value pairs) for the Cache-Control header.
476 * Boolean values will be formatted as such, by including or omitting
477 * without an equals sign.
479 * Cache control values set here will only be used if the cache mode is not
480 * private, see setCacheMode().
482 * @param array $directives
484 public function setCacheControl( $directives ) {
485 $this->mCacheControl = $directives + $this->mCacheControl;
489 * Create an instance of an output formatter by its name
491 * @param string $format
493 * @return ApiFormatBase
495 public function createPrinterByName( $format ) {
496 $printer = $this->mModuleMgr->getModule( $format, 'format' );
497 if ( $printer === null ) {
498 $this->dieWithError(
499 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
503 return $printer;
507 * Execute api request. Any errors will be handled if the API was called by the remote client.
509 public function execute() {
510 if ( $this->mInternalMode ) {
511 $this->executeAction();
512 } else {
513 $this->executeActionWithErrorHandling();
518 * Execute an action, and in case of an error, erase whatever partial results
519 * have been accumulated, and replace it with an error message and a help screen.
521 protected function executeActionWithErrorHandling() {
522 // Verify the CORS header before executing the action
523 if ( !$this->handleCORS() ) {
524 // handleCORS() has sent a 403, abort
525 return;
528 // Exit here if the request method was OPTIONS
529 // (assume there will be a followup GET or POST)
530 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
531 return;
534 // In case an error occurs during data output,
535 // clear the output buffer and print just the error information
536 $obLevel = ob_get_level();
537 ob_start();
539 $t = microtime( true );
540 $isError = false;
541 try {
542 $this->executeAction();
543 $runTime = microtime( true ) - $t;
544 $this->logRequest( $runTime );
545 if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
546 $this->getStats()->timing(
547 'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
550 } catch ( Exception $e ) {
551 $this->handleException( $e );
552 $this->logRequest( microtime( true ) - $t, $e );
553 $isError = true;
556 // Commit DBs and send any related cookies and headers
557 MediaWiki::preOutputCommit( $this->getContext() );
559 // Send cache headers after any code which might generate an error, to
560 // avoid sending public cache headers for errors.
561 $this->sendCacheHeaders( $isError );
563 // Executing the action might have already messed with the output
564 // buffers.
565 while ( ob_get_level() > $obLevel ) {
566 ob_end_flush();
571 * Handle an exception as an API response
573 * @since 1.23
574 * @param Exception $e
576 protected function handleException( Exception $e ) {
577 // Bug 63145: Rollback any open database transactions
578 if ( !( $e instanceof ApiUsageException || $e instanceof UsageException ) ) {
579 // UsageExceptions are intentional, so don't rollback if that's the case
580 try {
581 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
582 } catch ( DBError $e2 ) {
583 // Rollback threw an exception too. Log it, but don't interrupt
584 // our regularly scheduled exception handling.
585 MWExceptionHandler::logException( $e2 );
589 // Allow extra cleanup and logging
590 Hooks::run( 'ApiMain::onException', [ $this, $e ] );
592 // Log it
593 if ( !( $e instanceof ApiUsageException || $e instanceof UsageException ) ) {
594 MWExceptionHandler::logException( $e );
597 // Handle any kind of exception by outputting properly formatted error message.
598 // If this fails, an unhandled exception should be thrown so that global error
599 // handler will process and log it.
601 $errCodes = $this->substituteResultWithError( $e );
603 // Error results should not be cached
604 $this->setCacheMode( 'private' );
606 $response = $this->getRequest()->response();
607 $headerStr = 'MediaWiki-API-Error: ' . join( ', ', $errCodes );
608 $response->header( $headerStr );
610 // Reset and print just the error message
611 ob_clean();
613 // Printer may not be initialized if the extractRequestParams() fails for the main module
614 $this->createErrorPrinter();
616 $failed = false;
617 try {
618 $this->printResult( $e->getCode() );
619 } catch ( ApiUsageException $ex ) {
620 // The error printer itself is failing. Try suppressing its request
621 // parameters and redo.
622 $failed = true;
623 $this->addWarning( 'apiwarn-errorprinterfailed' );
624 foreach ( $ex->getStatusValue()->getErrors() as $error ) {
625 try {
626 $this->mPrinter->addWarning( $error );
627 } catch ( Exception $ex2 ) {
628 // WTF?
629 $this->addWarning( $error );
632 } catch ( UsageException $ex ) {
633 // The error printer itself is failing. Try suppressing its request
634 // parameters and redo.
635 $failed = true;
636 $this->addWarning(
637 [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
640 if ( $failed ) {
641 $this->mPrinter = null;
642 $this->createErrorPrinter();
643 $this->mPrinter->forceDefaultParams();
644 if ( $e->getCode() ) {
645 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
647 $this->printResult( $e->getCode() );
652 * Handle an exception from the ApiBeforeMain hook.
654 * This tries to print the exception as an API response, to be more
655 * friendly to clients. If it fails, it will rethrow the exception.
657 * @since 1.23
658 * @param Exception $e
659 * @throws Exception
661 public static function handleApiBeforeMainException( Exception $e ) {
662 ob_start();
664 try {
665 $main = new self( RequestContext::getMain(), false );
666 $main->handleException( $e );
667 $main->logRequest( 0, $e );
668 } catch ( Exception $e2 ) {
669 // Nope, even that didn't work. Punt.
670 throw $e;
673 // Reset cache headers
674 $main->sendCacheHeaders( true );
676 ob_end_flush();
680 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
682 * If no origin parameter is present, nothing happens.
683 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
684 * is set and false is returned.
685 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
686 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
687 * headers are set.
688 * https://www.w3.org/TR/cors/#resource-requests
689 * https://www.w3.org/TR/cors/#resource-preflight-requests
691 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
693 protected function handleCORS() {
694 $originParam = $this->getParameter( 'origin' ); // defaults to null
695 if ( $originParam === null ) {
696 // No origin parameter, nothing to do
697 return true;
700 $request = $this->getRequest();
701 $response = $request->response();
703 $matchOrigin = false;
704 $allowTiming = false;
705 $varyOrigin = true;
707 if ( $originParam === '*' ) {
708 // Request for anonymous CORS
709 $matchOrigin = true;
710 $allowOrigin = '*';
711 $allowCredentials = 'false';
712 $varyOrigin = false; // No need to vary
713 } else {
714 // Non-anonymous CORS, check we allow the domain
716 // Origin: header is a space-separated list of origins, check all of them
717 $originHeader = $request->getHeader( 'Origin' );
718 if ( $originHeader === false ) {
719 $origins = [];
720 } else {
721 $originHeader = trim( $originHeader );
722 $origins = preg_split( '/\s+/', $originHeader );
725 if ( !in_array( $originParam, $origins ) ) {
726 // origin parameter set but incorrect
727 // Send a 403 response
728 $response->statusHeader( 403 );
729 $response->header( 'Cache-Control: no-cache' );
730 echo "'origin' parameter does not match Origin header\n";
732 return false;
735 $config = $this->getConfig();
736 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
737 $originParam,
738 $config->get( 'CrossSiteAJAXdomains' ),
739 $config->get( 'CrossSiteAJAXdomainExceptions' )
742 $allowOrigin = $originHeader;
743 $allowCredentials = 'true';
744 $allowTiming = $originHeader;
747 if ( $matchOrigin ) {
748 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
749 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
750 if ( $preflight ) {
751 // This is a CORS preflight request
752 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
753 // If method is not a case-sensitive match, do not set any additional headers and terminate.
754 return true;
756 // We allow the actual request to send the following headers
757 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
758 if ( $requestedHeaders !== false ) {
759 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
760 return true;
762 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
765 // We only allow the actual request to be GET or POST
766 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
769 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
770 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
771 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
772 if ( $allowTiming !== false ) {
773 $response->header( "Timing-Allow-Origin: $allowTiming" );
776 if ( !$preflight ) {
777 $response->header(
778 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
783 if ( $varyOrigin ) {
784 $this->getOutput()->addVaryHeader( 'Origin' );
787 return true;
791 * Attempt to match an Origin header against a set of rules and a set of exceptions
792 * @param string $value Origin header
793 * @param array $rules Set of wildcard rules
794 * @param array $exceptions Set of wildcard rules
795 * @return bool True if $value matches a rule in $rules and doesn't match
796 * any rules in $exceptions, false otherwise
798 protected static function matchOrigin( $value, $rules, $exceptions ) {
799 foreach ( $rules as $rule ) {
800 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
801 // Rule matches, check exceptions
802 foreach ( $exceptions as $exc ) {
803 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
804 return false;
808 return true;
812 return false;
816 * Attempt to validate the value of Access-Control-Request-Headers against a list
817 * of headers that we allow the follow up request to send.
819 * @param string $requestedHeaders Comma seperated list of HTTP headers
820 * @return bool True if all requested headers are in the list of allowed headers
822 protected static function matchRequestedHeaders( $requestedHeaders ) {
823 if ( trim( $requestedHeaders ) === '' ) {
824 return true;
826 $requestedHeaders = explode( ',', $requestedHeaders );
827 $allowedAuthorHeaders = array_flip( [
828 /* simple headers (see spec) */
829 'accept',
830 'accept-language',
831 'content-language',
832 'content-type',
833 /* non-authorable headers in XHR, which are however requested by some UAs */
834 'accept-encoding',
835 'dnt',
836 'origin',
837 /* MediaWiki whitelist */
838 'api-user-agent',
839 ] );
840 foreach ( $requestedHeaders as $rHeader ) {
841 $rHeader = strtolower( trim( $rHeader ) );
842 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
843 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
844 return false;
847 return true;
851 * Helper function to convert wildcard string into a regex
852 * '*' => '.*?'
853 * '?' => '.'
855 * @param string $wildcard String with wildcards
856 * @return string Regular expression
858 protected static function wildcardToRegex( $wildcard ) {
859 $wildcard = preg_quote( $wildcard, '/' );
860 $wildcard = str_replace(
861 [ '\*', '\?' ],
862 [ '.*?', '.' ],
863 $wildcard
866 return "/^https?:\/\/$wildcard$/";
870 * Send caching headers
871 * @param bool $isError Whether an error response is being output
872 * @since 1.26 added $isError parameter
874 protected function sendCacheHeaders( $isError ) {
875 $response = $this->getRequest()->response();
876 $out = $this->getOutput();
878 $out->addVaryHeader( 'Treat-as-Untrusted' );
880 $config = $this->getConfig();
882 if ( $config->get( 'VaryOnXFP' ) ) {
883 $out->addVaryHeader( 'X-Forwarded-Proto' );
886 if ( !$isError && $this->mModule &&
887 ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
889 $etag = $this->mModule->getConditionalRequestData( 'etag' );
890 if ( $etag !== null ) {
891 $response->header( "ETag: $etag" );
893 $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
894 if ( $lastMod !== null ) {
895 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
899 // The logic should be:
900 // $this->mCacheControl['max-age'] is set?
901 // Use it, the module knows better than our guess.
902 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
903 // Use 0 because we can guess caching is probably the wrong thing to do.
904 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
905 $maxage = 0;
906 if ( isset( $this->mCacheControl['max-age'] ) ) {
907 $maxage = $this->mCacheControl['max-age'];
908 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
909 $this->mCacheMode !== 'private'
911 $maxage = $this->getParameter( 'maxage' );
913 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
915 if ( $this->mCacheMode == 'private' ) {
916 $response->header( "Cache-Control: $privateCache" );
917 return;
920 $useKeyHeader = $config->get( 'UseKeyHeader' );
921 if ( $this->mCacheMode == 'anon-public-user-private' ) {
922 $out->addVaryHeader( 'Cookie' );
923 $response->header( $out->getVaryHeader() );
924 if ( $useKeyHeader ) {
925 $response->header( $out->getKeyHeader() );
926 if ( $out->haveCacheVaryCookies() ) {
927 // Logged in, mark this request private
928 $response->header( "Cache-Control: $privateCache" );
929 return;
931 // Logged out, send normal public headers below
932 } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
933 // Logged in or otherwise has session (e.g. anonymous users who have edited)
934 // Mark request private
935 $response->header( "Cache-Control: $privateCache" );
937 return;
938 } // else no Key and anonymous, send public headers below
941 // Send public headers
942 $response->header( $out->getVaryHeader() );
943 if ( $useKeyHeader ) {
944 $response->header( $out->getKeyHeader() );
947 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
948 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
949 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
951 if ( !isset( $this->mCacheControl['max-age'] ) ) {
952 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
955 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
956 // Public cache not requested
957 // Sending a Vary header in this case is harmless, and protects us
958 // against conditional calls of setCacheMaxAge().
959 $response->header( "Cache-Control: $privateCache" );
961 return;
964 $this->mCacheControl['public'] = true;
966 // Send an Expires header
967 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
968 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
969 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
971 // Construct the Cache-Control header
972 $ccHeader = '';
973 $separator = '';
974 foreach ( $this->mCacheControl as $name => $value ) {
975 if ( is_bool( $value ) ) {
976 if ( $value ) {
977 $ccHeader .= $separator . $name;
978 $separator = ', ';
980 } else {
981 $ccHeader .= $separator . "$name=$value";
982 $separator = ', ';
986 $response->header( "Cache-Control: $ccHeader" );
990 * Create the printer for error output
992 private function createErrorPrinter() {
993 if ( !isset( $this->mPrinter ) ) {
994 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
995 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
996 $value = self::API_DEFAULT_FORMAT;
998 $this->mPrinter = $this->createPrinterByName( $value );
1001 // Printer may not be able to handle errors. This is particularly
1002 // likely if the module returns something for getCustomPrinter().
1003 if ( !$this->mPrinter->canPrintErrors() ) {
1004 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1009 * Create an error message for the given exception.
1011 * If an ApiUsageException, errors/warnings will be extracted from the
1012 * embedded StatusValue.
1014 * If a base UsageException, the getMessageArray() method will be used to
1015 * extract the code and English message for a single error (no warnings).
1017 * Any other exception will be returned with a generic code and wrapper
1018 * text around the exception's (presumably English) message as a single
1019 * error (no warnings).
1021 * @param Exception $e
1022 * @param string $type 'error' or 'warning'
1023 * @return ApiMessage[]
1024 * @since 1.27
1026 protected function errorMessagesFromException( $e, $type = 'error' ) {
1027 $messages = [];
1028 if ( $e instanceof ApiUsageException ) {
1029 foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1030 $messages[] = ApiMessage::create( $error );
1032 } elseif ( $type !== 'error' ) {
1033 // None of the rest have any messages for non-error types
1034 } elseif ( $e instanceof UsageException ) {
1035 // User entered incorrect parameters - generate error response
1036 $data = $e->getMessageArray();
1037 $code = $data['code'];
1038 $info = $data['info'];
1039 unset( $data['code'], $data['info'] );
1040 $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1041 } else {
1042 // Something is seriously wrong
1043 $config = $this->getConfig();
1044 $code = 'internal_api_error_' . get_class( $e );
1045 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
1046 $params = [ 'apierror-databaseerror', WebRequest::getRequestId() ];
1047 } else {
1048 $params = [
1049 'apierror-exceptioncaught',
1050 WebRequest::getRequestId(),
1051 $e instanceof ILocalizedException
1052 ? $e->getMessageObject()
1053 : wfEscapeWikiText( $e->getMessage() )
1056 $messages[] = ApiMessage::create( $params, $code );
1058 return $messages;
1062 * Replace the result data with the information about an exception.
1063 * @param Exception $e
1064 * @return string[] Error codes
1066 protected function substituteResultWithError( $e ) {
1067 $result = $this->getResult();
1068 $formatter = $this->getErrorFormatter();
1069 $config = $this->getConfig();
1070 $errorCodes = [];
1072 // Remember existing warnings and errors across the reset
1073 $errors = $result->getResultData( [ 'errors' ] );
1074 $warnings = $result->getResultData( [ 'warnings' ] );
1075 $result->reset();
1076 if ( $warnings !== null ) {
1077 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1079 if ( $errors !== null ) {
1080 $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1082 // Collect the copied error codes for the return value
1083 foreach ( $errors as $error ) {
1084 if ( isset( $error['code'] ) ) {
1085 $errorCodes[$error['code']] = true;
1090 // Add errors from the exception
1091 $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1092 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1093 $errorCodes[$msg->getApiCode()] = true;
1094 $formatter->addError( $modulePath, $msg );
1096 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1097 $formatter->addWarning( $modulePath, $msg );
1100 // Add additional data. Path depends on whether we're in BC mode or not.
1101 // Data depends on the type of exception.
1102 if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1103 $path = [ 'error' ];
1104 } else {
1105 $path = null;
1107 if ( $e instanceof ApiUsageException || $e instanceof UsageException ) {
1108 $link = wfExpandUrl( wfScript( 'api' ) );
1109 $result->addContentValue(
1110 $path,
1111 'docref',
1112 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1114 } else {
1115 if ( $config->get( 'ShowExceptionDetails' ) ) {
1116 $result->addContentValue(
1117 $path,
1118 'trace',
1119 $this->msg( 'api-exception-trace',
1120 get_class( $e ),
1121 $e->getFile(),
1122 $e->getLine(),
1123 MWExceptionHandler::getRedactedTraceAsString( $e )
1124 )->inLanguage( $formatter->getLanguage() )->text()
1129 // Add the id and such
1130 $this->addRequestedFields( [ 'servedby' ] );
1132 return array_keys( $errorCodes );
1136 * Add requested fields to the result
1137 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1138 * - servedby
1140 protected function addRequestedFields( $force = [] ) {
1141 $result = $this->getResult();
1143 $requestid = $this->getParameter( 'requestid' );
1144 if ( $requestid !== null ) {
1145 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1148 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1149 in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1150 ) ) {
1151 $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1154 if ( $this->getParameter( 'curtimestamp' ) ) {
1155 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1156 ApiResult::NO_SIZE_CHECK );
1159 if ( $this->getParameter( 'responselanginfo' ) ) {
1160 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1161 ApiResult::NO_SIZE_CHECK );
1162 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1163 ApiResult::NO_SIZE_CHECK );
1168 * Set up for the execution.
1169 * @return array
1171 protected function setupExecuteAction() {
1172 $this->addRequestedFields();
1174 $params = $this->extractRequestParams();
1175 $this->mAction = $params['action'];
1177 return $params;
1181 * Set up the module for response
1182 * @return ApiBase The module that will handle this action
1183 * @throws MWException
1184 * @throws ApiUsageException
1186 protected function setupModule() {
1187 // Instantiate the module requested by the user
1188 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1189 if ( $module === null ) {
1190 $this->dieWithError(
1191 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1194 $moduleParams = $module->extractRequestParams();
1196 // Check token, if necessary
1197 if ( $module->needsToken() === true ) {
1198 throw new MWException(
1199 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1200 'See documentation for ApiBase::needsToken for details.'
1203 if ( $module->needsToken() ) {
1204 if ( !$module->mustBePosted() ) {
1205 throw new MWException(
1206 "Module '{$module->getModuleName()}' must require POST to use tokens."
1210 if ( !isset( $moduleParams['token'] ) ) {
1211 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1214 $module->requirePostedParameters( [ 'token' ] );
1216 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1217 $module->dieWithError( 'apierror-badtoken' );
1221 return $module;
1225 * Check the max lag if necessary
1226 * @param ApiBase $module Api module being used
1227 * @param array $params Array an array containing the request parameters.
1228 * @return bool True on success, false should exit immediately
1230 protected function checkMaxLag( $module, $params ) {
1231 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1232 $maxLag = $params['maxlag'];
1233 list( $host, $lag ) = wfGetLB()->getMaxLag();
1234 if ( $lag > $maxLag ) {
1235 $response = $this->getRequest()->response();
1237 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1238 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1240 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1241 $this->dieWithError( [ 'apierror-maxlag', $lag, $host ] );
1244 $this->dieWithError( [ 'apierror-maxlag-generic', $lag ], 'maxlag' );
1248 return true;
1252 * Check selected RFC 7232 precondition headers
1254 * RFC 7232 envisions a particular model where you send your request to "a
1255 * resource", and for write requests that you can read "the resource" by
1256 * changing the method to GET. When the API receives a GET request, it
1257 * works out even though "the resource" from RFC 7232's perspective might
1258 * be many resources from MediaWiki's perspective. But it totally fails for
1259 * a POST, since what HTTP sees as "the resource" is probably just
1260 * "/api.php" with all the interesting bits in the body.
1262 * Therefore, we only support RFC 7232 precondition headers for GET (and
1263 * HEAD). That means we don't need to bother with If-Match and
1264 * If-Unmodified-Since since they only apply to modification requests.
1266 * And since we don't support Range, If-Range is ignored too.
1268 * @since 1.26
1269 * @param ApiBase $module Api module being used
1270 * @return bool True on success, false should exit immediately
1272 protected function checkConditionalRequestHeaders( $module ) {
1273 if ( $this->mInternalMode ) {
1274 // No headers to check in internal mode
1275 return true;
1278 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1279 // Don't check POSTs
1280 return true;
1283 $return304 = false;
1285 $ifNoneMatch = array_diff(
1286 $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1287 [ '' ]
1289 if ( $ifNoneMatch ) {
1290 if ( $ifNoneMatch === [ '*' ] ) {
1291 // API responses always "exist"
1292 $etag = '*';
1293 } else {
1294 $etag = $module->getConditionalRequestData( 'etag' );
1297 if ( $ifNoneMatch && $etag !== null ) {
1298 $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1299 $match = array_map( function ( $s ) {
1300 return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1301 }, $ifNoneMatch );
1302 $return304 = in_array( $test, $match, true );
1303 } else {
1304 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1306 // Some old browsers sends sizes after the date, like this:
1307 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1308 // Ignore that.
1309 $i = strpos( $value, ';' );
1310 if ( $i !== false ) {
1311 $value = trim( substr( $value, 0, $i ) );
1314 if ( $value !== '' ) {
1315 try {
1316 $ts = new MWTimestamp( $value );
1317 if (
1318 // RFC 7231 IMF-fixdate
1319 $ts->getTimestamp( TS_RFC2822 ) === $value ||
1320 // RFC 850
1321 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1322 // asctime (with and without space-padded day)
1323 $ts->format( 'D M j H:i:s Y' ) === $value ||
1324 $ts->format( 'D M j H:i:s Y' ) === $value
1326 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1327 if ( $lastMod !== null ) {
1328 // Mix in some MediaWiki modification times
1329 $modifiedTimes = [
1330 'page' => $lastMod,
1331 'user' => $this->getUser()->getTouched(),
1332 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1334 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1335 // T46570: the core page itself may not change, but resources might
1336 $modifiedTimes['sepoch'] = wfTimestamp(
1337 TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1340 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1341 $lastMod = max( $modifiedTimes );
1342 $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1345 } catch ( TimestampException $e ) {
1346 // Invalid timestamp, ignore it
1351 if ( $return304 ) {
1352 $this->getRequest()->response()->statusHeader( 304 );
1354 // Avoid outputting the compressed representation of a zero-length body
1355 MediaWiki\suppressWarnings();
1356 ini_set( 'zlib.output_compression', 0 );
1357 MediaWiki\restoreWarnings();
1358 wfClearOutputBuffers();
1360 return false;
1363 return true;
1367 * Check for sufficient permissions to execute
1368 * @param ApiBase $module An Api module
1370 protected function checkExecutePermissions( $module ) {
1371 $user = $this->getUser();
1372 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1373 !$user->isAllowed( 'read' )
1375 $this->dieWithError( 'apierror-readapidenied' );
1378 if ( $module->isWriteMode() ) {
1379 if ( !$this->mEnableWrite ) {
1380 $this->dieWithError( 'apierror-noapiwrite' );
1381 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1382 $this->dieWithError( 'apierror-writeapidenied' );
1383 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1384 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1387 $this->checkReadOnly( $module );
1390 // Allow extensions to stop execution for arbitrary reasons.
1391 $message = false;
1392 if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1393 $this->dieWithError( $message );
1398 * Check if the DB is read-only for this user
1399 * @param ApiBase $module An Api module
1401 protected function checkReadOnly( $module ) {
1402 if ( wfReadOnly() ) {
1403 $this->dieReadOnly();
1406 if ( $module->isWriteMode()
1407 && $this->getUser()->isBot()
1408 && wfGetLB()->getServerCount() > 1
1410 $this->checkBotReadOnly();
1415 * Check whether we are readonly for bots
1417 private function checkBotReadOnly() {
1418 // Figure out how many servers have passed the lag threshold
1419 $numLagged = 0;
1420 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1421 $laggedServers = [];
1422 $loadBalancer = wfGetLB();
1423 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1424 if ( $lag > $lagLimit ) {
1425 ++$numLagged;
1426 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1430 // If a majority of replica DBs are too lagged then disallow writes
1431 $replicaCount = wfGetLB()->getServerCount() - 1;
1432 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1433 $laggedServers = implode( ', ', $laggedServers );
1434 wfDebugLog(
1435 'api-readonly',
1436 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1439 $this->dieWithError(
1440 'readonly_lag',
1441 'readonly',
1442 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1448 * Check asserts of the user's rights
1449 * @param array $params
1451 protected function checkAsserts( $params ) {
1452 if ( isset( $params['assert'] ) ) {
1453 $user = $this->getUser();
1454 switch ( $params['assert'] ) {
1455 case 'user':
1456 if ( $user->isAnon() ) {
1457 $this->dieWithError( 'apierror-assertuserfailed' );
1459 break;
1460 case 'bot':
1461 if ( !$user->isAllowed( 'bot' ) ) {
1462 $this->dieWithError( 'apierror-assertbotfailed' );
1464 break;
1467 if ( isset( $params['assertuser'] ) ) {
1468 $assertUser = User::newFromName( $params['assertuser'], false );
1469 if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1470 $this->dieWithError(
1471 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1478 * Check POST for external response and setup result printer
1479 * @param ApiBase $module An Api module
1480 * @param array $params An array with the request parameters
1482 protected function setupExternalResponse( $module, $params ) {
1483 $request = $this->getRequest();
1484 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1485 // Module requires POST. GET request might still be allowed
1486 // if $wgDebugApi is true, otherwise fail.
1487 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1490 // See if custom printer is used
1491 $this->mPrinter = $module->getCustomPrinter();
1492 if ( is_null( $this->mPrinter ) ) {
1493 // Create an appropriate printer
1494 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1497 if ( $request->getProtocol() === 'http' && (
1498 $request->getSession()->shouldForceHTTPS() ||
1499 ( $this->getUser()->isLoggedIn() &&
1500 $this->getUser()->requiresHTTPS() )
1501 ) ) {
1502 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1507 * Execute the actual module, without any error handling
1509 protected function executeAction() {
1510 $params = $this->setupExecuteAction();
1511 $module = $this->setupModule();
1512 $this->mModule = $module;
1514 if ( !$this->mInternalMode ) {
1515 $this->setRequestExpectations( $module );
1518 $this->checkExecutePermissions( $module );
1520 if ( !$this->checkMaxLag( $module, $params ) ) {
1521 return;
1524 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1525 return;
1528 if ( !$this->mInternalMode ) {
1529 $this->setupExternalResponse( $module, $params );
1532 $this->checkAsserts( $params );
1534 // Execute
1535 $module->execute();
1536 Hooks::run( 'APIAfterExecute', [ &$module ] );
1538 $this->reportUnusedParams();
1540 if ( !$this->mInternalMode ) {
1541 // append Debug information
1542 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1544 // Print result data
1545 $this->printResult();
1550 * Set database connection, query, and write expectations given this module request
1551 * @param ApiBase $module
1553 protected function setRequestExpectations( ApiBase $module ) {
1554 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1555 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1556 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1557 if ( $this->getRequest()->hasSafeMethod() ) {
1558 $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1559 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1560 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1561 $this->getRequest()->markAsSafeRequest();
1562 } else {
1563 $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1568 * Log the preceding request
1569 * @param float $time Time in seconds
1570 * @param Exception $e Exception caught while processing the request
1572 protected function logRequest( $time, $e = null ) {
1573 $request = $this->getRequest();
1574 $logCtx = [
1575 'ts' => time(),
1576 'ip' => $request->getIP(),
1577 'userAgent' => $this->getUserAgent(),
1578 'wiki' => wfWikiID(),
1579 'timeSpentBackend' => (int)round( $time * 1000 ),
1580 'hadError' => $e !== null,
1581 'errorCodes' => [],
1582 'params' => [],
1585 if ( $e ) {
1586 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1587 $logCtx['errorCodes'][] = $msg->getApiCode();
1591 // Construct space separated message for 'api' log channel
1592 $msg = "API {$request->getMethod()} " .
1593 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1594 " {$logCtx['ip']} " .
1595 "T={$logCtx['timeSpentBackend']}ms";
1597 foreach ( $this->getParamsUsed() as $name ) {
1598 $value = $request->getVal( $name );
1599 if ( $value === null ) {
1600 continue;
1603 if ( strlen( $value ) > 256 ) {
1604 $value = substr( $value, 0, 256 );
1605 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1606 } else {
1607 $encValue = $this->encodeRequestLogValue( $value );
1610 $logCtx['params'][$name] = $value;
1611 $msg .= " {$name}={$encValue}";
1614 wfDebugLog( 'api', $msg, 'private' );
1615 // ApiAction channel is for structured data consumers
1616 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1620 * Encode a value in a format suitable for a space-separated log line.
1621 * @param string $s
1622 * @return string
1624 protected function encodeRequestLogValue( $s ) {
1625 static $table;
1626 if ( !$table ) {
1627 $chars = ';@$!*(),/:';
1628 $numChars = strlen( $chars );
1629 for ( $i = 0; $i < $numChars; $i++ ) {
1630 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1634 return strtr( rawurlencode( $s ), $table );
1638 * Get the request parameters used in the course of the preceding execute() request
1639 * @return array
1641 protected function getParamsUsed() {
1642 return array_keys( $this->mParamsUsed );
1646 * Mark parameters as used
1647 * @param string|string[] $params
1649 public function markParamsUsed( $params ) {
1650 $this->mParamsUsed += array_fill_keys( (array)$params, true );
1654 * Get a request value, and register the fact that it was used, for logging.
1655 * @param string $name
1656 * @param mixed $default
1657 * @return mixed
1659 public function getVal( $name, $default = null ) {
1660 $this->mParamsUsed[$name] = true;
1662 $ret = $this->getRequest()->getVal( $name );
1663 if ( $ret === null ) {
1664 if ( $this->getRequest()->getArray( $name ) !== null ) {
1665 // See bug 10262 for why we don't just implode( '|', ... ) the
1666 // array.
1667 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1669 $ret = $default;
1671 return $ret;
1675 * Get a boolean request value, and register the fact that the parameter
1676 * was used, for logging.
1677 * @param string $name
1678 * @return bool
1680 public function getCheck( $name ) {
1681 return $this->getVal( $name, null ) !== null;
1685 * Get a request upload, and register the fact that it was used, for logging.
1687 * @since 1.21
1688 * @param string $name Parameter name
1689 * @return WebRequestUpload
1691 public function getUpload( $name ) {
1692 $this->mParamsUsed[$name] = true;
1694 return $this->getRequest()->getUpload( $name );
1698 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1699 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1701 protected function reportUnusedParams() {
1702 $paramsUsed = $this->getParamsUsed();
1703 $allParams = $this->getRequest()->getValueNames();
1705 if ( !$this->mInternalMode ) {
1706 // Printer has not yet executed; don't warn that its parameters are unused
1707 $printerParams = $this->mPrinter->encodeParamName(
1708 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1710 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1711 } else {
1712 $unusedParams = array_diff( $allParams, $paramsUsed );
1715 if ( count( $unusedParams ) ) {
1716 $this->addWarning( [
1717 'apierror-unrecognizedparams',
1718 Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1719 count( $unusedParams )
1720 ] );
1725 * Print results using the current printer
1727 * @param int $httpCode HTTP status code, or 0 to not change
1729 protected function printResult( $httpCode = 0 ) {
1730 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1731 $this->addWarning( 'apiwarn-wgDebugAPI' );
1734 $printer = $this->mPrinter;
1735 $printer->initPrinter( false );
1736 if ( $httpCode ) {
1737 $printer->setHttpStatus( $httpCode );
1739 $printer->execute();
1740 $printer->closePrinter();
1744 * @return bool
1746 public function isReadMode() {
1747 return false;
1751 * See ApiBase for description.
1753 * @return array
1755 public function getAllowedParams() {
1756 return [
1757 'action' => [
1758 ApiBase::PARAM_DFLT => 'help',
1759 ApiBase::PARAM_TYPE => 'submodule',
1761 'format' => [
1762 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1763 ApiBase::PARAM_TYPE => 'submodule',
1765 'maxlag' => [
1766 ApiBase::PARAM_TYPE => 'integer'
1768 'smaxage' => [
1769 ApiBase::PARAM_TYPE => 'integer',
1770 ApiBase::PARAM_DFLT => 0
1772 'maxage' => [
1773 ApiBase::PARAM_TYPE => 'integer',
1774 ApiBase::PARAM_DFLT => 0
1776 'assert' => [
1777 ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1779 'assertuser' => [
1780 ApiBase::PARAM_TYPE => 'user',
1782 'requestid' => null,
1783 'servedby' => false,
1784 'curtimestamp' => false,
1785 'responselanginfo' => false,
1786 'origin' => null,
1787 'uselang' => [
1788 ApiBase::PARAM_DFLT => self::API_DEFAULT_USELANG,
1790 'errorformat' => [
1791 ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1792 ApiBase::PARAM_DFLT => 'bc',
1794 'errorlang' => [
1795 ApiBase::PARAM_DFLT => 'uselang',
1797 'errorsuselocal' => [
1798 ApiBase::PARAM_DFLT => false,
1803 /** @see ApiBase::getExamplesMessages() */
1804 protected function getExamplesMessages() {
1805 return [
1806 'action=help'
1807 => 'apihelp-help-example-main',
1808 'action=help&recursivesubmodules=1'
1809 => 'apihelp-help-example-recursive',
1813 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1814 // Wish PHP had an "array_insert_before". Instead, we have to manually
1815 // reindex the array to get 'permissions' in the right place.
1816 $oldHelp = $help;
1817 $help = [];
1818 foreach ( $oldHelp as $k => $v ) {
1819 if ( $k === 'submodules' ) {
1820 $help['permissions'] = '';
1822 $help[$k] = $v;
1824 $help['datatypes'] = '';
1825 $help['credits'] = '';
1827 // Fill 'permissions'
1828 $help['permissions'] .= Html::openElement( 'div',
1829 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1830 $m = $this->msg( 'api-help-permissions' );
1831 if ( !$m->isDisabled() ) {
1832 $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1833 $m->numParams( count( self::$mRights ) )->parse()
1836 $help['permissions'] .= Html::openElement( 'dl' );
1837 foreach ( self::$mRights as $right => $rightMsg ) {
1838 $help['permissions'] .= Html::element( 'dt', null, $right );
1840 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1841 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1843 $groups = array_map( function ( $group ) {
1844 return $group == '*' ? 'all' : $group;
1845 }, User::getGroupsWithPermission( $right ) );
1847 $help['permissions'] .= Html::rawElement( 'dd', null,
1848 $this->msg( 'api-help-permissions-granted-to' )
1849 ->numParams( count( $groups ) )
1850 ->params( Message::listParam( $groups ) )
1851 ->parse()
1854 $help['permissions'] .= Html::closeElement( 'dl' );
1855 $help['permissions'] .= Html::closeElement( 'div' );
1857 // Fill 'datatypes' and 'credits', if applicable
1858 if ( empty( $options['nolead'] ) ) {
1859 $level = $options['headerlevel'];
1860 $tocnumber = &$options['tocnumber'];
1862 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1864 // Add an additional span with sanitized ID
1865 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1866 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1867 $header;
1869 $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1870 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1871 $header
1873 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1874 if ( !isset( $tocData['main/datatypes'] ) ) {
1875 $tocnumber[$level]++;
1876 $tocData['main/datatypes'] = [
1877 'toclevel' => count( $tocnumber ),
1878 'level' => $level,
1879 'anchor' => 'main/datatypes',
1880 'line' => $header,
1881 'number' => implode( '.', $tocnumber ),
1882 'index' => false,
1886 // Add an additional span with sanitized ID
1887 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1888 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1889 $header;
1891 $header = $this->msg( 'api-credits-header' )->parse();
1892 $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1893 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1894 $header
1896 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1897 if ( !isset( $tocData['main/credits'] ) ) {
1898 $tocnumber[$level]++;
1899 $tocData['main/credits'] = [
1900 'toclevel' => count( $tocnumber ),
1901 'level' => $level,
1902 'anchor' => 'main/credits',
1903 'line' => $header,
1904 'number' => implode( '.', $tocnumber ),
1905 'index' => false,
1911 private $mCanApiHighLimits = null;
1914 * Check whether the current user is allowed to use high limits
1915 * @return bool
1917 public function canApiHighLimits() {
1918 if ( !isset( $this->mCanApiHighLimits ) ) {
1919 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1922 return $this->mCanApiHighLimits;
1926 * Overrides to return this instance's module manager.
1927 * @return ApiModuleManager
1929 public function getModuleManager() {
1930 return $this->mModuleMgr;
1934 * Fetches the user agent used for this request
1936 * The value will be the combination of the 'Api-User-Agent' header (if
1937 * any) and the standard User-Agent header (if any).
1939 * @return string
1941 public function getUserAgent() {
1942 return trim(
1943 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1944 $this->getRequest()->getHeader( 'User-agent' )
1950 * For really cool vim folding this needs to be at the end:
1951 * vim: foldmarker=@{,@} foldmethod=marker