MediaWiki fundraising/REL1_35
ApiMain Class Reference

This is the main API class, used for both external and internal processing. More...

Inheritance diagram for ApiMain:
Collaboration diagram for ApiMain:

Public Member Functions

 __construct ( $context=null, $enableWrite=false)
 Constructs an instance of ApiMain that utilizes the module and format specified by $request.
 
 canApiHighLimits ()
 Check whether the current user is allowed to use high limits.
 
 createPrinterByName ( $format)
 Create an instance of an output formatter by its name.
 
 execute ()
 Execute api request.
 
 getAllowedParams ()
 See ApiBase for description.
 
 getCheck ( $name)
 Get a boolean request value, and register the fact that the parameter was used, for logging.
 
 getContinuationManager ()
 Get the continuation manager.
 
 getErrorFormatter ()
 Get the ApiErrorFormatter object associated with current request.
 
 getModule ()
 Get the API module object.
 
 getModuleManager ()
 Overrides to return this instance's module manager.
 
 getParamValidator ()
 Get the parameter validator.
 
 getPrinter ()
 Get the result formatter object.
 
 getResult ()
 Get the ApiResult object associated with current request.
 
 getUpload ( $name)
 Get a request upload, and register the fact that it was used, for logging.
 
 getUserAgent ()
 Fetches the user agent used for this request.
 
 getVal ( $name, $default=null)
 Get a request value, and register the fact that it was used, for logging.
 
 isInternalMode ()
 Return true if the API was started by other PHP code using FauxRequest.
 
 isReadMode ()
 
 lacksSameOriginSecurity ()
 Get the security flag for the current request.
 
 markParamsSensitive ( $params)
 Mark parameters as sensitive.
 
 markParamsUsed ( $params)
 Mark parameters as used.
 
 modifyHelp (array &$help, array $options, array &$tocData)
 Called from ApiHelp before the pieces are joined together and returned.This exists mainly for ApiMain to add the Permissions and Credits sections. Other modules probably don't need it.Stable to override

Parameters
string[]&$helpArray of help data
array$optionsOptions passed to ApiHelp::getHelp
array&$tocDataIf a TOC is being generated, this array has keys as anchors in the page and values as for Linker::generateTOC().
-param array{nolead?:bool,headerlevel?:int,tocnumber?:int[]} $options
 
 setCacheControl ( $directives)
 Set directives (key/value pairs) for the Cache-Control header.
 
 setCacheMaxAge ( $maxage)
 Set how long the response should be cached.
 
 setCacheMode ( $mode)
 Set the type of caching headers which will be sent.
 
 setContinuationManager (ApiContinuationManager $manager=null)
 Set the continuation manager.
 
