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',
76 'purge' => 'ApiPurge',
77 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
78 'rollback' => 'ApiRollback',
79 'delete' => 'ApiDelete',
80 'undelete' => 'ApiUndelete',
81 'protect' => 'ApiProtect',
82 'block' => 'ApiBlock',
83 'unblock' => 'ApiUnblock',
85 'edit' => 'ApiEditPage',
86 'upload' => 'ApiUpload',
87 'filerevert' => 'ApiFileRevert',
88 'emailuser' => 'ApiEmailUser',
89 'watch' => 'ApiWatch',
90 'patrol' => 'ApiPatrol',
91 'import' => 'ApiImport',
92 'clearhasmsg' => 'ApiClearHasMsg',
93 'userrights' => 'ApiUserrights',
94 'options' => 'ApiOptions',
95 'imagerotate' => 'ApiImageRotate',
96 'revisiondelete' => 'ApiRevisionDelete',
97 'managetags' => 'ApiManageTags',
99 'mergehistory' => 'ApiMergeHistory',
103 * List of available formats: format name => format class
105 private static $Formats = [
106 'json' => 'ApiFormatJson',
107 'jsonfm' => 'ApiFormatJson',
108 'php' => 'ApiFormatPhp',
109 'phpfm' => 'ApiFormatPhp',
110 'xml' => 'ApiFormatXml',
111 'xmlfm' => 'ApiFormatXml',
112 'rawfm' => 'ApiFormatJson',
113 'none' => 'ApiFormatNone',
116 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
118 * List of user roles that are specifically relevant to the API.
119 * array( 'right' => array ( 'msg' => 'Some message with a $1',
120 * 'params' => array ( $someVarToSubst ) ),
123 private static $mRights = [
125 'msg' => 'right-writeapi',
129 'msg' => 'api-help-right-apihighlimits',
130 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
133 // @codingStandardsIgnoreEnd
140 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
142 private $mEnableWrite;
143 private $mInternalMode, $mSquidMaxage;
147 private $mCacheMode = 'private';
148 private $mCacheControl = [];
149 private $mParamsUsed = [];
151 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
152 private $lacksSameOriginSecurity = null;
155 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
157 * @param IContextSource|WebRequest $context If this is an instance of
158 * FauxRequest, errors are thrown and no printing occurs
159 * @param bool $enableWrite Should be set to true if the api may modify data
161 public function __construct( $context = null, $enableWrite = false ) {
162 if ( $context === null ) {
163 $context = RequestContext
::getMain();
164 } elseif ( $context instanceof WebRequest
) {
167 $context = RequestContext
::getMain();
169 // We set a derivative context so we can change stuff later
170 $this->setContext( new DerivativeContext( $context ) );
172 if ( isset( $request ) ) {
173 $this->getContext()->setRequest( $request );
176 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
178 // Special handling for the main module: $parent === $this
179 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
181 if ( !$this->mInternalMode
) {
182 // Impose module restrictions.
183 // If the current user cannot read,
184 // Remove all modules other than login
187 if ( $this->lacksSameOriginSecurity() ) {
188 // If we're in a mode that breaks the same-origin policy, strip
189 // user credentials for security.
190 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
191 $wgUser = new User();
192 $this->getContext()->setUser( $wgUser );
196 $uselang = $this->getParameter( 'uselang' );
197 if ( $uselang === 'user' ) {
198 // Assume the parent context is going to return the user language
199 // for uselang=user (see T85635).
201 if ( $uselang === 'content' ) {
203 $uselang = $wgContLang->getCode();
205 $code = RequestContext
::sanitizeLangCode( $uselang );
206 $this->getContext()->setLanguage( $code );
207 if ( !$this->mInternalMode
) {
209 $wgLang = $this->getContext()->getLanguage();
210 RequestContext
::getMain()->setLanguage( $wgLang );
214 $config = $this->getConfig();
215 $this->mModuleMgr
= new ApiModuleManager( $this );
216 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
217 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
218 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
219 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
221 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
223 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
224 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
225 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
226 $this->mResult
->setMainForContinuation( $this );
227 $this->mContinuationManager
= null;
228 $this->mEnableWrite
= $enableWrite;
230 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
231 $this->mCommit
= false;
235 * Return true if the API was started by other PHP code using FauxRequest
238 public function isInternalMode() {
239 return $this->mInternalMode
;
243 * Get the ApiResult object associated with current request
247 public function getResult() {
248 return $this->mResult
;
252 * Get the security flag for the current request
255 public function lacksSameOriginSecurity() {
256 if ( $this->lacksSameOriginSecurity
!== null ) {
257 return $this->lacksSameOriginSecurity
;
260 $request = $this->getRequest();
263 if ( $request->getVal( 'callback' ) !== null ) {
264 $this->lacksSameOriginSecurity
= true;
268 // Header to be used from XMLHTTPRequest when the request might
269 // otherwise be used for XSS.
270 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
271 $this->lacksSameOriginSecurity
= true;
275 // Allow extensions to override.
276 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
277 return $this->lacksSameOriginSecurity
;
281 * Get the ApiErrorFormatter object associated with current request
282 * @return ApiErrorFormatter
284 public function getErrorFormatter() {
285 return $this->mErrorFormatter
;
289 * Get the continuation manager
290 * @return ApiContinuationManager|null
292 public function getContinuationManager() {
293 return $this->mContinuationManager
;
297 * Set the continuation manager
298 * @param ApiContinuationManager|null
300 public function setContinuationManager( $manager ) {
301 if ( $manager !== null ) {
302 if ( !$manager instanceof ApiContinuationManager
) {
303 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
304 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
307 if ( $this->mContinuationManager
!== null ) {
308 throw new UnexpectedValueException(
309 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
310 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
314 $this->mContinuationManager
= $manager;
318 * Get the API module object. Only works after executeAction()
322 public function getModule() {
323 return $this->mModule
;
327 * Get the result formatter object. Only works after setupExecuteAction()
329 * @return ApiFormatBase
331 public function getPrinter() {
332 return $this->mPrinter
;
336 * Set how long the response should be cached.
340 public function setCacheMaxAge( $maxage ) {
341 $this->setCacheControl( [
342 'max-age' => $maxage,
343 's-maxage' => $maxage
348 * Set the type of caching headers which will be sent.
350 * @param string $mode One of:
351 * - 'public': Cache this object in public caches, if the maxage or smaxage
352 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
353 * not provided by any of these means, the object will be private.
354 * - 'private': Cache this object only in private client-side caches.
355 * - 'anon-public-user-private': Make this object cacheable for logged-out
356 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
357 * set consistently for a given URL, it cannot be set differently depending on
358 * things like the contents of the database, or whether the user is logged in.
360 * If the wiki does not allow anonymous users to read it, the mode set here
361 * will be ignored, and private caching headers will always be sent. In other words,
362 * the "public" mode is equivalent to saying that the data sent is as public as a page
365 * For user-dependent data, the private mode should generally be used. The
366 * anon-public-user-private mode should only be used where there is a particularly
367 * good performance reason for caching the anonymous response, but where the
368 * response to logged-in users may differ, or may contain private data.
370 * If this function is never called, then the default will be the private mode.
372 public function setCacheMode( $mode ) {
373 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
374 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
376 // Ignore for forwards-compatibility
380 if ( !User
::isEveryoneAllowed( 'read' ) ) {
381 // Private wiki, only private headers
382 if ( $mode !== 'private' ) {
383 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
389 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
390 // User language is used for i18n, so we don't want to publicly
391 // cache. Anons are ok, because if they have non-default language
392 // then there's an appropriate Vary header set by whatever set
393 // their non-default language.
394 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
395 "'anon-public-user-private' due to uselang=user\n" );
396 $mode = 'anon-public-user-private';
399 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
400 $this->mCacheMode
= $mode;
404 * Set directives (key/value pairs) for the Cache-Control header.
405 * Boolean values will be formatted as such, by including or omitting
406 * without an equals sign.
408 * Cache control values set here will only be used if the cache mode is not
409 * private, see setCacheMode().
411 * @param array $directives
413 public function setCacheControl( $directives ) {
414 $this->mCacheControl
= $directives +
$this->mCacheControl
;
418 * Create an instance of an output formatter by its name
420 * @param string $format
422 * @return ApiFormatBase
424 public function createPrinterByName( $format ) {
425 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
426 if ( $printer === null ) {
427 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
434 * Execute api request. Any errors will be handled if the API was called by the remote client.
436 public function execute() {
437 if ( $this->mInternalMode
) {
438 $this->executeAction();
440 $this->executeActionWithErrorHandling();
445 * Execute an action, and in case of an error, erase whatever partial results
446 * have been accumulated, and replace it with an error message and a help screen.
448 protected function executeActionWithErrorHandling() {
449 // Verify the CORS header before executing the action
450 if ( !$this->handleCORS() ) {
451 // handleCORS() has sent a 403, abort
455 // Exit here if the request method was OPTIONS
456 // (assume there will be a followup GET or POST)
457 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
461 // In case an error occurs during data output,
462 // clear the output buffer and print just the error information
463 $obLevel = ob_get_level();
466 $t = microtime( true );
469 $this->executeAction();
470 $runTime = microtime( true ) - $t;
471 $this->logRequest( $runTime );
472 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
473 $this->getStats()->timing(
474 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
477 } catch ( Exception
$e ) {
478 $this->handleException( $e );
479 $this->logRequest( microtime( true ) - $t, $e );
483 // Commit DBs and send any related cookies and headers
484 MediaWiki
::preOutputCommit( $this->getContext() );
486 // Send cache headers after any code which might generate an error, to
487 // avoid sending public cache headers for errors.
488 $this->sendCacheHeaders( $isError );
490 // Executing the action might have already messed with the output
492 while ( ob_get_level() > $obLevel ) {
498 * Handle an exception as an API response
501 * @param Exception $e
503 protected function handleException( Exception
$e ) {
504 // Bug 63145: Rollback any open database transactions
505 if ( !( $e instanceof UsageException
) ) {
506 // UsageExceptions are intentional, so don't rollback if that's the case
508 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
509 } catch ( DBError
$e2 ) {
510 // Rollback threw an exception too. Log it, but don't interrupt
511 // our regularly scheduled exception handling.
512 MWExceptionHandler
::logException( $e2 );
516 // Allow extra cleanup and logging
517 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
520 if ( !( $e instanceof UsageException
) ) {
521 MWExceptionHandler
::logException( $e );
524 // Handle any kind of exception by outputting properly formatted error message.
525 // If this fails, an unhandled exception should be thrown so that global error
526 // handler will process and log it.
528 $errCode = $this->substituteResultWithError( $e );
530 // Error results should not be cached
531 $this->setCacheMode( 'private' );
533 $response = $this->getRequest()->response();
534 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
535 if ( $e->getCode() === 0 ) {
536 $response->header( $headerStr );
538 $response->header( $headerStr, true, $e->getCode() );
541 // Reset and print just the error message
544 // Printer may not be initialized if the extractRequestParams() fails for the main module
545 $this->createErrorPrinter();
548 $this->printResult( true );
549 } catch ( UsageException
$ex ) {
550 // The error printer itself is failing. Try suppressing its request
551 // parameters and redo.
553 'Error printer failed (will retry without params): ' . $ex->getMessage()
555 $this->mPrinter
= null;
556 $this->createErrorPrinter();
557 $this->mPrinter
->forceDefaultParams();
558 $this->printResult( true );
563 * Handle an exception from the ApiBeforeMain hook.
565 * This tries to print the exception as an API response, to be more
566 * friendly to clients. If it fails, it will rethrow the exception.
569 * @param Exception $e
572 public static function handleApiBeforeMainException( Exception
$e ) {
576 $main = new self( RequestContext
::getMain(), false );
577 $main->handleException( $e );
578 $main->logRequest( 0, $e );
579 } catch ( Exception
$e2 ) {
580 // Nope, even that didn't work. Punt.
584 // Reset cache headers
585 $main->sendCacheHeaders( true );
591 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
593 * If no origin parameter is present, nothing happens.
594 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
595 * is set and false is returned.
596 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
597 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
599 * http://www.w3.org/TR/cors/#resource-requests
600 * http://www.w3.org/TR/cors/#resource-preflight-requests
602 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
604 protected function handleCORS() {
605 $originParam = $this->getParameter( 'origin' ); // defaults to null
606 if ( $originParam === null ) {
607 // No origin parameter, nothing to do
611 $request = $this->getRequest();
612 $response = $request->response();
614 // Origin: header is a space-separated list of origins, check all of them
615 $originHeader = $request->getHeader( 'Origin' );
616 if ( $originHeader === false ) {
619 $originHeader = trim( $originHeader );
620 $origins = preg_split( '/\s+/', $originHeader );
623 if ( !in_array( $originParam, $origins ) ) {
624 // origin parameter set but incorrect
625 // Send a 403 response
626 $response->statusHeader( 403 );
627 $response->header( 'Cache-Control: no-cache' );
628 echo "'origin' parameter does not match Origin header\n";
633 $config = $this->getConfig();
634 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
636 $config->get( 'CrossSiteAJAXdomains' ),
637 $config->get( 'CrossSiteAJAXdomainExceptions' )
640 if ( $matchOrigin ) {
641 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
642 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
644 // This is a CORS preflight request
645 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
646 // If method is not a case-sensitive match, do not set any additional headers and terminate.
649 // We allow the actual request to send the following headers
650 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
651 if ( $requestedHeaders !== false ) {
652 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
655 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
658 // We only allow the actual request to be GET or POST
659 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
662 $response->header( "Access-Control-Allow-Origin: $originHeader" );
663 $response->header( 'Access-Control-Allow-Credentials: true' );
664 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
665 $response->header( "Timing-Allow-Origin: $originHeader" );
669 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
674 $this->getOutput()->addVaryHeader( 'Origin' );
679 * Attempt to match an Origin header against a set of rules and a set of exceptions
680 * @param string $value Origin header
681 * @param array $rules Set of wildcard rules
682 * @param array $exceptions Set of wildcard rules
683 * @return bool True if $value matches a rule in $rules and doesn't match
684 * any rules in $exceptions, false otherwise
686 protected static function matchOrigin( $value, $rules, $exceptions ) {
687 foreach ( $rules as $rule ) {
688 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
689 // Rule matches, check exceptions
690 foreach ( $exceptions as $exc ) {
691 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
704 * Attempt to validate the value of Access-Control-Request-Headers against a list
705 * of headers that we allow the follow up request to send.
707 * @param string $requestedHeaders Comma seperated list of HTTP headers
708 * @return bool True if all requested headers are in the list of allowed headers
710 protected static function matchRequestedHeaders( $requestedHeaders ) {
711 if ( trim( $requestedHeaders ) === '' ) {
714 $requestedHeaders = explode( ',', $requestedHeaders );
715 $allowedAuthorHeaders = array_flip( [
716 /* simple headers (see spec) */
721 /* non-authorable headers in XHR, which are however requested by some UAs */
725 /* MediaWiki whitelist */
728 foreach ( $requestedHeaders as $rHeader ) {
729 $rHeader = strtolower( trim( $rHeader ) );
730 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
731 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
739 * Helper function to convert wildcard string into a regex
743 * @param string $wildcard String with wildcards
744 * @return string Regular expression
746 protected static function wildcardToRegex( $wildcard ) {
747 $wildcard = preg_quote( $wildcard, '/' );
748 $wildcard = str_replace(
754 return "/^https?:\/\/$wildcard$/";
758 * Send caching headers
759 * @param bool $isError Whether an error response is being output
760 * @since 1.26 added $isError parameter
762 protected function sendCacheHeaders( $isError ) {
763 $response = $this->getRequest()->response();
764 $out = $this->getOutput();
766 $out->addVaryHeader( 'Treat-as-Untrusted' );
768 $config = $this->getConfig();
770 if ( $config->get( 'VaryOnXFP' ) ) {
771 $out->addVaryHeader( 'X-Forwarded-Proto' );
774 if ( !$isError && $this->mModule
&&
775 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
777 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
778 if ( $etag !== null ) {
779 $response->header( "ETag: $etag" );
781 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
782 if ( $lastMod !== null ) {
783 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
787 // The logic should be:
788 // $this->mCacheControl['max-age'] is set?
789 // Use it, the module knows better than our guess.
790 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
791 // Use 0 because we can guess caching is probably the wrong thing to do.
792 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
794 if ( isset( $this->mCacheControl
['max-age'] ) ) {
795 $maxage = $this->mCacheControl
['max-age'];
796 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
797 $this->mCacheMode
!== 'private'
799 $maxage = $this->getParameter( 'maxage' );
801 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
803 if ( $this->mCacheMode
== 'private' ) {
804 $response->header( "Cache-Control: $privateCache" );
808 $useKeyHeader = $config->get( 'UseKeyHeader' );
809 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
810 $out->addVaryHeader( 'Cookie' );
811 $response->header( $out->getVaryHeader() );
812 if ( $useKeyHeader ) {
813 $response->header( $out->getKeyHeader() );
814 if ( $out->haveCacheVaryCookies() ) {
815 // Logged in, mark this request private
816 $response->header( "Cache-Control: $privateCache" );
819 // Logged out, send normal public headers below
820 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
821 // Logged in or otherwise has session (e.g. anonymous users who have edited)
822 // Mark request private
823 $response->header( "Cache-Control: $privateCache" );
826 } // else no Key and anonymous, send public headers below
829 // Send public headers
830 $response->header( $out->getVaryHeader() );
831 if ( $useKeyHeader ) {
832 $response->header( $out->getKeyHeader() );
835 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
836 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
837 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
839 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
840 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
843 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
844 // Public cache not requested
845 // Sending a Vary header in this case is harmless, and protects us
846 // against conditional calls of setCacheMaxAge().
847 $response->header( "Cache-Control: $privateCache" );
852 $this->mCacheControl
['public'] = true;
854 // Send an Expires header
855 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
856 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
857 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
859 // Construct the Cache-Control header
862 foreach ( $this->mCacheControl
as $name => $value ) {
863 if ( is_bool( $value ) ) {
865 $ccHeader .= $separator . $name;
869 $ccHeader .= $separator . "$name=$value";
874 $response->header( "Cache-Control: $ccHeader" );
878 * Create the printer for error output
880 private function createErrorPrinter() {
881 if ( !isset( $this->mPrinter
) ) {
882 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
883 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
884 $value = self
::API_DEFAULT_FORMAT
;
886 $this->mPrinter
= $this->createPrinterByName( $value );
889 // Printer may not be able to handle errors. This is particularly
890 // likely if the module returns something for getCustomPrinter().
891 if ( !$this->mPrinter
->canPrintErrors() ) {
892 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
897 * Create an error message for the given exception.
899 * If the exception is a UsageException then
900 * UsageException::getMessageArray() will be called to create the message.
902 * @param Exception $e
903 * @return array ['code' => 'some string', 'info' => 'some other string']
906 protected function errorMessageFromException( $e ) {
907 if ( $e instanceof UsageException
) {
908 // User entered incorrect parameters - generate error response
909 $errMessage = $e->getMessageArray();
911 $config = $this->getConfig();
912 // Something is seriously wrong
913 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
914 $info = 'Database query error';
916 $info = "Exception Caught: {$e->getMessage()}";
920 'code' => 'internal_api_error_' . get_class( $e ),
921 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
928 * Replace the result data with the information about an exception.
929 * Returns the error code
930 * @param Exception $e
933 protected function substituteResultWithError( $e ) {
934 $result = $this->getResult();
935 $config = $this->getConfig();
937 $errMessage = $this->errorMessageFromException( $e );
938 if ( $e instanceof UsageException
) {
939 // User entered incorrect parameters - generate error response
940 $link = wfExpandUrl( wfScript( 'api' ) );
941 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
943 // Something is seriously wrong
944 if ( $config->get( 'ShowExceptionDetails' ) ) {
945 ApiResult
::setContentValue(
948 MWExceptionHandler
::getRedactedTraceAsString( $e )
953 // Remember all the warnings to re-add them later
954 $warnings = $result->getResultData( [ 'warnings' ] );
958 $requestid = $this->getParameter( 'requestid' );
959 if ( !is_null( $requestid ) ) {
960 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
962 if ( $config->get( 'ShowHostnames' ) ) {
963 // servedby is especially useful when debugging errors
964 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
966 if ( $warnings !== null ) {
967 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
970 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
972 return $errMessage['code'];
976 * Set up for the execution.
979 protected function setupExecuteAction() {
980 // First add the id to the top element
981 $result = $this->getResult();
982 $requestid = $this->getParameter( 'requestid' );
983 if ( !is_null( $requestid ) ) {
984 $result->addValue( null, 'requestid', $requestid );
987 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
988 $servedby = $this->getParameter( 'servedby' );
990 $result->addValue( null, 'servedby', wfHostname() );
994 if ( $this->getParameter( 'curtimestamp' ) ) {
995 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
996 ApiResult
::NO_SIZE_CHECK
);
999 $params = $this->extractRequestParams();
1001 $this->mAction
= $params['action'];
1003 if ( !is_string( $this->mAction
) ) {
1004 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1011 * Set up the module for response
1012 * @return ApiBase The module that will handle this action
1013 * @throws MWException
1014 * @throws UsageException
1016 protected function setupModule() {
1017 // Instantiate the module requested by the user
1018 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1019 if ( $module === null ) {
1020 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1022 $moduleParams = $module->extractRequestParams();
1024 // Check token, if necessary
1025 if ( $module->needsToken() === true ) {
1026 throw new MWException(
1027 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1028 'See documentation for ApiBase::needsToken for details.'
1031 if ( $module->needsToken() ) {
1032 if ( !$module->mustBePosted() ) {
1033 throw new MWException(
1034 "Module '{$module->getModuleName()}' must require POST to use tokens."
1038 if ( !isset( $moduleParams['token'] ) ) {
1039 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1042 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1044 $module->encodeParamName( 'token' ),
1045 $this->getRequest()->getQueryValues()
1049 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1050 'found in the query string, but must be in the POST body',
1055 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1056 $this->dieUsageMsg( 'sessionfailure' );
1064 * Check the max lag if necessary
1065 * @param ApiBase $module Api module being used
1066 * @param array $params Array an array containing the request parameters.
1067 * @return bool True on success, false should exit immediately
1069 protected function checkMaxLag( $module, $params ) {
1070 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1071 $maxLag = $params['maxlag'];
1072 list( $host, $lag ) = wfGetLB()->getMaxLag();
1073 if ( $lag > $maxLag ) {
1074 $response = $this->getRequest()->response();
1076 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1077 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1079 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1080 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1083 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1091 * Check selected RFC 7232 precondition headers
1093 * RFC 7232 envisions a particular model where you send your request to "a
1094 * resource", and for write requests that you can read "the resource" by
1095 * changing the method to GET. When the API receives a GET request, it
1096 * works out even though "the resource" from RFC 7232's perspective might
1097 * be many resources from MediaWiki's perspective. But it totally fails for
1098 * a POST, since what HTTP sees as "the resource" is probably just
1099 * "/api.php" with all the interesting bits in the body.
1101 * Therefore, we only support RFC 7232 precondition headers for GET (and
1102 * HEAD). That means we don't need to bother with If-Match and
1103 * If-Unmodified-Since since they only apply to modification requests.
1105 * And since we don't support Range, If-Range is ignored too.
1108 * @param ApiBase $module Api module being used
1109 * @return bool True on success, false should exit immediately
1111 protected function checkConditionalRequestHeaders( $module ) {
1112 if ( $this->mInternalMode
) {
1113 // No headers to check in internal mode
1117 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1118 // Don't check POSTs
1124 $ifNoneMatch = array_diff(
1125 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1128 if ( $ifNoneMatch ) {
1129 if ( $ifNoneMatch === [ '*' ] ) {
1130 // API responses always "exist"
1133 $etag = $module->getConditionalRequestData( 'etag' );
1136 if ( $ifNoneMatch && $etag !== null ) {
1137 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1138 $match = array_map( function ( $s ) {
1139 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1141 $return304 = in_array( $test, $match, true );
1143 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1145 // Some old browsers sends sizes after the date, like this:
1146 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1148 $i = strpos( $value, ';' );
1149 if ( $i !== false ) {
1150 $value = trim( substr( $value, 0, $i ) );
1153 if ( $value !== '' ) {
1155 $ts = new MWTimestamp( $value );
1157 // RFC 7231 IMF-fixdate
1158 $ts->getTimestamp( TS_RFC2822
) === $value ||
1160 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1161 // asctime (with and without space-padded day)
1162 $ts->format( 'D M j H:i:s Y' ) === $value ||
1163 $ts->format( 'D M j H:i:s Y' ) === $value
1165 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1166 if ( $lastMod !== null ) {
1167 // Mix in some MediaWiki modification times
1170 'user' => $this->getUser()->getTouched(),
1171 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1173 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1174 // T46570: the core page itself may not change, but resources might
1175 $modifiedTimes['sepoch'] = wfTimestamp(
1176 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1179 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1180 $lastMod = max( $modifiedTimes );
1181 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1184 } catch ( TimestampException
$e ) {
1185 // Invalid timestamp, ignore it
1191 $this->getRequest()->response()->statusHeader( 304 );
1193 // Avoid outputting the compressed representation of a zero-length body
1194 MediaWiki\
suppressWarnings();
1195 ini_set( 'zlib.output_compression', 0 );
1196 MediaWiki\restoreWarnings
();
1197 wfClearOutputBuffers();
1206 * Check for sufficient permissions to execute
1207 * @param ApiBase $module An Api module
1209 protected function checkExecutePermissions( $module ) {
1210 $user = $this->getUser();
1211 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1212 !$user->isAllowed( 'read' )
1214 $this->dieUsageMsg( 'readrequired' );
1217 if ( $module->isWriteMode() ) {
1218 if ( !$this->mEnableWrite
) {
1219 $this->dieUsageMsg( 'writedisabled' );
1220 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1221 $this->dieUsageMsg( 'writerequired' );
1222 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1224 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1225 'promised-nonwrite-api'
1229 $this->checkReadOnly( $module );
1232 // Allow extensions to stop execution for arbitrary reasons.
1234 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1235 $this->dieUsageMsg( $message );
1240 * Check if the DB is read-only for this user
1241 * @param ApiBase $module An Api module
1243 protected function checkReadOnly( $module ) {
1244 if ( wfReadOnly() ) {
1245 $this->dieReadOnly();
1248 if ( $module->isWriteMode()
1249 && in_array( 'bot', $this->getUser()->getGroups() )
1250 && wfGetLB()->getServerCount() > 1
1252 $this->checkBotReadOnly();
1257 * Check whether we are readonly for bots
1259 private function checkBotReadOnly() {
1260 // Figure out how many servers have passed the lag threshold
1262 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1263 $laggedServers = [];
1264 $loadBalancer = wfGetLB();
1265 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1266 if ( $lag > $lagLimit ) {
1268 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1272 // If a majority of slaves are too lagged then disallow writes
1273 $slaveCount = wfGetLB()->getServerCount() - 1;
1274 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1275 $laggedServers = implode( ', ', $laggedServers );
1278 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1281 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1287 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1293 * Check asserts of the user's rights
1294 * @param array $params
1296 protected function checkAsserts( $params ) {
1297 if ( isset( $params['assert'] ) ) {
1298 $user = $this->getUser();
1299 switch ( $params['assert'] ) {
1301 if ( $user->isAnon() ) {
1302 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1306 if ( !$user->isAllowed( 'bot' ) ) {
1307 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1315 * Check POST for external response and setup result printer
1316 * @param ApiBase $module An Api module
1317 * @param array $params An array with the request parameters
1319 protected function setupExternalResponse( $module, $params ) {
1320 $request = $this->getRequest();
1321 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1322 // Module requires POST. GET request might still be allowed
1323 // if $wgDebugApi is true, otherwise fail.
1324 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1327 // See if custom printer is used
1328 $this->mPrinter
= $module->getCustomPrinter();
1329 if ( is_null( $this->mPrinter
) ) {
1330 // Create an appropriate printer
1331 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1334 if ( $request->getProtocol() === 'http' && (
1335 $request->getSession()->shouldForceHTTPS() ||
1336 ( $this->getUser()->isLoggedIn() &&
1337 $this->getUser()->requiresHTTPS() )
1339 $this->logFeatureUsage( 'https-expected' );
1340 $this->setWarning( 'HTTP used when HTTPS was expected' );
1345 * Execute the actual module, without any error handling
1347 protected function executeAction() {
1348 $params = $this->setupExecuteAction();
1349 $module = $this->setupModule();
1350 $this->mModule
= $module;
1352 if ( !$this->mInternalMode
) {
1353 $this->setRequestExpectations( $module );
1356 $this->checkExecutePermissions( $module );
1358 if ( !$this->checkMaxLag( $module, $params ) ) {
1362 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1366 if ( !$this->mInternalMode
) {
1367 $this->setupExternalResponse( $module, $params );
1370 $this->checkAsserts( $params );
1374 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1376 $this->reportUnusedParams();
1378 if ( !$this->mInternalMode
) {
1379 // append Debug information
1380 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1382 // Print result data
1383 $this->printResult( false );
1388 * Set database connection, query, and write expectations given this module request
1389 * @param ApiBase $module
1391 protected function setRequestExpectations( ApiBase
$module ) {
1392 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1393 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1394 if ( $this->getRequest()->hasSafeMethod() ) {
1395 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1396 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1397 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1398 $this->getRequest()->markAsSafeRequest();
1400 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1405 * Log the preceding request
1406 * @param float $time Time in seconds
1407 * @param Exception $e Exception caught while processing the request
1409 protected function logRequest( $time, $e = null ) {
1410 $request = $this->getRequest();
1413 'ip' => $request->getIP(),
1414 'userAgent' => $this->getUserAgent(),
1415 'wiki' => wfWikiID(),
1416 'timeSpentBackend' => (int) round( $time * 1000 ),
1417 'hadError' => $e !== null,
1423 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1426 // Construct space separated message for 'api' log channel
1427 $msg = "API {$request->getMethod()} " .
1428 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1429 " {$logCtx['ip']} " .
1430 "T={$logCtx['timeSpentBackend']}ms";
1432 foreach ( $this->getParamsUsed() as $name ) {
1433 $value = $request->getVal( $name );
1434 if ( $value === null ) {
1438 if ( strlen( $value ) > 256 ) {
1439 $value = substr( $value, 0, 256 );
1440 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1442 $encValue = $this->encodeRequestLogValue( $value );
1445 $logCtx['params'][$name] = $value;
1446 $msg .= " {$name}={$encValue}";
1449 wfDebugLog( 'api', $msg, 'private' );
1450 // ApiAction channel is for structured data consumers
1451 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1455 * Encode a value in a format suitable for a space-separated log line.
1459 protected function encodeRequestLogValue( $s ) {
1462 $chars = ';@$!*(),/:';
1463 $numChars = strlen( $chars );
1464 for ( $i = 0; $i < $numChars; $i++
) {
1465 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1469 return strtr( rawurlencode( $s ), $table );
1473 * Get the request parameters used in the course of the preceding execute() request
1476 protected function getParamsUsed() {
1477 return array_keys( $this->mParamsUsed
);
1481 * Mark parameters as used
1482 * @param string|string[] $params
1484 public function markParamsUsed( $params ) {
1485 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1489 * Get a request value, and register the fact that it was used, for logging.
1490 * @param string $name
1491 * @param mixed $default
1494 public function getVal( $name, $default = null ) {
1495 $this->mParamsUsed
[$name] = true;
1497 $ret = $this->getRequest()->getVal( $name );
1498 if ( $ret === null ) {
1499 if ( $this->getRequest()->getArray( $name ) !== null ) {
1500 // See bug 10262 for why we don't just implode( '|', ... ) the
1503 "Parameter '$name' uses unsupported PHP array syntax"
1512 * Get a boolean request value, and register the fact that the parameter
1513 * was used, for logging.
1514 * @param string $name
1517 public function getCheck( $name ) {
1518 return $this->getVal( $name, null ) !== null;
1522 * Get a request upload, and register the fact that it was used, for logging.
1525 * @param string $name Parameter name
1526 * @return WebRequestUpload
1528 public function getUpload( $name ) {
1529 $this->mParamsUsed
[$name] = true;
1531 return $this->getRequest()->getUpload( $name );
1535 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1536 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1538 protected function reportUnusedParams() {
1539 $paramsUsed = $this->getParamsUsed();
1540 $allParams = $this->getRequest()->getValueNames();
1542 if ( !$this->mInternalMode
) {
1543 // Printer has not yet executed; don't warn that its parameters are unused
1544 $printerParams = array_map(
1545 [ $this->mPrinter
, 'encodeParamName' ],
1546 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1548 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1550 $unusedParams = array_diff( $allParams, $paramsUsed );
1553 if ( count( $unusedParams ) ) {
1554 $s = count( $unusedParams ) > 1 ?
's' : '';
1555 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1560 * Print results using the current printer
1562 * @param bool $isError
1564 protected function printResult( $isError ) {
1565 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1566 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1569 $printer = $this->mPrinter
;
1570 $printer->initPrinter( false );
1571 $printer->execute();
1572 $printer->closePrinter();
1578 public function isReadMode() {
1583 * See ApiBase for description.
1587 public function getAllowedParams() {
1590 ApiBase
::PARAM_DFLT
=> 'help',
1591 ApiBase
::PARAM_TYPE
=> 'submodule',
1594 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1595 ApiBase
::PARAM_TYPE
=> 'submodule',
1598 ApiBase
::PARAM_TYPE
=> 'integer'
1601 ApiBase
::PARAM_TYPE
=> 'integer',
1602 ApiBase
::PARAM_DFLT
=> 0
1605 ApiBase
::PARAM_TYPE
=> 'integer',
1606 ApiBase
::PARAM_DFLT
=> 0
1609 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1611 'requestid' => null,
1612 'servedby' => false,
1613 'curtimestamp' => false,
1616 ApiBase
::PARAM_DFLT
=> 'user',
1621 /** @see ApiBase::getExamplesMessages() */
1622 protected function getExamplesMessages() {
1625 => 'apihelp-help-example-main',
1626 'action=help&recursivesubmodules=1'
1627 => 'apihelp-help-example-recursive',
1631 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1632 // Wish PHP had an "array_insert_before". Instead, we have to manually
1633 // reindex the array to get 'permissions' in the right place.
1636 foreach ( $oldHelp as $k => $v ) {
1637 if ( $k === 'submodules' ) {
1638 $help['permissions'] = '';
1642 $help['datatypes'] = '';
1643 $help['credits'] = '';
1645 // Fill 'permissions'
1646 $help['permissions'] .= Html
::openElement( 'div',
1647 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1648 $m = $this->msg( 'api-help-permissions' );
1649 if ( !$m->isDisabled() ) {
1650 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1651 $m->numParams( count( self
::$mRights ) )->parse()
1654 $help['permissions'] .= Html
::openElement( 'dl' );
1655 foreach ( self
::$mRights as $right => $rightMsg ) {
1656 $help['permissions'] .= Html
::element( 'dt', null, $right );
1658 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1659 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1661 $groups = array_map( function ( $group ) {
1662 return $group == '*' ?
'all' : $group;
1663 }, User
::getGroupsWithPermission( $right ) );
1665 $help['permissions'] .= Html
::rawElement( 'dd', null,
1666 $this->msg( 'api-help-permissions-granted-to' )
1667 ->numParams( count( $groups ) )
1668 ->params( $this->getLanguage()->commaList( $groups ) )
1672 $help['permissions'] .= Html
::closeElement( 'dl' );
1673 $help['permissions'] .= Html
::closeElement( 'div' );
1675 // Fill 'datatypes' and 'credits', if applicable
1676 if ( empty( $options['nolead'] ) ) {
1677 $level = $options['headerlevel'];
1678 $tocnumber = &$options['tocnumber'];
1680 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1682 // Add an additional span with sanitized ID
1683 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1684 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1687 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1688 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1691 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1692 if ( !isset( $tocData['main/datatypes'] ) ) {
1693 $tocnumber[$level]++
;
1694 $tocData['main/datatypes'] = [
1695 'toclevel' => count( $tocnumber ),
1697 'anchor' => 'main/datatypes',
1699 'number' => implode( '.', $tocnumber ),
1704 // Add an additional span with sanitized ID
1705 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1706 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1709 $header = $this->msg( 'api-credits-header' )->parse();
1710 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1711 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1714 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1715 if ( !isset( $tocData['main/credits'] ) ) {
1716 $tocnumber[$level]++
;
1717 $tocData['main/credits'] = [
1718 'toclevel' => count( $tocnumber ),
1720 'anchor' => 'main/credits',
1722 'number' => implode( '.', $tocnumber ),
1729 private $mCanApiHighLimits = null;
1732 * Check whether the current user is allowed to use high limits
1735 public function canApiHighLimits() {
1736 if ( !isset( $this->mCanApiHighLimits
) ) {
1737 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1740 return $this->mCanApiHighLimits
;
1744 * Overrides to return this instance's module manager.
1745 * @return ApiModuleManager
1747 public function getModuleManager() {
1748 return $this->mModuleMgr
;
1752 * Fetches the user agent used for this request
1754 * The value will be the combination of the 'Api-User-Agent' header (if
1755 * any) and the standard User-Agent header (if any).
1759 public function getUserAgent() {
1761 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1762 $this->getRequest()->getHeader( 'User-agent' )
1766 /************************************************************************//**
1772 * Sets whether the pretty-printer should format *bold* and $italics$
1774 * @deprecated since 1.25
1777 public function setHelp( $help = true ) {
1778 wfDeprecated( __METHOD__
, '1.25' );
1779 $this->mPrinter
->setHelp( $help );
1783 * Override the parent to generate help messages for all available modules.
1785 * @deprecated since 1.25
1788 public function makeHelpMsg() {
1789 wfDeprecated( __METHOD__
, '1.25' );
1792 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1794 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1797 $this->getModuleName(),
1798 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1800 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1801 [ $this, 'reallyMakeHelpMsg' ]
1806 * @deprecated since 1.25
1807 * @return mixed|string
1809 public function reallyMakeHelpMsg() {
1810 wfDeprecated( __METHOD__
, '1.25' );
1813 // Use parent to make default message for the main module
1814 $msg = parent
::makeHelpMsg();
1816 $asterisks = str_repeat( '*** ', 14 );
1817 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1819 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1820 $module = $this->mModuleMgr
->getModule( $name );
1821 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1823 $msg2 = $module->makeHelpMsg();
1824 if ( $msg2 !== false ) {
1830 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1831 foreach ( self
::$mRights as $right => $rightMsg ) {
1832 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1833 ->useDatabase( false )
1834 ->inLanguage( 'en' )
1836 $groups = User
::getGroupsWithPermission( $right );
1837 $msg .= '* ' . $right . " *\n $rightsMsg" .
1838 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1841 $msg .= "\n$asterisks Formats $asterisks\n\n";
1842 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1843 $module = $this->mModuleMgr
->getModule( $name );
1844 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1845 $msg2 = $module->makeHelpMsg();
1846 if ( $msg2 !== false ) {
1852 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1853 $credits = str_replace( "\n", "\n ", $credits );
1854 $msg .= "\n*** Credits: ***\n $credits\n";
1860 * @deprecated since 1.25
1861 * @param ApiBase $module
1862 * @param string $paramName What type of request is this? e.g. action,
1863 * query, list, prop, meta, format
1866 public static function makeHelpMsgHeader( $module, $paramName ) {
1867 wfDeprecated( __METHOD__
, '1.25' );
1868 $modulePrefix = $module->getModulePrefix();
1869 if ( strval( $modulePrefix ) !== '' ) {
1870 $modulePrefix = "($modulePrefix) ";
1873 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1881 * This exception will be thrown when dieUsage is called to stop module execution.
1885 class UsageException
extends MWException
{
1892 private $mExtraData;
1895 * @param string $message
1896 * @param string $codestr
1898 * @param array|null $extradata
1900 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1901 parent
::__construct( $message, $code );
1902 $this->mCodestr
= $codestr;
1903 $this->mExtraData
= $extradata;
1909 public function getCodeString() {
1910 return $this->mCodestr
;
1916 public function getMessageArray() {
1918 'code' => $this->mCodestr
,
1919 'info' => $this->getMessage()
1921 if ( is_array( $this->mExtraData
) ) {
1922 $result = array_merge( $result, $this->mExtraData
);
1931 public function __toString() {
1932 return "{$this->getCodeString()}: {$this->getMessage()}";
1937 * For really cool vim folding this needs to be at the end:
1938 * vim: foldmarker=@{,@} foldmethod=marker