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
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * List of available modules: action name => module class
50 private static $Modules = [
51 'login' => 'ApiLogin',
52 'clientlogin' => 'ApiClientLogin',
53 'logout' => 'ApiLogout',
54 'createaccount' => 'ApiAMCreateAccount',
55 'linkaccount' => 'ApiLinkAccount',
56 'unlinkaccount' => 'ApiRemoveAuthenticationData',
57 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
58 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
59 'resetpassword' => 'ApiResetPassword',
60 'query' => 'ApiQuery',
61 'expandtemplates' => 'ApiExpandTemplates',
62 'parse' => 'ApiParse',
63 'stashedit' => 'ApiStashEdit',
64 'opensearch' => 'ApiOpenSearch',
65 'feedcontributions' => 'ApiFeedContributions',
66 'feedrecentchanges' => 'ApiFeedRecentChanges',
67 'feedwatchlist' => 'ApiFeedWatchlist',
69 'paraminfo' => 'ApiParamInfo',
71 'compare' => 'ApiComparePages',
72 'tokens' => 'ApiTokens',
73 'checktoken' => 'ApiCheckToken',
74 'cspreport' => 'ApiCSPReport',
77 'purge' => 'ApiPurge',
78 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
79 'rollback' => 'ApiRollback',
80 'delete' => 'ApiDelete',
81 'undelete' => 'ApiUndelete',
82 'protect' => 'ApiProtect',
83 'block' => 'ApiBlock',
84 'unblock' => 'ApiUnblock',
86 'edit' => 'ApiEditPage',
87 'upload' => 'ApiUpload',
88 'filerevert' => 'ApiFileRevert',
89 'emailuser' => 'ApiEmailUser',
90 'watch' => 'ApiWatch',
91 'patrol' => 'ApiPatrol',
92 'import' => 'ApiImport',
93 'clearhasmsg' => 'ApiClearHasMsg',
94 'userrights' => 'ApiUserrights',
95 'options' => 'ApiOptions',
96 'imagerotate' => 'ApiImageRotate',
97 'revisiondelete' => 'ApiRevisionDelete',
98 'managetags' => 'ApiManageTags',
100 'mergehistory' => 'ApiMergeHistory',
104 * List of available formats: format name => format class
106 private static $Formats = [
107 'json' => 'ApiFormatJson',
108 'jsonfm' => 'ApiFormatJson',
109 'php' => 'ApiFormatPhp',
110 'phpfm' => 'ApiFormatPhp',
111 'xml' => 'ApiFormatXml',
112 'xmlfm' => 'ApiFormatXml',
113 'rawfm' => 'ApiFormatJson',
114 'none' => 'ApiFormatNone',
117 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
119 * List of user roles that are specifically relevant to the API.
120 * array( 'right' => array ( 'msg' => 'Some message with a $1',
121 * 'params' => array ( $someVarToSubst ) ),
124 private static $mRights = [
126 'msg' => 'right-writeapi',
130 'msg' => 'api-help-right-apihighlimits',
131 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
134 // @codingStandardsIgnoreEnd
141 private $mModuleMgr, $mResult, $mErrorFormatter;
142 /** @var ApiContinuationManager|null */
143 private $mContinuationManager;
145 private $mEnableWrite;
146 private $mInternalMode, $mSquidMaxage;
150 private $mCacheMode = 'private';
151 private $mCacheControl = [];
152 private $mParamsUsed = [];
154 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
155 private $lacksSameOriginSecurity = null;
158 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
160 * @param IContextSource|WebRequest $context If this is an instance of
161 * FauxRequest, errors are thrown and no printing occurs
162 * @param bool $enableWrite Should be set to true if the api may modify data
164 public function __construct( $context = null, $enableWrite = false ) {
165 if ( $context === null ) {
166 $context = RequestContext
::getMain();
167 } elseif ( $context instanceof WebRequest
) {
170 $context = RequestContext
::getMain();
172 // We set a derivative context so we can change stuff later
173 $this->setContext( new DerivativeContext( $context ) );
175 if ( isset( $request ) ) {
176 $this->getContext()->setRequest( $request );
178 $request = $this->getRequest();
181 $this->mInternalMode
= ( $request instanceof FauxRequest
);
183 // Special handling for the main module: $parent === $this
184 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
186 $config = $this->getConfig();
188 if ( !$this->mInternalMode
) {
189 // Log if a request with a non-whitelisted Origin header is seen
190 // with session cookies.
191 $originHeader = $request->getHeader( 'Origin' );
192 if ( $originHeader === false ) {
195 $originHeader = trim( $originHeader );
196 $origins = preg_split( '/\s+/', $originHeader );
198 $sessionCookies = array_intersect(
199 array_keys( $_COOKIE ),
200 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
202 if ( $origins && $sessionCookies && (
203 count( $origins ) !== 1 ||
!self
::matchOrigin(
205 $config->get( 'CrossSiteAJAXdomains' ),
206 $config->get( 'CrossSiteAJAXdomainExceptions' )
209 MediaWiki\Logger\LoggerFactory
::getInstance( 'cors' )->warning(
210 'Non-whitelisted CORS request with session cookies', [
211 'origin' => $originHeader,
212 'cookies' => $sessionCookies,
213 'ip' => $request->getIP(),
214 'userAgent' => $this->getUserAgent(),
215 'wiki' => wfWikiID(),
220 // If we're in a mode that breaks the same-origin policy, strip
221 // user credentials for security.
222 if ( $this->lacksSameOriginSecurity() ) {
224 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
225 $wgUser = new User();
226 $this->getContext()->setUser( $wgUser );
230 $uselang = $this->getParameter( 'uselang' );
231 if ( $uselang === 'user' ) {
232 // Assume the parent context is going to return the user language
233 // for uselang=user (see T85635).
235 if ( $uselang === 'content' ) {
237 $uselang = $wgContLang->getCode();
239 $code = RequestContext
::sanitizeLangCode( $uselang );
240 $this->getContext()->setLanguage( $code );
241 if ( !$this->mInternalMode
) {
243 $wgLang = $this->getContext()->getLanguage();
244 RequestContext
::getMain()->setLanguage( $wgLang );
248 $this->mModuleMgr
= new ApiModuleManager( $this );
249 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
250 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
251 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
252 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
254 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
256 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
257 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
258 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
259 $this->mResult
->setMainForContinuation( $this );
260 $this->mContinuationManager
= null;
261 $this->mEnableWrite
= $enableWrite;
263 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
264 $this->mCommit
= false;
268 * Return true if the API was started by other PHP code using FauxRequest
271 public function isInternalMode() {
272 return $this->mInternalMode
;
276 * Get the ApiResult object associated with current request
280 public function getResult() {
281 return $this->mResult
;
285 * Get the security flag for the current request
288 public function lacksSameOriginSecurity() {
289 if ( $this->lacksSameOriginSecurity
!== null ) {
290 return $this->lacksSameOriginSecurity
;
293 $request = $this->getRequest();
296 if ( $request->getVal( 'callback' ) !== null ) {
297 $this->lacksSameOriginSecurity
= true;
301 // Header to be used from XMLHTTPRequest when the request might
302 // otherwise be used for XSS.
303 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
304 $this->lacksSameOriginSecurity
= true;
308 // Allow extensions to override.
309 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
310 return $this->lacksSameOriginSecurity
;
314 * Get the ApiErrorFormatter object associated with current request
315 * @return ApiErrorFormatter
317 public function getErrorFormatter() {
318 return $this->mErrorFormatter
;
322 * Get the continuation manager
323 * @return ApiContinuationManager|null
325 public function getContinuationManager() {
326 return $this->mContinuationManager
;
330 * Set the continuation manager
331 * @param ApiContinuationManager|null
333 public function setContinuationManager( $manager ) {
334 if ( $manager !== null ) {
335 if ( !$manager instanceof ApiContinuationManager
) {
336 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
337 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
340 if ( $this->mContinuationManager
!== null ) {
341 throw new UnexpectedValueException(
342 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
343 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
347 $this->mContinuationManager
= $manager;
351 * Get the API module object. Only works after executeAction()
355 public function getModule() {
356 return $this->mModule
;
360 * Get the result formatter object. Only works after setupExecuteAction()
362 * @return ApiFormatBase
364 public function getPrinter() {
365 return $this->mPrinter
;
369 * Set how long the response should be cached.
373 public function setCacheMaxAge( $maxage ) {
374 $this->setCacheControl( [
375 'max-age' => $maxage,
376 's-maxage' => $maxage
381 * Set the type of caching headers which will be sent.
383 * @param string $mode One of:
384 * - 'public': Cache this object in public caches, if the maxage or smaxage
385 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
386 * not provided by any of these means, the object will be private.
387 * - 'private': Cache this object only in private client-side caches.
388 * - 'anon-public-user-private': Make this object cacheable for logged-out
389 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
390 * set consistently for a given URL, it cannot be set differently depending on
391 * things like the contents of the database, or whether the user is logged in.
393 * If the wiki does not allow anonymous users to read it, the mode set here
394 * will be ignored, and private caching headers will always be sent. In other words,
395 * the "public" mode is equivalent to saying that the data sent is as public as a page
398 * For user-dependent data, the private mode should generally be used. The
399 * anon-public-user-private mode should only be used where there is a particularly
400 * good performance reason for caching the anonymous response, but where the
401 * response to logged-in users may differ, or may contain private data.
403 * If this function is never called, then the default will be the private mode.
405 public function setCacheMode( $mode ) {
406 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
407 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
409 // Ignore for forwards-compatibility
413 if ( !User
::isEveryoneAllowed( 'read' ) ) {
414 // Private wiki, only private headers
415 if ( $mode !== 'private' ) {
416 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
422 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
423 // User language is used for i18n, so we don't want to publicly
424 // cache. Anons are ok, because if they have non-default language
425 // then there's an appropriate Vary header set by whatever set
426 // their non-default language.
427 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
428 "'anon-public-user-private' due to uselang=user\n" );
429 $mode = 'anon-public-user-private';
432 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
433 $this->mCacheMode
= $mode;
437 * Set directives (key/value pairs) for the Cache-Control header.
438 * Boolean values will be formatted as such, by including or omitting
439 * without an equals sign.
441 * Cache control values set here will only be used if the cache mode is not
442 * private, see setCacheMode().
444 * @param array $directives
446 public function setCacheControl( $directives ) {
447 $this->mCacheControl
= $directives +
$this->mCacheControl
;
451 * Create an instance of an output formatter by its name
453 * @param string $format
455 * @return ApiFormatBase
457 public function createPrinterByName( $format ) {
458 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
459 if ( $printer === null ) {
460 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
467 * Execute api request. Any errors will be handled if the API was called by the remote client.
469 public function execute() {
470 if ( $this->mInternalMode
) {
471 $this->executeAction();
473 $this->executeActionWithErrorHandling();
478 * Execute an action, and in case of an error, erase whatever partial results
479 * have been accumulated, and replace it with an error message and a help screen.
481 protected function executeActionWithErrorHandling() {
482 // Verify the CORS header before executing the action
483 if ( !$this->handleCORS() ) {
484 // handleCORS() has sent a 403, abort
488 // Exit here if the request method was OPTIONS
489 // (assume there will be a followup GET or POST)
490 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
494 // In case an error occurs during data output,
495 // clear the output buffer and print just the error information
496 $obLevel = ob_get_level();
499 $t = microtime( true );
502 $this->executeAction();
503 $runTime = microtime( true ) - $t;
504 $this->logRequest( $runTime );
505 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
506 $this->getStats()->timing(
507 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
510 } catch ( Exception
$e ) {
511 $this->handleException( $e );
512 $this->logRequest( microtime( true ) - $t, $e );
516 // Commit DBs and send any related cookies and headers
517 MediaWiki
::preOutputCommit( $this->getContext() );
519 // Send cache headers after any code which might generate an error, to
520 // avoid sending public cache headers for errors.
521 $this->sendCacheHeaders( $isError );
523 // Executing the action might have already messed with the output
525 while ( ob_get_level() > $obLevel ) {
531 * Handle an exception as an API response
534 * @param Exception $e
536 protected function handleException( Exception
$e ) {
537 // Bug 63145: Rollback any open database transactions
538 if ( !( $e instanceof UsageException
) ) {
539 // UsageExceptions are intentional, so don't rollback if that's the case
541 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
542 } catch ( DBError
$e2 ) {
543 // Rollback threw an exception too. Log it, but don't interrupt
544 // our regularly scheduled exception handling.
545 MWExceptionHandler
::logException( $e2 );
549 // Allow extra cleanup and logging
550 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
553 if ( !( $e instanceof UsageException
) ) {
554 MWExceptionHandler
::logException( $e );
557 // Handle any kind of exception by outputting properly formatted error message.
558 // If this fails, an unhandled exception should be thrown so that global error
559 // handler will process and log it.
561 $errCode = $this->substituteResultWithError( $e );
563 // Error results should not be cached
564 $this->setCacheMode( 'private' );
566 $response = $this->getRequest()->response();
567 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
568 if ( $e->getCode() === 0 ) {
569 $response->header( $headerStr );
571 $response->header( $headerStr, true, $e->getCode() );
574 // Reset and print just the error message
577 // Printer may not be initialized if the extractRequestParams() fails for the main module
578 $this->createErrorPrinter();
581 $this->printResult( true );
582 } catch ( UsageException
$ex ) {
583 // The error printer itself is failing. Try suppressing its request
584 // parameters and redo.
586 'Error printer failed (will retry without params): ' . $ex->getMessage()
588 $this->mPrinter
= null;
589 $this->createErrorPrinter();
590 $this->mPrinter
->forceDefaultParams();
591 $this->printResult( true );
596 * Handle an exception from the ApiBeforeMain hook.
598 * This tries to print the exception as an API response, to be more
599 * friendly to clients. If it fails, it will rethrow the exception.
602 * @param Exception $e
605 public static function handleApiBeforeMainException( Exception
$e ) {
609 $main = new self( RequestContext
::getMain(), false );
610 $main->handleException( $e );
611 $main->logRequest( 0, $e );
612 } catch ( Exception
$e2 ) {
613 // Nope, even that didn't work. Punt.
617 // Reset cache headers
618 $main->sendCacheHeaders( true );
624 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
626 * If no origin parameter is present, nothing happens.
627 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
628 * is set and false is returned.
629 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
630 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
632 * http://www.w3.org/TR/cors/#resource-requests
633 * http://www.w3.org/TR/cors/#resource-preflight-requests
635 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
637 protected function handleCORS() {
638 $originParam = $this->getParameter( 'origin' ); // defaults to null
639 if ( $originParam === null ) {
640 // No origin parameter, nothing to do
644 $request = $this->getRequest();
645 $response = $request->response();
647 // Origin: header is a space-separated list of origins, check all of them
648 $originHeader = $request->getHeader( 'Origin' );
649 if ( $originHeader === false ) {
652 $originHeader = trim( $originHeader );
653 $origins = preg_split( '/\s+/', $originHeader );
656 if ( !in_array( $originParam, $origins ) ) {
657 // origin parameter set but incorrect
658 // Send a 403 response
659 $response->statusHeader( 403 );
660 $response->header( 'Cache-Control: no-cache' );
661 echo "'origin' parameter does not match Origin header\n";
666 $config = $this->getConfig();
667 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
669 $config->get( 'CrossSiteAJAXdomains' ),
670 $config->get( 'CrossSiteAJAXdomainExceptions' )
673 if ( $matchOrigin ) {
674 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
675 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
677 // This is a CORS preflight request
678 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
679 // If method is not a case-sensitive match, do not set any additional headers and terminate.
682 // We allow the actual request to send the following headers
683 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
684 if ( $requestedHeaders !== false ) {
685 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
688 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
691 // We only allow the actual request to be GET or POST
692 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
695 $response->header( "Access-Control-Allow-Origin: $originHeader" );
696 $response->header( 'Access-Control-Allow-Credentials: true' );
697 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
698 $response->header( "Timing-Allow-Origin: $originHeader" );
702 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
707 $this->getOutput()->addVaryHeader( 'Origin' );
712 * Attempt to match an Origin header against a set of rules and a set of exceptions
713 * @param string $value Origin header
714 * @param array $rules Set of wildcard rules
715 * @param array $exceptions Set of wildcard rules
716 * @return bool True if $value matches a rule in $rules and doesn't match
717 * any rules in $exceptions, false otherwise
719 protected static function matchOrigin( $value, $rules, $exceptions ) {
720 foreach ( $rules as $rule ) {
721 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
722 // Rule matches, check exceptions
723 foreach ( $exceptions as $exc ) {
724 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
737 * Attempt to validate the value of Access-Control-Request-Headers against a list
738 * of headers that we allow the follow up request to send.
740 * @param string $requestedHeaders Comma seperated list of HTTP headers
741 * @return bool True if all requested headers are in the list of allowed headers
743 protected static function matchRequestedHeaders( $requestedHeaders ) {
744 if ( trim( $requestedHeaders ) === '' ) {
747 $requestedHeaders = explode( ',', $requestedHeaders );
748 $allowedAuthorHeaders = array_flip( [
749 /* simple headers (see spec) */
754 /* non-authorable headers in XHR, which are however requested by some UAs */
758 /* MediaWiki whitelist */
761 foreach ( $requestedHeaders as $rHeader ) {
762 $rHeader = strtolower( trim( $rHeader ) );
763 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
764 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
772 * Helper function to convert wildcard string into a regex
776 * @param string $wildcard String with wildcards
777 * @return string Regular expression
779 protected static function wildcardToRegex( $wildcard ) {
780 $wildcard = preg_quote( $wildcard, '/' );
781 $wildcard = str_replace(
787 return "/^https?:\/\/$wildcard$/";
791 * Send caching headers
792 * @param bool $isError Whether an error response is being output
793 * @since 1.26 added $isError parameter
795 protected function sendCacheHeaders( $isError ) {
796 $response = $this->getRequest()->response();
797 $out = $this->getOutput();
799 $out->addVaryHeader( 'Treat-as-Untrusted' );
801 $config = $this->getConfig();
803 if ( $config->get( 'VaryOnXFP' ) ) {
804 $out->addVaryHeader( 'X-Forwarded-Proto' );
807 if ( !$isError && $this->mModule
&&
808 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
810 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
811 if ( $etag !== null ) {
812 $response->header( "ETag: $etag" );
814 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
815 if ( $lastMod !== null ) {
816 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
820 // The logic should be:
821 // $this->mCacheControl['max-age'] is set?
822 // Use it, the module knows better than our guess.
823 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
824 // Use 0 because we can guess caching is probably the wrong thing to do.
825 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
827 if ( isset( $this->mCacheControl
['max-age'] ) ) {
828 $maxage = $this->mCacheControl
['max-age'];
829 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
830 $this->mCacheMode
!== 'private'
832 $maxage = $this->getParameter( 'maxage' );
834 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
836 if ( $this->mCacheMode
== 'private' ) {
837 $response->header( "Cache-Control: $privateCache" );
841 $useKeyHeader = $config->get( 'UseKeyHeader' );
842 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
843 $out->addVaryHeader( 'Cookie' );
844 $response->header( $out->getVaryHeader() );
845 if ( $useKeyHeader ) {
846 $response->header( $out->getKeyHeader() );
847 if ( $out->haveCacheVaryCookies() ) {
848 // Logged in, mark this request private
849 $response->header( "Cache-Control: $privateCache" );
852 // Logged out, send normal public headers below
853 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
854 // Logged in or otherwise has session (e.g. anonymous users who have edited)
855 // Mark request private
856 $response->header( "Cache-Control: $privateCache" );
859 } // else no Key and anonymous, send public headers below
862 // Send public headers
863 $response->header( $out->getVaryHeader() );
864 if ( $useKeyHeader ) {
865 $response->header( $out->getKeyHeader() );
868 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
869 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
870 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
872 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
873 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
876 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
877 // Public cache not requested
878 // Sending a Vary header in this case is harmless, and protects us
879 // against conditional calls of setCacheMaxAge().
880 $response->header( "Cache-Control: $privateCache" );
885 $this->mCacheControl
['public'] = true;
887 // Send an Expires header
888 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
889 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
890 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
892 // Construct the Cache-Control header
895 foreach ( $this->mCacheControl
as $name => $value ) {
896 if ( is_bool( $value ) ) {
898 $ccHeader .= $separator . $name;
902 $ccHeader .= $separator . "$name=$value";
907 $response->header( "Cache-Control: $ccHeader" );
911 * Create the printer for error output
913 private function createErrorPrinter() {
914 if ( !isset( $this->mPrinter
) ) {
915 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
916 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
917 $value = self
::API_DEFAULT_FORMAT
;
919 $this->mPrinter
= $this->createPrinterByName( $value );
922 // Printer may not be able to handle errors. This is particularly
923 // likely if the module returns something for getCustomPrinter().
924 if ( !$this->mPrinter
->canPrintErrors() ) {
925 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
930 * Create an error message for the given exception.
932 * If the exception is a UsageException then
933 * UsageException::getMessageArray() will be called to create the message.
935 * @param Exception $e
936 * @return array ['code' => 'some string', 'info' => 'some other string']
939 protected function errorMessageFromException( $e ) {
940 if ( $e instanceof UsageException
) {
941 // User entered incorrect parameters - generate error response
942 $errMessage = $e->getMessageArray();
944 $config = $this->getConfig();
945 // Something is seriously wrong
946 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
947 $info = 'Database query error';
949 $info = "Exception Caught: {$e->getMessage()}";
953 'code' => 'internal_api_error_' . get_class( $e ),
954 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
961 * Replace the result data with the information about an exception.
962 * Returns the error code
963 * @param Exception $e
966 protected function substituteResultWithError( $e ) {
967 $result = $this->getResult();
968 $config = $this->getConfig();
970 $errMessage = $this->errorMessageFromException( $e );
971 if ( $e instanceof UsageException
) {
972 // User entered incorrect parameters - generate error response
973 $link = wfExpandUrl( wfScript( 'api' ) );
974 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
976 // Something is seriously wrong
977 if ( $config->get( 'ShowExceptionDetails' ) ) {
978 ApiResult
::setContentValue(
981 MWExceptionHandler
::getRedactedTraceAsString( $e )
986 // Remember all the warnings to re-add them later
987 $warnings = $result->getResultData( [ 'warnings' ] );
991 $requestid = $this->getParameter( 'requestid' );
992 if ( !is_null( $requestid ) ) {
993 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
995 if ( $config->get( 'ShowHostnames' ) ) {
996 // servedby is especially useful when debugging errors
997 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
999 if ( $warnings !== null ) {
1000 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1003 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
1005 return $errMessage['code'];
1009 * Set up for the execution.
1012 protected function setupExecuteAction() {
1013 // First add the id to the top element
1014 $result = $this->getResult();
1015 $requestid = $this->getParameter( 'requestid' );
1016 if ( !is_null( $requestid ) ) {
1017 $result->addValue( null, 'requestid', $requestid );
1020 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1021 $servedby = $this->getParameter( 'servedby' );
1023 $result->addValue( null, 'servedby', wfHostname() );
1027 if ( $this->getParameter( 'curtimestamp' ) ) {
1028 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1029 ApiResult
::NO_SIZE_CHECK
);
1032 $params = $this->extractRequestParams();
1034 $this->mAction
= $params['action'];
1036 if ( !is_string( $this->mAction
) ) {
1037 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1044 * Set up the module for response
1045 * @return ApiBase The module that will handle this action
1046 * @throws MWException
1047 * @throws UsageException
1049 protected function setupModule() {
1050 // Instantiate the module requested by the user
1051 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1052 if ( $module === null ) {
1053 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1055 $moduleParams = $module->extractRequestParams();
1057 // Check token, if necessary
1058 if ( $module->needsToken() === true ) {
1059 throw new MWException(
1060 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1061 'See documentation for ApiBase::needsToken for details.'
1064 if ( $module->needsToken() ) {
1065 if ( !$module->mustBePosted() ) {
1066 throw new MWException(
1067 "Module '{$module->getModuleName()}' must require POST to use tokens."
1071 if ( !isset( $moduleParams['token'] ) ) {
1072 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1075 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1077 $module->encodeParamName( 'token' ),
1078 $this->getRequest()->getQueryValues()
1082 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1083 'found in the query string, but must be in the POST body',
1088 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1089 $this->dieUsageMsg( 'sessionfailure' );
1097 * Check the max lag if necessary
1098 * @param ApiBase $module Api module being used
1099 * @param array $params Array an array containing the request parameters.
1100 * @return bool True on success, false should exit immediately
1102 protected function checkMaxLag( $module, $params ) {
1103 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1104 $maxLag = $params['maxlag'];
1105 list( $host, $lag ) = wfGetLB()->getMaxLag();
1106 if ( $lag > $maxLag ) {
1107 $response = $this->getRequest()->response();
1109 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1110 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1112 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1113 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1116 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1124 * Check selected RFC 7232 precondition headers
1126 * RFC 7232 envisions a particular model where you send your request to "a
1127 * resource", and for write requests that you can read "the resource" by
1128 * changing the method to GET. When the API receives a GET request, it
1129 * works out even though "the resource" from RFC 7232's perspective might
1130 * be many resources from MediaWiki's perspective. But it totally fails for
1131 * a POST, since what HTTP sees as "the resource" is probably just
1132 * "/api.php" with all the interesting bits in the body.
1134 * Therefore, we only support RFC 7232 precondition headers for GET (and
1135 * HEAD). That means we don't need to bother with If-Match and
1136 * If-Unmodified-Since since they only apply to modification requests.
1138 * And since we don't support Range, If-Range is ignored too.
1141 * @param ApiBase $module Api module being used
1142 * @return bool True on success, false should exit immediately
1144 protected function checkConditionalRequestHeaders( $module ) {
1145 if ( $this->mInternalMode
) {
1146 // No headers to check in internal mode
1150 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1151 // Don't check POSTs
1157 $ifNoneMatch = array_diff(
1158 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1161 if ( $ifNoneMatch ) {
1162 if ( $ifNoneMatch === [ '*' ] ) {
1163 // API responses always "exist"
1166 $etag = $module->getConditionalRequestData( 'etag' );
1169 if ( $ifNoneMatch && $etag !== null ) {
1170 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1171 $match = array_map( function ( $s ) {
1172 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1174 $return304 = in_array( $test, $match, true );
1176 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1178 // Some old browsers sends sizes after the date, like this:
1179 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1181 $i = strpos( $value, ';' );
1182 if ( $i !== false ) {
1183 $value = trim( substr( $value, 0, $i ) );
1186 if ( $value !== '' ) {
1188 $ts = new MWTimestamp( $value );
1190 // RFC 7231 IMF-fixdate
1191 $ts->getTimestamp( TS_RFC2822
) === $value ||
1193 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1194 // asctime (with and without space-padded day)
1195 $ts->format( 'D M j H:i:s Y' ) === $value ||
1196 $ts->format( 'D M j H:i:s Y' ) === $value
1198 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1199 if ( $lastMod !== null ) {
1200 // Mix in some MediaWiki modification times
1203 'user' => $this->getUser()->getTouched(),
1204 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1206 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1207 // T46570: the core page itself may not change, but resources might
1208 $modifiedTimes['sepoch'] = wfTimestamp(
1209 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1212 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1213 $lastMod = max( $modifiedTimes );
1214 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1217 } catch ( TimestampException
$e ) {
1218 // Invalid timestamp, ignore it
1224 $this->getRequest()->response()->statusHeader( 304 );
1226 // Avoid outputting the compressed representation of a zero-length body
1227 MediaWiki\
suppressWarnings();
1228 ini_set( 'zlib.output_compression', 0 );
1229 MediaWiki\restoreWarnings
();
1230 wfClearOutputBuffers();
1239 * Check for sufficient permissions to execute
1240 * @param ApiBase $module An Api module
1242 protected function checkExecutePermissions( $module ) {
1243 $user = $this->getUser();
1244 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1245 !$user->isAllowed( 'read' )
1247 $this->dieUsageMsg( 'readrequired' );
1250 if ( $module->isWriteMode() ) {
1251 if ( !$this->mEnableWrite
) {
1252 $this->dieUsageMsg( 'writedisabled' );
1253 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1254 $this->dieUsageMsg( 'writerequired' );
1255 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1257 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1258 'promised-nonwrite-api'
1262 $this->checkReadOnly( $module );
1265 // Allow extensions to stop execution for arbitrary reasons.
1267 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1268 $this->dieUsageMsg( $message );
1273 * Check if the DB is read-only for this user
1274 * @param ApiBase $module An Api module
1276 protected function checkReadOnly( $module ) {
1277 if ( wfReadOnly() ) {
1278 $this->dieReadOnly();
1281 if ( $module->isWriteMode()
1282 && in_array( 'bot', $this->getUser()->getGroups() )
1283 && wfGetLB()->getServerCount() > 1
1285 $this->checkBotReadOnly();
1290 * Check whether we are readonly for bots
1292 private function checkBotReadOnly() {
1293 // Figure out how many servers have passed the lag threshold
1295 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1296 $laggedServers = [];
1297 $loadBalancer = wfGetLB();
1298 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1299 if ( $lag > $lagLimit ) {
1301 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1305 // If a majority of slaves are too lagged then disallow writes
1306 $slaveCount = wfGetLB()->getServerCount() - 1;
1307 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1308 $laggedServers = implode( ', ', $laggedServers );
1311 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1314 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1320 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1326 * Check asserts of the user's rights
1327 * @param array $params
1329 protected function checkAsserts( $params ) {
1330 if ( isset( $params['assert'] ) ) {
1331 $user = $this->getUser();
1332 switch ( $params['assert'] ) {
1334 if ( $user->isAnon() ) {
1335 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1339 if ( !$user->isAllowed( 'bot' ) ) {
1340 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1348 * Check POST for external response and setup result printer
1349 * @param ApiBase $module An Api module
1350 * @param array $params An array with the request parameters
1352 protected function setupExternalResponse( $module, $params ) {
1353 $request = $this->getRequest();
1354 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1355 // Module requires POST. GET request might still be allowed
1356 // if $wgDebugApi is true, otherwise fail.
1357 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1360 // See if custom printer is used
1361 $this->mPrinter
= $module->getCustomPrinter();
1362 if ( is_null( $this->mPrinter
) ) {
1363 // Create an appropriate printer
1364 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1367 if ( $request->getProtocol() === 'http' && (
1368 $request->getSession()->shouldForceHTTPS() ||
1369 ( $this->getUser()->isLoggedIn() &&
1370 $this->getUser()->requiresHTTPS() )
1372 $this->logFeatureUsage( 'https-expected' );
1373 $this->setWarning( 'HTTP used when HTTPS was expected' );
1378 * Execute the actual module, without any error handling
1380 protected function executeAction() {
1381 $params = $this->setupExecuteAction();
1382 $module = $this->setupModule();
1383 $this->mModule
= $module;
1385 if ( !$this->mInternalMode
) {
1386 $this->setRequestExpectations( $module );
1389 $this->checkExecutePermissions( $module );
1391 if ( !$this->checkMaxLag( $module, $params ) ) {
1395 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1399 if ( !$this->mInternalMode
) {
1400 $this->setupExternalResponse( $module, $params );
1403 $this->checkAsserts( $params );
1407 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1409 $this->reportUnusedParams();
1411 if ( !$this->mInternalMode
) {
1412 // append Debug information
1413 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1415 // Print result data
1416 $this->printResult( false );
1421 * Set database connection, query, and write expectations given this module request
1422 * @param ApiBase $module
1424 protected function setRequestExpectations( ApiBase
$module ) {
1425 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1426 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1427 if ( $this->getRequest()->hasSafeMethod() ) {
1428 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1429 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1430 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1431 $this->getRequest()->markAsSafeRequest();
1433 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1438 * Log the preceding request
1439 * @param float $time Time in seconds
1440 * @param Exception $e Exception caught while processing the request
1442 protected function logRequest( $time, $e = null ) {
1443 $request = $this->getRequest();
1446 'ip' => $request->getIP(),
1447 'userAgent' => $this->getUserAgent(),
1448 'wiki' => wfWikiID(),
1449 'timeSpentBackend' => (int) round( $time * 1000 ),
1450 'hadError' => $e !== null,
1456 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1459 // Construct space separated message for 'api' log channel
1460 $msg = "API {$request->getMethod()} " .
1461 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1462 " {$logCtx['ip']} " .
1463 "T={$logCtx['timeSpentBackend']}ms";
1465 foreach ( $this->getParamsUsed() as $name ) {
1466 $value = $request->getVal( $name );
1467 if ( $value === null ) {
1471 if ( strlen( $value ) > 256 ) {
1472 $value = substr( $value, 0, 256 );
1473 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1475 $encValue = $this->encodeRequestLogValue( $value );
1478 $logCtx['params'][$name] = $value;
1479 $msg .= " {$name}={$encValue}";
1482 wfDebugLog( 'api', $msg, 'private' );
1483 // ApiAction channel is for structured data consumers
1484 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1488 * Encode a value in a format suitable for a space-separated log line.
1492 protected function encodeRequestLogValue( $s ) {
1495 $chars = ';@$!*(),/:';
1496 $numChars = strlen( $chars );
1497 for ( $i = 0; $i < $numChars; $i++
) {
1498 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1502 return strtr( rawurlencode( $s ), $table );
1506 * Get the request parameters used in the course of the preceding execute() request
1509 protected function getParamsUsed() {
1510 return array_keys( $this->mParamsUsed
);
1514 * Mark parameters as used
1515 * @param string|string[] $params
1517 public function markParamsUsed( $params ) {
1518 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1522 * Get a request value, and register the fact that it was used, for logging.
1523 * @param string $name
1524 * @param mixed $default
1527 public function getVal( $name, $default = null ) {
1528 $this->mParamsUsed
[$name] = true;
1530 $ret = $this->getRequest()->getVal( $name );
1531 if ( $ret === null ) {
1532 if ( $this->getRequest()->getArray( $name ) !== null ) {
1533 // See bug 10262 for why we don't just implode( '|', ... ) the
1536 "Parameter '$name' uses unsupported PHP array syntax"
1545 * Get a boolean request value, and register the fact that the parameter
1546 * was used, for logging.
1547 * @param string $name
1550 public function getCheck( $name ) {
1551 return $this->getVal( $name, null ) !== null;
1555 * Get a request upload, and register the fact that it was used, for logging.
1558 * @param string $name Parameter name
1559 * @return WebRequestUpload
1561 public function getUpload( $name ) {
1562 $this->mParamsUsed
[$name] = true;
1564 return $this->getRequest()->getUpload( $name );
1568 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1569 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1571 protected function reportUnusedParams() {
1572 $paramsUsed = $this->getParamsUsed();
1573 $allParams = $this->getRequest()->getValueNames();
1575 if ( !$this->mInternalMode
) {
1576 // Printer has not yet executed; don't warn that its parameters are unused
1577 $printerParams = array_map(
1578 [ $this->mPrinter
, 'encodeParamName' ],
1579 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1581 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1583 $unusedParams = array_diff( $allParams, $paramsUsed );
1586 if ( count( $unusedParams ) ) {
1587 $s = count( $unusedParams ) > 1 ?
's' : '';
1588 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1593 * Print results using the current printer
1595 * @param bool $isError
1597 protected function printResult( $isError ) {
1598 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1599 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1602 $printer = $this->mPrinter
;
1603 $printer->initPrinter( false );
1604 $printer->execute();
1605 $printer->closePrinter();
1611 public function isReadMode() {
1616 * See ApiBase for description.
1620 public function getAllowedParams() {
1623 ApiBase
::PARAM_DFLT
=> 'help',
1624 ApiBase
::PARAM_TYPE
=> 'submodule',
1627 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1628 ApiBase
::PARAM_TYPE
=> 'submodule',
1631 ApiBase
::PARAM_TYPE
=> 'integer'
1634 ApiBase
::PARAM_TYPE
=> 'integer',
1635 ApiBase
::PARAM_DFLT
=> 0
1638 ApiBase
::PARAM_TYPE
=> 'integer',
1639 ApiBase
::PARAM_DFLT
=> 0
1642 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1644 'requestid' => null,
1645 'servedby' => false,
1646 'curtimestamp' => false,
1649 ApiBase
::PARAM_DFLT
=> 'user',
1654 /** @see ApiBase::getExamplesMessages() */
1655 protected function getExamplesMessages() {
1658 => 'apihelp-help-example-main',
1659 'action=help&recursivesubmodules=1'
1660 => 'apihelp-help-example-recursive',
1664 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1665 // Wish PHP had an "array_insert_before". Instead, we have to manually
1666 // reindex the array to get 'permissions' in the right place.
1669 foreach ( $oldHelp as $k => $v ) {
1670 if ( $k === 'submodules' ) {
1671 $help['permissions'] = '';
1675 $help['datatypes'] = '';
1676 $help['credits'] = '';
1678 // Fill 'permissions'
1679 $help['permissions'] .= Html
::openElement( 'div',
1680 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1681 $m = $this->msg( 'api-help-permissions' );
1682 if ( !$m->isDisabled() ) {
1683 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1684 $m->numParams( count( self
::$mRights ) )->parse()
1687 $help['permissions'] .= Html
::openElement( 'dl' );
1688 foreach ( self
::$mRights as $right => $rightMsg ) {
1689 $help['permissions'] .= Html
::element( 'dt', null, $right );
1691 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1692 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1694 $groups = array_map( function ( $group ) {
1695 return $group == '*' ?
'all' : $group;
1696 }, User
::getGroupsWithPermission( $right ) );
1698 $help['permissions'] .= Html
::rawElement( 'dd', null,
1699 $this->msg( 'api-help-permissions-granted-to' )
1700 ->numParams( count( $groups ) )
1701 ->params( $this->getLanguage()->commaList( $groups ) )
1705 $help['permissions'] .= Html
::closeElement( 'dl' );
1706 $help['permissions'] .= Html
::closeElement( 'div' );
1708 // Fill 'datatypes' and 'credits', if applicable
1709 if ( empty( $options['nolead'] ) ) {
1710 $level = $options['headerlevel'];
1711 $tocnumber = &$options['tocnumber'];
1713 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1715 // Add an additional span with sanitized ID
1716 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1717 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1720 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1721 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1724 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1725 if ( !isset( $tocData['main/datatypes'] ) ) {
1726 $tocnumber[$level]++
;
1727 $tocData['main/datatypes'] = [
1728 'toclevel' => count( $tocnumber ),
1730 'anchor' => 'main/datatypes',
1732 'number' => implode( '.', $tocnumber ),
1737 // Add an additional span with sanitized ID
1738 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1739 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1742 $header = $this->msg( 'api-credits-header' )->parse();
1743 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1744 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1747 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1748 if ( !isset( $tocData['main/credits'] ) ) {
1749 $tocnumber[$level]++
;
1750 $tocData['main/credits'] = [
1751 'toclevel' => count( $tocnumber ),
1753 'anchor' => 'main/credits',
1755 'number' => implode( '.', $tocnumber ),
1762 private $mCanApiHighLimits = null;
1765 * Check whether the current user is allowed to use high limits
1768 public function canApiHighLimits() {
1769 if ( !isset( $this->mCanApiHighLimits
) ) {
1770 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1773 return $this->mCanApiHighLimits
;
1777 * Overrides to return this instance's module manager.
1778 * @return ApiModuleManager
1780 public function getModuleManager() {
1781 return $this->mModuleMgr
;
1785 * Fetches the user agent used for this request
1787 * The value will be the combination of the 'Api-User-Agent' header (if
1788 * any) and the standard User-Agent header (if any).
1792 public function getUserAgent() {
1794 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1795 $this->getRequest()->getHeader( 'User-agent' )
1799 /************************************************************************//**
1805 * Sets whether the pretty-printer should format *bold* and $italics$
1807 * @deprecated since 1.25
1810 public function setHelp( $help = true ) {
1811 wfDeprecated( __METHOD__
, '1.25' );
1812 $this->mPrinter
->setHelp( $help );
1816 * Override the parent to generate help messages for all available modules.
1818 * @deprecated since 1.25
1821 public function makeHelpMsg() {
1822 wfDeprecated( __METHOD__
, '1.25' );
1825 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1827 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1830 $this->getModuleName(),
1831 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1833 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1834 [ $this, 'reallyMakeHelpMsg' ]
1839 * @deprecated since 1.25
1840 * @return mixed|string
1842 public function reallyMakeHelpMsg() {
1843 wfDeprecated( __METHOD__
, '1.25' );
1846 // Use parent to make default message for the main module
1847 $msg = parent
::makeHelpMsg();
1849 $asterisks = str_repeat( '*** ', 14 );
1850 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1852 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1853 $module = $this->mModuleMgr
->getModule( $name );
1854 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1856 $msg2 = $module->makeHelpMsg();
1857 if ( $msg2 !== false ) {
1863 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1864 foreach ( self
::$mRights as $right => $rightMsg ) {
1865 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1866 ->useDatabase( false )
1867 ->inLanguage( 'en' )
1869 $groups = User
::getGroupsWithPermission( $right );
1870 $msg .= '* ' . $right . " *\n $rightsMsg" .
1871 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1874 $msg .= "\n$asterisks Formats $asterisks\n\n";
1875 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1876 $module = $this->mModuleMgr
->getModule( $name );
1877 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1878 $msg2 = $module->makeHelpMsg();
1879 if ( $msg2 !== false ) {
1885 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1886 $credits = str_replace( "\n", "\n ", $credits );
1887 $msg .= "\n*** Credits: ***\n $credits\n";
1893 * @deprecated since 1.25
1894 * @param ApiBase $module
1895 * @param string $paramName What type of request is this? e.g. action,
1896 * query, list, prop, meta, format
1899 public static function makeHelpMsgHeader( $module, $paramName ) {
1900 wfDeprecated( __METHOD__
, '1.25' );
1901 $modulePrefix = $module->getModulePrefix();
1902 if ( strval( $modulePrefix ) !== '' ) {
1903 $modulePrefix = "($modulePrefix) ";
1906 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1914 * This exception will be thrown when dieUsage is called to stop module execution.
1918 class UsageException
extends MWException
{
1925 private $mExtraData;
1928 * @param string $message
1929 * @param string $codestr
1931 * @param array|null $extradata
1933 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1934 parent
::__construct( $message, $code );
1935 $this->mCodestr
= $codestr;
1936 $this->mExtraData
= $extradata;
1938 // This should never happen, so throw an exception about it that will
1939 // hopefully get logged with a backtrace (T138585)
1940 if ( !is_string( $codestr ) ||
$codestr === '' ) {
1941 throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1942 ( $codestr === '' ?
'empty string' : gettype( $codestr ) )
1950 public function getCodeString() {
1951 return $this->mCodestr
;
1957 public function getMessageArray() {
1959 'code' => $this->mCodestr
,
1960 'info' => $this->getMessage()
1962 if ( is_array( $this->mExtraData
) ) {
1963 $result = array_merge( $result, $this->mExtraData
);
1972 public function __toString() {
1973 return "{$this->getCodeString()}: {$this->getMessage()}";
1978 * For really cool vim folding this needs to be at the end:
1979 * vim: foldmarker=@{,@} foldmethod=marker