MediaWiki  1.28.0
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. More...
 
 canApiHighLimits ()
 Check whether the current user is allowed to use high limits. More...
 
 createPrinterByName ($format)
 Create an instance of an output formatter by its name. More...
 
 execute ()
 Execute api request. More...
 
 getAllowedParams ()
 See ApiBase for description. More...
 
 getCheck ($name)
 Get a boolean request value, and register the fact that the parameter was used, for logging. More...
 
 getContinuationManager ()
 Get the continuation manager. More...
 
 getErrorFormatter ()
 Get the ApiErrorFormatter object associated with current request. More...
 
 getModule ()
 Get the API module object. More...
 
 getModuleManager ()
 Overrides to return this instance's module manager. More...
 
 getPrinter ()
 Get the result formatter object. More...
 
 getResult ()
 Get the ApiResult object associated with current request. More...
 
 getUpload ($name)
 Get a request upload, and register the fact that it was used, for logging. More...
 
 getUserAgent ()
 Fetches the user agent used for this request. More...
 
 getVal ($name, $default=null)
 Get a request value, and register the fact that it was used, for logging. More...
 
 isInternalMode ()
 Return true if the API was started by other PHP code using FauxRequest. More...
 
 isReadMode ()
 
 lacksSameOriginSecurity ()
 Get the security flag for the current request. More...
 
 markParamsUsed ($params)
 Mark parameters as used. More...
 
 modifyHelp (array &$help, array $options, array &$tocData)
 
 setCacheControl ($directives)
 Set directives (key/value pairs) for the Cache-Control header. More...
 
 setCacheMaxAge ($maxage)
 Set how long the response should be cached. More...
 
 setCacheMode ($mode)
 Set the type of caching headers which will be sent. More...
 
 setContinuationManager ($manager)
 Set the continuation manager. More...
 
- Public Member Functions inherited from ApiBase
 __construct (ApiMain $mainModule, $moduleName, $modulePrefix= '')
 
 execute ()
 Evaluates the parameters, performs the requested query, and sets up the result. More...
 
 getModuleManager ()
 Get the module manager, or null if this module has no sub-modules. More...
 
 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. More...
 
 getHelpUrls ()
 Return links to more detailed help pages about the module. More...
 
 shouldCheckMaxlag ()
 Indicates if this module needs maxlag to be checked. More...
 
 isReadMode ()
 Indicates whether this module requires read rights. More...
 
 isWriteMode ()
 Indicates whether this module requires write mode. More...
 
 mustBePosted ()
 Indicates whether this module must be called with a POST request. More...
 
 isDeprecated ()
 Indicates whether this module is deprecated. More...
 
 isInternal ()
 Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party use and may be unstable. More...
 
 needsToken ()
 Returns the token type this module requires in order to execute. More...
 
 getConditionalRequestData ($condition)
 Returns data for HTTP conditional request mechanisms. More...
 
 getModuleName ()
 Get the name of the module being executed by this instance. More...
 
 getModulePrefix ()
 Get parameter prefix (usually two letters or an empty string). More...
 
 getMain ()
 Get the main module. More...
 
 isMain ()
 Returns true if this module is the main module ($this === $this->mMainModule), false otherwise. More...
 
 getParent ()
 Get the parent of this module. More...
 
 lacksSameOriginSecurity ()
 Returns true if the current request breaks the same-origin policy. More...
 
 getModulePath ()
 Get the path to this module. More...
 
 getModuleFromPath ($path)
 Get a module from its module path. More...
 
 getResult ()
 Get the result object. More...
 
 getErrorFormatter ()
 Get the error formatter. More...
 
 getContinuationManager ()
 Get the continuation manager. More...
 
 setContinuationManager ($manager)
 Set the continuation manager. More...
 
 dynamicParameterDocumentation ()
 Indicate if the module supports dynamically-determined parameters that cannot be included in self::getAllowedParams(). More...
 
 encodeParamName ($paramName)
 This method mangles parameter name based on the prefix supplied to the constructor. More...
 
 extractRequestParams ($parseLimit=true)
 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. More...
 
 requireOnlyOneParameter ($params, $required)
 Die if none or more than one of a certain set of parameters is set and not false. More...
 
 requireMaxOneParameter ($params, $required)
 Die if more than one of a certain set of parameters is set and not false. More...
 
 requireAtLeastOneParameter ($params, $required)
 Die if none of a certain set of parameters is set and not false. More...
 
 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. More...
 
 getTitleOrPageId ($params, $load=false)
 Get a WikiPage object from a title or pageid param, if possible. More...
 
 validateToken ($token, array $params)
 Validate the supplied token. More...
 
 getWatchlistUser ($params)
 Gets the user for whom to get the watchlist. More...
 
 setWarning ($warning)
 Set warning section for this module. More...
 
 dieUsage ($description, $errorCode, $httpRespCode=0, $extradata=null)
 Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an error message. More...
 
 dieBlocked (Block $block)
 Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an error message including block info. More...
 
 getErrorFromStatus ($status, &$extraData=null)
 Get error (as code, string) from a Status object. More...
 
 dieStatus ($status)
 Throw a UsageException based on the errors in the Status object. More...
 