- Public Member Functions inherited from ApiBase
 __construct (ApiMain $mainModule, $moduleName, $modulePrefix='')
 Stable to call.
 
 getCustomPrinter ()
 If the module may only be used with a certain format module, it should override this method to return an instance of that formatter.
 
 getHelpUrls ()
 Return links to more detailed help pages about the module.
 
 shouldCheckMaxlag ()
 Indicates if this module needs maxlag to be checked Stable to override.
 
 isWriteMode ()
 Indicates whether this module requires write mode.
 
 mustBePosted ()
 Indicates whether this module must be called with a POST request Stable to override.
 
 isDeprecated ()
 Indicates whether this module is deprecated.
 
 isInternal ()
 Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party use and may be unstable.
 
 needsToken ()
 Returns the token type this module requires in order to execute.
 
 getConditionalRequestData ( $condition)
 Returns data for HTTP conditional request mechanisms.
 
 getModuleName ()
 Get the name of the module being executed by this instance.
 
 getModulePrefix ()
 Get parameter prefix (usually two letters or an empty string).
 
 getMain ()
 Get the main module.
 
 isMain ()
 Returns true if this module is the main module ($this === $this->mMainModule), false otherwise.
 
 getParent ()
 Get the parent of this module Stable to override.
 
 getModulePath ()
 Get the path to this module.
 
 getModuleFromPath ( $path)
 Get a module from its module path.
 
 dynamicParameterDocumentation ()
 Indicate if the module supports dynamically-determined parameters that cannot be included in self::getAllowedParams().
 
 encodeParamName ( $paramName)
 This method mangles parameter name based on the prefix supplied to the constructor.
 
 extractRequestParams ( $options=[])
 Using getAllowedParams(), this function makes an array of the values provided by the user, with key being the name of the variable, and value - validated value from user or default.
 
 requireOnlyOneParameter ( $params,... $required)
 Die if none or more than one of a certain set of parameters is set and not false.
 
 requireMaxOneParameter ( $params,... $required)
 Die if more than one of a certain set of parameters is set and not false.
 
 requireAtLeastOneParameter ( $params,... $required)
 Die if none of a certain set of parameters is set and not false.
 
 requirePostedParameters ( $params, $prefix='prefix')
 Die if any of the specified parameters were found in the query part of the URL rather than the post body.
 
 getTitleOrPageId ( $params, $load=false)
 Get a WikiPage object from a title or pageid param, if possible.
 
 getTitleFromTitleOrPageId ( $params)
 Get a Title object from a title or pageid param, if possible.
 
 handleParamNormalization ( $paramName, $value, $rawValue)
 Handle when a parameter was Unicode-normalized.
 
 validateToken ( $token, array $params)
 Validate the supplied token.
 
 getWatchlistUser ( $params)
 Gets the user for whom to get the watchlist.
 
 errorArrayToStatus (array $errors, User $user=null)
 Turn an array of message keys or key+param arrays into a Status.
 
 addBlockInfoToStatus (StatusValue $status, User $user=null)
 Add block info to block messages in a Status.
 
 addWarning ( $msg, $code=null, $data=null)
 Add a warning for this module.
 
 addDeprecation ( $msg, $feature, $data=[])
 Add a deprecation warning for this module.
 
 addError ( $msg, $code=null, $data=null)
 Add an error for this module without aborting.
 
 addMessagesFromStatus (StatusValue $status, $types=[ 'warning', 'error'], array $filter=[])
 Add warnings and/or errors from a Status.
 
 dieWithError ( $msg, $code=null, $data=null, $httpCode=0)
 Abort execution with an error.
 
 dieWithException (Throwable $exception, array $options=[])
 Abort execution with an error derived from a throwable.
 
 dieBlocked (AbstractBlock $block)
 Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die with an error message including block info.
 
 dieStatus (StatusValue $status)
 Throw an ApiUsageException based on the Status object.
 
 dieReadOnly ()
 Helper function for readonly errors.
 
 checkUserRightsAny ( $rights, $user=null)
 Helper function for permission-denied errors.
 
 checkTitleUserPermissions (LinkTarget $linkTarget, $actions, array $options=[])
 Helper function for permission-denied errors.
 
 dieWithErrorOrDebug ( $msg, $code=null, $data=null, $httpCode=null)
 Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
 
 logFeatureUsage ( $feature)
 Write logging information for API features to a debug log, for usage analysis.
 
 getFinalSummary ()
 Get final module summary.
 
 getFinalDescription ()
 Get final module description, after hooks have had a chance to tweak it as needed.
 
 getFinalParams ( $flags=0)
 Get final list of parameters, after hooks have had a chance to tweak it as needed.
 
 getFinalParamDescription ()
 Get final parameter descriptions, after hooks have had a chance to tweak it as needed.
 
- Public Member Functions inherited from ContextSource
 canUseWikiPage ()
 Check whether a WikiPage object can be get with getWikiPage().
 
 exportSession ()
 Export the resolved user IP, HTTP headers, user ID, and session ID.
 
 getConfig ()
 
 getContext ()
 Get the base IContextSource object.
 
 getLanguage ()
 
 getOutput ()
 
 getRequest ()
 
 getSkin ()
 
 getStats ()
 
 getTiming ()
 
 getTitle ()
 
 getUser ()
 Stable to override.
 
 getWikiPage ()
 Get the WikiPage object.
 
 msg ( $key,... $params)
 Get a Message object with context set Parameters are the same as wfMessage()
 
 setContext (IContextSource $context)
 

Static Public Member Functions

static handleApiBeforeMainException (Throwable $e)
 Handle a throwable from the ApiBeforeMain hook.
 
- Static Public Member Functions inherited from ApiBase
static makeMessage ( $msg, IContextSource $context, array $params=null)
 Create a Message from a string or array.
 

Protected Member Functions

 addRequestedFields ( $force=[])
 Add requested fields to the result.
 
 checkAsserts ( $params)
 Check asserts of the user's rights.
 
 checkConditionalRequestHeaders ( $module)
 Check selected RFC 7232 precondition headers.
 
 checkExecutePermissions ( $module)
 Check for sufficient permissions to execute.
 
 checkMaxLag ( $module, $params)
 Check the max lag if necessary.
 
 checkReadOnly ( $module)
 Check if the DB is read-only for this user.
 
 encodeRequestLogValue ( $s)
 Encode a value in a format suitable for a space-separated log line.
 
 errorMessagesFromException (Throwable $e, $type='error')
 Create an error message for the given throwable.
 
 executeAction ()
 Execute the actual module, without any error handling.
 
 executeActionWithErrorHandling ()
 Execute an action, and in case of an error, erase whatever partial results have been accumulated, and replace it with an error message and a help screen.
 
 getExamplesMessages ()
 Returns usage examples for this module.Return value has query strings as keys, with values being either strings (message key), arrays (message key + parameter), or Message objects.Do not call this base class implementation when overriding this method.
