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 );
175 $request = $this->getRequest();
178 $this->mInternalMode
= ( $request instanceof FauxRequest
);
180 // Special handling for the main module: $parent === $this
181 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
183 $config = $this->getConfig();
185 if ( !$this->mInternalMode
) {
186 // Log if a request with a non-whitelisted Origin header is seen
187 // with session cookies.
188 $originHeader = $request->getHeader( 'Origin' );
189 if ( $originHeader === false ) {
192 $originHeader = trim( $originHeader );
193 $origins = preg_split( '/\s+/', $originHeader );
195 $sessionCookies = array_intersect(
196 array_keys( $_COOKIE ),
197 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
199 if ( $origins && $sessionCookies && (
200 count( $origins ) !== 1 ||
!self
::matchOrigin(
202 $config->get( 'CrossSiteAJAXdomains' ),
203 $config->get( 'CrossSiteAJAXdomainExceptions' )
206 MediaWiki\Logger\LoggerFactory
::getInstance( 'cors' )->warning(
207 'Non-whitelisted CORS request with session cookies', [
208 'origin' => $originHeader,
209 'cookies' => $sessionCookies,
210 'ip' => $request->getIP(),
211 'userAgent' => $this->getUserAgent(),
212 'wiki' => wfWikiID(),
217 // If we're in a mode that breaks the same-origin policy, strip
218 // user credentials for security.
219 if ( $this->lacksSameOriginSecurity() ) {
221 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
222 $wgUser = new User();
223 $this->getContext()->setUser( $wgUser );
227 $uselang = $this->getParameter( 'uselang' );
228 if ( $uselang === 'user' ) {
229 // Assume the parent context is going to return the user language
230 // for uselang=user (see T85635).
232 if ( $uselang === 'content' ) {
234 $uselang = $wgContLang->getCode();
236 $code = RequestContext
::sanitizeLangCode( $uselang );
237 $this->getContext()->setLanguage( $code );
238 if ( !$this->mInternalMode
) {
240 $wgLang = $this->getContext()->getLanguage();
241 RequestContext
::getMain()->setLanguage( $wgLang );
245 $this->mModuleMgr
= new ApiModuleManager( $this );
246 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
247 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
248 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
249 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
251 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
253 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
254 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
255 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
256 $this->mResult
->setMainForContinuation( $this );
257 $this->mContinuationManager
= null;
258 $this->mEnableWrite
= $enableWrite;
260 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
261 $this->mCommit
= false;
265 * Return true if the API was started by other PHP code using FauxRequest
268 public function isInternalMode() {
269 return $this->mInternalMode
;
273 * Get the ApiResult object associated with current request
277 public function getResult() {
278 return $this->mResult
;
282 * Get the security flag for the current request
285 public function lacksSameOriginSecurity() {
286 if ( $this->lacksSameOriginSecurity
!== null ) {
287 return $this->lacksSameOriginSecurity
;
290 $request = $this->getRequest();
293 if ( $request->getVal( 'callback' ) !== null ) {
294 $this->lacksSameOriginSecurity
= true;
298 // Header to be used from XMLHTTPRequest when the request might
299 // otherwise be used for XSS.
300 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
301 $this->lacksSameOriginSecurity
= true;
305 // Allow extensions to override.
306 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
307 return $this->lacksSameOriginSecurity
;
311 * Get the ApiErrorFormatter object associated with current request
312 * @return ApiErrorFormatter
314 public function getErrorFormatter() {
315 return $this->mErrorFormatter
;
319 * Get the continuation manager
320 * @return ApiContinuationManager|null
322 public function getContinuationManager() {
323 return $this->mContinuationManager
;
327 * Set the continuation manager
328 * @param ApiContinuationManager|null
330 public function setContinuationManager( $manager ) {
331 if ( $manager !== null ) {
332 if ( !$manager instanceof ApiContinuationManager
) {
333 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
334 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
337 if ( $this->mContinuationManager
!== null ) {
338 throw new UnexpectedValueException(
339 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
340 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
344 $this->mContinuationManager
= $manager;
348 * Get the API module object. Only works after executeAction()
352 public function getModule() {
353 return $this->mModule
;
357 * Get the result formatter object. Only works after setupExecuteAction()
359 * @return ApiFormatBase
361 public function getPrinter() {
362 return $this->mPrinter
;
366 * Set how long the response should be cached.
370 public function setCacheMaxAge( $maxage ) {
371 $this->setCacheControl( [
372 'max-age' => $maxage,
373 's-maxage' => $maxage
378 * Set the type of caching headers which will be sent.
380 * @param string $mode One of:
381 * - 'public': Cache this object in public caches, if the maxage or smaxage
382 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
383 * not provided by any of these means, the object will be private.
384 * - 'private': Cache this object only in private client-side caches.
385 * - 'anon-public-user-private': Make this object cacheable for logged-out
386 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
387 * set consistently for a given URL, it cannot be set differently depending on
388 * things like the contents of the database, or whether the user is logged in.
390 * If the wiki does not allow anonymous users to read it, the mode set here
391 * will be ignored, and private caching headers will always be sent. In other words,
392 * the "public" mode is equivalent to saying that the data sent is as public as a page
395 * For user-dependent data, the private mode should generally be used. The
396 * anon-public-user-private mode should only be used where there is a particularly
397 * good performance reason for caching the anonymous response, but where the
398 * response to logged-in users may differ, or may contain private data.
400 * If this function is never called, then the default will be the private mode.
402 public function setCacheMode( $mode ) {
403 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
404 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
406 // Ignore for forwards-compatibility
410 if ( !User
::isEveryoneAllowed( 'read' ) ) {
411 // Private wiki, only private headers
412 if ( $mode !== 'private' ) {
413 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
419 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
420 // User language is used for i18n, so we don't want to publicly
421 // cache. Anons are ok, because if they have non-default language
422 // then there's an appropriate Vary header set by whatever set
423 // their non-default language.
424 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
425 "'anon-public-user-private' due to uselang=user\n" );
426 $mode = 'anon-public-user-private';
429 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
430 $this->mCacheMode
= $mode;
434 * Set directives (key/value pairs) for the Cache-Control header.
435 * Boolean values will be formatted as such, by including or omitting
436 * without an equals sign.
438 * Cache control values set here will only be used if the cache mode is not
439 * private, see setCacheMode().
441 * @param array $directives
443 public function setCacheControl( $directives ) {
444 $this->mCacheControl
= $directives +
$this->mCacheControl
;
448 * Create an instance of an output formatter by its name
450 * @param string $format
452 * @return ApiFormatBase
454 public function createPrinterByName( $format ) {
455 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
456 if ( $printer === null ) {
457 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
464 * Execute api request. Any errors will be handled if the API was called by the remote client.
466 public function execute() {
467 if ( $this->mInternalMode
) {
468 $this->executeAction();
470 $this->executeActionWithErrorHandling();
475 * Execute an action, and in case of an error, erase whatever partial results
476 * have been accumulated, and replace it with an error message and a help screen.
478 protected function executeActionWithErrorHandling() {
479 // Verify the CORS header before executing the action
480 if ( !$this->handleCORS() ) {
481 // handleCORS() has sent a 403, abort
485 // Exit here if the request method was OPTIONS
486 // (assume there will be a followup GET or POST)
487 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
491 // In case an error occurs during data output,
492 // clear the output buffer and print just the error information
493 $obLevel = ob_get_level();
496 $t = microtime( true );
499 $this->executeAction();
500 $runTime = microtime( true ) - $t;
501 $this->logRequest( $runTime );
502 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
503 $this->getStats()->timing(
504 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
507 } catch ( Exception
$e ) {
508 $this->handleException( $e );
509 $this->logRequest( microtime( true ) - $t, $e );
513 // Commit DBs and send any related cookies and headers
514 MediaWiki
::preOutputCommit( $this->getContext() );
516 // Send cache headers after any code which might generate an error, to
517 // avoid sending public cache headers for errors.
518 $this->sendCacheHeaders( $isError );
520 // Executing the action might have already messed with the output
522 while ( ob_get_level() > $obLevel ) {
528 * Handle an exception as an API response
531 * @param Exception $e
533 protected function handleException( Exception
$e ) {
534 // Bug 63145: Rollback any open database transactions
535 if ( !( $e instanceof UsageException
) ) {
536 // UsageExceptions are intentional, so don't rollback if that's the case
538 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
539 } catch ( DBError
$e2 ) {
540 // Rollback threw an exception too. Log it, but don't interrupt
541 // our regularly scheduled exception handling.
542 MWExceptionHandler
::logException( $e2 );
546 // Allow extra cleanup and logging
547 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
550 if ( !( $e instanceof UsageException
) ) {
551 MWExceptionHandler
::logException( $e );
554 // Handle any kind of exception by outputting properly formatted error message.
555 // If this fails, an unhandled exception should be thrown so that global error
556 // handler will process and log it.
558 $errCode = $this->substituteResultWithError( $e );
560 // Error results should not be cached
561 $this->setCacheMode( 'private' );
563 $response = $this->getRequest()->response();
564 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
565 if ( $e->getCode() === 0 ) {
566 $response->header( $headerStr );
568 $response->header( $headerStr, true, $e->getCode() );
571 // Reset and print just the error message
574 // Printer may not be initialized if the extractRequestParams() fails for the main module
575 $this->createErrorPrinter();
578 $this->printResult( true );
579 } catch ( UsageException
$ex ) {
580 // The error printer itself is failing. Try suppressing its request
581 // parameters and redo.
583 'Error printer failed (will retry without params): ' . $ex->getMessage()
585 $this->mPrinter
= null;
586 $this->createErrorPrinter();
587 $this->mPrinter
->forceDefaultParams();
588 $this->printResult( true );
593 * Handle an exception from the ApiBeforeMain hook.
595 * This tries to print the exception as an API response, to be more
596 * friendly to clients. If it fails, it will rethrow the exception.
599 * @param Exception $e
602 public static function handleApiBeforeMainException( Exception
$e ) {
606 $main = new self( RequestContext
::getMain(), false );
607 $main->handleException( $e );
608 $main->logRequest( 0, $e );
609 } catch ( Exception
$e2 ) {
610 // Nope, even that didn't work. Punt.
614 // Reset cache headers
615 $main->sendCacheHeaders( true );
621 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
623 * If no origin parameter is present, nothing happens.
624 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
625 * is set and false is returned.
626 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
627 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
629 * http://www.w3.org/TR/cors/#resource-requests
630 * http://www.w3.org/TR/cors/#resource-preflight-requests
632 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
634 protected function handleCORS() {
635 $originParam = $this->getParameter( 'origin' ); // defaults to null
636 if ( $originParam === null ) {
637 // No origin parameter, nothing to do
641 $request = $this->getRequest();
642 $response = $request->response();
644 // Origin: header is a space-separated list of origins, check all of them
645 $originHeader = $request->getHeader( 'Origin' );
646 if ( $originHeader === false ) {
649 $originHeader = trim( $originHeader );
650 $origins = preg_split( '/\s+/', $originHeader );
653 if ( !in_array( $originParam, $origins ) ) {
654 // origin parameter set but incorrect
655 // Send a 403 response
656 $response->statusHeader( 403 );
657 $response->header( 'Cache-Control: no-cache' );
658 echo "'origin' parameter does not match Origin header\n";
663 $config = $this->getConfig();
664 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
666 $config->get( 'CrossSiteAJAXdomains' ),
667 $config->get( 'CrossSiteAJAXdomainExceptions' )
670 if ( $matchOrigin ) {
671 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
672 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
674 // This is a CORS preflight request
675 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
676 // If method is not a case-sensitive match, do not set any additional headers and terminate.
679 // We allow the actual request to send the following headers
680 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
681 if ( $requestedHeaders !== false ) {
682 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
685 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
688 // We only allow the actual request to be GET or POST
689 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
692 $response->header( "Access-Control-Allow-Origin: $originHeader" );
693 $response->header( 'Access-Control-Allow-Credentials: true' );
694 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
695 $response->header( "Timing-Allow-Origin: $originHeader" );
699 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
704 $this->getOutput()->addVaryHeader( 'Origin' );
709 * Attempt to match an Origin header against a set of rules and a set of exceptions
710 * @param string $value Origin header
711 * @param array $rules Set of wildcard rules
712 * @param array $exceptions Set of wildcard rules
713 * @return bool True if $value matches a rule in $rules and doesn't match
714 * any rules in $exceptions, false otherwise
716 protected static function matchOrigin( $value, $rules, $exceptions ) {
717 foreach ( $rules as $rule ) {
718 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
719 // Rule matches, check exceptions
720 foreach ( $exceptions as $exc ) {
721 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
734 * Attempt to validate the value of Access-Control-Request-Headers against a list
735 * of headers that we allow the follow up request to send.
737 * @param string $requestedHeaders Comma seperated list of HTTP headers
738 * @return bool True if all requested headers are in the list of allowed headers
740 protected static function matchRequestedHeaders( $requestedHeaders ) {
741 if ( trim( $requestedHeaders ) === '' ) {
744 $requestedHeaders = explode( ',', $requestedHeaders );
745 $allowedAuthorHeaders = array_flip( [
746 /* simple headers (see spec) */
751 /* non-authorable headers in XHR, which are however requested by some UAs */
755 /* MediaWiki whitelist */
758 foreach ( $requestedHeaders as $rHeader ) {
759 $rHeader = strtolower( trim( $rHeader ) );
760 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
761 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
769 * Helper function to convert wildcard string into a regex
773 * @param string $wildcard String with wildcards
774 * @return string Regular expression
776 protected static function wildcardToRegex( $wildcard ) {
777 $wildcard = preg_quote( $wildcard, '/' );
778 $wildcard = str_replace(
784 return "/^https?:\/\/$wildcard$/";
788 * Send caching headers
789 * @param bool $isError Whether an error response is being output
790 * @since 1.26 added $isError parameter
792 protected function sendCacheHeaders( $isError ) {
793 $response = $this->getRequest()->response();
794 $out = $this->getOutput();
796 $out->addVaryHeader( 'Treat-as-Untrusted' );
798 $config = $this->getConfig();
800 if ( $config->get( 'VaryOnXFP' ) ) {
801 $out->addVaryHeader( 'X-Forwarded-Proto' );
804 if ( !$isError && $this->mModule
&&
805 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
807 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
808 if ( $etag !== null ) {
809 $response->header( "ETag: $etag" );
811 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
812 if ( $lastMod !== null ) {
813 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
817 // The logic should be:
818 // $this->mCacheControl['max-age'] is set?
819 // Use it, the module knows better than our guess.
820 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
821 // Use 0 because we can guess caching is probably the wrong thing to do.
822 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
824 if ( isset( $this->mCacheControl
['max-age'] ) ) {
825 $maxage = $this->mCacheControl
['max-age'];
826 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
827 $this->mCacheMode
!== 'private'
829 $maxage = $this->getParameter( 'maxage' );
831 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
833 if ( $this->mCacheMode
== 'private' ) {
834 $response->header( "Cache-Control: $privateCache" );
838 $useKeyHeader = $config->get( 'UseKeyHeader' );
839 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
840 $out->addVaryHeader( 'Cookie' );
841 $response->header( $out->getVaryHeader() );
842 if ( $useKeyHeader ) {
843 $response->header( $out->getKeyHeader() );
844 if ( $out->haveCacheVaryCookies() ) {
845 // Logged in, mark this request private
846 $response->header( "Cache-Control: $privateCache" );
849 // Logged out, send normal public headers below
850 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
851 // Logged in or otherwise has session (e.g. anonymous users who have edited)
852 // Mark request private
853 $response->header( "Cache-Control: $privateCache" );
856 } // else no Key and anonymous, send public headers below
859 // Send public headers
860 $response->header( $out->getVaryHeader() );
861 if ( $useKeyHeader ) {
862 $response->header( $out->getKeyHeader() );
865 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
866 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
867 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
869 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
870 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
873 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
874 // Public cache not requested
875 // Sending a Vary header in this case is harmless, and protects us
876 // against conditional calls of setCacheMaxAge().
877 $response->header( "Cache-Control: $privateCache" );
882 $this->mCacheControl
['public'] = true;
884 // Send an Expires header
885 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
886 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
887 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
889 // Construct the Cache-Control header
892 foreach ( $this->mCacheControl
as $name => $value ) {
893 if ( is_bool( $value ) ) {
895 $ccHeader .= $separator . $name;
899 $ccHeader .= $separator . "$name=$value";
904 $response->header( "Cache-Control: $ccHeader" );
908 * Create the printer for error output
910 private function createErrorPrinter() {
911 if ( !isset( $this->mPrinter
) ) {
912 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
913 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
914 $value = self
::API_DEFAULT_FORMAT
;
916 $this->mPrinter
= $this->createPrinterByName( $value );
919 // Printer may not be able to handle errors. This is particularly
920 // likely if the module returns something for getCustomPrinter().
921 if ( !$this->mPrinter
->canPrintErrors() ) {
922 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
927 * Create an error message for the given exception.
929 * If the exception is a UsageException then
930 * UsageException::getMessageArray() will be called to create the message.
932 * @param Exception $e
933 * @return array ['code' => 'some string', 'info' => 'some other string']
936 protected function errorMessageFromException( $e ) {
937 if ( $e instanceof UsageException
) {
938 // User entered incorrect parameters - generate error response
939 $errMessage = $e->getMessageArray();
941 $config = $this->getConfig();
942 // Something is seriously wrong
943 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
944 $info = 'Database query error';
946 $info = "Exception Caught: {$e->getMessage()}";
950 'code' => 'internal_api_error_' . get_class( $e ),
951 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
958 * Replace the result data with the information about an exception.
959 * Returns the error code
960 * @param Exception $e
963 protected function substituteResultWithError( $e ) {
964 $result = $this->getResult();
965 $config = $this->getConfig();
967 $errMessage = $this->errorMessageFromException( $e );
968 if ( $e instanceof UsageException
) {
969 // User entered incorrect parameters - generate error response
970 $link = wfExpandUrl( wfScript( 'api' ) );
971 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
973 // Something is seriously wrong
974 if ( $config->get( 'ShowExceptionDetails' ) ) {
975 ApiResult
::setContentValue(
978 MWExceptionHandler
::getRedactedTraceAsString( $e )
983 // Remember all the warnings to re-add them later
984 $warnings = $result->getResultData( [ 'warnings' ] );
988 $requestid = $this->getParameter( 'requestid' );
989 if ( !is_null( $requestid ) ) {
990 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
992 if ( $config->get( 'ShowHostnames' ) ) {
993 // servedby is especially useful when debugging errors
994 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
996 if ( $warnings !== null ) {
997 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1000 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
1002 return $errMessage['code'];
1006 * Set up for the execution.
1009 protected function setupExecuteAction() {
1010 // First add the id to the top element
1011 $result = $this->getResult();
1012 $requestid = $this->getParameter( 'requestid' );
1013 if ( !is_null( $requestid ) ) {
1014 $result->addValue( null, 'requestid', $requestid );
1017 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1018 $servedby = $this->getParameter( 'servedby' );
1020 $result->addValue( null, 'servedby', wfHostname() );
1024 if ( $this->getParameter( 'curtimestamp' ) ) {
1025 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1026 ApiResult
::NO_SIZE_CHECK
);
1029 $params = $this->extractRequestParams();
1031 $this->mAction
= $params['action'];
1033 if ( !is_string( $this->mAction
) ) {
1034 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1041 * Set up the module for response
1042 * @return ApiBase The module that will handle this action
1043 * @throws MWException
1044 * @throws UsageException
1046 protected function setupModule() {
1047 // Instantiate the module requested by the user
1048 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1049 if ( $module === null ) {
1050 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1052 $moduleParams = $module->extractRequestParams();
1054 // Check token, if necessary
1055 if ( $module->needsToken() === true ) {
1056 throw new MWException(
1057 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1058 'See documentation for ApiBase::needsToken for details.'
1061 if ( $module->needsToken() ) {
1062 if ( !$module->mustBePosted() ) {
1063 throw new MWException(
1064 "Module '{$module->getModuleName()}' must require POST to use tokens."
1068 if ( !isset( $moduleParams['token'] ) ) {
1069 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1072 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1074 $module->encodeParamName( 'token' ),
1075 $this->getRequest()->getQueryValues()
1079 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1080 'found in the query string, but must be in the POST body',
1085 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1086 $this->dieUsageMsg( 'sessionfailure' );
1094 * Check the max lag if necessary
1095 * @param ApiBase $module Api module being used
1096 * @param array $params Array an array containing the request parameters.
1097 * @return bool True on success, false should exit immediately
1099 protected function checkMaxLag( $module, $params ) {
1100 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1101 $maxLag = $params['maxlag'];
1102 list( $host, $lag ) = wfGetLB()->getMaxLag();
1103 if ( $lag > $maxLag ) {
1104 $response = $this->getRequest()->response();
1106 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1107 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1109 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1110 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1113 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1121 * Check selected RFC 7232 precondition headers
1123 * RFC 7232 envisions a particular model where you send your request to "a
1124 * resource", and for write requests that you can read "the resource" by
1125 * changing the method to GET. When the API receives a GET request, it
1126 * works out even though "the resource" from RFC 7232's perspective might
1127 * be many resources from MediaWiki's perspective. But it totally fails for
1128 * a POST, since what HTTP sees as "the resource" is probably just
1129 * "/api.php" with all the interesting bits in the body.
1131 * Therefore, we only support RFC 7232 precondition headers for GET (and
1132 * HEAD). That means we don't need to bother with If-Match and
1133 * If-Unmodified-Since since they only apply to modification requests.
1135 * And since we don't support Range, If-Range is ignored too.
1138 * @param ApiBase $module Api module being used
1139 * @return bool True on success, false should exit immediately
1141 protected function checkConditionalRequestHeaders( $module ) {
1142 if ( $this->mInternalMode
) {
1143 // No headers to check in internal mode
1147 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1148 // Don't check POSTs
1154 $ifNoneMatch = array_diff(
1155 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1158 if ( $ifNoneMatch ) {
1159 if ( $ifNoneMatch === [ '*' ] ) {
1160 // API responses always "exist"
1163 $etag = $module->getConditionalRequestData( 'etag' );
1166 if ( $ifNoneMatch && $etag !== null ) {
1167 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1168 $match = array_map( function ( $s ) {
1169 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1171 $return304 = in_array( $test, $match, true );
1173 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1175 // Some old browsers sends sizes after the date, like this:
1176 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1178 $i = strpos( $value, ';' );
1179 if ( $i !== false ) {
1180 $value = trim( substr( $value, 0, $i ) );
1183 if ( $value !== '' ) {
1185 $ts = new MWTimestamp( $value );
1187 // RFC 7231 IMF-fixdate
1188 $ts->getTimestamp( TS_RFC2822
) === $value ||
1190 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1191 // asctime (with and without space-padded day)
1192 $ts->format( 'D M j H:i:s Y' ) === $value ||
1193 $ts->format( 'D M j H:i:s Y' ) === $value
1195 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1196 if ( $lastMod !== null ) {
1197 // Mix in some MediaWiki modification times
1200 'user' => $this->getUser()->getTouched(),
1201 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1203 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1204 // T46570: the core page itself may not change, but resources might
1205 $modifiedTimes['sepoch'] = wfTimestamp(
1206 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1209 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1210 $lastMod = max( $modifiedTimes );
1211 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1214 } catch ( TimestampException
$e ) {
1215 // Invalid timestamp, ignore it
1221 $this->getRequest()->response()->statusHeader( 304 );
1223 // Avoid outputting the compressed representation of a zero-length body
1224 MediaWiki\
suppressWarnings();
1225 ini_set( 'zlib.output_compression', 0 );
1226 MediaWiki\restoreWarnings
();
1227 wfClearOutputBuffers();
1236 * Check for sufficient permissions to execute
1237 * @param ApiBase $module An Api module
1239 protected function checkExecutePermissions( $module ) {
1240 $user = $this->getUser();
1241 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1242 !$user->isAllowed( 'read' )
1244 $this->dieUsageMsg( 'readrequired' );
1247 if ( $module->isWriteMode() ) {
1248 if ( !$this->mEnableWrite
) {
1249 $this->dieUsageMsg( 'writedisabled' );
1250 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1251 $this->dieUsageMsg( 'writerequired' );
1252 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1254 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1255 'promised-nonwrite-api'
1259 $this->checkReadOnly( $module );
1262 // Allow extensions to stop execution for arbitrary reasons.
1264 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1265 $this->dieUsageMsg( $message );
1270 * Check if the DB is read-only for this user
1271 * @param ApiBase $module An Api module
1273 protected function checkReadOnly( $module ) {
1274 if ( wfReadOnly() ) {
1275 $this->dieReadOnly();
1278 if ( $module->isWriteMode()
1279 && in_array( 'bot', $this->getUser()->getGroups() )
1280 && wfGetLB()->getServerCount() > 1
1282 $this->checkBotReadOnly();
1287 * Check whether we are readonly for bots
1289 private function checkBotReadOnly() {
1290 // Figure out how many servers have passed the lag threshold
1292 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1293 $laggedServers = [];
1294 $loadBalancer = wfGetLB();
1295 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1296 if ( $lag > $lagLimit ) {
1298 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1302 // If a majority of slaves are too lagged then disallow writes
1303 $slaveCount = wfGetLB()->getServerCount() - 1;
1304 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1305 $laggedServers = implode( ', ', $laggedServers );
1308 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1311 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1317 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1323 * Check asserts of the user's rights
1324 * @param array $params
1326 protected function checkAsserts( $params ) {
1327 if ( isset( $params['assert'] ) ) {
1328 $user = $this->getUser();
1329 switch ( $params['assert'] ) {
1331 if ( $user->isAnon() ) {
1332 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1336 if ( !$user->isAllowed( 'bot' ) ) {
1337 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1345 * Check POST for external response and setup result printer
1346 * @param ApiBase $module An Api module
1347 * @param array $params An array with the request parameters
1349 protected function setupExternalResponse( $module, $params ) {
1350 $request = $this->getRequest();
1351 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1352 // Module requires POST. GET request might still be allowed
1353 // if $wgDebugApi is true, otherwise fail.
1354 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1357 // See if custom printer is used
1358 $this->mPrinter
= $module->getCustomPrinter();
1359 if ( is_null( $this->mPrinter
) ) {
1360 // Create an appropriate printer
1361 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1364 if ( $request->getProtocol() === 'http' && (
1365 $request->getSession()->shouldForceHTTPS() ||
1366 ( $this->getUser()->isLoggedIn() &&
1367 $this->getUser()->requiresHTTPS() )
1369 $this->logFeatureUsage( 'https-expected' );
1370 $this->setWarning( 'HTTP used when HTTPS was expected' );
1375 * Execute the actual module, without any error handling
1377 protected function executeAction() {
1378 $params = $this->setupExecuteAction();
1379 $module = $this->setupModule();
1380 $this->mModule
= $module;
1382 if ( !$this->mInternalMode
) {
1383 $this->setRequestExpectations( $module );
1386 $this->checkExecutePermissions( $module );
1388 if ( !$this->checkMaxLag( $module, $params ) ) {
1392 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1396 if ( !$this->mInternalMode
) {
1397 $this->setupExternalResponse( $module, $params );
1400 $this->checkAsserts( $params );
1404 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1406 $this->reportUnusedParams();
1408 if ( !$this->mInternalMode
) {
1409 // append Debug information
1410 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1412 // Print result data
1413 $this->printResult( false );
1418 * Set database connection, query, and write expectations given this module request
1419 * @param ApiBase $module
1421 protected function setRequestExpectations( ApiBase
$module ) {
1422 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1423 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1424 if ( $this->getRequest()->hasSafeMethod() ) {
1425 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1426 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1427 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1428 $this->getRequest()->markAsSafeRequest();
1430 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1435 * Log the preceding request
1436 * @param float $time Time in seconds
1437 * @param Exception $e Exception caught while processing the request
1439 protected function logRequest( $time, $e = null ) {
1440 $request = $this->getRequest();
1443 'ip' => $request->getIP(),
1444 'userAgent' => $this->getUserAgent(),
1445 'wiki' => wfWikiID(),
1446 'timeSpentBackend' => (int) round( $time * 1000 ),
1447 'hadError' => $e !== null,
1453 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1456 // Construct space separated message for 'api' log channel
1457 $msg = "API {$request->getMethod()} " .
1458 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1459 " {$logCtx['ip']} " .
1460 "T={$logCtx['timeSpentBackend']}ms";
1462 foreach ( $this->getParamsUsed() as $name ) {
1463 $value = $request->getVal( $name );
1464 if ( $value === null ) {
1468 if ( strlen( $value ) > 256 ) {
1469 $value = substr( $value, 0, 256 );
1470 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1472 $encValue = $this->encodeRequestLogValue( $value );
1475 $logCtx['params'][$name] = $value;
1476 $msg .= " {$name}={$encValue}";
1479 wfDebugLog( 'api', $msg, 'private' );
1480 // ApiAction channel is for structured data consumers
1481 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1485 * Encode a value in a format suitable for a space-separated log line.
1489 protected function encodeRequestLogValue( $s ) {
1492 $chars = ';@$!*(),/:';
1493 $numChars = strlen( $chars );
1494 for ( $i = 0; $i < $numChars; $i++
) {
1495 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1499 return strtr( rawurlencode( $s ), $table );
1503 * Get the request parameters used in the course of the preceding execute() request
1506 protected function getParamsUsed() {
1507 return array_keys( $this->mParamsUsed
);
1511 * Mark parameters as used
1512 * @param string|string[] $params
1514 public function markParamsUsed( $params ) {
1515 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1519 * Get a request value, and register the fact that it was used, for logging.
1520 * @param string $name
1521 * @param mixed $default
1524 public function getVal( $name, $default = null ) {
1525 $this->mParamsUsed
[$name] = true;
1527 $ret = $this->getRequest()->getVal( $name );
1528 if ( $ret === null ) {
1529 if ( $this->getRequest()->getArray( $name ) !== null ) {
1530 // See bug 10262 for why we don't just implode( '|', ... ) the
1533 "Parameter '$name' uses unsupported PHP array syntax"
1542 * Get a boolean request value, and register the fact that the parameter
1543 * was used, for logging.
1544 * @param string $name
1547 public function getCheck( $name ) {
1548 return $this->getVal( $name, null ) !== null;
1552 * Get a request upload, and register the fact that it was used, for logging.
1555 * @param string $name Parameter name
1556 * @return WebRequestUpload
1558 public function getUpload( $name ) {
1559 $this->mParamsUsed
[$name] = true;
1561 return $this->getRequest()->getUpload( $name );
1565 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1566 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1568 protected function reportUnusedParams() {
1569 $paramsUsed = $this->getParamsUsed();
1570 $allParams = $this->getRequest()->getValueNames();
1572 if ( !$this->mInternalMode
) {
1573 // Printer has not yet executed; don't warn that its parameters are unused
1574 $printerParams = array_map(
1575 [ $this->mPrinter
, 'encodeParamName' ],
1576 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1578 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1580 $unusedParams = array_diff( $allParams, $paramsUsed );
1583 if ( count( $unusedParams ) ) {
1584 $s = count( $unusedParams ) > 1 ?
's' : '';
1585 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1590 * Print results using the current printer
1592 * @param bool $isError
1594 protected function printResult( $isError ) {
1595 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1596 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1599 $printer = $this->mPrinter
;
1600 $printer->initPrinter( false );
1601 $printer->execute();
1602 $printer->closePrinter();
1608 public function isReadMode() {
1613 * See ApiBase for description.
1617 public function getAllowedParams() {
1620 ApiBase
::PARAM_DFLT
=> 'help',
1621 ApiBase
::PARAM_TYPE
=> 'submodule',
1624 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1625 ApiBase
::PARAM_TYPE
=> 'submodule',
1628 ApiBase
::PARAM_TYPE
=> 'integer'
1631 ApiBase
::PARAM_TYPE
=> 'integer',
1632 ApiBase
::PARAM_DFLT
=> 0
1635 ApiBase
::PARAM_TYPE
=> 'integer',
1636 ApiBase
::PARAM_DFLT
=> 0
1639 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1641 'requestid' => null,
1642 'servedby' => false,
1643 'curtimestamp' => false,
1646 ApiBase
::PARAM_DFLT
=> 'user',
1651 /** @see ApiBase::getExamplesMessages() */
1652 protected function getExamplesMessages() {
1655 => 'apihelp-help-example-main',
1656 'action=help&recursivesubmodules=1'
1657 => 'apihelp-help-example-recursive',
1661 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1662 // Wish PHP had an "array_insert_before". Instead, we have to manually
1663 // reindex the array to get 'permissions' in the right place.
1666 foreach ( $oldHelp as $k => $v ) {
1667 if ( $k === 'submodules' ) {
1668 $help['permissions'] = '';
1672 $help['datatypes'] = '';
1673 $help['credits'] = '';
1675 // Fill 'permissions'
1676 $help['permissions'] .= Html
::openElement( 'div',
1677 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1678 $m = $this->msg( 'api-help-permissions' );
1679 if ( !$m->isDisabled() ) {
1680 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1681 $m->numParams( count( self
::$mRights ) )->parse()
1684 $help['permissions'] .= Html
::openElement( 'dl' );
1685 foreach ( self
::$mRights as $right => $rightMsg ) {
1686 $help['permissions'] .= Html
::element( 'dt', null, $right );
1688 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1689 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1691 $groups = array_map( function ( $group ) {
1692 return $group == '*' ?
'all' : $group;
1693 }, User
::getGroupsWithPermission( $right ) );
1695 $help['permissions'] .= Html
::rawElement( 'dd', null,
1696 $this->msg( 'api-help-permissions-granted-to' )
1697 ->numParams( count( $groups ) )
1698 ->params( $this->getLanguage()->commaList( $groups ) )
1702 $help['permissions'] .= Html
::closeElement( 'dl' );
1703 $help['permissions'] .= Html
::closeElement( 'div' );
1705 // Fill 'datatypes' and 'credits', if applicable
1706 if ( empty( $options['nolead'] ) ) {
1707 $level = $options['headerlevel'];
1708 $tocnumber = &$options['tocnumber'];
1710 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1712 // Add an additional span with sanitized ID
1713 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1714 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1717 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1718 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1721 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1722 if ( !isset( $tocData['main/datatypes'] ) ) {
1723 $tocnumber[$level]++
;
1724 $tocData['main/datatypes'] = [
1725 'toclevel' => count( $tocnumber ),
1727 'anchor' => 'main/datatypes',
1729 'number' => implode( '.', $tocnumber ),
1734 // Add an additional span with sanitized ID
1735 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1736 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1739 $header = $this->msg( 'api-credits-header' )->parse();
1740 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1741 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1744 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1745 if ( !isset( $tocData['main/credits'] ) ) {
1746 $tocnumber[$level]++
;
1747 $tocData['main/credits'] = [
1748 'toclevel' => count( $tocnumber ),
1750 'anchor' => 'main/credits',
1752 'number' => implode( '.', $tocnumber ),
1759 private $mCanApiHighLimits = null;
1762 * Check whether the current user is allowed to use high limits
1765 public function canApiHighLimits() {
1766 if ( !isset( $this->mCanApiHighLimits
) ) {
1767 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1770 return $this->mCanApiHighLimits
;
1774 * Overrides to return this instance's module manager.
1775 * @return ApiModuleManager
1777 public function getModuleManager() {
1778 return $this->mModuleMgr
;
1782 * Fetches the user agent used for this request
1784 * The value will be the combination of the 'Api-User-Agent' header (if
1785 * any) and the standard User-Agent header (if any).
1789 public function getUserAgent() {
1791 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1792 $this->getRequest()->getHeader( 'User-agent' )
1796 /************************************************************************//**
1802 * Sets whether the pretty-printer should format *bold* and $italics$
1804 * @deprecated since 1.25
1807 public function setHelp( $help = true ) {
1808 wfDeprecated( __METHOD__
, '1.25' );
1809 $this->mPrinter
->setHelp( $help );
1813 * Override the parent to generate help messages for all available modules.
1815 * @deprecated since 1.25
1818 public function makeHelpMsg() {
1819 wfDeprecated( __METHOD__
, '1.25' );
1822 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1824 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1827 $this->getModuleName(),
1828 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1830 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1831 [ $this, 'reallyMakeHelpMsg' ]
1836 * @deprecated since 1.25
1837 * @return mixed|string
1839 public function reallyMakeHelpMsg() {
1840 wfDeprecated( __METHOD__
, '1.25' );
1843 // Use parent to make default message for the main module
1844 $msg = parent
::makeHelpMsg();
1846 $asterisks = str_repeat( '*** ', 14 );
1847 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1849 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1850 $module = $this->mModuleMgr
->getModule( $name );
1851 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1853 $msg2 = $module->makeHelpMsg();
1854 if ( $msg2 !== false ) {
1860 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1861 foreach ( self
::$mRights as $right => $rightMsg ) {
1862 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1863 ->useDatabase( false )
1864 ->inLanguage( 'en' )
1866 $groups = User
::getGroupsWithPermission( $right );
1867 $msg .= '* ' . $right . " *\n $rightsMsg" .
1868 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1871 $msg .= "\n$asterisks Formats $asterisks\n\n";
1872 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1873 $module = $this->mModuleMgr
->getModule( $name );
1874 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1875 $msg2 = $module->makeHelpMsg();
1876 if ( $msg2 !== false ) {
1882 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1883 $credits = str_replace( "\n", "\n ", $credits );
1884 $msg .= "\n*** Credits: ***\n $credits\n";
1890 * @deprecated since 1.25
1891 * @param ApiBase $module
1892 * @param string $paramName What type of request is this? e.g. action,
1893 * query, list, prop, meta, format
1896 public static function makeHelpMsgHeader( $module, $paramName ) {
1897 wfDeprecated( __METHOD__
, '1.25' );
1898 $modulePrefix = $module->getModulePrefix();
1899 if ( strval( $modulePrefix ) !== '' ) {
1900 $modulePrefix = "($modulePrefix) ";
1903 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1911 * This exception will be thrown when dieUsage is called to stop module execution.
1915 class UsageException
extends MWException
{
1922 private $mExtraData;
1925 * @param string $message
1926 * @param string $codestr
1928 * @param array|null $extradata
1930 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1931 parent
::__construct( $message, $code );
1932 $this->mCodestr
= $codestr;
1933 $this->mExtraData
= $extradata;
1939 public function getCodeString() {
1940 return $this->mCodestr
;
1946 public function getMessageArray() {
1948 'code' => $this->mCodestr
,
1949 'info' => $this->getMessage()
1951 if ( is_array( $this->mExtraData
) ) {
1952 $result = array_merge( $result, $this->mExtraData
);
1961 public function __toString() {
1962 return "{$this->getCodeString()}: {$this->getMessage()}";
1967 * For really cool vim folding this needs to be at the end:
1968 * vim: foldmarker=@{,@} foldmethod=marker