static dieReadOnly ()
 Helper function for readonly errors. More...
 
 dieUsageMsg ($error)
 Output the error message related to a certain array. More...
 
 dieUsageMsgOrDebug ($error)
 Will only set a warning instead of failing if the global $wgDebugAPI is set to true. More...
 
 parseMsg ($error)
 Return the error message related to a certain array. More...
 
 logFeatureUsage ($feature)
 Write logging information for API features to a debug log, for usage analysis. More...
 
 getFinalDescription ()
 Get final module description, after hooks have had a chance to tweak it as needed. More...
 
 getFinalParams ($flags=0)
 Get final list of parameters, after hooks have had a chance to tweak it as needed. More...
 
 getFinalParamDescription ()
 Get final parameter descriptions, after hooks have had a chance to tweak it as needed. More...
 
 modifyHelp (array &$help, array $options, array &$tocData)
 Called from ApiHelp before the pieces are joined together and returned. More...
 
 getModuleProfileName ($db=false)
 
 profileIn ()
 
 profileOut ()
 
 safeProfileOut ()
 
 getProfileTime ()
 
 profileDBIn ()
 
 profileDBOut ()
 
 getProfileDBTime ()
 
- Public Member Functions inherited from ContextSource
 canUseWikiPage ()
 Check whether a WikiPage object can be get with getWikiPage(). More...
 
 exportSession ()
 Export the resolved user IP, HTTP headers, user ID, and session ID. More...
 
 getConfig ()
 Get the Config object. More...
 
 getContext ()
 Get the base IContextSource object. More...
 
 getLanguage ()
 Get the Language object. More...
 
 getOutput ()
 Get the OutputPage object. More...
 
 getRequest ()
 Get the WebRequest object. More...
 
 getSkin ()
 Get the Skin object. More...
 
 getStats ()
 Get the Stats object. More...
 
 getTiming ()
 Get the Timing object. More...
 
 getTitle ()
 Get the Title object. More...
 
 getUser ()
 Get the User object. More...
 
 getWikiPage ()
 Get the WikiPage object. More...
 
 msg ()
 Get a Message object with context set Parameters are the same as wfMessage() More...
 
 setContext (IContextSource $context)
 Set the IContextSource object. More...
 

Static Public Member Functions

static handleApiBeforeMainException (Exception $e)
 Handle an exception from the ApiBeforeMain hook. More...
 
- Static Public Member Functions inherited from ApiBase
static truncateArray (&$arr, $limit)
 Truncate an array to a certain length. More...
 
static makeMessage ($msg, IContextSource $context, array $params=null)
 Create a Message from a string or array. More...
 

Public Attributes

 $mErrorFormatter
 
 $mResult
 
 $mSquidMaxage
 
const API_DEFAULT_FORMAT = 'jsonfm'
 When no format parameter is given, this format will be used. More...
 
- Public Attributes inherited from ApiBase
string $mModulePrefix
 
const GET_VALUES_FOR_HELP = 1
 getAllowedParams() flag: When set, the result could take longer to generate, but should be more thorough. More...
 
const LIMIT_BIG1 = 500
 Fast query, standard limit. More...
 
const LIMIT_BIG2 = 5000
 Fast query, apihighlimits limit. More...
 
const LIMIT_SML1 = 50
 Slow query, standard limit. More...
 