Since
1.25 Stable to override
Returns
array

 
 getParamsUsed ()
 Get the request parameters used in the course of the preceding execute() request.
 
 getSensitiveParams ()
 Get the request parameters that should be considered sensitive.
 
 handleCORS ()
 Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
 
 handleException (Throwable $e)
 Handle a throwable as an API response.
 
 logRequest ( $time, Throwable $e=null)
 Log the preceding request.
 
 printResult ( $httpCode=0)
 Print results using the current printer.
 
 reportUnusedParams ()
 Report unused parameters, so the client gets a hint in case it gave us parameters we don't know, for example in case of spelling mistakes or a missing 'g' prefix for generators.
 
 sendCacheHeaders ( $isError)
 Send caching headers.
 
 setRequestExpectations (ApiBase $module)
 Set database connection, query, and write expectations given this module request.
 
 setupExecuteAction ()
 Set up for the execution.
 
 setupExternalResponse ( $module, $params)
 Check POST for external response and setup result printer.
 
 setupModule ()
 Set up the module for response.
 
 substituteResultWithError (Throwable $e)
 Replace the result data with the information about a throwable.
 
- Protected Member Functions inherited from ApiBase
 explodeMultiValue ( $value, $limit)
 Split a multi-valued parameter string, like explode()
 
 parseMultiValue ( $valueName, $value, $allowMultiple, $allowedValues, $allSpecifier=null, $limit1=null, $limit2=null)
 Return an array of values that were given in a 'a|b|c' notation, after it optionally validates them against the list allowed values.
 
 validateLimit ( $name, &$value, $min, $max, $botMax=null, $enforceLimits=false)
 Validate the value against the minimum and user/bot maximum limits.
 
 validateTimestamp ( $value, $encParamName)
 Validate and normalize parameters of type 'timestamp'.
 
 getWebUITokenSalt (array $params)
 Fetch the salt used in the Web UI corresponding to this module.
 
 getDB ()
 Gets a default replica DB connection object Stable to override.
 
 getPermissionManager ()
 Obtain a PermissionManager instance that subclasses may use in their authorization checks.
 
 getHookContainer ()
 Get a HookContainer, for running extension hooks or for hook metadata.
 
 getHookRunner ()
 Get an ApiHookRunner for running core API hooks.
 
 getParameter ( $paramName, $parseLimit=true)
 Get a value for the given parameter.
 
 getParameterFromSettings ( $name, $settings, $parseLimit)
 Using the settings determine the value for the given parameter.
 
 useTransactionalTimeLimit ()
 Call wfTransactionalTimeLimit() if this request was POSTed.
 
 filterIDs ( $fields, array $ids)
 Filter out-of-range values from a list of positive integer IDs.
 
 dieContinueUsageIf ( $condition)
 Die with the 'badcontinue' error.
 
 getSummaryMessage ()
 Return the summary message.
 
 getExtendedDescription ()
 Return the extended help text message.
 
 getHelpFlags ()
 Generates the list of flags for the help screen and for action=paraminfo.
 
 getModuleSourceInfo ()
 Returns information about the source of this module, if known.
 

Static Protected Member Functions

static matchOrigin ( $value, $rules, $exceptions)
 Attempt to match an Origin header against a set of rules and a set of exceptions.
 
static matchRequestedHeaders ( $requestedHeaders, $allowedHeaders)
 Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we allow the follow up request to send.
 
static wildcardToRegex ( $wildcard)
 Helper function to convert wildcard string into a regex '*' => '.
 
- Static Protected Member Functions inherited from ApiBase
static dieDebug ( $method, $message)
 Internal code errors should be reported with this method.
 

Private Member Functions

 checkBotReadOnly ()
 Check whether we are readonly for bots.
 
 createErrorPrinter ()
 Create the printer for error output.
 
 getMaxLag ()
 

Private Attributes

bool null $lacksSameOriginSecurity = null
 Cached return value from self::lacksSameOriginSecurity()
 
 $mAction
 
array $mCacheControl = []
 
 $mCacheMode = 'private'
 
 $mCanApiHighLimits = null
 
 $mCdnMaxAge
 
ApiContinuationManager null $mContinuationManager
 
 $mEnableWrite
 
 $mErrorFormatter = null
 
 $mInternalMode
 
ApiBase $mModule
 
 $mModuleMgr
 
 $mParamsSensitive = []
 
 $mParamsUsed = []
 
 $mParamValidator
 
ApiFormatBase $mPrinter
 
 $mResult
 
const API_DEFAULT_FORMAT = 'jsonfm'
 When no format parameter is given, this format will be used.
 
const API_DEFAULT_USELANG = 'user'
 When no uselang parameter is given, this language will be used.
 

Static Private Attributes

static $Formats
 List of available formats: format name => format class.
 
static $Modules
 List of available modules: action name => module class.
 
static $mRights
 List of user roles that are specifically relevant to the API.
 

Additional Inherited Members

- Public Attributes inherited from ApiBase
const ALL_DEFAULT_STRING = '*'
 
const GET_VALUES_FOR_HELP = 1
 getAllowedParams() flag: When set, the result could take longer to generate, but should be more thorough.
 
const LIMIT_BIG1 = 500
 Fast query, standard limit.
 
const LIMIT_BIG2 = 5000
 Fast query, apihighlimits limit.
 
const LIMIT_SML1 = 50
 Slow query, standard limit.
 
