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
28 use MediaWiki\Logger\LoggerFactory
;
31 * This is the main API class, used for both external and internal processing.
32 * When executed, it will create the requested formatter object,
33 * instantiate and execute an object associated with the needed action,
34 * and use formatter to print results.
35 * In case of an exception, an error message will be printed using the same formatter.
37 * To use API from another application, run it using FauxRequest object, in which
38 * case any internal exceptions will not be handled but passed up to the caller.
39 * After successful execution, use getResult() for the resulting data.
43 class ApiMain
extends ApiBase
{
45 * When no format parameter is given, this format will be used
47 const API_DEFAULT_FORMAT
= 'jsonfm';
50 * List of available modules: action name => module class
52 private static $Modules = [
53 'login' => 'ApiLogin',
54 'clientlogin' => 'ApiClientLogin',
55 'logout' => 'ApiLogout',
56 'createaccount' => 'ApiAMCreateAccount',
57 'linkaccount' => 'ApiLinkAccount',
58 'unlinkaccount' => 'ApiRemoveAuthenticationData',
59 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
60 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
61 'resetpassword' => 'ApiResetPassword',
62 'query' => 'ApiQuery',
63 'expandtemplates' => 'ApiExpandTemplates',
64 'parse' => 'ApiParse',
65 'stashedit' => 'ApiStashEdit',
66 'opensearch' => 'ApiOpenSearch',
67 'feedcontributions' => 'ApiFeedContributions',
68 'feedrecentchanges' => 'ApiFeedRecentChanges',
69 'feedwatchlist' => 'ApiFeedWatchlist',
71 'paraminfo' => 'ApiParamInfo',
73 'compare' => 'ApiComparePages',
74 'tokens' => 'ApiTokens',
75 'checktoken' => 'ApiCheckToken',
76 'cspreport' => 'ApiCSPReport',
79 'purge' => 'ApiPurge',
80 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
81 'rollback' => 'ApiRollback',
82 'delete' => 'ApiDelete',
83 'undelete' => 'ApiUndelete',
84 'protect' => 'ApiProtect',
85 'block' => 'ApiBlock',
86 'unblock' => 'ApiUnblock',
88 'edit' => 'ApiEditPage',
89 'upload' => 'ApiUpload',
90 'filerevert' => 'ApiFileRevert',
91 'emailuser' => 'ApiEmailUser',
92 'watch' => 'ApiWatch',
93 'patrol' => 'ApiPatrol',
94 'import' => 'ApiImport',
95 'clearhasmsg' => 'ApiClearHasMsg',
96 'userrights' => 'ApiUserrights',
97 'options' => 'ApiOptions',
98 'imagerotate' => 'ApiImageRotate',
99 'revisiondelete' => 'ApiRevisionDelete',
100 'managetags' => 'ApiManageTags',
102 'mergehistory' => 'ApiMergeHistory',
106 * List of available formats: format name => format class
108 private static $Formats = [
109 'json' => 'ApiFormatJson',
110 'jsonfm' => 'ApiFormatJson',
111 'php' => 'ApiFormatPhp',
112 'phpfm' => 'ApiFormatPhp',
113 'xml' => 'ApiFormatXml',
114 'xmlfm' => 'ApiFormatXml',
115 'rawfm' => 'ApiFormatJson',
116 'none' => 'ApiFormatNone',
119 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
121 * List of user roles that are specifically relevant to the API.
122 * [ 'right' => [ 'msg' => 'Some message with a $1',
123 * 'params' => [ $someVarToSubst ] ],
126 private static $mRights = [
128 'msg' => 'right-writeapi',
132 'msg' => 'api-help-right-apihighlimits',
133 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
136 // @codingStandardsIgnoreEnd
143 private $mModuleMgr, $mResult, $mErrorFormatter;
144 /** @var ApiContinuationManager|null */
145 private $mContinuationManager;
147 private $mEnableWrite;
148 private $mInternalMode, $mSquidMaxage;
152 private $mCacheMode = 'private';
153 private $mCacheControl = [];
154 private $mParamsUsed = [];
156 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
157 private $lacksSameOriginSecurity = null;
160 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
162 * @param IContextSource|WebRequest $context If this is an instance of
163 * FauxRequest, errors are thrown and no printing occurs
164 * @param bool $enableWrite Should be set to true if the api may modify data
166 public function __construct( $context = null, $enableWrite = false ) {
167 if ( $context === null ) {
168 $context = RequestContext
::getMain();
169 } elseif ( $context instanceof WebRequest
) {
172 $context = RequestContext
::getMain();
174 // We set a derivative context so we can change stuff later
175 $this->setContext( new DerivativeContext( $context ) );
177 if ( isset( $request ) ) {
178 $this->getContext()->setRequest( $request );
180 $request = $this->getRequest();
183 $this->mInternalMode
= ( $request instanceof FauxRequest
);
185 // Special handling for the main module: $parent === $this
186 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
188 $config = $this->getConfig();
190 if ( !$this->mInternalMode
) {
191 // Log if a request with a non-whitelisted Origin header is seen
192 // with session cookies.
193 $originHeader = $request->getHeader( 'Origin' );
194 if ( $originHeader === false ) {
197 $originHeader = trim( $originHeader );
198 $origins = preg_split( '/\s+/', $originHeader );
200 $sessionCookies = array_intersect(
201 array_keys( $_COOKIE ),
202 MediaWiki\Session\SessionManager
::singleton()->getVaryCookies()
204 if ( $origins && $sessionCookies && (
205 count( $origins ) !== 1 ||
!self
::matchOrigin(
207 $config->get( 'CrossSiteAJAXdomains' ),
208 $config->get( 'CrossSiteAJAXdomainExceptions' )
211 LoggerFactory
::getInstance( 'cors' )->warning(
212 'Non-whitelisted CORS request with session cookies', [
213 'origin' => $originHeader,
214 'cookies' => $sessionCookies,
215 'ip' => $request->getIP(),
216 'userAgent' => $this->getUserAgent(),
217 'wiki' => wfWikiID(),
222 // If we're in a mode that breaks the same-origin policy, strip
223 // user credentials for security.
224 if ( $this->lacksSameOriginSecurity() ) {
226 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
227 $wgUser = new User();
228 $this->getContext()->setUser( $wgUser );
232 $uselang = $this->getParameter( 'uselang' );
233 if ( $uselang === 'user' ) {
234 // Assume the parent context is going to return the user language
235 // for uselang=user (see T85635).
237 if ( $uselang === 'content' ) {
239 $uselang = $wgContLang->getCode();
241 $code = RequestContext
::sanitizeLangCode( $uselang );
242 $this->getContext()->setLanguage( $code );
243 if ( !$this->mInternalMode
) {
245 $wgLang = $this->getContext()->getLanguage();
246 RequestContext
::getMain()->setLanguage( $wgLang );
250 $this->mModuleMgr
= new ApiModuleManager( $this );
251 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
252 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
253 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
254 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
256 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
258 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
259 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
260 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
261 $this->mResult
->setMainForContinuation( $this );
262 $this->mContinuationManager
= null;
263 $this->mEnableWrite
= $enableWrite;
265 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
266 $this->mCommit
= false;
270 * Return true if the API was started by other PHP code using FauxRequest
273 public function isInternalMode() {
274 return $this->mInternalMode
;
278 * Get the ApiResult object associated with current request
282 public function getResult() {
283 return $this->mResult
;
287 * Get the security flag for the current request
290 public function lacksSameOriginSecurity() {
291 if ( $this->lacksSameOriginSecurity
!== null ) {
292 return $this->lacksSameOriginSecurity
;
295 $request = $this->getRequest();
298 if ( $request->getVal( 'callback' ) !== null ) {
299 $this->lacksSameOriginSecurity
= true;
304 if ( $request->getVal( 'origin' ) === '*' ) {
305 $this->lacksSameOriginSecurity
= true;
309 // Header to be used from XMLHTTPRequest when the request might
310 // otherwise be used for XSS.
311 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
312 $this->lacksSameOriginSecurity
= true;
316 // Allow extensions to override.
317 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
318 return $this->lacksSameOriginSecurity
;
322 * Get the ApiErrorFormatter object associated with current request
323 * @return ApiErrorFormatter
325 public function getErrorFormatter() {
326 return $this->mErrorFormatter
;
330 * Get the continuation manager
331 * @return ApiContinuationManager|null
333 public function getContinuationManager() {
334 return $this->mContinuationManager
;
338 * Set the continuation manager
339 * @param ApiContinuationManager|null
341 public function setContinuationManager( $manager ) {
342 if ( $manager !== null ) {
343 if ( !$manager instanceof ApiContinuationManager
) {
344 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
345 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
348 if ( $this->mContinuationManager
!== null ) {
349 throw new UnexpectedValueException(
350 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
351 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
355 $this->mContinuationManager
= $manager;
359 * Get the API module object. Only works after executeAction()
363 public function getModule() {
364 return $this->mModule
;
368 * Get the result formatter object. Only works after setupExecuteAction()
370 * @return ApiFormatBase
372 public function getPrinter() {
373 return $this->mPrinter
;
377 * Set how long the response should be cached.
381 public function setCacheMaxAge( $maxage ) {
382 $this->setCacheControl( [
383 'max-age' => $maxage,
384 's-maxage' => $maxage
389 * Set the type of caching headers which will be sent.
391 * @param string $mode One of:
392 * - 'public': Cache this object in public caches, if the maxage or smaxage
393 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
394 * not provided by any of these means, the object will be private.
395 * - 'private': Cache this object only in private client-side caches.
396 * - 'anon-public-user-private': Make this object cacheable for logged-out
397 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
398 * set consistently for a given URL, it cannot be set differently depending on
399 * things like the contents of the database, or whether the user is logged in.
401 * If the wiki does not allow anonymous users to read it, the mode set here
402 * will be ignored, and private caching headers will always be sent. In other words,
403 * the "public" mode is equivalent to saying that the data sent is as public as a page
406 * For user-dependent data, the private mode should generally be used. The
407 * anon-public-user-private mode should only be used where there is a particularly
408 * good performance reason for caching the anonymous response, but where the
409 * response to logged-in users may differ, or may contain private data.
411 * If this function is never called, then the default will be the private mode.
413 public function setCacheMode( $mode ) {
414 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
415 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
417 // Ignore for forwards-compatibility
421 if ( !User
::isEveryoneAllowed( 'read' ) ) {
422 // Private wiki, only private headers
423 if ( $mode !== 'private' ) {
424 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
430 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
431 // User language is used for i18n, so we don't want to publicly
432 // cache. Anons are ok, because if they have non-default language
433 // then there's an appropriate Vary header set by whatever set
434 // their non-default language.
435 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
436 "'anon-public-user-private' due to uselang=user\n" );
437 $mode = 'anon-public-user-private';
440 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
441 $this->mCacheMode
= $mode;
445 * Set directives (key/value pairs) for the Cache-Control header.
446 * Boolean values will be formatted as such, by including or omitting
447 * without an equals sign.
449 * Cache control values set here will only be used if the cache mode is not
450 * private, see setCacheMode().
452 * @param array $directives
454 public function setCacheControl( $directives ) {
455 $this->mCacheControl
= $directives +
$this->mCacheControl
;
459 * Create an instance of an output formatter by its name
461 * @param string $format
463 * @return ApiFormatBase
465 public function createPrinterByName( $format ) {
466 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
467 if ( $printer === null ) {
468 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
475 * Execute api request. Any errors will be handled if the API was called by the remote client.
477 public function execute() {
478 if ( $this->mInternalMode
) {
479 $this->executeAction();
481 $this->executeActionWithErrorHandling();
486 * Execute an action, and in case of an error, erase whatever partial results
487 * have been accumulated, and replace it with an error message and a help screen.
489 protected function executeActionWithErrorHandling() {
490 // Verify the CORS header before executing the action
491 if ( !$this->handleCORS() ) {
492 // handleCORS() has sent a 403, abort
496 // Exit here if the request method was OPTIONS
497 // (assume there will be a followup GET or POST)
498 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
502 // In case an error occurs during data output,
503 // clear the output buffer and print just the error information
504 $obLevel = ob_get_level();
507 $t = microtime( true );
510 $this->executeAction();
511 $runTime = microtime( true ) - $t;
512 $this->logRequest( $runTime );
513 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
514 $this->getStats()->timing(
515 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
518 } catch ( Exception
$e ) {
519 $this->handleException( $e );
520 $this->logRequest( microtime( true ) - $t, $e );
524 // Commit DBs and send any related cookies and headers
525 MediaWiki
::preOutputCommit( $this->getContext() );
527 // Send cache headers after any code which might generate an error, to
528 // avoid sending public cache headers for errors.
529 $this->sendCacheHeaders( $isError );
531 // Executing the action might have already messed with the output
533 while ( ob_get_level() > $obLevel ) {
539 * Handle an exception as an API response
542 * @param Exception $e
544 protected function handleException( Exception
$e ) {
545 // Bug 63145: Rollback any open database transactions
546 if ( !( $e instanceof UsageException
) ) {
547 // UsageExceptions are intentional, so don't rollback if that's the case
549 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
550 } catch ( DBError
$e2 ) {
551 // Rollback threw an exception too. Log it, but don't interrupt
552 // our regularly scheduled exception handling.
553 MWExceptionHandler
::logException( $e2 );
557 // Allow extra cleanup and logging
558 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
561 if ( !( $e instanceof UsageException
) ) {
562 MWExceptionHandler
::logException( $e );
565 // Handle any kind of exception by outputting properly formatted error message.
566 // If this fails, an unhandled exception should be thrown so that global error
567 // handler will process and log it.
569 $errCode = $this->substituteResultWithError( $e );
571 // Error results should not be cached
572 $this->setCacheMode( 'private' );
574 $response = $this->getRequest()->response();
575 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
576 if ( $e->getCode() === 0 ) {
577 $response->header( $headerStr );
579 $response->header( $headerStr, true, $e->getCode() );
582 // Reset and print just the error message
585 // Printer may not be initialized if the extractRequestParams() fails for the main module
586 $this->createErrorPrinter();
589 $this->printResult( true );
590 } catch ( UsageException
$ex ) {
591 // The error printer itself is failing. Try suppressing its request
592 // parameters and redo.
594 'Error printer failed (will retry without params): ' . $ex->getMessage()
596 $this->mPrinter
= null;
597 $this->createErrorPrinter();
598 $this->mPrinter
->forceDefaultParams();
599 $this->printResult( true );
604 * Handle an exception from the ApiBeforeMain hook.
606 * This tries to print the exception as an API response, to be more
607 * friendly to clients. If it fails, it will rethrow the exception.
610 * @param Exception $e
613 public static function handleApiBeforeMainException( Exception
$e ) {
617 $main = new self( RequestContext
::getMain(), false );
618 $main->handleException( $e );
619 $main->logRequest( 0, $e );
620 } catch ( Exception
$e2 ) {
621 // Nope, even that didn't work. Punt.
625 // Reset cache headers
626 $main->sendCacheHeaders( true );
632 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
634 * If no origin parameter is present, nothing happens.
635 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
636 * is set and false is returned.
637 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
638 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
640 * http://www.w3.org/TR/cors/#resource-requests
641 * http://www.w3.org/TR/cors/#resource-preflight-requests
643 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
645 protected function handleCORS() {
646 $originParam = $this->getParameter( 'origin' ); // defaults to null
647 if ( $originParam === null ) {
648 // No origin parameter, nothing to do
652 $request = $this->getRequest();
653 $response = $request->response();
655 $matchOrigin = false;
656 $allowTiming = false;
659 if ( $originParam === '*' ) {
660 // Request for anonymous CORS
663 $allowCredentials = 'false';
664 $varyOrigin = false; // No need to vary
666 // Non-anonymous CORS, check we allow the domain
668 // Origin: header is a space-separated list of origins, check all of them
669 $originHeader = $request->getHeader( 'Origin' );
670 if ( $originHeader === false ) {
673 $originHeader = trim( $originHeader );
674 $origins = preg_split( '/\s+/', $originHeader );
677 if ( !in_array( $originParam, $origins ) ) {
678 // origin parameter set but incorrect
679 // Send a 403 response
680 $response->statusHeader( 403 );
681 $response->header( 'Cache-Control: no-cache' );
682 echo "'origin' parameter does not match Origin header\n";
687 $config = $this->getConfig();
688 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
690 $config->get( 'CrossSiteAJAXdomains' ),
691 $config->get( 'CrossSiteAJAXdomainExceptions' )
694 $allowOrigin = $originHeader;
695 $allowCredentials = 'true';
696 $allowTiming = $originHeader;
699 if ( $matchOrigin ) {
700 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
701 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
703 // This is a CORS preflight request
704 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
705 // If method is not a case-sensitive match, do not set any additional headers and terminate.
708 // We allow the actual request to send the following headers
709 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
710 if ( $requestedHeaders !== false ) {
711 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
714 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
717 // We only allow the actual request to be GET or POST
718 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
721 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
722 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
723 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
724 if ( $allowTiming !== false ) {
725 $response->header( "Timing-Allow-Origin: $allowTiming" );
730 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
736 $this->getOutput()->addVaryHeader( 'Origin' );
743 * Attempt to match an Origin header against a set of rules and a set of exceptions
744 * @param string $value Origin header
745 * @param array $rules Set of wildcard rules
746 * @param array $exceptions Set of wildcard rules
747 * @return bool True if $value matches a rule in $rules and doesn't match
748 * any rules in $exceptions, false otherwise
750 protected static function matchOrigin( $value, $rules, $exceptions ) {
751 foreach ( $rules as $rule ) {
752 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
753 // Rule matches, check exceptions
754 foreach ( $exceptions as $exc ) {
755 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
768 * Attempt to validate the value of Access-Control-Request-Headers against a list
769 * of headers that we allow the follow up request to send.
771 * @param string $requestedHeaders Comma seperated list of HTTP headers
772 * @return bool True if all requested headers are in the list of allowed headers
774 protected static function matchRequestedHeaders( $requestedHeaders ) {
775 if ( trim( $requestedHeaders ) === '' ) {
778 $requestedHeaders = explode( ',', $requestedHeaders );
779 $allowedAuthorHeaders = array_flip( [
780 /* simple headers (see spec) */
785 /* non-authorable headers in XHR, which are however requested by some UAs */
789 /* MediaWiki whitelist */
792 foreach ( $requestedHeaders as $rHeader ) {
793 $rHeader = strtolower( trim( $rHeader ) );
794 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
795 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
803 * Helper function to convert wildcard string into a regex
807 * @param string $wildcard String with wildcards
808 * @return string Regular expression
810 protected static function wildcardToRegex( $wildcard ) {
811 $wildcard = preg_quote( $wildcard, '/' );
812 $wildcard = str_replace(
818 return "/^https?:\/\/$wildcard$/";
822 * Send caching headers
823 * @param bool $isError Whether an error response is being output
824 * @since 1.26 added $isError parameter
826 protected function sendCacheHeaders( $isError ) {
827 $response = $this->getRequest()->response();
828 $out = $this->getOutput();
830 $out->addVaryHeader( 'Treat-as-Untrusted' );
832 $config = $this->getConfig();
834 if ( $config->get( 'VaryOnXFP' ) ) {
835 $out->addVaryHeader( 'X-Forwarded-Proto' );
838 if ( !$isError && $this->mModule
&&
839 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
841 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
842 if ( $etag !== null ) {
843 $response->header( "ETag: $etag" );
845 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
846 if ( $lastMod !== null ) {
847 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
851 // The logic should be:
852 // $this->mCacheControl['max-age'] is set?
853 // Use it, the module knows better than our guess.
854 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
855 // Use 0 because we can guess caching is probably the wrong thing to do.
856 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
858 if ( isset( $this->mCacheControl
['max-age'] ) ) {
859 $maxage = $this->mCacheControl
['max-age'];
860 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
861 $this->mCacheMode
!== 'private'
863 $maxage = $this->getParameter( 'maxage' );
865 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
867 if ( $this->mCacheMode
== 'private' ) {
868 $response->header( "Cache-Control: $privateCache" );
872 $useKeyHeader = $config->get( 'UseKeyHeader' );
873 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
874 $out->addVaryHeader( 'Cookie' );
875 $response->header( $out->getVaryHeader() );
876 if ( $useKeyHeader ) {
877 $response->header( $out->getKeyHeader() );
878 if ( $out->haveCacheVaryCookies() ) {
879 // Logged in, mark this request private
880 $response->header( "Cache-Control: $privateCache" );
883 // Logged out, send normal public headers below
884 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
885 // Logged in or otherwise has session (e.g. anonymous users who have edited)
886 // Mark request private
887 $response->header( "Cache-Control: $privateCache" );
890 } // else no Key and anonymous, send public headers below
893 // Send public headers
894 $response->header( $out->getVaryHeader() );
895 if ( $useKeyHeader ) {
896 $response->header( $out->getKeyHeader() );
899 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
900 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
901 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
903 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
904 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
907 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
908 // Public cache not requested
909 // Sending a Vary header in this case is harmless, and protects us
910 // against conditional calls of setCacheMaxAge().
911 $response->header( "Cache-Control: $privateCache" );
916 $this->mCacheControl
['public'] = true;
918 // Send an Expires header
919 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
920 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
921 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
923 // Construct the Cache-Control header
926 foreach ( $this->mCacheControl
as $name => $value ) {
927 if ( is_bool( $value ) ) {
929 $ccHeader .= $separator . $name;
933 $ccHeader .= $separator . "$name=$value";
938 $response->header( "Cache-Control: $ccHeader" );
942 * Create the printer for error output
944 private function createErrorPrinter() {
945 if ( !isset( $this->mPrinter
) ) {
946 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
947 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
948 $value = self
::API_DEFAULT_FORMAT
;
950 $this->mPrinter
= $this->createPrinterByName( $value );
953 // Printer may not be able to handle errors. This is particularly
954 // likely if the module returns something for getCustomPrinter().
955 if ( !$this->mPrinter
->canPrintErrors() ) {
956 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
961 * Create an error message for the given exception.
963 * If the exception is a UsageException then
964 * UsageException::getMessageArray() will be called to create the message.
966 * @param Exception $e
967 * @return array ['code' => 'some string', 'info' => 'some other string']
970 protected function errorMessageFromException( $e ) {
971 if ( $e instanceof UsageException
) {
972 // User entered incorrect parameters - generate error response
973 $errMessage = $e->getMessageArray();
975 $config = $this->getConfig();
976 // Something is seriously wrong
977 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
978 $info = 'Database query error';
980 $info = "Exception Caught: {$e->getMessage()}";
984 'code' => 'internal_api_error_' . get_class( $e ),
985 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
992 * Replace the result data with the information about an exception.
993 * Returns the error code
994 * @param Exception $e
997 protected function substituteResultWithError( $e ) {
998 $result = $this->getResult();
999 $config = $this->getConfig();
1001 $errMessage = $this->errorMessageFromException( $e );
1002 if ( $e instanceof UsageException
) {
1003 // User entered incorrect parameters - generate error response
1004 $link = wfExpandUrl( wfScript( 'api' ) );
1005 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
1007 // Something is seriously wrong
1008 if ( $config->get( 'ShowExceptionDetails' ) ) {
1009 ApiResult
::setContentValue(
1012 MWExceptionHandler
::getRedactedTraceAsString( $e )
1017 // Remember all the warnings to re-add them later
1018 $warnings = $result->getResultData( [ 'warnings' ] );
1022 $requestid = $this->getParameter( 'requestid' );
1023 if ( !is_null( $requestid ) ) {
1024 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
1026 if ( $config->get( 'ShowHostnames' ) ) {
1027 // servedby is especially useful when debugging errors
1028 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
1030 if ( $warnings !== null ) {
1031 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
1034 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
1036 return $errMessage['code'];
1040 * Set up for the execution.
1043 protected function setupExecuteAction() {
1044 // First add the id to the top element
1045 $result = $this->getResult();
1046 $requestid = $this->getParameter( 'requestid' );
1047 if ( !is_null( $requestid ) ) {
1048 $result->addValue( null, 'requestid', $requestid );
1051 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1052 $servedby = $this->getParameter( 'servedby' );
1054 $result->addValue( null, 'servedby', wfHostname() );
1058 if ( $this->getParameter( 'curtimestamp' ) ) {
1059 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1060 ApiResult
::NO_SIZE_CHECK
);
1063 $params = $this->extractRequestParams();
1065 $this->mAction
= $params['action'];
1067 if ( !is_string( $this->mAction
) ) {
1068 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1075 * Set up the module for response
1076 * @return ApiBase The module that will handle this action
1077 * @throws MWException
1078 * @throws UsageException
1080 protected function setupModule() {
1081 // Instantiate the module requested by the user
1082 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1083 if ( $module === null ) {
1084 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1086 $moduleParams = $module->extractRequestParams();
1088 // Check token, if necessary
1089 if ( $module->needsToken() === true ) {
1090 throw new MWException(
1091 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1092 'See documentation for ApiBase::needsToken for details.'
1095 if ( $module->needsToken() ) {
1096 if ( !$module->mustBePosted() ) {
1097 throw new MWException(
1098 "Module '{$module->getModuleName()}' must require POST to use tokens."
1102 if ( !isset( $moduleParams['token'] ) ) {
1103 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1106 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1108 $module->encodeParamName( 'token' ),
1109 $this->getRequest()->getQueryValues()
1113 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1114 'found in the query string, but must be in the POST body',
1119 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1120 $this->dieUsageMsg( 'sessionfailure' );
1128 * Check the max lag if necessary
1129 * @param ApiBase $module Api module being used
1130 * @param array $params Array an array containing the request parameters.
1131 * @return bool True on success, false should exit immediately
1133 protected function checkMaxLag( $module, $params ) {
1134 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1135 $maxLag = $params['maxlag'];
1136 list( $host, $lag ) = wfGetLB()->getMaxLag();
1137 if ( $lag > $maxLag ) {
1138 $response = $this->getRequest()->response();
1140 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1141 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1143 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1144 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1147 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1155 * Check selected RFC 7232 precondition headers
1157 * RFC 7232 envisions a particular model where you send your request to "a
1158 * resource", and for write requests that you can read "the resource" by
1159 * changing the method to GET. When the API receives a GET request, it
1160 * works out even though "the resource" from RFC 7232's perspective might
1161 * be many resources from MediaWiki's perspective. But it totally fails for
1162 * a POST, since what HTTP sees as "the resource" is probably just
1163 * "/api.php" with all the interesting bits in the body.
1165 * Therefore, we only support RFC 7232 precondition headers for GET (and
1166 * HEAD). That means we don't need to bother with If-Match and
1167 * If-Unmodified-Since since they only apply to modification requests.
1169 * And since we don't support Range, If-Range is ignored too.
1172 * @param ApiBase $module Api module being used
1173 * @return bool True on success, false should exit immediately
1175 protected function checkConditionalRequestHeaders( $module ) {
1176 if ( $this->mInternalMode
) {
1177 // No headers to check in internal mode
1181 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1182 // Don't check POSTs
1188 $ifNoneMatch = array_diff(
1189 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1192 if ( $ifNoneMatch ) {
1193 if ( $ifNoneMatch === [ '*' ] ) {
1194 // API responses always "exist"
1197 $etag = $module->getConditionalRequestData( 'etag' );
1200 if ( $ifNoneMatch && $etag !== null ) {
1201 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1202 $match = array_map( function ( $s ) {
1203 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1205 $return304 = in_array( $test, $match, true );
1207 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1209 // Some old browsers sends sizes after the date, like this:
1210 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1212 $i = strpos( $value, ';' );
1213 if ( $i !== false ) {
1214 $value = trim( substr( $value, 0, $i ) );
1217 if ( $value !== '' ) {
1219 $ts = new MWTimestamp( $value );
1221 // RFC 7231 IMF-fixdate
1222 $ts->getTimestamp( TS_RFC2822
) === $value ||
1224 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1225 // asctime (with and without space-padded day)
1226 $ts->format( 'D M j H:i:s Y' ) === $value ||
1227 $ts->format( 'D M j H:i:s Y' ) === $value
1229 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1230 if ( $lastMod !== null ) {
1231 // Mix in some MediaWiki modification times
1234 'user' => $this->getUser()->getTouched(),
1235 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1237 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1238 // T46570: the core page itself may not change, but resources might
1239 $modifiedTimes['sepoch'] = wfTimestamp(
1240 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1243 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1244 $lastMod = max( $modifiedTimes );
1245 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1248 } catch ( TimestampException
$e ) {
1249 // Invalid timestamp, ignore it
1255 $this->getRequest()->response()->statusHeader( 304 );
1257 // Avoid outputting the compressed representation of a zero-length body
1258 MediaWiki\
suppressWarnings();
1259 ini_set( 'zlib.output_compression', 0 );
1260 MediaWiki\restoreWarnings
();
1261 wfClearOutputBuffers();
1270 * Check for sufficient permissions to execute
1271 * @param ApiBase $module An Api module
1273 protected function checkExecutePermissions( $module ) {
1274 $user = $this->getUser();
1275 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1276 !$user->isAllowed( 'read' )
1278 $this->dieUsageMsg( 'readrequired' );
1281 if ( $module->isWriteMode() ) {
1282 if ( !$this->mEnableWrite
) {
1283 $this->dieUsageMsg( 'writedisabled' );
1284 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1285 $this->dieUsageMsg( 'writerequired' );
1286 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1288 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1289 'promised-nonwrite-api'
1293 $this->checkReadOnly( $module );
1296 // Allow extensions to stop execution for arbitrary reasons.
1298 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1299 $this->dieUsageMsg( $message );
1304 * Check if the DB is read-only for this user
1305 * @param ApiBase $module An Api module
1307 protected function checkReadOnly( $module ) {
1308 if ( wfReadOnly() ) {
1309 $this->dieReadOnly();
1312 if ( $module->isWriteMode()
1313 && in_array( 'bot', $this->getUser()->getGroups() )
1314 && wfGetLB()->getServerCount() > 1
1316 $this->checkBotReadOnly();
1321 * Check whether we are readonly for bots
1323 private function checkBotReadOnly() {
1324 // Figure out how many servers have passed the lag threshold
1326 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1327 $laggedServers = [];
1328 $loadBalancer = wfGetLB();
1329 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1330 if ( $lag > $lagLimit ) {
1332 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1336 // If a majority of slaves are too lagged then disallow writes
1337 $slaveCount = wfGetLB()->getServerCount() - 1;
1338 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1339 $laggedServers = implode( ', ', $laggedServers );
1342 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1345 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1351 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1357 * Check asserts of the user's rights
1358 * @param array $params
1360 protected function checkAsserts( $params ) {
1361 if ( isset( $params['assert'] ) ) {
1362 $user = $this->getUser();
1363 switch ( $params['assert'] ) {
1365 if ( $user->isAnon() ) {
1366 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1370 if ( !$user->isAllowed( 'bot' ) ) {
1371 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1379 * Check POST for external response and setup result printer
1380 * @param ApiBase $module An Api module
1381 * @param array $params An array with the request parameters
1383 protected function setupExternalResponse( $module, $params ) {
1384 $request = $this->getRequest();
1385 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1386 // Module requires POST. GET request might still be allowed
1387 // if $wgDebugApi is true, otherwise fail.
1388 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1391 // See if custom printer is used
1392 $this->mPrinter
= $module->getCustomPrinter();
1393 if ( is_null( $this->mPrinter
) ) {
1394 // Create an appropriate printer
1395 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1398 if ( $request->getProtocol() === 'http' && (
1399 $request->getSession()->shouldForceHTTPS() ||
1400 ( $this->getUser()->isLoggedIn() &&
1401 $this->getUser()->requiresHTTPS() )
1403 $this->logFeatureUsage( 'https-expected' );
1404 $this->setWarning( 'HTTP used when HTTPS was expected' );
1409 * Execute the actual module, without any error handling
1411 protected function executeAction() {
1412 $params = $this->setupExecuteAction();
1413 $module = $this->setupModule();
1414 $this->mModule
= $module;
1416 if ( !$this->mInternalMode
) {
1417 $this->setRequestExpectations( $module );
1420 $this->checkExecutePermissions( $module );
1422 if ( !$this->checkMaxLag( $module, $params ) ) {
1426 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1430 if ( !$this->mInternalMode
) {
1431 $this->setupExternalResponse( $module, $params );
1434 $this->checkAsserts( $params );
1438 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1440 $this->reportUnusedParams();
1442 if ( !$this->mInternalMode
) {
1443 // append Debug information
1444 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1446 // Print result data
1447 $this->printResult( false );
1452 * Set database connection, query, and write expectations given this module request
1453 * @param ApiBase $module
1455 protected function setRequestExpectations( ApiBase
$module ) {
1456 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1457 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1458 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
1459 if ( $this->getRequest()->hasSafeMethod() ) {
1460 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1461 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1462 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1463 $this->getRequest()->markAsSafeRequest();
1465 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1470 * Log the preceding request
1471 * @param float $time Time in seconds
1472 * @param Exception $e Exception caught while processing the request
1474 protected function logRequest( $time, $e = null ) {
1475 $request = $this->getRequest();
1478 'ip' => $request->getIP(),
1479 'userAgent' => $this->getUserAgent(),
1480 'wiki' => wfWikiID(),
1481 'timeSpentBackend' => (int) round( $time * 1000 ),
1482 'hadError' => $e !== null,
1488 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1491 // Construct space separated message for 'api' log channel
1492 $msg = "API {$request->getMethod()} " .
1493 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1494 " {$logCtx['ip']} " .
1495 "T={$logCtx['timeSpentBackend']}ms";
1497 foreach ( $this->getParamsUsed() as $name ) {
1498 $value = $request->getVal( $name );
1499 if ( $value === null ) {
1503 if ( strlen( $value ) > 256 ) {
1504 $value = substr( $value, 0, 256 );
1505 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1507 $encValue = $this->encodeRequestLogValue( $value );
1510 $logCtx['params'][$name] = $value;
1511 $msg .= " {$name}={$encValue}";
1514 wfDebugLog( 'api', $msg, 'private' );
1515 // ApiAction channel is for structured data consumers
1516 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1520 * Encode a value in a format suitable for a space-separated log line.
1524 protected function encodeRequestLogValue( $s ) {
1527 $chars = ';@$!*(),/:';
1528 $numChars = strlen( $chars );
1529 for ( $i = 0; $i < $numChars; $i++
) {
1530 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1534 return strtr( rawurlencode( $s ), $table );
1538 * Get the request parameters used in the course of the preceding execute() request
1541 protected function getParamsUsed() {
1542 return array_keys( $this->mParamsUsed
);
1546 * Mark parameters as used
1547 * @param string|string[] $params
1549 public function markParamsUsed( $params ) {
1550 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1554 * Get a request value, and register the fact that it was used, for logging.
1555 * @param string $name
1556 * @param mixed $default
1559 public function getVal( $name, $default = null ) {
1560 $this->mParamsUsed
[$name] = true;
1562 $ret = $this->getRequest()->getVal( $name );
1563 if ( $ret === null ) {
1564 if ( $this->getRequest()->getArray( $name ) !== null ) {
1565 // See bug 10262 for why we don't just implode( '|', ... ) the
1568 "Parameter '$name' uses unsupported PHP array syntax"
1577 * Get a boolean request value, and register the fact that the parameter
1578 * was used, for logging.
1579 * @param string $name
1582 public function getCheck( $name ) {
1583 return $this->getVal( $name, null ) !== null;
1587 * Get a request upload, and register the fact that it was used, for logging.
1590 * @param string $name Parameter name
1591 * @return WebRequestUpload
1593 public function getUpload( $name ) {
1594 $this->mParamsUsed
[$name] = true;
1596 return $this->getRequest()->getUpload( $name );
1600 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1601 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1603 protected function reportUnusedParams() {
1604 $paramsUsed = $this->getParamsUsed();
1605 $allParams = $this->getRequest()->getValueNames();
1607 if ( !$this->mInternalMode
) {
1608 // Printer has not yet executed; don't warn that its parameters are unused
1609 $printerParams = array_map(
1610 [ $this->mPrinter
, 'encodeParamName' ],
1611 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1613 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1615 $unusedParams = array_diff( $allParams, $paramsUsed );
1618 if ( count( $unusedParams ) ) {
1619 $s = count( $unusedParams ) > 1 ?
's' : '';
1620 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1625 * Print results using the current printer
1627 * @param bool $isError
1629 protected function printResult( $isError ) {
1630 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1631 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1634 $printer = $this->mPrinter
;
1635 $printer->initPrinter( false );
1636 $printer->execute();
1637 $printer->closePrinter();
1643 public function isReadMode() {
1648 * See ApiBase for description.
1652 public function getAllowedParams() {
1655 ApiBase
::PARAM_DFLT
=> 'help',
1656 ApiBase
::PARAM_TYPE
=> 'submodule',
1659 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1660 ApiBase
::PARAM_TYPE
=> 'submodule',
1663 ApiBase
::PARAM_TYPE
=> 'integer'
1666 ApiBase
::PARAM_TYPE
=> 'integer',
1667 ApiBase
::PARAM_DFLT
=> 0
1670 ApiBase
::PARAM_TYPE
=> 'integer',
1671 ApiBase
::PARAM_DFLT
=> 0
1674 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1676 'requestid' => null,
1677 'servedby' => false,
1678 'curtimestamp' => false,
1681 ApiBase
::PARAM_DFLT
=> 'user',
1686 /** @see ApiBase::getExamplesMessages() */
1687 protected function getExamplesMessages() {
1690 => 'apihelp-help-example-main',
1691 'action=help&recursivesubmodules=1'
1692 => 'apihelp-help-example-recursive',
1696 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1697 // Wish PHP had an "array_insert_before". Instead, we have to manually
1698 // reindex the array to get 'permissions' in the right place.
1701 foreach ( $oldHelp as $k => $v ) {
1702 if ( $k === 'submodules' ) {
1703 $help['permissions'] = '';
1707 $help['datatypes'] = '';
1708 $help['credits'] = '';
1710 // Fill 'permissions'
1711 $help['permissions'] .= Html
::openElement( 'div',
1712 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1713 $m = $this->msg( 'api-help-permissions' );
1714 if ( !$m->isDisabled() ) {
1715 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1716 $m->numParams( count( self
::$mRights ) )->parse()
1719 $help['permissions'] .= Html
::openElement( 'dl' );
1720 foreach ( self
::$mRights as $right => $rightMsg ) {
1721 $help['permissions'] .= Html
::element( 'dt', null, $right );
1723 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1724 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1726 $groups = array_map( function ( $group ) {
1727 return $group == '*' ?
'all' : $group;
1728 }, User
::getGroupsWithPermission( $right ) );
1730 $help['permissions'] .= Html
::rawElement( 'dd', null,
1731 $this->msg( 'api-help-permissions-granted-to' )
1732 ->numParams( count( $groups ) )
1733 ->params( $this->getLanguage()->commaList( $groups ) )
1737 $help['permissions'] .= Html
::closeElement( 'dl' );
1738 $help['permissions'] .= Html
::closeElement( 'div' );
1740 // Fill 'datatypes' and 'credits', if applicable
1741 if ( empty( $options['nolead'] ) ) {
1742 $level = $options['headerlevel'];
1743 $tocnumber = &$options['tocnumber'];
1745 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1747 // Add an additional span with sanitized ID
1748 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1749 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1752 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1753 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1756 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1757 if ( !isset( $tocData['main/datatypes'] ) ) {
1758 $tocnumber[$level]++
;
1759 $tocData['main/datatypes'] = [
1760 'toclevel' => count( $tocnumber ),
1762 'anchor' => 'main/datatypes',
1764 'number' => implode( '.', $tocnumber ),
1769 // Add an additional span with sanitized ID
1770 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1771 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1774 $header = $this->msg( 'api-credits-header' )->parse();
1775 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1776 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1779 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1780 if ( !isset( $tocData['main/credits'] ) ) {
1781 $tocnumber[$level]++
;
1782 $tocData['main/credits'] = [
1783 'toclevel' => count( $tocnumber ),
1785 'anchor' => 'main/credits',
1787 'number' => implode( '.', $tocnumber ),
1794 private $mCanApiHighLimits = null;
1797 * Check whether the current user is allowed to use high limits
1800 public function canApiHighLimits() {
1801 if ( !isset( $this->mCanApiHighLimits
) ) {
1802 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1805 return $this->mCanApiHighLimits
;
1809 * Overrides to return this instance's module manager.
1810 * @return ApiModuleManager
1812 public function getModuleManager() {
1813 return $this->mModuleMgr
;
1817 * Fetches the user agent used for this request
1819 * The value will be the combination of the 'Api-User-Agent' header (if
1820 * any) and the standard User-Agent header (if any).
1824 public function getUserAgent() {
1826 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1827 $this->getRequest()->getHeader( 'User-agent' )
1831 /************************************************************************//**
1837 * Sets whether the pretty-printer should format *bold* and $italics$
1839 * @deprecated since 1.25
1842 public function setHelp( $help = true ) {
1843 wfDeprecated( __METHOD__
, '1.25' );
1844 $this->mPrinter
->setHelp( $help );
1848 * Override the parent to generate help messages for all available modules.
1850 * @deprecated since 1.25
1853 public function makeHelpMsg() {
1854 wfDeprecated( __METHOD__
, '1.25' );
1857 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1859 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1862 $this->getModuleName(),
1863 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1865 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1866 [ $this, 'reallyMakeHelpMsg' ]
1871 * @deprecated since 1.25
1872 * @return mixed|string
1874 public function reallyMakeHelpMsg() {
1875 wfDeprecated( __METHOD__
, '1.25' );
1878 // Use parent to make default message for the main module
1879 $msg = parent
::makeHelpMsg();
1881 $asterisks = str_repeat( '*** ', 14 );
1882 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1884 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1885 $module = $this->mModuleMgr
->getModule( $name );
1886 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1888 $msg2 = $module->makeHelpMsg();
1889 if ( $msg2 !== false ) {
1895 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1896 foreach ( self
::$mRights as $right => $rightMsg ) {
1897 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1898 ->useDatabase( false )
1899 ->inLanguage( 'en' )
1901 $groups = User
::getGroupsWithPermission( $right );
1902 $msg .= '* ' . $right . " *\n $rightsMsg" .
1903 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1906 $msg .= "\n$asterisks Formats $asterisks\n\n";
1907 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1908 $module = $this->mModuleMgr
->getModule( $name );
1909 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1910 $msg2 = $module->makeHelpMsg();
1911 if ( $msg2 !== false ) {
1917 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1918 $credits = str_replace( "\n", "\n ", $credits );
1919 $msg .= "\n*** Credits: ***\n $credits\n";
1925 * @deprecated since 1.25
1926 * @param ApiBase $module
1927 * @param string $paramName What type of request is this? e.g. action,
1928 * query, list, prop, meta, format
1931 public static function makeHelpMsgHeader( $module, $paramName ) {
1932 wfDeprecated( __METHOD__
, '1.25' );
1933 $modulePrefix = $module->getModulePrefix();
1934 if ( strval( $modulePrefix ) !== '' ) {
1935 $modulePrefix = "($modulePrefix) ";
1938 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1946 * This exception will be thrown when dieUsage is called to stop module execution.
1950 class UsageException
extends MWException
{
1957 private $mExtraData;
1960 * @param string $message
1961 * @param string $codestr
1963 * @param array|null $extradata
1965 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1966 parent
::__construct( $message, $code );
1967 $this->mCodestr
= $codestr;
1968 $this->mExtraData
= $extradata;
1970 // This should never happen, so throw an exception about it that will
1971 // hopefully get logged with a backtrace (T138585)
1972 if ( !is_string( $codestr ) ||
$codestr === '' ) {
1973 throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1974 ( $codestr === '' ?
'empty string' : gettype( $codestr ) )
1982 public function getCodeString() {
1983 return $this->mCodestr
;
1989 public function getMessageArray() {
1991 'code' => $this->mCodestr
,
1992 'info' => $this->getMessage()
1994 if ( is_array( $this->mExtraData
) ) {
1995 $result = array_merge( $result, $this->mExtraData
);
2004 public function __toString() {
2005 return "{$this->getCodeString()}: {$this->getMessage()}";
2010 * For really cool vim folding this needs to be at the end:
2011 * vim: foldmarker=@{,@} foldmethod=marker