const LIMIT_SML2 = 500
 Slow query, apihighlimits limit. More...
 
const PARAM_DFLT = 0
 (null|boolean|integer|string) Default value of the parameter. More...
 
const PARAM_ISMULTI = 1
 (boolean) Accept multiple pipe-separated values for this parameter (e.g. More...
 
const PARAM_TYPE = 2
 (string|string[]) Either an array of allowed value strings, or a string type as described below. More...
 
const PARAM_MAX = 3
 (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. More...
 
const PARAM_MAX2 = 4
 (integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE 'limit'. More...
 
const PARAM_MIN = 5
 (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. More...
 
const PARAM_ALLOW_DUPLICATES = 6
 (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? More...
 
const PARAM_DEPRECATED = 7
 (boolean) Is the parameter deprecated (will show a warning)? More...
 
const PARAM_REQUIRED = 8
 (boolean) Is the parameter required? More...
 
const PARAM_RANGE_ENFORCE = 9
 (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX? More...
 
const PARAM_HELP_MSG = 10
 (string|array|Message) Specify an alternative i18n documentation message for this parameter. More...
 
const PARAM_HELP_MSG_APPEND = 11
 ((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this parameter. More...
 
const PARAM_HELP_MSG_INFO = 12
 (array) Specify additional information tags for the parameter. More...
 
const PARAM_VALUE_LINKS = 13
 (string[]) When PARAM_TYPE is an array, this may be an array mapping those values to page titles which will be linked in the help. More...
 
const PARAM_HELP_MSG_PER_VALUE = 14
 ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg for ApiBase::makeMessage(). More...
 
const PARAM_SUBMODULE_MAP = 15
 (string[]) When PARAM_TYPE is 'submodule', map parameter values to submodule paths. More...
 
const PARAM_SUBMODULE_PARAM_PREFIX = 16
 (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix added by ApiQueryGeneratorBase (and similar if anything else ever does that). More...
 

Protected Member Functions

 checkAsserts ($params)
 Check asserts of the user's rights. More...
 
 checkConditionalRequestHeaders ($module)
 Check selected RFC 7232 precondition headers. More...
 
 checkExecutePermissions ($module)
 Check for sufficient permissions to execute. More...
 
 checkMaxLag ($module, $params)
 Check the max lag if necessary. More...
 
 checkReadOnly ($module)
 Check if the DB is read-only for this user. More...
 
 encodeRequestLogValue ($s)
 Encode a value in a format suitable for a space-separated log line. More...
 
 errorMessageFromException ($e)
 Create an error message for the given exception. More...
 
 executeAction ()
 Execute the actual module, without any error handling. More...
 
 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. More...
 
 getExamplesMessages ()
 
 getParamsUsed ()
 Get the request parameters used in the course of the preceding execute() request. More...
 
 handleCORS ()
 Check the &origin= query parameter against the Origin: HTTP header and respond appropriately. More...
 
 handleException (Exception $e)
 Handle an exception as an API response. More...
 
 logRequest ($time, $e=null)
 Log the preceding request. More...
 
 printResult ($isError)
 Print results using the current printer. More...
 
 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. More...
 
 sendCacheHeaders ($isError)
 Send caching headers. More...
 
 setRequestExpectations (ApiBase $module)
 Set database connection, query, and write expectations given this module request. More...
 
 setupExecuteAction ()
 Set up for the execution. More...
 
 setupExternalResponse ($module, $params)
 Check POST for external response and setup result printer. More...
 
 setupModule ()
 Set up the module for response. More...
 
 substituteResultWithError ($e)
 Replace the result data with the information about an exception. More...
 
- Protected Member Functions inherited from ApiBase
 getExamplesMessages ()
 Returns usage examples for this module. More...
 
 getAllowedParams ()
 Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (array with PARAM_* constants as keys) Don't call this function directly: use getFinalParams() to allow hooks to modify parameters as needed. More...
 
 getWebUITokenSalt (array $params)
 Fetch the salt used in the Web UI corresponding to this module. More...
 
 getDB ()
 Gets a default replica DB connection object. More...
 
 getParameter ($paramName, $parseLimit=true)
 Get a value for the given parameter. More...
 
 getWatchlistValue ($watchlist, $titleObj, $userOption=null)
 Return true if we're to watch the page, false if not, null if no change. More...
 
 getParameterFromSettings ($paramName, $paramSettings, $parseLimit)
 Using the settings determine the value for the given parameter. More...
 
 handleParamNormalization ($paramName, $value, $rawValue)
 Handle when a parameter was Unicode-normalized. More...
 
 explodeMultiValue ($value, $limit)
 Split a multi-valued parameter string, like explode() More...
 
 parseMultiValue ($valueName, $value, $allowMultiple, $allowedValues)
 Return an array of values that were given in a 'a|b|c' notation, after it optionally validates them against the list allowed values. More...
 
 validateLimit ($paramName, &$value, $min, $max, $botMax=null, $enforceLimits=false)
 Validate the value against the minimum and user/bot maximum limits. More...
 
 validateTimestamp ($value, $encParamName)
 Validate and normalize of parameters of type 'timestamp'. More...
 
 setWatch ($watch, $titleObj, $userOption=null)
 Set a watch (or unwatch) based the based on a watchlist parameter. More...
 
 dieContinueUsageIf ($condition)
 Die with the $prefix. More...
 
 getDescriptionMessage ()
 Return the description message. More...
 
 getHelpFlags ()
 Generates the list of flags for the help screen and for action=paraminfo. More...
 
 getModuleSourceInfo ()
 Returns information about the source of this module, if known. More...
 
 getDescription ()
 Returns the description string for this module. More...
 
 getParamDescription ()
 Returns an array of parameter descriptions. More...
 
 getExamples ()
 Returns usage examples for this module. More...
 
 useTransactionalTimeLimit ()
 Call wfTransactionalTimeLimit() if this request was POSTed. More...
 

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. More...
 
static matchRequestedHeaders ($requestedHeaders)
 Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we allow the follow up request to send. More...
 
static wildcardToRegex ($wildcard)
 Helper function to convert wildcard string into a regex '*' => '. More...
 
- Static Protected Member Functions inherited from ApiBase
static dieDebug ($method, $message)
 Internal code errors should be reported with this method. More...
 

Private Member Functions

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

Private Attributes

bool null $lacksSameOriginSecurity = null
 Cached return value from self::lacksSameOriginSecurity() More...
 
 $mAction
 
 $mCacheControl = []
 
 $mCacheMode = 'private'
 
 $mCanApiHighLimits = null
 
ApiContinuationManager null $mContinuationManager
 
 $mEnableWrite
 
 $mInternalMode
 
ApiBase $mModule
 
 $mModuleMgr
 
 $mParamsUsed = []
 
static static static ApiFormatBase $mPrinter
 

Static Private Attributes

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

Additional Inherited Members

- Static Public Attributes inherited from ApiBase
static $messageMap
 Array that maps message keys to error messages. More...
 

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.

Definition at line 43 of file ApiMain.php.

Constructor & Destructor Documentation

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

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

Parameters
IContextSource | WebRequest$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 166 of file ApiMain.php.

References $code, ContextSource\$context, $request, $wgContLang, $wgLang, $wgUser, ContextSource\getConfig(), ContextSource\getContext(), RequestContext\getMain(), ApiBase\getParameter(), ContextSource\getRequest(), getUserAgent(), global, lacksSameOriginSecurity(), Hooks\run(), RequestContext\sanitizeLangCode(), ContextSource\setContext(), User, wfDebug(), and wfWikiID().

Member Function Documentation

ApiMain::canApiHighLimits ( )

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

Returns
bool

Definition at line 1800 of file ApiMain.php.

References $mCanApiHighLimits, and ContextSource\getUser().

ApiMain::checkAsserts (   $params)
protected

Check asserts of the user's rights.

Parameters
array$params

Definition at line 1348 of file ApiMain.php.

References $params, $user, ApiBase\dieUsage(), ContextSource\getUser(), and User\newFromName().

Referenced by executeAction().

ApiMain::checkBotReadOnly ( )
private

Check whether we are readonly for bots.

Definition at line 1311 of file ApiMain.php.

References as, ApiBase\dieUsage(), ContextSource\getConfig(), ApiBase\parseMsg(), wfDebugLog(), and wfGetLB().

Referenced by checkReadOnly().

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 1163 of file ApiMain.php.

References $e, $s, $value, ContextSource\getConfig(), WebRequest\GETHEADER_LIST, ContextSource\getOutput(), ContextSource\getRequest(), ContextSource\getUser(), Hooks\run(), TS_MW, TS_RFC2822, wfClearOutputBuffers(), and wfTimestamp().

Referenced by executeAction().

ApiMain::checkExecutePermissions (   $module)
protected

Check for sufficient permissions to execute.

Parameters
ApiBase$moduleAn Api module

Definition at line 1261 of file ApiMain.php.

References $user, checkReadOnly(), ApiBase\dieUsage(), ApiBase\dieUsageMsg(), ContextSource\getRequest(), ContextSource\getUser(), User\isEveryoneAllowed(), and Hooks\run().

Referenced by executeAction().

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 1121 of file ApiMain.php.

References $params, $response, ApiBase\dieUsage(), ContextSource\getConfig(), ContextSource\getRequest(), list, and wfGetLB().

Referenced by executeAction().

ApiMain::checkReadOnly (   $module)
protected

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

Parameters
ApiBase$moduleAn Api module

Definition at line 1295 of file ApiMain.php.

References checkBotReadOnly(), ApiBase\dieReadOnly(), ContextSource\getUser(), wfGetLB(), and wfReadOnly().

Referenced by checkExecutePermissions().

ApiMain::createErrorPrinter ( )
private

Create the printer for error output.

Definition at line 943 of file ApiMain.php.

References $value, createPrinterByName(), and ContextSource\getRequest().

Referenced by handleException().

ApiMain::createPrinterByName (   $format)

Create an instance of an output formatter by its name.

Parameters
string$format
Returns
ApiFormatBase

Definition at line 464 of file ApiMain.php.

References ApiBase\dieUsage().

Referenced by ApiFormatRaw\__construct(), createErrorPrinter(), and setupExternalResponse().

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 1521 of file ApiMain.php.

References $s.

Referenced by logRequest().

ApiMain::errorMessageFromException (   $e)
protected

Create an error message for the given exception.

If the exception is a UsageException then UsageException::getMessageArray() will be called to create the message.

Parameters
Exception$e
Returns
array ['code' => 'some string', 'info' => 'some other string']
Since
1.27

Definition at line 969 of file ApiMain.php.

References $e, ContextSource\getConfig(), and WebRequest\getRequestId().

Referenced by logRequest(), and substituteResultWithError().

ApiMain::execute ( )

Execute api request.

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

Definition at line 476 of file ApiMain.php.

References executeAction(), and 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 488 of file ApiMain.php.

References $e, $t, executeAction(), ContextSource\getContext(), ContextSource\getRequest(), ContextSource\getStats(), handleCORS(), handleException(), logRequest(), MediaWiki\preOutputCommit(), and sendCacheHeaders().

Referenced by execute().

ApiMain::getAllowedParams ( )

See ApiBase for description.

Returns
array

Definition at line 1649 of file ApiMain.php.

References API_DEFAULT_FORMAT, ApiBase\PARAM_DFLT, and ApiBase\PARAM_TYPE.

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 1579 of file ApiMain.php.

References $name, and getVal().

ApiMain::getContinuationManager ( )

Get the continuation manager.

Returns
ApiContinuationManager|null

Definition at line 332 of file ApiMain.php.

References $mContinuationManager.

ApiMain::getErrorFormatter ( )

Get the ApiErrorFormatter object associated with current request.

Returns
ApiErrorFormatter

Definition at line 324 of file ApiMain.php.

References $mErrorFormatter.

ApiMain::getExamplesMessages ( )
protected
See also
ApiBase::getExamplesMessages()

Definition at line 1687 of file ApiMain.php.

ApiMain::getModule ( )

Get the API module object.

Only works after executeAction()

Returns
ApiBase

Definition at line 362 of file ApiMain.php.

References $mModule.

ApiMain::getModuleManager ( )

Overrides to return this instance's module manager.

Returns
ApiModuleManager

Definition at line 1812 of file ApiMain.php.

References $mModuleMgr.

Referenced by ApiDocumentationTest\provideDocumentationExists().

ApiMain::getParamsUsed ( )
protected

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

Returns
array

Definition at line 1538 of file ApiMain.php.

Referenced by logRequest(), and reportUnusedParams().

ApiMain::getPrinter ( )

Get the result formatter object.

Only works after setupExecuteAction()

Returns
ApiFormatBase

Definition at line 371 of file ApiMain.php.

References $mPrinter.

ApiMain::getResult ( )

Get the ApiResult object associated with current request.

Returns
ApiResult

Definition at line 281 of file ApiMain.php.

References $mResult.

Referenced by executeAction(), setupExecuteAction(), and substituteResultWithError().

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 1590 of file ApiMain.php.

References $name, and ContextSource\getRequest().

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 1824 of file ApiMain.php.

References ContextSource\getRequest().

Referenced by __construct(), and logRequest().

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

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

Parameters
string$name
mixed$default
Returns
mixed

Definition at line 1556 of file ApiMain.php.

References $name, $ret, ContextSource\getRequest(), and ApiBase\setWarning().

Referenced by getCheck().

static ApiMain::handleApiBeforeMainException ( Exception  $e)
static

Handle an exception from the ApiBeforeMain hook.

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

Since
1.23
Parameters
Exception$e
Exceptions
Exception

Definition at line 612 of file ApiMain.php.

References $e, false, and RequestContext\getMain().

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. http://www.w3.org/TR/cors/#resource-requests http://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 644 of file ApiMain.php.

References $request, $response, ContextSource\getConfig(), ContextSource\getOutput(), ApiBase\getParameter(), and ContextSource\getRequest().

Referenced by executeActionWithErrorHandling().

ApiMain::handleException ( Exception  $e)
protected
ApiMain::isInternalMode ( )

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

Returns
bool

Definition at line 272 of file ApiMain.php.

References $mInternalMode.

ApiMain::isReadMode ( )
Returns
bool

Definition at line 1640 of file ApiMain.php.

ApiMain::lacksSameOriginSecurity ( )

Get the security flag for the current request.

Returns
bool

Definition at line 289 of file ApiMain.php.

References $lacksSameOriginSecurity, $request, false, ContextSource\getRequest(), and Hooks\run().

Referenced by __construct().

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

Log the preceding request.

Parameters
float$timeTime in seconds
Exception$eException caught while processing the request

Definition at line 1471 of file ApiMain.php.

References $e, $name, $request, $time, $value, as, encodeRequestLogValue(), errorMessageFromException(), getParamsUsed(), ContextSource\getRequest(), ContextSource\getUser(), getUserAgent(), wfDebugLog(), wfUrlencode(), and wfWikiID().

Referenced by executeActionWithErrorHandling().

ApiMain::markParamsUsed (   $params)

Mark parameters as used.

Parameters
string|string[]$params

Definition at line 1546 of file ApiMain.php.

References $params, and array().

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 749 of file ApiMain.php.

References $value, and as.

static ApiMain::matchRequestedHeaders (   $requestedHeaders)
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 seperated list of HTTP headers
Returns
bool True if all requested headers are in the list of allowed headers

Definition at line 773 of file ApiMain.php.

References as, and wfDebugLog().

ApiMain::printResult (   $isError)
protected

Print results using the current printer.

Parameters
bool$isError

Definition at line 1626 of file ApiMain.php.

References $mPrinter, ContextSource\getConfig(), ApiFormatBase\initPrinter(), and ApiBase\setWarning().

Referenced by executeAction(), and handleException().

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 1600 of file ApiMain.php.

References $s, getParamsUsed(), ContextSource\getRequest(), and ApiBase\setWarning().

Referenced by executeAction().

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 825 of file ApiMain.php.

References $name, $out, $response, $value, as, ContextSource\getConfig(), ContextSource\getOutput(), ApiBase\getParameter(), ContextSource\getRequest(), TS_RFC2822, and wfTimestamp().

Referenced by executeActionWithErrorHandling().

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 453 of file ApiMain.php.

References $mCacheControl.

Referenced by setCacheMaxAge().

ApiMain::setCacheMaxAge (   $maxage)

Set how long the response should be cached.

Parameters
int$maxage

Definition at line 380 of file ApiMain.php.

References setCacheControl().

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 412 of file ApiMain.php.

References ApiBase\getParameter(), User\isEveryoneAllowed(), and wfDebug().

Referenced by handleException().

ApiMain::setContinuationManager (   $manager)

Set the continuation manager.

Parameters
ApiContinuationManager|null

Definition at line 340 of file ApiMain.php.

ApiMain::setRequestExpectations ( ApiBase  $module)
protected

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

Parameters
ApiBase$module

Definition at line 1452 of file ApiMain.php.

References ContextSource\getConfig(), ContextSource\getRequest(), Profiler\instance(), and ApiBase\isWriteMode().

Referenced by executeAction().

ApiMain::setupExecuteAction ( )
protected
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 1380 of file ApiMain.php.

References $params, $request, createPrinterByName(), ApiBase\dieUsageMsgOrDebug(), ContextSource\getRequest(), ContextSource\getUser(), ApiBase\logFeatureUsage(), and ApiBase\setWarning().

Referenced by executeAction().

ApiMain::setupModule ( )
protected

Set up the module for response.

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

Definition at line 1079 of file ApiMain.php.

References ApiBase\dieUsage(), ApiBase\dieUsageMsg(), and true.

Referenced by executeAction().

ApiMain::substituteResultWithError (   $e)
protected

Replace the result data with the information about an exception.

Returns the error code

Parameters
Exception$e
Returns
string

Definition at line 996 of file ApiMain.php.

References $e, $link, errorMessageFromException(), ContextSource\getConfig(), ApiBase\getParameter(), MWExceptionHandler\getRedactedTraceAsString(), getResult(), ApiResult\NO_SIZE_CHECK, ApiResult\setContentValue(), wfExpandUrl(), wfHostname(), and wfScript().

Referenced by handleException().

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 809 of file ApiMain.php.

Member Data Documentation

static ApiMain::$Formats
staticprivate
Initial value:
= [
'json' => 'ApiFormatJson'

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

Definition at line 108 of file ApiMain.php.

bool null ApiMain::$lacksSameOriginSecurity = null
private

Cached return value from self::lacksSameOriginSecurity()

Definition at line 157 of file ApiMain.php.

Referenced by lacksSameOriginSecurity().

ApiMain::$mAction
private

Definition at line 146 of file ApiMain.php.

ApiMain::$mCacheControl = []
private

Definition at line 153 of file ApiMain.php.

Referenced by setCacheControl().

ApiMain::$mCacheMode = 'private'
private

Definition at line 152 of file ApiMain.php.

ApiMain::$mCanApiHighLimits = null
private

Definition at line 1794 of file ApiMain.php.

Referenced by canApiHighLimits().

ApiContinuationManager null ApiMain::$mContinuationManager
private

Definition at line 145 of file ApiMain.php.

Referenced by getContinuationManager().

ApiMain::$mEnableWrite
private

Definition at line 147 of file ApiMain.php.

ApiMain::$mErrorFormatter

Definition at line 143 of file ApiMain.php.

Referenced by getErrorFormatter().

ApiMain::$mInternalMode
private

Definition at line 148 of file ApiMain.php.

Referenced by isInternalMode().

ApiBase ApiMain::$mModule
private

Definition at line 150 of file ApiMain.php.

Referenced by getModule().

ApiMain::$mModuleMgr
private

Definition at line 143 of file ApiMain.php.

Referenced by getModuleManager().

ApiMain::$Modules
staticprivate
Initial value:
= [
'login' => 'ApiLogin'

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

Definition at line 52 of file ApiMain.php.

ApiMain::$mParamsUsed = []
private

Definition at line 154 of file ApiMain.php.

static static ApiFormatBase ApiMain::$mPrinter
private
Initial value:
=> []
],
'apihighlimits' => [
'msg' => 'api-help-right-apihighlimits',
]
]

Definition at line 129 of file ApiMain.php.

Referenced by getPrinter(), and printResult().

ApiMain::$mResult

Definition at line 143 of file ApiMain.php.

Referenced by getResult().

static static ApiMain::$mRights
staticprivate
Initial value:
= [
'writeapi' => [
'msg' => 'right-writeapi'

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

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

Definition at line 126 of file ApiMain.php.

ApiMain::$mSquidMaxage

Definition at line 148 of file ApiMain.php.

const ApiMain::API_DEFAULT_FORMAT = 'jsonfm'

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

Definition at line 47 of file ApiMain.php.

Referenced by getAllowedParams().


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