const LIMIT_SML2 = 500
 Slow query, apihighlimits limit.
 
const PARAM_DFLT = ParamValidator::PARAM_DEFAULT
 
const PARAM_ISMULTI = ParamValidator::PARAM_ISMULTI
 
const PARAM_TYPE = ParamValidator::PARAM_TYPE
 
const PARAM_MAX = IntegerDef::PARAM_MAX
 
const PARAM_MAX2 = IntegerDef::PARAM_MAX2
 
const PARAM_MIN = IntegerDef::PARAM_MIN
 
const PARAM_ALLOW_DUPLICATES = ParamValidator::PARAM_ALLOW_DUPLICATES
 
const PARAM_DEPRECATED = ParamValidator::PARAM_DEPRECATED
 
const PARAM_REQUIRED = ParamValidator::PARAM_REQUIRED
 
const PARAM_SUBMODULE_MAP = SubmoduleDef::PARAM_SUBMODULE_MAP
 
const PARAM_SUBMODULE_PARAM_PREFIX = SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX
 
const PARAM_ALL = ParamValidator::PARAM_ALL
 
const PARAM_EXTRA_NAMESPACES = NamespaceDef::PARAM_EXTRA_NAMESPACES
 
const PARAM_SENSITIVE = ParamValidator::PARAM_SENSITIVE
 
const PARAM_DEPRECATED_VALUES = EnumDef::PARAM_DEPRECATED_VALUES
 
const PARAM_ISMULTI_LIMIT1 = ParamValidator::PARAM_ISMULTI_LIMIT1
 
const PARAM_ISMULTI_LIMIT2 = ParamValidator::PARAM_ISMULTI_LIMIT2
 
const PARAM_MAX_BYTES = StringDef::PARAM_MAX_BYTES
 
const PARAM_MAX_CHARS = StringDef::PARAM_MAX_CHARS
 
