Use adaptive CDN TTLs for page views
[mediawiki.git] / includes / api / ApiMain.php
blob22b079dee10e669f73c87ed7e1a7a702f209b730
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 * List of available modules: action name => module class
52 private static $Modules = [
53 'login' => 'ApiLogin',
54 'clientlogin' => 'ApiClientLogin',
55 'logout' => 'ApiLogout',
56 'createaccount' => 'ApiAMCreateAccount',
57 'linkaccount' => 'ApiLinkAccount',
58 'unlinkaccount' => 'ApiRemoveAuthenticationData',
59 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
60 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
61 'resetpassword' => 'ApiResetPassword',
62 'query' => 'ApiQuery',
63 'expandtemplates' => 'ApiExpandTemplates',
64 'parse' => 'ApiParse',
65 'stashedit' => 'ApiStashEdit',
66 'opensearch' => 'ApiOpenSearch',
67 'feedcontributions' => 'ApiFeedContributions',
68 'feedrecentchanges' => 'ApiFeedRecentChanges',
69 'feedwatchlist' => 'ApiFeedWatchlist',
70 'help' => 'ApiHelp',
71 'paraminfo' => 'ApiParamInfo',
72 'rsd' => 'ApiRsd',
73 'compare' => 'ApiComparePages',
74 'tokens' => 'ApiTokens',
75 'checktoken' => 'ApiCheckToken',
76 'cspreport' => 'ApiCSPReport',
78 // Write modules
79 'purge' => 'ApiPurge',
80 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
81 'rollback' => 'ApiRollback',
82 'delete' => 'ApiDelete',
83 'undelete' => 'ApiUndelete',
84 'protect' => 'ApiProtect',
85 'block' => 'ApiBlock',
86 'unblock' => 'ApiUnblock',
87 'move' => 'ApiMove',
88 'edit' => 'ApiEditPage',
89 'upload' => 'ApiUpload',
90 'filerevert' => 'ApiFileRevert',
91 'emailuser' => 'ApiEmailUser',
92 'watch' => 'ApiWatch',
93 'patrol' => 'ApiPatrol',
94 'import' => 'ApiImport',
95 'clearhasmsg' => 'ApiClearHasMsg',
96 'userrights' => 'ApiUserrights',
97 'options' => 'ApiOptions',
98 'imagerotate' => 'ApiImageRotate',
99 'revisiondelete' => 'ApiRevisionDelete',
100 'managetags' => 'ApiManageTags',
101 'tag' => 'ApiTag',
102 'mergehistory' => 'ApiMergeHistory',
106 * List of available formats: format name => format class
108 private static $Formats = [
109 'json' => 'ApiFormatJson',
110 'jsonfm' => 'ApiFormatJson',
111 'php' => 'ApiFormatPhp',
112 'phpfm' => 'ApiFormatPhp',
113 'xml' => 'ApiFormatXml',
114 'xmlfm' => 'ApiFormatXml',
115 'rawfm' => 'ApiFormatJson',
116 'none' => 'ApiFormatNone',
119 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
121 * List of user roles that are specifically relevant to the API.
122 * [ 'right' => [ 'msg' => 'Some message with a $1',
123 * 'params' => [ $someVarToSubst ] ],
124 * ];
126 private static $mRights = [
127 'writeapi' => [
128 'msg' => 'right-writeapi',
129 'params' => []
131 'apihighlimits' => [
132 'msg' => 'api-help-right-apihighlimits',
133 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ]
136 // @codingStandardsIgnoreEnd
139 * @var ApiFormatBase
141 private $mPrinter;
143 private $mModuleMgr, $mResult, $mErrorFormatter;
144 /** @var ApiContinuationManager|null */
145 private $mContinuationManager;
146 private $mAction;
147 private $mEnableWrite;
148 private $mInternalMode, $mSquidMaxage;
149 /** @var ApiBase */
150 private $mModule;
152 private $mCacheMode = 'private';
153 private $mCacheControl = [];
154 private $mParamsUsed = [];
156 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
157 private $lacksSameOriginSecurity = null;
160 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
162 * @param IContextSource|WebRequest $context If this is an instance of
163 * FauxRequest, errors are thrown and no printing occurs
164 * @param bool $enableWrite Should be set to true if the api may modify data
166 public function __construct( $context = null, $enableWrite = false ) {
167 if ( $context === null ) {
168 $context = RequestContext::getMain();
169 } elseif ( $context instanceof WebRequest ) {
170 // BC for pre-1.19
171 $request = $context;
172 $context = RequestContext::getMain();
174 // We set a derivative context so we can change stuff later
175 $this->setContext( new DerivativeContext( $context ) );
177 if ( isset( $request ) ) {
178 $this->getContext()->setRequest( $request );
179 } else {
180 $request = $this->getRequest();
183 $this->mInternalMode = ( $request instanceof FauxRequest );
185 // Special handling for the main module: $parent === $this
186 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
188 $config = $this->getConfig();
190 if ( !$this->mInternalMode ) {
191 // Log if a request with a non-whitelisted Origin header is seen
192 // with session cookies.
193 $originHeader = $request->getHeader( 'Origin' );
194 if ( $originHeader === false ) {
195 $origins = [];
196 } else {
197 $originHeader = trim( $originHeader );
198 $origins = preg_split( '/\s+/', $originHeader );
200 $sessionCookies = array_intersect(
201 array_keys( $_COOKIE ),
202 MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
204 if ( $origins && $sessionCookies && (
205 count( $origins ) !== 1 || !self::matchOrigin(
206 $origins[0],
207 $config->get( 'CrossSiteAJAXdomains' ),
208 $config->get( 'CrossSiteAJAXdomainExceptions' )
210 ) ) {
211 LoggerFactory::getInstance( 'cors' )->warning(
212 'Non-whitelisted CORS request with session cookies', [
213 'origin' => $originHeader,
214 'cookies' => $sessionCookies,
215 'ip' => $request->getIP(),
216 'userAgent' => $this->getUserAgent(),
217 'wiki' => wfWikiID(),
222 // If we're in a mode that breaks the same-origin policy, strip
223 // user credentials for security.
224 if ( $this->lacksSameOriginSecurity() ) {
225 global $wgUser;
226 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
227 $wgUser = new User();
228 $this->getContext()->setUser( $wgUser );
232 $uselang = $this->getParameter( 'uselang' );
233 if ( $uselang === 'user' ) {
234 // Assume the parent context is going to return the user language
235 // for uselang=user (see T85635).
236 } else {
237 if ( $uselang === 'content' ) {
238 global $wgContLang;
239 $uselang = $wgContLang->getCode();
241 $code = RequestContext::sanitizeLangCode( $uselang );
242 $this->getContext()->setLanguage( $code );
243 if ( !$this->mInternalMode ) {
244 global $wgLang;
245 $wgLang = $this->getContext()->getLanguage();
246 RequestContext::getMain()->setLanguage( $wgLang );
250 $this->mModuleMgr = new ApiModuleManager( $this );
251 $this->mModuleMgr->addModules( self::$Modules, 'action' );
252 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
253 $this->mModuleMgr->addModules( self::$Formats, 'format' );
254 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
256 Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
258 $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
259 $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
260 $this->mResult->setErrorFormatter( $this->mErrorFormatter );
261 $this->mResult->setMainForContinuation( $this );
262 $this->mContinuationManager = null;
263 $this->mEnableWrite = $enableWrite;
265 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
266 $this->mCommit = false;
270 * Return true if the API was started by other PHP code using FauxRequest
271 * @return bool
273 public function isInternalMode() {
274 return $this->mInternalMode;
278 * Get the ApiResult object associated with current request
280 * @return ApiResult
282 public function getResult() {
283 return $this->mResult;
287 * Get the security flag for the current request
288 * @return bool
290 public function lacksSameOriginSecurity() {
291 if ( $this->lacksSameOriginSecurity !== null ) {
292 return $this->lacksSameOriginSecurity;
295 $request = $this->getRequest();
297 // JSONP mode
298 if ( $request->getVal( 'callback' ) !== null ) {
299 $this->lacksSameOriginSecurity = true;
300 return true;
303 // Anonymous CORS
304 if ( $request->getVal( 'origin' ) === '*' ) {
305 $this->lacksSameOriginSecurity = true;
306 return true;
309 // Header to be used from XMLHTTPRequest when the request might
310 // otherwise be used for XSS.
311 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
312 $this->lacksSameOriginSecurity = true;
313 return true;
316 // Allow extensions to override.
317 $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
318 return $this->lacksSameOriginSecurity;
322 * Get the ApiErrorFormatter object associated with current request
323 * @return ApiErrorFormatter
325 public function getErrorFormatter() {
326 return $this->mErrorFormatter;
330 * Get the continuation manager
331 * @return ApiContinuationManager|null
333 public function getContinuationManager() {
334 return $this->mContinuationManager;
338 * Set the continuation manager
339 * @param ApiContinuationManager|null
341 public function setContinuationManager( $manager ) {
342 if ( $manager !== null ) {
343 if ( !$manager instanceof ApiContinuationManager ) {
344 throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
345 is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
348 if ( $this->mContinuationManager !== null ) {
349 throw new UnexpectedValueException(
350 __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
351 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
355 $this->mContinuationManager = $manager;
359 * Get the API module object. Only works after executeAction()
361 * @return ApiBase
363 public function getModule() {
364 return $this->mModule;
368 * Get the result formatter object. Only works after setupExecuteAction()
370 * @return ApiFormatBase
372 public function getPrinter() {
373 return $this->mPrinter;
377 * Set how long the response should be cached.
379 * @param int $maxage
381 public function setCacheMaxAge( $maxage ) {
382 $this->setCacheControl( [
383 'max-age' => $maxage,
384 's-maxage' => $maxage
385 ] );
389 * Set the type of caching headers which will be sent.
391 * @param string $mode One of:
392 * - 'public': Cache this object in public caches, if the maxage or smaxage
393 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
394 * not provided by any of these means, the object will be private.
395 * - 'private': Cache this object only in private client-side caches.
396 * - 'anon-public-user-private': Make this object cacheable for logged-out
397 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
398 * set consistently for a given URL, it cannot be set differently depending on
399 * things like the contents of the database, or whether the user is logged in.
401 * If the wiki does not allow anonymous users to read it, the mode set here
402 * will be ignored, and private caching headers will always be sent. In other words,
403 * the "public" mode is equivalent to saying that the data sent is as public as a page
404 * view.
406 * For user-dependent data, the private mode should generally be used. The
407 * anon-public-user-private mode should only be used where there is a particularly
408 * good performance reason for caching the anonymous response, but where the
409 * response to logged-in users may differ, or may contain private data.
411 * If this function is never called, then the default will be the private mode.
413 public function setCacheMode( $mode ) {
414 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
415 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
417 // Ignore for forwards-compatibility
418 return;
421 if ( !User::isEveryoneAllowed( 'read' ) ) {
422 // Private wiki, only private headers
423 if ( $mode !== 'private' ) {
424 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
426 return;
430 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
431 // User language is used for i18n, so we don't want to publicly
432 // cache. Anons are ok, because if they have non-default language
433 // then there's an appropriate Vary header set by whatever set
434 // their non-default language.
435 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
436 "'anon-public-user-private' due to uselang=user\n" );
437 $mode = 'anon-public-user-private';
440 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
441 $this->mCacheMode = $mode;
445 * Set directives (key/value pairs) for the Cache-Control header.
446 * Boolean values will be formatted as such, by including or omitting
447 * without an equals sign.
449 * Cache control values set here will only be used if the cache mode is not
450 * private, see setCacheMode().
452 * @param array $directives
454 public function setCacheControl( $directives ) {
455 $this->mCacheControl = $directives + $this->mCacheControl;
459 * Create an instance of an output formatter by its name
461 * @param string $format
463 * @return ApiFormatBase
465 public function createPrinterByName( $format ) {
466 $printer = $this->mModuleMgr->getModule( $format, 'format' );
467 if ( $printer === null ) {
468 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
471 return $printer;
475 * Execute api request. Any errors will be handled if the API was called by the remote client.
477 public function execute() {
478 if ( $this->mInternalMode ) {
479 $this->executeAction();
480 } else {
481 $this->executeActionWithErrorHandling();
486 * Execute an action, and in case of an error, erase whatever partial results
487 * have been accumulated, and replace it with an error message and a help screen.
489 protected function executeActionWithErrorHandling() {
490 // Verify the CORS header before executing the action
491 if ( !$this->handleCORS() ) {
492 // handleCORS() has sent a 403, abort
493 return;
496 // Exit here if the request method was OPTIONS
497 // (assume there will be a followup GET or POST)
498 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
499 return;
502 // In case an error occurs during data output,
503 // clear the output buffer and print just the error information
504 $obLevel = ob_get_level();
505 ob_start();
507 $t = microtime( true );
508 $isError = false;
509 try {
510 $this->executeAction();
511 $runTime = microtime( true ) - $t;
512 $this->logRequest( $runTime );
513 if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
514 $this->getStats()->timing(
515 'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
518 } catch ( Exception $e ) {
519 $this->handleException( $e );
520 $this->logRequest( microtime( true ) - $t, $e );
521 $isError = true;
524 // Commit DBs and send any related cookies and headers
525 MediaWiki::preOutputCommit( $this->getContext() );
527 // Send cache headers after any code which might generate an error, to
528 // avoid sending public cache headers for errors.
529 $this->sendCacheHeaders( $isError );
531 // Executing the action might have already messed with the output
532 // buffers.
533 while ( ob_get_level() > $obLevel ) {
534 ob_end_flush();
539 * Handle an exception as an API response
541 * @since 1.23
542 * @param Exception $e
544 protected function handleException( Exception $e ) {
545 // Bug 63145: Rollback any open database transactions
546 if ( !( $e instanceof UsageException ) ) {
547 // UsageExceptions are intentional, so don't rollback if that's the case
548 try {
549 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
550 } catch ( DBError $e2 ) {
551 // Rollback threw an exception too. Log it, but don't interrupt
552 // our regularly scheduled exception handling.
553 MWExceptionHandler::logException( $e2 );
557 // Allow extra cleanup and logging
558 Hooks::run( 'ApiMain::onException', [ $this, $e ] );
560 // Log it
561 if ( !( $e instanceof UsageException ) ) {
562 MWExceptionHandler::logException( $e );
565 // Handle any kind of exception by outputting properly formatted error message.
566 // If this fails, an unhandled exception should be thrown so that global error
567 // handler will process and log it.
569 $errCode = $this->substituteResultWithError( $e );
571 // Error results should not be cached
572 $this->setCacheMode( 'private' );
574 $response = $this->getRequest()->response();
575 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
576 if ( $e->getCode() === 0 ) {
577 $response->header( $headerStr );
578 } else {
579 $response->header( $headerStr, true, $e->getCode() );
582 // Reset and print just the error message
583 ob_clean();
585 // Printer may not be initialized if the extractRequestParams() fails for the main module
586 $this->createErrorPrinter();
588 try {
589 $this->printResult( true );
590 } catch ( UsageException $ex ) {
591 // The error printer itself is failing. Try suppressing its request
592 // parameters and redo.
593 $this->setWarning(
594 'Error printer failed (will retry without params): ' . $ex->getMessage()
596 $this->mPrinter = null;
597 $this->createErrorPrinter();
598 $this->mPrinter->forceDefaultParams();
599 $this->printResult( true );
604 * Handle an exception from the ApiBeforeMain hook.
606 * This tries to print the exception as an API response, to be more
607 * friendly to clients. If it fails, it will rethrow the exception.
609 * @since 1.23
610 * @param Exception $e
611 * @throws Exception
613 public static function handleApiBeforeMainException( Exception $e ) {
614 ob_start();
616 try {
617 $main = new self( RequestContext::getMain(), false );
618 $main->handleException( $e );
619 $main->logRequest( 0, $e );
620 } catch ( Exception $e2 ) {
621 // Nope, even that didn't work. Punt.
622 throw $e;
625 // Reset cache headers
626 $main->sendCacheHeaders( true );
628 ob_end_flush();
632 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
634 * If no origin parameter is present, nothing happens.
635 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
636 * is set and false is returned.
637 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
638 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
639 * headers are set.
640 * http://www.w3.org/TR/cors/#resource-requests
641 * http://www.w3.org/TR/cors/#resource-preflight-requests
643 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
645 protected function handleCORS() {
646 $originParam = $this->getParameter( 'origin' ); // defaults to null
647 if ( $originParam === null ) {
648 // No origin parameter, nothing to do
649 return true;
652 $request = $this->getRequest();
653 $response = $request->response();
655 $matchOrigin = false;
656 $allowTiming = false;
657 $varyOrigin = true;
659 if ( $originParam === '*' ) {
660 // Request for anonymous CORS
661 $matchOrigin = true;
662 $allowOrigin = '*';
663 $allowCredentials = 'false';
664 $varyOrigin = false; // No need to vary
665 } else {
666 // Non-anonymous CORS, check we allow the domain
668 // Origin: header is a space-separated list of origins, check all of them
669 $originHeader = $request->getHeader( 'Origin' );
670 if ( $originHeader === false ) {
671 $origins = [];
672 } else {
673 $originHeader = trim( $originHeader );
674 $origins = preg_split( '/\s+/', $originHeader );
677 if ( !in_array( $originParam, $origins ) ) {
678 // origin parameter set but incorrect
679 // Send a 403 response
680 $response->statusHeader( 403 );
681 $response->header( 'Cache-Control: no-cache' );
682 echo "'origin' parameter does not match Origin header\n";
684 return false;
687 $config = $this->getConfig();
688 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
689 $originParam,
690 $config->get( 'CrossSiteAJAXdomains' ),
691 $config->get( 'CrossSiteAJAXdomainExceptions' )
694 $allowOrigin = $originHeader;
695 $allowCredentials = 'true';
696 $allowTiming = $originHeader;
699 if ( $matchOrigin ) {
700 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
701 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
702 if ( $preflight ) {
703 // This is a CORS preflight request
704 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
705 // If method is not a case-sensitive match, do not set any additional headers and terminate.
706 return true;
708 // We allow the actual request to send the following headers
709 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
710 if ( $requestedHeaders !== false ) {
711 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
712 return true;
714 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
717 // We only allow the actual request to be GET or POST
718 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
721 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
722 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
723 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
724 if ( $allowTiming !== false ) {
725 $response->header( "Timing-Allow-Origin: $allowTiming" );
728 if ( !$preflight ) {
729 $response->header(
730 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
735 if ( $varyOrigin ) {
736 $this->getOutput()->addVaryHeader( 'Origin' );
739 return true;
743 * Attempt to match an Origin header against a set of rules and a set of exceptions
744 * @param string $value Origin header
745 * @param array $rules Set of wildcard rules
746 * @param array $exceptions Set of wildcard rules
747 * @return bool True if $value matches a rule in $rules and doesn't match
748 * any rules in $exceptions, false otherwise
750 protected static function matchOrigin( $value, $rules, $exceptions ) {
751 foreach ( $rules as $rule ) {
752 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
753 // Rule matches, check exceptions
754 foreach ( $exceptions as $exc ) {
755 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
756 return false;
760 return true;
764 return false;
768 * Attempt to validate the value of Access-Control-Request-Headers against a list
769 * of headers that we allow the follow up request to send.
771 * @param string $requestedHeaders Comma seperated list of HTTP headers
772 * @return bool True if all requested headers are in the list of allowed headers
774 protected static function matchRequestedHeaders( $requestedHeaders ) {
775 if ( trim( $requestedHeaders ) === '' ) {
776 return true;
778 $requestedHeaders = explode( ',', $requestedHeaders );
779 $allowedAuthorHeaders = array_flip( [
780 /* simple headers (see spec) */
781 'accept',
782 'accept-language',
783 'content-language',
784 'content-type',
785 /* non-authorable headers in XHR, which are however requested by some UAs */
786 'accept-encoding',
787 'dnt',
788 'origin',
789 /* MediaWiki whitelist */
790 'api-user-agent',
791 ] );
792 foreach ( $requestedHeaders as $rHeader ) {
793 $rHeader = strtolower( trim( $rHeader ) );
794 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
795 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
796 return false;
799 return true;
803 * Helper function to convert wildcard string into a regex
804 * '*' => '.*?'
805 * '?' => '.'
807 * @param string $wildcard String with wildcards
808 * @return string Regular expression
810 protected static function wildcardToRegex( $wildcard ) {
811 $wildcard = preg_quote( $wildcard, '/' );
812 $wildcard = str_replace(
813 [ '\*', '\?' ],
814 [ '.*?', '.' ],
815 $wildcard
818 return "/^https?:\/\/$wildcard$/";
822 * Send caching headers
823 * @param bool $isError Whether an error response is being output
824 * @since 1.26 added $isError parameter
826 protected function sendCacheHeaders( $isError ) {
827 $response = $this->getRequest()->response();
828 $out = $this->getOutput();
830 $out->addVaryHeader( 'Treat-as-Untrusted' );
832 $config = $this->getConfig();
834 if ( $config->get( 'VaryOnXFP' ) ) {
835 $out->addVaryHeader( 'X-Forwarded-Proto' );
838 if ( !$isError && $this->mModule &&
839 ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
841 $etag = $this->mModule->getConditionalRequestData( 'etag' );
842 if ( $etag !== null ) {
843 $response->header( "ETag: $etag" );
845 $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
846 if ( $lastMod !== null ) {
847 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
851 // The logic should be:
852 // $this->mCacheControl['max-age'] is set?
853 // Use it, the module knows better than our guess.
854 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
855 // Use 0 because we can guess caching is probably the wrong thing to do.
856 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
857 $maxage = 0;
858 if ( isset( $this->mCacheControl['max-age'] ) ) {
859 $maxage = $this->mCacheControl['max-age'];
860 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
861 $this->mCacheMode !== 'private'
863 $maxage = $this->getParameter( 'maxage' );
865 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
867 if ( $this->mCacheMode == 'private' ) {
868 $response->header( "Cache-Control: $privateCache" );
869 return;
872 $useKeyHeader = $config->get( 'UseKeyHeader' );
873 if ( $this->mCacheMode == 'anon-public-user-private' ) {
874 $out->addVaryHeader( 'Cookie' );
875 $response->header( $out->getVaryHeader() );
876 if ( $useKeyHeader ) {
877 $response->header( $out->getKeyHeader() );
878 if ( $out->haveCacheVaryCookies() ) {
879 // Logged in, mark this request private
880 $response->header( "Cache-Control: $privateCache" );
881 return;
883 // Logged out, send normal public headers below
884 } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
885 // Logged in or otherwise has session (e.g. anonymous users who have edited)
886 // Mark request private
887 $response->header( "Cache-Control: $privateCache" );
889 return;
890 } // else no Key and anonymous, send public headers below
893 // Send public headers
894 $response->header( $out->getVaryHeader() );
895 if ( $useKeyHeader ) {
896 $response->header( $out->getKeyHeader() );
899 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
900 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
901 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
903 if ( !isset( $this->mCacheControl['max-age'] ) ) {
904 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
907 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
908 // Public cache not requested
909 // Sending a Vary header in this case is harmless, and protects us
910 // against conditional calls of setCacheMaxAge().
911 $response->header( "Cache-Control: $privateCache" );
913 return;
916 $this->mCacheControl['public'] = true;
918 // Send an Expires header
919 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
920 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
921 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
923 // Construct the Cache-Control header
924 $ccHeader = '';
925 $separator = '';
926 foreach ( $this->mCacheControl as $name => $value ) {
927 if ( is_bool( $value ) ) {
928 if ( $value ) {
929 $ccHeader .= $separator . $name;
930 $separator = ', ';
932 } else {
933 $ccHeader .= $separator . "$name=$value";
934 $separator = ', ';
938 $response->header( "Cache-Control: $ccHeader" );
942 * Create the printer for error output
944 private function createErrorPrinter() {
945 if ( !isset( $this->mPrinter ) ) {
946 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
947 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
948 $value = self::API_DEFAULT_FORMAT;
950 $this->mPrinter = $this->createPrinterByName( $value );
953 // Printer may not be able to handle errors. This is particularly
954 // likely if the module returns something for getCustomPrinter().
955 if ( !$this->mPrinter->canPrintErrors() ) {
956 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
961 * Create an error message for the given exception.
963 * If the exception is a UsageException then
964 * UsageException::getMessageArray() will be called to create the message.
966 * @param Exception $e
967 * @return array ['code' => 'some string', 'info' => 'some other string']
968 * @since 1.27
970 protected function errorMessageFromException( $e ) {
971 if ( $e instanceof UsageException ) {
972 // User entered incorrect parameters - generate error response
973 $errMessage = $e->getMessageArray();
974 } else {
975 $config = $this->getConfig();
976 // Something is seriously wrong
977 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
978 $info = 'Database query error';
979 } else {
980 $info = "Exception Caught: {$e->getMessage()}";
983 $errMessage = [
984 'code' => 'internal_api_error_' . get_class( $e ),
985 'info' => '[' . WebRequest::getRequestId() . '] ' . $info,
988 return $errMessage;
992 * Replace the result data with the information about an exception.
993 * Returns the error code
994 * @param Exception $e
995 * @return string
997 protected function substituteResultWithError( $e ) {
998 $result = $this->getResult();
999 $config = $this->getConfig();
1001 $errMessage = $this->errorMessageFromException( $e );
1002 if ( $e instanceof UsageException ) {
1003 // User entered incorrect parameters - generate error response
1004 $link = wfExpandUrl( wfScript( 'api' ) );
1005 ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
1006 } else {
1007 // Something is seriously wrong
1008 if ( $config->get( 'ShowExceptionDetails' ) ) {
1009 ApiResult::setContentValue(
1010 $errMessage,
1011 'trace',
1012 MWExceptionHandler::getRedactedTraceAsString( $e )
1017 // Remember all the warnings to re-add them later
1018 $warnings = $result->getResultData( [ 'warnings' ] );
1020 $result->reset();
1021 // Re-add the id
1022 $requestid = $this->getParameter( 'requestid' );
1023 if ( !is_null( $requestid ) ) {
1024 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1026 if ( $config->get( 'ShowHostnames' ) ) {
1027 // servedby is especially useful when debugging errors
1028 $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1030 if ( $warnings !== null ) {
1031 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1034 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
1036 return $errMessage['code'];
1040 * Set up for the execution.
1041 * @return array
1043 protected function setupExecuteAction() {
1044 // First add the id to the top element
1045 $result = $this->getResult();
1046 $requestid = $this->getParameter( 'requestid' );
1047 if ( !is_null( $requestid ) ) {
1048 $result->addValue( null, 'requestid', $requestid );
1051 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1052 $servedby = $this->getParameter( 'servedby' );
1053 if ( $servedby ) {
1054 $result->addValue( null, 'servedby', wfHostname() );
1058 if ( $this->getParameter( 'curtimestamp' ) ) {
1059 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1060 ApiResult::NO_SIZE_CHECK );
1063 $params = $this->extractRequestParams();
1065 $this->mAction = $params['action'];
1067 if ( !is_string( $this->mAction ) ) {
1068 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1071 return $params;
1075 * Set up the module for response
1076 * @return ApiBase The module that will handle this action
1077 * @throws MWException
1078 * @throws UsageException
1080 protected function setupModule() {
1081 // Instantiate the module requested by the user
1082 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1083 if ( $module === null ) {
1084 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1086 $moduleParams = $module->extractRequestParams();
1088 // Check token, if necessary
1089 if ( $module->needsToken() === true ) {
1090 throw new MWException(
1091 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1092 'See documentation for ApiBase::needsToken for details.'
1095 if ( $module->needsToken() ) {
1096 if ( !$module->mustBePosted() ) {
1097 throw new MWException(
1098 "Module '{$module->getModuleName()}' must require POST to use tokens."
1102 if ( !isset( $moduleParams['token'] ) ) {
1103 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1106 $module->requirePostedParameters( [ 'token' ] );
1108 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1109 $this->dieUsageMsg( 'sessionfailure' );
1113 return $module;
1117 * Check the max lag if necessary
1118 * @param ApiBase $module Api module being used
1119 * @param array $params Array an array containing the request parameters.
1120 * @return bool True on success, false should exit immediately
1122 protected function checkMaxLag( $module, $params ) {
1123 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1124 $maxLag = $params['maxlag'];
1125 list( $host, $lag ) = wfGetLB()->getMaxLag();
1126 if ( $lag > $maxLag ) {
1127 $response = $this->getRequest()->response();
1129 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1130 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1132 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1133 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1136 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1140 return true;
1144 * Check selected RFC 7232 precondition headers
1146 * RFC 7232 envisions a particular model where you send your request to "a
1147 * resource", and for write requests that you can read "the resource" by
1148 * changing the method to GET. When the API receives a GET request, it
1149 * works out even though "the resource" from RFC 7232's perspective might
1150 * be many resources from MediaWiki's perspective. But it totally fails for
1151 * a POST, since what HTTP sees as "the resource" is probably just
1152 * "/api.php" with all the interesting bits in the body.
1154 * Therefore, we only support RFC 7232 precondition headers for GET (and
1155 * HEAD). That means we don't need to bother with If-Match and
1156 * If-Unmodified-Since since they only apply to modification requests.
1158 * And since we don't support Range, If-Range is ignored too.
1160 * @since 1.26
1161 * @param ApiBase $module Api module being used
1162 * @return bool True on success, false should exit immediately
1164 protected function checkConditionalRequestHeaders( $module ) {
1165 if ( $this->mInternalMode ) {
1166 // No headers to check in internal mode
1167 return true;
1170 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1171 // Don't check POSTs
1172 return true;
1175 $return304 = false;
1177 $ifNoneMatch = array_diff(
1178 $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1179 [ '' ]
1181 if ( $ifNoneMatch ) {
1182 if ( $ifNoneMatch === [ '*' ] ) {
1183 // API responses always "exist"
1184 $etag = '*';
1185 } else {
1186 $etag = $module->getConditionalRequestData( 'etag' );
1189 if ( $ifNoneMatch && $etag !== null ) {
1190 $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1191 $match = array_map( function ( $s ) {
1192 return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1193 }, $ifNoneMatch );
1194 $return304 = in_array( $test, $match, true );
1195 } else {
1196 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1198 // Some old browsers sends sizes after the date, like this:
1199 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1200 // Ignore that.
1201 $i = strpos( $value, ';' );
1202 if ( $i !== false ) {
1203 $value = trim( substr( $value, 0, $i ) );
1206 if ( $value !== '' ) {
1207 try {
1208 $ts = new MWTimestamp( $value );
1209 if (
1210 // RFC 7231 IMF-fixdate
1211 $ts->getTimestamp( TS_RFC2822 ) === $value ||
1212 // RFC 850
1213 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1214 // asctime (with and without space-padded day)
1215 $ts->format( 'D M j H:i:s Y' ) === $value ||
1216 $ts->format( 'D M j H:i:s Y' ) === $value
1218 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1219 if ( $lastMod !== null ) {
1220 // Mix in some MediaWiki modification times
1221 $modifiedTimes = [
1222 'page' => $lastMod,
1223 'user' => $this->getUser()->getTouched(),
1224 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1226 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1227 // T46570: the core page itself may not change, but resources might
1228 $modifiedTimes['sepoch'] = wfTimestamp(
1229 TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1232 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1233 $lastMod = max( $modifiedTimes );
1234 $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1237 } catch ( TimestampException $e ) {
1238 // Invalid timestamp, ignore it
1243 if ( $return304 ) {
1244 $this->getRequest()->response()->statusHeader( 304 );
1246 // Avoid outputting the compressed representation of a zero-length body
1247 MediaWiki\suppressWarnings();
1248 ini_set( 'zlib.output_compression', 0 );
1249 MediaWiki\restoreWarnings();
1250 wfClearOutputBuffers();
1252 return false;
1255 return true;
1259 * Check for sufficient permissions to execute
1260 * @param ApiBase $module An Api module
1262 protected function checkExecutePermissions( $module ) {
1263 $user = $this->getUser();
1264 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1265 !$user->isAllowed( 'read' )
1267 $this->dieUsageMsg( 'readrequired' );
1270 if ( $module->isWriteMode() ) {
1271 if ( !$this->mEnableWrite ) {
1272 $this->dieUsageMsg( 'writedisabled' );
1273 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1274 $this->dieUsageMsg( 'writerequired' );
1275 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1276 $this->dieUsage(
1277 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1278 'promised-nonwrite-api'
1282 $this->checkReadOnly( $module );
1285 // Allow extensions to stop execution for arbitrary reasons.
1286 $message = false;
1287 if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1288 $this->dieUsageMsg( $message );
1293 * Check if the DB is read-only for this user
1294 * @param ApiBase $module An Api module
1296 protected function checkReadOnly( $module ) {
1297 if ( wfReadOnly() ) {
1298 $this->dieReadOnly();
1301 if ( $module->isWriteMode()
1302 && in_array( 'bot', $this->getUser()->getGroups() )
1303 && wfGetLB()->getServerCount() > 1
1305 $this->checkBotReadOnly();
1310 * Check whether we are readonly for bots
1312 private function checkBotReadOnly() {
1313 // Figure out how many servers have passed the lag threshold
1314 $numLagged = 0;
1315 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1316 $laggedServers = [];
1317 $loadBalancer = wfGetLB();
1318 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1319 if ( $lag > $lagLimit ) {
1320 ++$numLagged;
1321 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1325 // If a majority of slaves are too lagged then disallow writes
1326 $slaveCount = wfGetLB()->getServerCount() - 1;
1327 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1328 $laggedServers = implode( ', ', $laggedServers );
1329 wfDebugLog(
1330 'api-readonly',
1331 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1334 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1335 $this->dieUsage(
1336 $parsed['info'],
1337 $parsed['code'],
1338 /* http error */
1340 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1346 * Check asserts of the user's rights
1347 * @param array $params
1349 protected function checkAsserts( $params ) {
1350 if ( isset( $params['assert'] ) ) {
1351 $user = $this->getUser();
1352 switch ( $params['assert'] ) {
1353 case 'user':
1354 if ( $user->isAnon() ) {
1355 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1357 break;
1358 case 'bot':
1359 if ( !$user->isAllowed( 'bot' ) ) {
1360 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1362 break;
1368 * Check POST for external response and setup result printer
1369 * @param ApiBase $module An Api module
1370 * @param array $params An array with the request parameters
1372 protected function setupExternalResponse( $module, $params ) {
1373 $request = $this->getRequest();
1374 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1375 // Module requires POST. GET request might still be allowed
1376 // if $wgDebugApi is true, otherwise fail.
1377 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] );
1380 // See if custom printer is used
1381 $this->mPrinter = $module->getCustomPrinter();
1382 if ( is_null( $this->mPrinter ) ) {
1383 // Create an appropriate printer
1384 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1387 if ( $request->getProtocol() === 'http' && (
1388 $request->getSession()->shouldForceHTTPS() ||
1389 ( $this->getUser()->isLoggedIn() &&
1390 $this->getUser()->requiresHTTPS() )
1391 ) ) {
1392 $this->logFeatureUsage( 'https-expected' );
1393 $this->setWarning( 'HTTP used when HTTPS was expected' );
1398 * Execute the actual module, without any error handling
1400 protected function executeAction() {
1401 $params = $this->setupExecuteAction();
1402 $module = $this->setupModule();
1403 $this->mModule = $module;
1405 if ( !$this->mInternalMode ) {
1406 $this->setRequestExpectations( $module );
1409 $this->checkExecutePermissions( $module );
1411 if ( !$this->checkMaxLag( $module, $params ) ) {
1412 return;
1415 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1416 return;
1419 if ( !$this->mInternalMode ) {
1420 $this->setupExternalResponse( $module, $params );
1423 $this->checkAsserts( $params );
1425 // Execute
1426 $module->execute();
1427 Hooks::run( 'APIAfterExecute', [ &$module ] );
1429 $this->reportUnusedParams();
1431 if ( !$this->mInternalMode ) {
1432 // append Debug information
1433 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1435 // Print result data
1436 $this->printResult( false );
1441 * Set database connection, query, and write expectations given this module request
1442 * @param ApiBase $module
1444 protected function setRequestExpectations( ApiBase $module ) {
1445 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1446 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1447 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1448 if ( $this->getRequest()->hasSafeMethod() ) {
1449 $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1450 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1451 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1452 $this->getRequest()->markAsSafeRequest();
1453 } else {
1454 $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1459 * Log the preceding request
1460 * @param float $time Time in seconds
1461 * @param Exception $e Exception caught while processing the request
1463 protected function logRequest( $time, $e = null ) {
1464 $request = $this->getRequest();
1465 $logCtx = [
1466 'ts' => time(),
1467 'ip' => $request->getIP(),
1468 'userAgent' => $this->getUserAgent(),
1469 'wiki' => wfWikiID(),
1470 'timeSpentBackend' => (int) round( $time * 1000 ),
1471 'hadError' => $e !== null,
1472 'errorCodes' => [],
1473 'params' => [],
1476 if ( $e ) {
1477 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1480 // Construct space separated message for 'api' log channel
1481 $msg = "API {$request->getMethod()} " .
1482 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1483 " {$logCtx['ip']} " .
1484 "T={$logCtx['timeSpentBackend']}ms";
1486 foreach ( $this->getParamsUsed() as $name ) {
1487 $value = $request->getVal( $name );
1488 if ( $value === null ) {
1489 continue;
1492 if ( strlen( $value ) > 256 ) {
1493 $value = substr( $value, 0, 256 );
1494 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1495 } else {
1496 $encValue = $this->encodeRequestLogValue( $value );
1499 $logCtx['params'][$name] = $value;
1500 $msg .= " {$name}={$encValue}";
1503 wfDebugLog( 'api', $msg, 'private' );
1504 // ApiAction channel is for structured data consumers
1505 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1509 * Encode a value in a format suitable for a space-separated log line.
1510 * @param string $s
1511 * @return string
1513 protected function encodeRequestLogValue( $s ) {
1514 static $table;
1515 if ( !$table ) {
1516 $chars = ';@$!*(),/:';
1517 $numChars = strlen( $chars );
1518 for ( $i = 0; $i < $numChars; $i++ ) {
1519 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1523 return strtr( rawurlencode( $s ), $table );
1527 * Get the request parameters used in the course of the preceding execute() request
1528 * @return array
1530 protected function getParamsUsed() {
1531 return array_keys( $this->mParamsUsed );
1535 * Mark parameters as used
1536 * @param string|string[] $params
1538 public function markParamsUsed( $params ) {
1539 $this->mParamsUsed += array_fill_keys( (array)$params, true );
1543 * Get a request value, and register the fact that it was used, for logging.
1544 * @param string $name
1545 * @param mixed $default
1546 * @return mixed
1548 public function getVal( $name, $default = null ) {
1549 $this->mParamsUsed[$name] = true;
1551 $ret = $this->getRequest()->getVal( $name );
1552 if ( $ret === null ) {
1553 if ( $this->getRequest()->getArray( $name ) !== null ) {
1554 // See bug 10262 for why we don't just implode( '|', ... ) the
1555 // array.
1556 $this->setWarning(
1557 "Parameter '$name' uses unsupported PHP array syntax"
1560 $ret = $default;
1562 return $ret;
1566 * Get a boolean request value, and register the fact that the parameter
1567 * was used, for logging.
1568 * @param string $name
1569 * @return bool
1571 public function getCheck( $name ) {
1572 return $this->getVal( $name, null ) !== null;
1576 * Get a request upload, and register the fact that it was used, for logging.
1578 * @since 1.21
1579 * @param string $name Parameter name
1580 * @return WebRequestUpload
1582 public function getUpload( $name ) {
1583 $this->mParamsUsed[$name] = true;
1585 return $this->getRequest()->getUpload( $name );
1589 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1590 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1592 protected function reportUnusedParams() {
1593 $paramsUsed = $this->getParamsUsed();
1594 $allParams = $this->getRequest()->getValueNames();
1596 if ( !$this->mInternalMode ) {
1597 // Printer has not yet executed; don't warn that its parameters are unused
1598 $printerParams = array_map(
1599 [ $this->mPrinter, 'encodeParamName' ],
1600 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1602 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1603 } else {
1604 $unusedParams = array_diff( $allParams, $paramsUsed );
1607 if ( count( $unusedParams ) ) {
1608 $s = count( $unusedParams ) > 1 ? 's' : '';
1609 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1614 * Print results using the current printer
1616 * @param bool $isError
1618 protected function printResult( $isError ) {
1619 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1620 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1623 $printer = $this->mPrinter;
1624 $printer->initPrinter( false );
1625 $printer->execute();
1626 $printer->closePrinter();
1630 * @return bool
1632 public function isReadMode() {
1633 return false;
1637 * See ApiBase for description.
1639 * @return array
1641 public function getAllowedParams() {
1642 return [
1643 'action' => [
1644 ApiBase::PARAM_DFLT => 'help',
1645 ApiBase::PARAM_TYPE => 'submodule',
1647 'format' => [
1648 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1649 ApiBase::PARAM_TYPE => 'submodule',
1651 'maxlag' => [
1652 ApiBase::PARAM_TYPE => 'integer'
1654 'smaxage' => [
1655 ApiBase::PARAM_TYPE => 'integer',
1656 ApiBase::PARAM_DFLT => 0
1658 'maxage' => [
1659 ApiBase::PARAM_TYPE => 'integer',
1660 ApiBase::PARAM_DFLT => 0
1662 'assert' => [
1663 ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1665 'requestid' => null,
1666 'servedby' => false,
1667 'curtimestamp' => false,
1668 'origin' => null,
1669 'uselang' => [
1670 ApiBase::PARAM_DFLT => 'user',
1675 /** @see ApiBase::getExamplesMessages() */
1676 protected function getExamplesMessages() {
1677 return [
1678 'action=help'
1679 => 'apihelp-help-example-main',
1680 'action=help&recursivesubmodules=1'
1681 => 'apihelp-help-example-recursive',
1685 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1686 // Wish PHP had an "array_insert_before". Instead, we have to manually
1687 // reindex the array to get 'permissions' in the right place.
1688 $oldHelp = $help;
1689 $help = [];
1690 foreach ( $oldHelp as $k => $v ) {
1691 if ( $k === 'submodules' ) {
1692 $help['permissions'] = '';
1694 $help[$k] = $v;
1696 $help['datatypes'] = '';
1697 $help['credits'] = '';
1699 // Fill 'permissions'
1700 $help['permissions'] .= Html::openElement( 'div',
1701 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1702 $m = $this->msg( 'api-help-permissions' );
1703 if ( !$m->isDisabled() ) {
1704 $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1705 $m->numParams( count( self::$mRights ) )->parse()
1708 $help['permissions'] .= Html::openElement( 'dl' );
1709 foreach ( self::$mRights as $right => $rightMsg ) {
1710 $help['permissions'] .= Html::element( 'dt', null, $right );
1712 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1713 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1715 $groups = array_map( function ( $group ) {
1716 return $group == '*' ? 'all' : $group;
1717 }, User::getGroupsWithPermission( $right ) );
1719 $help['permissions'] .= Html::rawElement( 'dd', null,
1720 $this->msg( 'api-help-permissions-granted-to' )
1721 ->numParams( count( $groups ) )
1722 ->params( $this->getLanguage()->commaList( $groups ) )
1723 ->parse()
1726 $help['permissions'] .= Html::closeElement( 'dl' );
1727 $help['permissions'] .= Html::closeElement( 'div' );
1729 // Fill 'datatypes' and 'credits', if applicable
1730 if ( empty( $options['nolead'] ) ) {
1731 $level = $options['headerlevel'];
1732 $tocnumber = &$options['tocnumber'];
1734 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1736 // Add an additional span with sanitized ID
1737 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1738 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1739 $header;
1741 $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1742 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1743 $header
1745 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1746 if ( !isset( $tocData['main/datatypes'] ) ) {
1747 $tocnumber[$level]++;
1748 $tocData['main/datatypes'] = [
1749 'toclevel' => count( $tocnumber ),
1750 'level' => $level,
1751 'anchor' => 'main/datatypes',
1752 'line' => $header,
1753 'number' => implode( '.', $tocnumber ),
1754 'index' => false,
1758 // Add an additional span with sanitized ID
1759 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1760 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1761 $header;
1763 $header = $this->msg( 'api-credits-header' )->parse();
1764 $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1765 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1766 $header
1768 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1769 if ( !isset( $tocData['main/credits'] ) ) {
1770 $tocnumber[$level]++;
1771 $tocData['main/credits'] = [
1772 'toclevel' => count( $tocnumber ),
1773 'level' => $level,
1774 'anchor' => 'main/credits',
1775 'line' => $header,
1776 'number' => implode( '.', $tocnumber ),
1777 'index' => false,
1783 private $mCanApiHighLimits = null;
1786 * Check whether the current user is allowed to use high limits
1787 * @return bool
1789 public function canApiHighLimits() {
1790 if ( !isset( $this->mCanApiHighLimits ) ) {
1791 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1794 return $this->mCanApiHighLimits;
1798 * Overrides to return this instance's module manager.
1799 * @return ApiModuleManager
1801 public function getModuleManager() {
1802 return $this->mModuleMgr;
1806 * Fetches the user agent used for this request
1808 * The value will be the combination of the 'Api-User-Agent' header (if
1809 * any) and the standard User-Agent header (if any).
1811 * @return string
1813 public function getUserAgent() {
1814 return trim(
1815 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1816 $this->getRequest()->getHeader( 'User-agent' )
1820 /************************************************************************//**
1821 * @name Deprecated
1822 * @{
1826 * Sets whether the pretty-printer should format *bold* and $italics$
1828 * @deprecated since 1.25
1829 * @param bool $help
1831 public function setHelp( $help = true ) {
1832 wfDeprecated( __METHOD__, '1.25' );
1833 $this->mPrinter->setHelp( $help );
1837 * Override the parent to generate help messages for all available modules.
1839 * @deprecated since 1.25
1840 * @return string
1842 public function makeHelpMsg() {
1843 wfDeprecated( __METHOD__, '1.25' );
1845 $this->setHelp();
1846 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1848 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1849 wfMemcKey(
1850 'apihelp',
1851 $this->getModuleName(),
1852 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
1854 $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
1855 [ $this, 'reallyMakeHelpMsg' ]
1860 * @deprecated since 1.25
1861 * @return mixed|string
1863 public function reallyMakeHelpMsg() {
1864 wfDeprecated( __METHOD__, '1.25' );
1865 $this->setHelp();
1867 // Use parent to make default message for the main module
1868 $msg = parent::makeHelpMsg();
1870 $asterisks = str_repeat( '*** ', 14 );
1871 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1873 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1874 $module = $this->mModuleMgr->getModule( $name );
1875 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1877 $msg2 = $module->makeHelpMsg();
1878 if ( $msg2 !== false ) {
1879 $msg .= $msg2;
1881 $msg .= "\n";
1884 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1885 foreach ( self::$mRights as $right => $rightMsg ) {
1886 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1887 ->useDatabase( false )
1888 ->inLanguage( 'en' )
1889 ->text();
1890 $groups = User::getGroupsWithPermission( $right );
1891 $msg .= '* ' . $right . " *\n $rightsMsg" .
1892 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1895 $msg .= "\n$asterisks Formats $asterisks\n\n";
1896 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1897 $module = $this->mModuleMgr->getModule( $name );
1898 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1899 $msg2 = $module->makeHelpMsg();
1900 if ( $msg2 !== false ) {
1901 $msg .= $msg2;
1903 $msg .= "\n";
1906 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1907 $credits = str_replace( "\n", "\n ", $credits );
1908 $msg .= "\n*** Credits: ***\n $credits\n";
1910 return $msg;
1914 * @deprecated since 1.25
1915 * @param ApiBase $module
1916 * @param string $paramName What type of request is this? e.g. action,
1917 * query, list, prop, meta, format
1918 * @return string
1920 public static function makeHelpMsgHeader( $module, $paramName ) {
1921 wfDeprecated( __METHOD__, '1.25' );
1922 $modulePrefix = $module->getModulePrefix();
1923 if ( strval( $modulePrefix ) !== '' ) {
1924 $modulePrefix = "($modulePrefix) ";
1927 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1930 /**@}*/
1935 * This exception will be thrown when dieUsage is called to stop module execution.
1937 * @ingroup API
1939 class UsageException extends MWException {
1941 private $mCodestr;
1944 * @var null|array
1946 private $mExtraData;
1949 * @param string $message
1950 * @param string $codestr
1951 * @param int $code
1952 * @param array|null $extradata
1954 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1955 parent::__construct( $message, $code );
1956 $this->mCodestr = $codestr;
1957 $this->mExtraData = $extradata;
1959 // This should never happen, so throw an exception about it that will
1960 // hopefully get logged with a backtrace (T138585)
1961 if ( !is_string( $codestr ) || $codestr === '' ) {
1962 throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1963 ( $codestr === '' ? 'empty string' : gettype( $codestr ) )
1969 * @return string
1971 public function getCodeString() {
1972 return $this->mCodestr;
1976 * @return array
1978 public function getMessageArray() {
1979 $result = [
1980 'code' => $this->mCodestr,
1981 'info' => $this->getMessage()
1983 if ( is_array( $this->mExtraData ) ) {
1984 $result = array_merge( $result, $this->mExtraData );
1987 return $result;
1991 * @return string
1993 public function __toString() {
1994 return "{$this->getCodeString()}: {$this->getMessage()}";
1999 * For really cool vim folding this needs to be at the end:
2000 * vim: foldmarker=@{,@} foldmethod=marker