const PARAM_RANGE_ENFORCE = 'api-param-range-enforce'
 (boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
 
const PARAM_HELP_MSG = 'api-param-help-msg'
 (string|array|Message) Specify an alternative i18n documentation message for this parameter.
 
const PARAM_HELP_MSG_APPEND = 'api-param-help-msg-append'
 ((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this parameter.
 
const PARAM_HELP_MSG_INFO = 'api-param-help-msg-info'
 (array) Specify additional information tags for the parameter.
 
const PARAM_VALUE_LINKS = 'api-param-value-links'
 Deprecated and unused.
 
const PARAM_HELP_MSG_PER_VALUE = 'api-param-help-msg-per-value'
 ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg for ApiBase::makeMessage().
 
const PARAM_TEMPLATE_VARS = 'param-template-vars'
 (array) Indicate that this is a templated parameter, and specify replacements.
 

Detailed Description

This is the main API class, used for both external and internal processing.

When executed, it will create the requested formatter object, instantiate and execute an object associated with the needed action, and use formatter to print results. In case of an exception, an error message will be printed using the same formatter.

To use API from another application, run it using FauxRequest object, in which case any internal exceptions will not be handled but passed up to the caller. After successful execution, use getResult() for the resulting data.

@newable

Note
marked as newable in 1.35 for lack of a better alternative, but should use a factory in the future.

Definition at line 47 of file ApiMain.php.

Constructor & Destructor Documentation

◆ __construct()

ApiMain::__construct ( $context = null,
$enableWrite = false )

Constructs an instance of ApiMain that utilizes the module and format specified by $request.

Stable to call

Parameters
IContextSource | WebRequest | null$contextIf this is an instance of FauxRequest, errors are thrown and no printing occurs
bool$enableWriteShould be set to true if the api may modify data

Definition at line 179 of file ApiMain.php.

References ContextSource\$context, $wgLang, ContextSource\getConfig(), getErrorFormatter(), ApiBase\getHookRunner(), ContextSource\getLanguage(), ContextSource\getRequest(), lacksSameOriginSecurity(), ContextSource\setContext(), and wfDebug().

Member Function Documentation

◆ addRequestedFields()

ApiMain::addRequestedFields ( $force = [])
protected

Add requested fields to the result.

Parameters
string[]$forceWhich fields to force even if not requested. Accepted values are:
  • servedby

Definition at line 1128 of file ApiMain.php.

References wfHostname(), and wfTimestamp().

◆ canApiHighLimits()

ApiMain::canApiHighLimits ( )

Check whether the current user is allowed to use high limits.

Returns
bool

Definition at line 2082 of file ApiMain.php.

References getPermissionManager(), and getUser().

◆ checkAsserts()

ApiMain::checkAsserts ( $params)
protected

Check asserts of the user's rights.

Parameters
array$params

Definition at line 1487 of file ApiMain.php.

References getPermissionManager(), getUser(), and wfEscapeWikiText().

◆ checkBotReadOnly()

ApiMain::checkBotReadOnly ( )
private

Check whether we are readonly for bots.

Definition at line 1448 of file ApiMain.php.

References wfDebugLog().

◆ checkConditionalRequestHeaders()

ApiMain::checkConditionalRequestHeaders ( $module)
protected

Check selected RFC 7232 precondition headers.

RFC 7232 envisions a particular model where you send your request to "a resource", and for write requests that you can read "the resource" by changing the method to GET. When the API receives a GET request, it works out even though "the resource" from RFC 7232's perspective might be many resources from MediaWiki's perspective. But it totally fails for a POST, since what HTTP sees as "the resource" is probably just "/api.php" with all the interesting bits in the body.

Therefore, we only support RFC 7232 precondition headers for GET (and HEAD). That means we don't need to bother with If-Match and If-Unmodified-Since since they only apply to modification requests.

And since we don't support Range, If-Range is ignored too.

Since
1.26
Parameters
ApiBase$moduleApi module being used
Returns
bool True on success, false should exit immediately

Definition at line 1300 of file ApiMain.php.

References $s, getUser(), wfClearOutputBuffers(), and wfTimestamp().

◆ checkExecutePermissions()

ApiMain::checkExecutePermissions ( $module)
protected

Check for sufficient permissions to execute.

Parameters
ApiBase$moduleAn Api module

Definition at line 1401 of file ApiMain.php.

References getPermissionManager(), and getUser().

◆ checkMaxLag()

ApiMain::checkMaxLag ( $module,
$params )
protected

Check the max lag if necessary.

Parameters
ApiBase$moduleApi module being used
array$paramsArray an array containing the request parameters.
Returns
bool True on success, false should exit immediately

Definition at line 1254 of file ApiMain.php.

◆ checkReadOnly()

ApiMain::checkReadOnly ( $module)
protected

Check if the DB is read-only for this user.

Parameters
ApiBase$moduleAn Api module

Definition at line 1432 of file ApiMain.php.

References wfReadOnly().

◆ createErrorPrinter()

ApiMain::createErrorPrinter ( )
private

Create the printer for error output.

Definition at line 975 of file ApiMain.php.

◆ createPrinterByName()

ApiMain::createPrinterByName ( $format)

Create an instance of an output formatter by its name.

Parameters
string$format
Returns
ApiFormatBase

Definition at line 482 of file ApiMain.php.

References wfEscapeWikiText().

Referenced by ApiFormatRaw\__construct().

◆ encodeRequestLogValue()

ApiMain::encodeRequestLogValue ( $s)
protected

Encode a value in a format suitable for a space-separated log line.

Parameters
string$s
Returns
string

Definition at line 1707 of file ApiMain.php.

References $s.

◆ errorMessagesFromException()

ApiMain::errorMessagesFromException ( Throwable $e,
$type = 'error' )
protected

Create an error message for the given throwable.

If an ApiUsageException, errors/warnings will be extracted from the embedded StatusValue.

Any other throwable will be returned with a generic code and wrapper text around the throwable's (presumably English) message as a single error (no warnings).

Parameters
Throwable$e
string$type'error' or 'warning'
Returns
ApiMessage[]
Since
1.27

Definition at line 1006 of file ApiMain.php.

References $type, Message\newFromSpecifier(), and wfEscapeWikiText().

◆ execute()

ApiMain::execute ( )

Execute api request.

Any errors will be handled if the API was called by the remote client.

Reimplemented from ApiBase.

Definition at line 496 of file ApiMain.php.

Referenced by MediaWiki\Rest\Handler\ActionModuleBasedHandler\execute().

◆ executeAction()

ApiMain::executeAction ( )
protected

Execute the actual module, without any error handling.

Definition at line 1565 of file ApiMain.php.

References getContext().

◆ executeActionWithErrorHandling()

ApiMain::executeActionWithErrorHandling ( )
protected

Execute an action, and in case of an error, erase whatever partial results have been accumulated, and replace it with an error message and a help screen.

Definition at line 508 of file ApiMain.php.

References $t, and getContext().

◆ getAllowedParams()

ApiMain::getAllowedParams ( )

See ApiBase for description.

Returns
array

Reimplemented from ApiBase.

Definition at line 1857 of file ApiMain.php.

References ApiBase\PARAM_DFLT, and ApiBase\PARAM_TYPE.

◆ getCheck()

ApiMain::getCheck ( $name)

Get a boolean request value, and register the fact that the parameter was used, for logging.

Parameters
string$name
Returns
bool

Definition at line 1781 of file ApiMain.php.

◆ getContinuationManager()

ApiMain::getContinuationManager ( )

Get the continuation manager.

Returns
ApiContinuationManager|null

Reimplemented from ApiBase.

Definition at line 349 of file ApiMain.php.

◆ getErrorFormatter()

ApiMain::getErrorFormatter ( )

Get the ApiErrorFormatter object associated with current request.

Returns
ApiErrorFormatter

Reimplemented from ApiBase.

Definition at line 341 of file ApiMain.php.

Referenced by __construct().

◆ getExamplesMessages()

ApiMain::getExamplesMessages ( )
protected

Returns usage examples for this module.Return value has query strings as keys, with values being either strings (message key), arrays (message key + parameter), or Message objects.Do not call this base class implementation when overriding this method.

Since
1.25 Stable to override
Returns
array

Reimplemented from ApiBase.

Definition at line 1907 of file ApiMain.php.

◆ getMaxLag()

ApiMain::getMaxLag ( )
private
Returns
array

Definition at line 1220 of file ApiMain.php.

References wfHostname().

◆ getModule()

ApiMain::getModule ( )

Get the API module object.

Only works after executeAction()

Returns
ApiBase

Definition at line 380 of file ApiMain.php.

◆ getModuleManager()

ApiMain::getModuleManager ( )

Overrides to return this instance's module manager.

Returns
ApiModuleManager

Reimplemented from ApiBase.

Definition at line 2095 of file ApiMain.php.

◆ getParamsUsed()

ApiMain::getParamsUsed ( )
protected

Get the request parameters used in the course of the preceding execute() request.

Returns
array

Definition at line 1724 of file ApiMain.php.

◆ getParamValidator()

ApiMain::getParamValidator ( )

Get the parameter validator.

Returns
ApiParamValidator

Definition at line 371 of file ApiMain.php.

◆ getPrinter()

ApiMain::getPrinter ( )

Get the result formatter object.

Only works after setupExecuteAction()

Returns
ApiFormatBase

Definition at line 389 of file ApiMain.php.

◆ getResult()

ApiMain::getResult ( )

Get the ApiResult object associated with current request.

Returns
ApiResult

Reimplemented from ApiBase.

Definition at line 297 of file ApiMain.php.

Referenced by MediaWiki\Rest\Handler\ActionModuleBasedHandler\execute().

◆ getSensitiveParams()

ApiMain::getSensitiveParams ( )
protected

Get the request parameters that should be considered sensitive.

Since
1.29
Returns
array

Definition at line 1741 of file ApiMain.php.

◆ getUpload()

ApiMain::getUpload ( $name)

Get a request upload, and register the fact that it was used, for logging.

Since
1.21
Parameters
string$nameParameter name
Returns
WebRequestUpload

Definition at line 1793 of file ApiMain.php.

◆ getUserAgent()

ApiMain::getUserAgent ( )

Fetches the user agent used for this request.

The value will be the combination of the 'Api-User-Agent' header (if any) and the standard User-Agent header (if any).

Returns
string

Definition at line 2107 of file ApiMain.php.

◆ getVal()

ApiMain::getVal ( $name,
$default = null )

Get a request value, and register the fact that it was used, for logging.

Parameters
string$name
string | null$default
Returns
string|null

Definition at line 1760 of file ApiMain.php.

◆ handleApiBeforeMainException()

static ApiMain::handleApiBeforeMainException ( Throwable $e)
static

Handle a throwable from the ApiBeforeMain hook.

This tries to print the throwable as an API response, to be more friendly to clients. If it fails, it will rethrow the throwable.

Since
1.23
Parameters
Throwable$e
Exceptions
Throwable

Definition at line 648 of file ApiMain.php.

◆ handleCORS()

ApiMain::handleCORS ( )
protected

Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.

If no origin parameter is present, nothing happens. If an origin parameter is present but doesn't match the Origin header, a 403 status code is set and false is returned. If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS headers are set. https://www.w3.org/TR/cors/#resource-requests https://www.w3.org/TR/cors/#resource-preflight-requests

Returns
bool False if the caller should abort (403 case), true otherwise (all other cases)

Definition at line 680 of file ApiMain.php.

◆ handleException()

ApiMain::handleException ( Throwable $e)
protected

Handle a throwable as an API response.

Since
1.23
Parameters
Throwable$e

Definition at line 574 of file ApiMain.php.

References ApiUsageException\getStatusValue().

◆ isInternalMode()

ApiMain::isInternalMode ( )

Return true if the API was started by other PHP code using FauxRequest.

Returns
bool

Definition at line 288 of file ApiMain.php.

◆ isReadMode()

ApiMain::isReadMode ( )
Returns
bool

Reimplemented from ApiBase.

Definition at line 1848 of file ApiMain.php.

◆ lacksSameOriginSecurity()

ApiMain::lacksSameOriginSecurity ( )

Get the security flag for the current request.

Returns
bool

Reimplemented from ApiBase.

Definition at line 305 of file ApiMain.php.

References ApiBase\getHookRunner(), ContextSource\getRequest(), and lacksSameOriginSecurity().

Referenced by __construct(), and lacksSameOriginSecurity().

◆ logRequest()

ApiMain::logRequest ( $time,
Throwable $e = null )
protected

Log the preceding request.

Parameters
float$timeTime in seconds
Throwable | null$eThrowable caught while processing the request

Definition at line 1628 of file ApiMain.php.

References $header, getUser(), wfDebugLog(), wfTimestamp(), and wfUrlencode().

◆ markParamsSensitive()

ApiMain::markParamsSensitive ( $params)

Mark parameters as sensitive.

Since
1.29
Parameters
string | string[]$params

Definition at line 1750 of file ApiMain.php.

◆ markParamsUsed()

ApiMain::markParamsUsed ( $params)

Mark parameters as used.

Parameters
string | string[]$params

Definition at line 1732 of file ApiMain.php.

◆ matchOrigin()

static ApiMain::matchOrigin ( $value,
$rules,
$exceptions )
staticprotected

Attempt to match an Origin header against a set of rules and a set of exceptions.

Parameters
string$valueOrigin header
array$rulesSet of wildcard rules
array$exceptionsSet of wildcard rules
Returns
bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise

Definition at line 800 of file ApiMain.php.

◆ matchRequestedHeaders()

static ApiMain::matchRequestedHeaders ( $requestedHeaders,
$allowedHeaders )
staticprotected

Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we allow the follow up request to send.

Parameters
string$requestedHeadersComma separated list of HTTP headers
string[]$allowedHeadersList of allowed HTTP headers
Returns
bool True if all requested headers are in the list of allowed headers

Definition at line 825 of file ApiMain.php.

◆ modifyHelp()

ApiMain::modifyHelp ( array & $help,
array $options,
array & $tocData )

Called from ApiHelp before the pieces are joined together and returned.This exists mainly for ApiMain to add the Permissions and Credits sections. Other modules probably don't need it.Stable to override

Parameters
string[]&$helpArray of help data
array$optionsOptions passed to ApiHelp::getHelp
array&$tocDataIf a TOC is being generated, this array has keys as anchors in the page and values as for Linker::generateTOC().
-param array{nolead?:bool,headerlevel?:int,tocnumber?:int[]} $options

Reimplemented from ApiBase.

Definition at line 1920 of file ApiMain.php.

References $header, $help, $type, getPermissionManager(), Message\listParam(), and Linker\makeHeadline().

◆ printResult()

ApiMain::printResult ( $httpCode = 0)
protected

Print results using the current printer.

Parameters
int$httpCodeHTTP status code, or 0 to not change

Definition at line 1831 of file ApiMain.php.

◆ reportUnusedParams()

ApiMain::reportUnusedParams ( )
protected

Report unused parameters, so the client gets a hint in case it gave us parameters we don't know, for example in case of spelling mistakes or a missing 'g' prefix for generators.

Definition at line 1803 of file ApiMain.php.

References Message\listParam().

◆ sendCacheHeaders()

ApiMain::sendCacheHeaders ( $isError)
protected

Send caching headers.

Parameters
bool$isErrorWhether an error response is being output
Since
1.26 added $isError parameter

Definition at line 869 of file ApiMain.php.

References wfTimestamp().

◆ setCacheControl()

ApiMain::setCacheControl ( $directives)

Set directives (key/value pairs) for the Cache-Control header.

Boolean values will be formatted as such, by including or omitting without an equals sign.

Cache control values set here will only be used if the cache mode is not private, see setCacheMode().

Parameters
array$directives

Definition at line 471 of file ApiMain.php.

◆ setCacheMaxAge()

ApiMain::setCacheMaxAge ( $maxage)

Set how long the response should be cached.

Parameters
int$maxage

Definition at line 398 of file ApiMain.php.

◆ setCacheMode()

ApiMain::setCacheMode ( $mode)

Set the type of caching headers which will be sent.

Parameters
string$modeOne of:
  • 'public': Cache this object in public caches, if the maxage or smaxage parameter is set, or if setCacheMaxAge() was called. If a maximum age is not provided by any of these means, the object will be private.
  • 'private': Cache this object only in private client-side caches.
  • 'anon-public-user-private': Make this object cacheable for logged-out users, but private for logged-in users. IMPORTANT: If this is set, it must be set consistently for a given URL, it cannot be set differently depending on things like the contents of the database, or whether the user is logged in.

If the wiki does not allow anonymous users to read it, the mode set here will be ignored, and private caching headers will always be sent. In other words, the "public" mode is equivalent to saying that the data sent is as public as a page view.

For user-dependent data, the private mode should generally be used. The anon-public-user-private mode should only be used where there is a particularly good performance reason for caching the anonymous response, but where the response to logged-in users may differ, or may contain private data.

If this function is never called, then the default will be the private mode.

Definition at line 430 of file ApiMain.php.

References getPermissionManager(), and wfDebug().

◆ setContinuationManager()

ApiMain::setContinuationManager ( ApiContinuationManager $manager = null)

Set the continuation manager.

Parameters
ApiContinuationManager | null$manager

Reimplemented from ApiBase.

Definition at line 357 of file ApiMain.php.

◆ setRequestExpectations()

ApiMain::setRequestExpectations ( ApiBase $module)
protected

Set database connection, query, and write expectations given this module request.

Parameters
ApiBase$module

Definition at line 1609 of file ApiMain.php.

References ApiBase\isWriteMode().

◆ setupExecuteAction()

ApiMain::setupExecuteAction ( )
protected

Set up for the execution.

Returns
array

Definition at line 1158 of file ApiMain.php.

◆ setupExternalResponse()

ApiMain::setupExternalResponse ( $module,
$params )
protected

Check POST for external response and setup result printer.

Parameters
ApiBase$moduleAn Api module
array$paramsAn array with the request parameters

Definition at line 1523 of file ApiMain.php.

◆ setupModule()

ApiMain::setupModule ( )
protected

Set up the module for response.

Returns
ApiBase The module that will handle this action
Exceptions
MWException
ApiUsageException

Definition at line 1173 of file ApiMain.php.

References wfEscapeWikiText().

◆ substituteResultWithError()

ApiMain::substituteResultWithError ( Throwable $e)
protected

Replace the result data with the information about a throwable.

Parameters
Throwable$e
Returns
string[] Error codes

Definition at line 1044 of file ApiMain.php.

References $path, ApiErrorFormatter\isValidApiCode(), wfExpandUrl(), and wfScript().

◆ wildcardToRegex()

static ApiMain::wildcardToRegex ( $wildcard)
staticprotected

Helper function to convert wildcard string into a regex '*' => '.

*?' '?' => '.'

Parameters
string$wildcardString with wildcards
Returns
string Regular expression

Definition at line 853 of file ApiMain.php.

Member Data Documentation

◆ $Formats

ApiMain::$Formats
staticprivate
Initial value:
= [
'json' => ApiFormatJson::class,
'jsonfm' => ApiFormatJson::class,
'php' => ApiFormatPhp::class,
'phpfm' => ApiFormatPhp::class,
'xml' => ApiFormatXml::class,
'xmlfm' => ApiFormatXml::class,
'rawfm' => ApiFormatJson::class,
'none' => ApiFormatNone::class,
]

List of available formats: format name => format class.

Definition at line 120 of file ApiMain.php.

◆ $lacksSameOriginSecurity

bool null ApiMain::$lacksSameOriginSecurity = null
private

Cached return value from self::lacksSameOriginSecurity()

Definition at line 169 of file ApiMain.php.

◆ $mAction

ApiMain::$mAction
private

Definition at line 156 of file ApiMain.php.

◆ $mCacheControl

array ApiMain::$mCacheControl = []
private

Definition at line 164 of file ApiMain.php.

◆ $mCacheMode

ApiMain::$mCacheMode = 'private'
private

Definition at line 162 of file ApiMain.php.

◆ $mCanApiHighLimits

ApiMain::$mCanApiHighLimits = null
private

Definition at line 2076 of file ApiMain.php.

◆ $mCdnMaxAge

ApiMain::$mCdnMaxAge
private

Definition at line 158 of file ApiMain.php.

◆ $mContinuationManager

ApiContinuationManager null ApiMain::$mContinuationManager
private

Definition at line 155 of file ApiMain.php.

◆ $mEnableWrite

ApiMain::$mEnableWrite
private

Definition at line 157 of file ApiMain.php.

◆ $mErrorFormatter

ApiMain::$mErrorFormatter = null
private

Definition at line 153 of file ApiMain.php.

◆ $mInternalMode

ApiMain::$mInternalMode
private

Definition at line 158 of file ApiMain.php.

◆ $mModule

ApiBase ApiMain::$mModule
private

Definition at line 160 of file ApiMain.php.

◆ $mModuleMgr

ApiMain::$mModuleMgr
private

Definition at line 153 of file ApiMain.php.

◆ $Modules

ApiMain::$Modules
staticprivate

List of available modules: action name => module class.

Definition at line 61 of file ApiMain.php.

◆ $mParamsSensitive

ApiMain::$mParamsSensitive = []
private

Definition at line 166 of file ApiMain.php.

◆ $mParamsUsed

ApiMain::$mParamsUsed = []
private

Definition at line 165 of file ApiMain.php.

◆ $mParamValidator

ApiMain::$mParamValidator
private

Definition at line 153 of file ApiMain.php.

◆ $mPrinter

ApiFormatBase ApiMain::$mPrinter
private

Definition at line 151 of file ApiMain.php.

◆ $mResult

ApiMain::$mResult
private

Definition at line 153 of file ApiMain.php.

◆ $mRights

ApiMain::$mRights
staticprivate
Initial value:
= [
'writeapi' => [
'msg' => 'right-writeapi',
'params' => []
],
'apihighlimits' => [
'msg' => 'api-help-right-apihighlimits',
]
]
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition ApiBase.php:226
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:222

List of user roles that are specifically relevant to the API.

[ 'right' => [ 'msg' => 'Some message with a $1', 'params' => [ $someVarToSubst ] ], ];

Definition at line 137 of file ApiMain.php.

◆ API_DEFAULT_FORMAT

const ApiMain::API_DEFAULT_FORMAT = 'jsonfm'
private

When no format parameter is given, this format will be used.

Definition at line 51 of file ApiMain.php.

◆ API_DEFAULT_USELANG

const ApiMain::API_DEFAULT_USELANG = 'user'
private

When no uselang parameter is given, this language will be used.

Definition at line 56 of file ApiMain.php.


The documentation for this class was generated from the following file: