<?php
-
-/*
- * Created on Sep 5, 2006
+/**
+ *
*
- * API for MediaWiki 1.8+
+ * Created on Sep 5, 2006
*
- * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
+ * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
- * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
*/
+use Wikimedia\Rdbms\IDatabase;
+
/**
- * This abstract class implements many basic API functions, and is the base of all API classes.
+ * This abstract class implements many basic API functions, and is the base of
+ * all API classes.
* The class functions are divided into several areas of functionality:
*
- * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
- * how to parse and validate them.
- *
- * Profiling: various methods to allow keeping tabs on various tasks and their time costs
+ * Module parameters: Derived classes can define getAllowedParams() to specify
+ * which parameters to expect, how to parse and validate them.
*
- * Self-documentation: code to allow api to document its own state.
+ * Self-documentation: code to allow the API to document its own state
*
* @ingroup API
*/
-abstract class ApiBase {
-
- // These constants allow modules to specify exactly how to treat incoming parameters.
-
- const PARAM_DFLT = 0; // Default value of the parameter
- const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
- const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
- const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
- const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
- const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
- const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
-
- const LIMIT_BIG1 = 500; // Fast query, std user limit
- const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
- const LIMIT_SML1 = 50; // Slow query, std user limit
- const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
-
- private $mMainModule, $mModuleName, $mModulePrefix;
+abstract class ApiBase extends ContextSource {
/**
- * Constructor
- */
- public function __construct($mainModule, $moduleName, $modulePrefix = '') {
- $this->mMainModule = $mainModule;
- $this->mModuleName = $moduleName;
- $this->mModulePrefix = $modulePrefix;
- }
+ * @name Constants for ::getAllowedParams() arrays
+ * These constants are keys in the arrays returned by ::getAllowedParams()
+ * and accepted by ::getParameterFromSettings() that define how the
+ * parameters coming in from the request are to be interpreted.
+ * @{
+ */
+
+ /** (null|boolean|integer|string) Default value of the parameter. */
+ const PARAM_DFLT = 0;
- /*****************************************************************************
- * ABSTRACT METHODS *
- *****************************************************************************/
+ /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
+ const PARAM_ISMULTI = 1;
/**
- * Evaluates the parameters, performs the requested query, and sets up the
- * result. Concrete implementations of ApiBase must override this method to
- * provide whatever functionality their module offers. Implementations must
- * not produce any output on their own and are not expected to handle any
- * errors.
+ * (string|string[]) Either an array of allowed value strings, or a string
+ * type as described below. If not specified, will be determined from the
+ * type of PARAM_DFLT.
*
- * The execute method will be invoked directly by ApiMain immediately before
- * the result of the module is output. Aside from the constructor, implementations
- * should assume that no other methods will be called externally on the module
- * before the result is processed.
- *
- * The result data should be stored in the result object referred to by
- * "getResult()". Refer to ApiResult.php for details on populating a result
- * object.
+ * Supported string types are:
+ * - boolean: A boolean parameter, returned as false if the parameter is
+ * omitted and true if present (even with a falsey value, i.e. it works
+ * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
+ * Cannot be used with PARAM_ISMULTI.
+ * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
+ * PARAM_RANGE_ENFORCE.
+ * - limit: An integer or the string 'max'. Default lower limit is 0 (but
+ * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
+ * specified. Cannot be used with PARAM_ISMULTI.
+ * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
+ * support easily specifying all namespaces.
+ * - NULL: Any string.
+ * - password: Any non-empty string. Input value is private or sensitive.
+ * <input type="password"> would be an appropriate HTML form field.
+ * - string: Any non-empty string, not expected to be very long or contain newlines.
+ * <input type="text"> would be an appropriate HTML form field.
+ * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
+ * - tags: A string naming an existing, explicitly-defined tag. Should usually be
+ * used with PARAM_ISMULTI.
+ * - text: Any non-empty string, expected to be very long or contain newlines.
+ * <textarea> would be an appropriate HTML form field.
+ * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
+ * string 'now' representing the current timestamp. Will be returned in
+ * TS_MW format.
+ * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
+ * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
+ * Cannot be used with PARAM_ISMULTI.
*/
- public abstract function execute();
+ const PARAM_TYPE = 2;
- /**
- * Returns a String that identifies the version of the extending class. Typically
- * includes the class name, the svn revision, timestamp, and last author. May
- * be severely incorrect in many implementations!
- */
- public abstract function getVersion();
+ /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
+ const PARAM_MAX = 3;
/**
- * Get the name of the module being executed by this instance
+ * (integer) Max value allowed for the parameter for users with the
+ * apihighlimits right, for PARAM_TYPE 'limit'.
*/
- public function getModuleName() {
- return $this->mModuleName;
- }
+ const PARAM_MAX2 = 4;
+
+ /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
+ const PARAM_MIN = 5;
+
+ /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
+ const PARAM_ALLOW_DUPLICATES = 6;
+
+ /** (boolean) Is the parameter deprecated (will show a warning)? */
+ const PARAM_DEPRECATED = 7;
/**
- * Get parameter prefix (usually two letters or an empty string).
+ * (boolean) Is the parameter required?
+ * @since 1.17
*/
- public function getModulePrefix() {
- return $this->mModulePrefix;
- }
+ const PARAM_REQUIRED = 8;
/**
- * Get the name of the module as shown in the profiler log
+ * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
+ * @since 1.17
*/
- public function getModuleProfileName($db = false) {
- if ($db)
- return 'API:' . $this->mModuleName . '-DB';
- else
- return 'API:' . $this->mModuleName;
- }
+ const PARAM_RANGE_ENFORCE = 9;
/**
- * Get main module
+ * (string|array|Message) Specify an alternative i18n documentation message
+ * for this parameter. Default is apihelp-{$path}-param-{$param}.
+ * @since 1.25
*/
- public function getMain() {
- return $this->mMainModule;
- }
+ const PARAM_HELP_MSG = 10;
/**
- * Returns true if this module is the main module ($this === $this->mMainModule),
- * false otherwise.
+ * ((string|array|Message)[]) Specify additional i18n messages to append to
+ * the normal message for this parameter.
+ * @since 1.25
*/
- public function isMain() {
- return $this === $this->mMainModule;
- }
+ const PARAM_HELP_MSG_APPEND = 11;
/**
- * Get the result object. Please refer to the documentation in ApiResult.php
- * for details on populating and accessing data in a result object.
+ * (array) Specify additional information tags for the parameter. Value is
+ * an array of arrays, with the first member being the 'tag' for the info
+ * and the remaining members being the values. In the help, this is
+ * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
+ * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
+ * @since 1.25
*/
- public function getResult() {
- // Main module has getResult() method overriden
- // Safety - avoid infinite loop:
- if ($this->isMain())
- ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
- return $this->getMain()->getResult();
- }
+ const PARAM_HELP_MSG_INFO = 12;
/**
- * Get the result data array
+ * (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.
+ * @since 1.25
*/
- public function & getResultData() {
- return $this->getResult()->getData();
- }
+ const PARAM_VALUE_LINKS = 13;
/**
- * Set warning section for this module. Users should monitor this section to
- * notice any changes in API.
+ * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
+ * mapping those values to $msg for ApiBase::makeMessage(). Any value not
+ * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
+ * @since 1.25
*/
- public function setWarning($warning) {
- # If there is a warning already, append it to the existing one
- $data =& $this->getResult()->getData();
- if(isset($data['warnings'][$this->getModuleName()]))
- {
- # Don't add duplicate warnings
- $warn_regex = preg_quote($warning, '/');
- if(preg_match("/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*']))
- return;
- $warning = "{$data['warnings'][$this->getModuleName()]['*']}\n$warning";
- unset($data['warnings'][$this->getModuleName()]);
- }
- $msg = array();
- ApiResult :: setContent($msg, $warning);
- $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
- }
+ const PARAM_HELP_MSG_PER_VALUE = 14;
/**
- * If the module may only be used with a certain format module,
- * it should override this method to return an instance of that formatter.
- * A value of null means the default format will be used.
+ * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
+ * submodule paths. Default is to use all modules in
+ * $this->getModuleManager() in the group matching the parameter name.
+ * @since 1.26
*/
- public function getCustomPrinter() {
- return null;
- }
+ const PARAM_SUBMODULE_MAP = 15;
/**
- * Generates help message for this module, or false if there is no description
+ * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
+ * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
+ * @since 1.26
*/
- public function makeHelpMsg() {
-
- static $lnPrfx = "\n ";
-
- $msg = $this->getDescription();
-
- if ($msg !== false) {
-
- if (!is_array($msg))
- $msg = array (
- $msg
- );
- $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
-
- if ($this->mustBePosted())
- $msg .= "\nThis module only accepts POST requests.\n";
-
- // Parameters
- $paramsMsg = $this->makeHelpMsgParameters();
- if ($paramsMsg !== false) {
- $msg .= "Parameters:\n$paramsMsg";
- }
-
- // Examples
- $examples = $this->getExamples();
- if ($examples !== false) {
- if (!is_array($examples))
- $examples = array (
- $examples
- );
- $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
- $msg .= implode($lnPrfx, $examples) . "\n";
- }
-
- if ($this->getMain()->getShowVersions()) {
- $versions = $this->getVersion();
- $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
- $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
-
- if (is_array($versions)) {
- foreach ($versions as &$v)
- $v = eregi_replace($pattern, $replacement, $v);
- $versions = implode("\n ", $versions);
- }
- else
- $versions = eregi_replace($pattern, $replacement, $versions);
-
- $msg .= "Version:\n $versions\n";
- }
- }
-
- return $msg;
- }
+ const PARAM_SUBMODULE_PARAM_PREFIX = 16;
/**
- * Generates the parameter descriptions for this module, to be displayed in the
- * module's help.
- */
- public function makeHelpMsgParameters() {
- $params = $this->getFinalParams();
- if ($params !== false) {
-
- $paramsDescription = $this->getFinalParamDescription();
- $msg = '';
- $paramPrefix = "\n" . str_repeat(' ', 19);
- foreach ($params as $paramName => $paramSettings) {
- $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
- if (is_array($desc))
- $desc = implode($paramPrefix, $desc);
-
- $type = isset($paramSettings[self :: PARAM_TYPE])? $paramSettings[self :: PARAM_TYPE] : null;
- if (isset ($type)) {
- if (isset ($paramSettings[self :: PARAM_ISMULTI]))
- $prompt = 'Values (separate with \'|\'): ';
- else
- $prompt = 'One value: ';
-
- if (is_array($type)) {
- $choices = array();
- $nothingPrompt = false;
- foreach ($type as $t)
- if ($t === '')
- $nothingPrompt = 'Can be empty, or ';
- else
- $choices[] = $t;
- $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
- } else {
- switch ($type) {
- case 'namespace':
- // Special handling because namespaces are type-limited, yet they are not given
- $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
- break;
- case 'limit':
- $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
- break;
- case 'integer':
- $hasMin = isset($paramSettings[self :: PARAM_MIN]);
- $hasMax = isset($paramSettings[self :: PARAM_MAX]);
- if ($hasMin || $hasMax) {
- if (!$hasMax)
- $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
- elseif (!$hasMin)
- $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
- else
- $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
-
- $desc .= $paramPrefix . $intRangeStr;
- }
- break;
- }
- }
- }
-
- $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
- if (!is_null($default) && $default !== false)
- $desc .= $paramPrefix . "Default: $default";
-
- $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
- }
- return $msg;
-
- } else
- return false;
- }
+ * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
+ * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
+ * every possible value. If a string is set, it will be used in place of the asterisk.
+ * @since 1.29
+ */
+ const PARAM_ALL = 17;
/**
- * Returns the description string for this module
+ * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
+ * @since 1.29
*/
- protected function getDescription() {
- return false;
- }
+ const PARAM_EXTRA_NAMESPACES = 18;
/**
- * Returns usage examples for this module. Return null if no examples are available.
+ * (boolean) Is the parameter sensitive? Note 'password'-type fields are
+ * always sensitive regardless of the value of this field.
+ * @since 1.29
*/
- protected function getExamples() {
- return false;
- }
+ const PARAM_SENSITIVE = 19;
/**
- * Returns an array of allowed parameters (keys) => default value for that parameter.
- * Don't call this function directly: use getFinalParams() to allow hooks
- * to modify parameters as needed.
+ * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
+ * Keys are the deprecated parameter values, values define the warning
+ * message to emit: either boolean true (to use a default message) or a
+ * $msg for ApiBase::makeMessage().
+ * @since 1.30
*/
- protected function getAllowedParams() {
- return false;
- }
+ const PARAM_DEPRECATED_VALUES = 20;
/**
- * Returns an array of parameter descriptions.
- * Don't call this functon directly: use getFinalParamDescription() to allow
- * hooks to modify descriptions as needed.
+ * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
+ * @since 1.30
*/
- protected function getParamDescription() {
- return false;
- }
-
+ const PARAM_ISMULTI_LIMIT1 = 21;
+
/**
- * Get final list of parameters, after hooks have had
- * a chance to tweak it as needed.
+ * (integer) Maximum number of values, for users with the apihighimits right.
+ * Must be used with PARAM_ISMULTI.
+ * @since 1.30
*/
- public function getFinalParams() {
- $params = $this->getAllowedParams();
- wfRunHooks('APIGetAllowedParams', array(&$this, &$params));
- return $params;
- }
-
-
- public function getFinalParamDescription() {
- $desc = $this->getParamDescription();
- wfRunHooks('APIGetParamDescription', array(&$this, &$desc));
- return $desc;
- }
+ const PARAM_ISMULTI_LIMIT2 = 22;
+
+ /**@}*/
+
+ const ALL_DEFAULT_STRING = '*';
+
+ /** Fast query, standard limit. */
+ const LIMIT_BIG1 = 500;
+ /** Fast query, apihighlimits limit. */
+ const LIMIT_BIG2 = 5000;
+ /** Slow query, standard limit. */
+ const LIMIT_SML1 = 50;
+ /** Slow query, apihighlimits limit. */
+ const LIMIT_SML2 = 500;
/**
- * This method mangles parameter name based on the prefix supplied to the constructor.
- * Override this method to change parameter name during runtime
+ * getAllowedParams() flag: When set, the result could take longer to generate,
+ * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
+ * @since 1.21
*/
- public function encodeParamName($paramName) {
- return $this->mModulePrefix . $paramName;
- }
+ const GET_VALUES_FOR_HELP = 1;
- /**
- * Using getAllowedParams(), 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.
- * limit=max will not be parsed if $parseMaxLimit is set to false; use this
- * when the max limit is not definite, e.g. when getting revisions.
- */
- public function extractRequestParams($parseMaxLimit = true) {
- $params = $this->getFinalParams();
- $results = array ();
+ /** @var array Maps extension paths to info arrays */
+ private static $extensionInfo = null;
+
+ /** @var ApiMain */
+ private $mMainModule;
+ /** @var string */
+ private $mModuleName, $mModulePrefix;
+ private $mSlaveDB = null;
+ private $mParamCache = [];
+ /** @var array|null|bool */
+ private $mModuleSource = false;
- foreach ($params as $paramName => $paramSettings)
- $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
+ /**
+ * @param ApiMain $mainModule
+ * @param string $moduleName Name of this module
+ * @param string $modulePrefix Prefix to use for parameter names
+ */
+ public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
+ $this->mMainModule = $mainModule;
+ $this->mModuleName = $moduleName;
+ $this->mModulePrefix = $modulePrefix;
- return $results;
+ if ( !$this->isMain() ) {
+ $this->setContext( $mainModule->getContext() );
+ }
}
+ /************************************************************************//**
+ * @name Methods to implement
+ * @{
+ */
+
/**
- * Get a value for the given parameter
+ * Evaluates the parameters, performs the requested query, and sets up
+ * the result. Concrete implementations of ApiBase must override this
+ * method to provide whatever functionality their module offers.
+ * Implementations must not produce any output on their own and are not
+ * expected to handle any errors.
+ *
+ * The execute() method will be invoked directly by ApiMain immediately
+ * before the result of the module is output. Aside from the
+ * constructor, implementations should assume that no other methods
+ * will be called externally on the module before the result is
+ * processed.
+ *
+ * The result data should be stored in the ApiResult object available
+ * through getResult().
*/
- protected function getParameter($paramName, $parseMaxLimit = true) {
- $params = $this->getFinalParams();
- $paramSettings = $params[$paramName];
- return $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
- }
-
+ abstract public function execute();
+
/**
- * Die if none or more than one of a certain set of parameters is set
+ * Get the module manager, or null if this module has no sub-modules
+ * @since 1.21
+ * @return ApiModuleManager
*/
- public function requireOnlyOneParameter($params) {
- $required = func_get_args();
- array_shift($required);
-
- $intersection = array_intersect(array_keys(array_filter($params,
- create_function('$x', 'return !is_null($x);')
- )), $required);
- if (count($intersection) > 1) {
- $this->dieUsage('The parameters '.implode(', ', $intersection).' can not be used together', 'invalidparammix');
- } elseif (count($intersection) == 0) {
- $this->dieUsage('One of the parameters '.implode(', ', $required).' is required', 'missingparam');
- }
+ public function getModuleManager() {
+ return null;
}
/**
- * Returns an array of the namespaces (by integer id) that exist on the
- * wiki. Used primarily in help documentation.
+ * If the module may only be used with a certain format module,
+ * it should override this method to return an instance of that formatter.
+ * A value of null means the default format will be used.
+ * @note Do not use this just because you don't want to support non-json
+ * formats. This should be used only when there is a fundamental
+ * requirement for a specific format.
+ * @return mixed Instance of a derived class of ApiFormatBase, or null
*/
- public static function getValidNamespaces() {
- static $mValidNamespaces = null;
- if (is_null($mValidNamespaces)) {
-
- global $wgContLang;
- $mValidNamespaces = array ();
- foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
- if ($ns >= 0)
- $mValidNamespaces[] = $ns;
- }
- }
- return $mValidNamespaces;
+ public function getCustomPrinter() {
+ return null;
}
/**
- * Using the settings determine the value for the given parameter
+ * 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.
*
- * @param $paramName String: parameter name
- * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
- * @param $parseMaxLimit Boolean: parse limit when max is given?
+ * Do not call this base class implementation when overriding this method.
+ *
+ * @since 1.25
+ * @return array
*/
- protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
-
- // Some classes may decide to change parameter names
- $encParamName = $this->encodeParamName($paramName);
-
- if (!is_array($paramSettings)) {
- $default = $paramSettings;
- $multi = false;
- $type = gettype($paramSettings);
- $dupes = false;
- } else {
- $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
- $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
- $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
- $dupes = isset ($paramSettings[self:: PARAM_ALLOW_DUPLICATES]) ? $paramSettings[self :: PARAM_ALLOW_DUPLICATES] : false;
-
- // When type is not given, and no choices, the type is the same as $default
- if (!isset ($type)) {
- if (isset ($default))
- $type = gettype($default);
- else
- $type = 'NULL'; // allow everything
- }
- }
-
- if ($type == 'boolean') {
- if (isset ($default) && $default !== false) {
- // Having a default value of anything other than 'false' is pointless
- ApiBase :: dieDebug(__METHOD__, "Boolean param $encParamName's default is set to '$default'");
- }
-
- $value = $this->getMain()->getRequest()->getCheck($encParamName);
- } else {
- $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
-
- if (isset ($value) && $type == 'namespace')
- $type = ApiBase :: getValidNamespaces();
- }
-
- if (isset ($value) && ($multi || is_array($type)))
- $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
-
- // More validation only when choices were not given
- // choices were validated in parseMultiValue()
- if (isset ($value)) {
- if (!is_array($type)) {
- switch ($type) {
- case 'NULL' : // nothing to do
- break;
- case 'string' : // nothing to do
- break;
- case 'integer' : // Force everything using intval() and optionally validate limits
-
- $value = is_array($value) ? array_map('intval', $value) : intval($value);
- $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : null;
- $max = isset ($paramSettings[self :: PARAM_MAX]) ? $paramSettings[self :: PARAM_MAX] : null;
-
- if (!is_null($min) || !is_null($max)) {
- $values = is_array($value) ? $value : array($value);
- foreach ($values as $v) {
- $this->validateLimit($paramName, $v, $min, $max);
- }
- }
- break;
- case 'limit' :
- if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
- ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName");
- if ($multi)
- ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
- $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
- if( $value == 'max' ) {
- if( $parseMaxLimit ) {
- $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self :: PARAM_MAX2] : $paramSettings[self :: PARAM_MAX];
- $this->getResult()->addValue( 'limits', $this->getModuleName(), $value );
- $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
- }
- }
- else {
- $value = intval($value);
- $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
- }
- break;
- case 'boolean' :
- if ($multi)
- ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
- break;
- case 'timestamp' :
- if ($multi)
- ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
- $value = wfTimestamp(TS_UNIX, $value);
- if ($value === 0)
- $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
- $value = wfTimestamp(TS_MW, $value);
- break;
- case 'user' :
- $title = Title::makeTitleSafe( NS_USER, $value );
- if ( is_null( $title ) )
- $this->dieUsage("Invalid value for user parameter $encParamName", "baduser_{$encParamName}");
- $value = $title->getText();
- break;
- default :
- ApiBase :: dieDebug(__METHOD__, "Param $encParamName's type is unknown - $type");
+ protected function getExamplesMessages() {
+ // Fall back to old non-localised method
+ $ret = [];
+
+ $examples = $this->getExamples();
+ if ( $examples ) {
+ if ( !is_array( $examples ) ) {
+ $examples = [ $examples ];
+ } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
+ array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
+ !preg_match( '/^\s*api\.php\?/', $examples[0] )
+ ) {
+ // Fix up the ugly "even numbered elements are description, odd
+ // numbered elemts are the link" format (see doc for self::getExamples)
+ $tmp = [];
+ $examplesCount = count( $examples );
+ for ( $i = 0; $i < $examplesCount; $i += 2 ) {
+ $tmp[$examples[$i + 1]] = $examples[$i];
}
+ $examples = $tmp;
}
- // Throw out duplicates if requested
- if (is_array($value) && !$dupes)
- $value = array_unique($value);
- }
-
- return $value;
- }
-
- /**
- * Return an array of values that were given in a 'a|b|c' notation,
- * after it optionally validates them against the list allowed values.
- *
- * @param valueName - The name of the parameter (for error reporting)
- * @param value - The value being parsed
- * @param allowMultiple - Can $value contain more than one value separated by '|'?
- * @param allowedValues - An array of values to check against. If null, all values are accepted.
- * @return (allowMultiple ? an_array_of_values : a_single_value)
- */
- protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
- if( trim($value) === "" )
- return array();
- $sizeLimit = $this->mMainModule->canApiHighLimits() ? self::LIMIT_SML2 : self::LIMIT_SML1;
- $valuesList = explode('|', $value, $sizeLimit + 1);
- if( self::truncateArray($valuesList, $sizeLimit) ) {
- $this->setWarning("Too many values supplied for parameter '$valueName': the limit is $sizeLimit");
- }
- if (!$allowMultiple && count($valuesList) != 1) {
- $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
- $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
- }
- if (is_array($allowedValues)) {
- # Check for unknown values
- $unknown = array_diff($valuesList, $allowedValues);
- if(count($unknown))
- {
- if($allowMultiple)
- {
- $s = count($unknown) > 1 ? "s" : "";
- $vals = implode(", ", $unknown);
- $this->setWarning("Unrecognized value$s for parameter '$valueName': $vals");
+ foreach ( $examples as $k => $v ) {
+ if ( is_numeric( $k ) ) {
+ $qs = $v;
+ $msg = '';
+ } else {
+ $qs = $k;
+ $msg = self::escapeWikiText( $v );
+ if ( is_array( $msg ) ) {
+ $msg = implode( ' ', $msg );
+ }
}
- else
- $this->dieUsage("Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName");
+
+ $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
+ $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
}
- # Now throw them out
- $valuesList = array_intersect($valuesList, $allowedValues);
}
- return $allowMultiple ? $valuesList : $valuesList[0];
+ return $ret;
}
/**
- * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
- */
- function validateLimit($paramName, $value, $min, $max, $botMax = null) {
- if (!is_null($min) && $value < $min) {
- $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
- }
-
- // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
- if ($this->getMain()->isInternalMode())
- return;
-
- // Optimization: do not check user's bot status unless really needed -- skips db query
- // assumes $botMax >= $max
- if (!is_null($max) && $value > $max) {
- if (!is_null($botMax) && $this->getMain()->canApiHighLimits()) {
- if ($value > $botMax) {
- $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
- }
- } else {
- $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
- }
- }
- }
-
- /**
- * Truncate an array to a certain length.
- * @param $arr array Array to truncate
- * @param $limit int Maximum length
- * @return bool True if the array was truncated, false otherwise
+ * Return links to more detailed help pages about the module.
+ * @since 1.25, returning boolean false is deprecated
+ * @return string|array
*/
- public static function truncateArray(&$arr, $limit)
- {
- $modified = false;
- while(count($arr) > $limit)
- {
- $junk = array_pop($arr);
- $modified = true;
- }
- return $modified;
+ public function getHelpUrls() {
+ return [];
}
/**
- * Call main module's error handler
- */
- public function dieUsage($description, $errorCode, $httpRespCode = 0) {
- throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
- }
-
- /**
- * Array that maps message keys to error messages. $1 and friends are replaced.
- */
- public static $messageMap = array(
- // This one MUST be present, or dieUsageMsg() will recurse infinitely
- 'unknownerror' => array('code' => 'unknownerror', 'info' => "Unknown error: ``\$1''"),
- 'unknownerror-nocode' => array('code' => 'unknownerror', 'info' => 'Unknown error'),
-
- // Messages from Title::getUserPermissionsErrors()
- 'ns-specialprotected' => array('code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited"),
- 'protectedinterface' => array('code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages"),
- 'namespaceprotected' => array('code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace"),
- 'customcssjsprotected' => array('code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages"),
- 'cascadeprotected' => array('code' => 'cascadeprotected', 'info' =>"The page you're trying to edit is protected because it's included in a cascade-protected page"),
- 'protectedpagetext' => array('code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page"),
- 'protect-cantedit' => array('code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it"),
- 'badaccess-group0' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Generic permission denied message
- 'badaccess-groups' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
- 'titleprotected' => array('code' => 'protectedtitle', 'info' => "This title has been protected from creation"),
- 'nocreate-loggedin' => array('code' => 'cantcreate', 'info' => "You don't have permission to create new pages"),
- 'nocreatetext' => array('code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages"),
- 'movenologintext' => array('code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages"),
- 'movenotallowed' => array('code' => 'cantmove', 'info' => "You don't have permission to move pages"),
- 'confirmedittext' => array('code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit"),
- 'blockedtext' => array('code' => 'blocked', 'info' => "You have been blocked from editing"),
- 'autoblockedtext' => array('code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"),
-
- // Miscellaneous interface messages
- 'actionthrottledtext' => array('code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again"),
- 'alreadyrolled' => array('code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back"),
- 'cantrollback' => array('code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author"),
- 'readonlytext' => array('code' => 'readonly', 'info' => "The wiki is currently in read-only mode"),
- 'sessionfailure' => array('code' => 'badtoken', 'info' => "Invalid token"),
- 'cannotdelete' => array('code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else"),
- 'notanarticle' => array('code' => 'missingtitle', 'info' => "The page you requested doesn't exist"),
- 'selfmove' => array('code' => 'selfmove', 'info' => "Can't move a page to itself"),
- 'immobile_namespace' => array('code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving"),
- 'articleexists' => array('code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article"),
- 'protectedpage' => array('code' => 'protectedpage', 'info' => "You don't have permission to perform this move"),
- 'hookaborted' => array('code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook"),
- 'cantmove-titleprotected' => array('code' => 'protectedtitle', 'info' => "The destination article has been protected from creation"),
- 'imagenocrossnamespace' => array('code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace"),
- 'imagetypemismatch' => array('code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type"),
- // 'badarticleerror' => shouldn't happen
- // 'badtitletext' => shouldn't happen
- 'ip_range_invalid' => array('code' => 'invalidrange', 'info' => "Invalid IP range"),
- 'range_block_disabled' => array('code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled"),
- 'nosuchusershort' => array('code' => 'nosuchuser', 'info' => "The user you specified doesn't exist"),
- 'badipaddress' => array('code' => 'invalidip', 'info' => "Invalid IP address specified"),
- 'ipb_expiry_invalid' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
- 'ipb_already_blocked' => array('code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked"),
- 'ipb_blocked_as_range' => array('code' => 'blockedasrange', 'info' => "IP address ``\$1'' was blocked as part of range ``\$2''. You can't unblock the IP invidually, but you can unblock the range as a whole."),
- 'ipb_cant_unblock' => array('code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already"),
- 'mailnologin' => array('code' => 'cantsend', 'info' => "You're not logged in or you don't have a confirmed e-mail address, so you can't send e-mail"),
- 'usermaildisabled' => array('code' => 'usermaildisabled', 'info' => "User email has been disabled"),
- 'blockedemailuser' => array('code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail"),
- 'notarget' => array('code' => 'notarget', 'info' => "You have not specified a valid target for this action"),
- 'noemail' => array('code' => 'noemail', 'info' => "The user has not specified a valid e-mail address, or has chosen not to receive e-mail from other users"),
- 'rcpatroldisabled' => array('code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki"),
- 'markedaspatrollederror-noautopatrol' => array('code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes"),
-
- // API-specific messages
- 'missingparam' => array('code' => 'no$1', 'info' => "The \$1 parameter must be set"),
- 'invalidtitle' => array('code' => 'invalidtitle', 'info' => "Bad title ``\$1''"),
- 'nosuchpageid' => array('code' => 'nosuchpageid', 'info' => "There is no page with ID \$1"),
- 'invaliduser' => array('code' => 'invaliduser', 'info' => "Invalid username ``\$1''"),
- 'invalidexpiry' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time ``\$1''"),
- 'pastexpiry' => array('code' => 'pastexpiry', 'info' => "Expiry time ``\$1'' is in the past"),
- 'create-titleexists' => array('code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'"),
- 'missingtitle-createonly' => array('code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'"),
- 'cantblock' => array('code' => 'cantblock', 'info' => "You don't have permission to block users"),
- 'canthide' => array('code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log"),
- 'cantblock-email' => array('code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki"),
- 'unblock-notarget' => array('code' => 'notarget', 'info' => "Either the id or the user parameter must be set"),
- 'unblock-idanduser' => array('code' => 'idanduser', 'info' => "The id and user parameters can't be used together"),
- 'cantunblock' => array('code' => 'permissiondenied', 'info' => "You don't have permission to unblock users"),
- 'cannotundelete' => array('code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"),
- 'permdenied-undelete' => array('code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions"),
- 'createonly-exists' => array('code' => 'articleexists', 'info' => "The article you tried to create has been created already"),
- 'nocreate-missing' => array('code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist"),
- 'nosuchrcid' => array('code' => 'nosuchrcid', 'info' => "There is no change with rcid ``\$1''"),
- 'cantpurge' => array('code' => 'cantpurge', 'info' => "Only users with the 'purge' right can purge pages via the API"),
- 'protect-invalidaction' => array('code' => 'protect-invalidaction', 'info' => "Invalid protection type ``\$1''"),
- 'protect-invalidlevel' => array('code' => 'protect-invalidlevel', 'info' => "Invalid protection level ``\$1''"),
- 'toofewexpiries' => array('code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed"),
-
-
- // ApiEditPage messages
- 'noimageredirect-anon' => array('code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects"),
- 'noimageredirect-logged' => array('code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects"),
- 'spamdetected' => array('code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: ``\$1''"),
- 'filtered' => array('code' => 'filtered', 'info' => "The filter callback function refused your edit"),
- 'contenttoobig' => array('code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 bytes"),
- 'noedit-anon' => array('code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages"),
- 'noedit' => array('code' => 'noedit', 'info' => "You don't have permission to edit pages"),
- 'wasdeleted' => array('code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp"),
- 'blankpage' => array('code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed"),
- 'editconflict' => array('code' => 'editconflict', 'info' => "Edit conflict detected"),
- 'hashcheckfailed' => array('code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect"),
- 'missingtext' => array('code' => 'notext', 'info' => "One of the text, appendtext and prependtext parameters must be set"),
- 'emptynewsection' => array('code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.'),
- );
-
- /**
- * Output the error message related to a certain array
- * @param array $error Element of a getUserPermissionsErrors()-style array
+ * 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.
+ *
+ * Some derived classes may choose to handle an integer $flags parameter
+ * in the overriding methods. Callers of this method can pass zero or
+ * more OR-ed flags like GET_VALUES_FOR_HELP.
+ *
+ * @return array
*/
- public function dieUsageMsg($error) {
- $parsed = $this->parseMsg($error);
- $this->dieUsage($parsed['code'], $parsed['info']);
- }
-
- /**
- * Return the error message related to a certain array
- * @param array $error Element of a getUserPermissionsErrors()-style array
- * @return array('code' => code, 'info' => info)
- */
- public function parseMsg($error) {
- $key = array_shift($error);
- if(isset(self::$messageMap[$key]))
- return array( 'code' =>
- wfMsgReplaceArgs(self::$messageMap[$key]['code'], $error),
- 'info' =>
- wfMsgReplaceArgs(self::$messageMap[$key]['info'], $error)
- );
- // If the key isn't present, throw an "unknown error"
- return $this->parseMsg(array('unknownerror', $key));
+ protected function getAllowedParams( /* $flags = 0 */ ) {
+ // int $flags is not declared because it causes "Strict standards"
+ // warning. Most derived classes do not implement it.
+ return [];
}
/**
- * Internal code errors should be reported with this method
+ * Indicates if this module needs maxlag to be checked
+ * @return bool
*/
- protected static function dieDebug($method, $message) {
- wfDebugDieBacktrace("Internal error in $method: $message");
+ public function shouldCheckMaxlag() {
+ return true;
}
/**
- * Indicates if API needs to check maxlag
+ * Indicates whether this module requires read rights
+ * @return bool
*/
- public function shouldCheckMaxlag() {
+ public function isReadMode() {
return true;
}
/**
- * Indicates if this module requires edit mode
+ * Indicates whether this module requires write mode
+ *
+ * This should return true for modules that may require synchronous database writes.
+ * Modules that do not need such writes should also not rely on master database access,
+ * since only read queries are needed and each master DB is a single point of failure.
+ * Additionally, requests that only need replica DBs can be efficiently routed to any
+ * datacenter via the Promise-Non-Write-API-Action header.
+ *
+ * @return bool
*/
- public function isEditMode() {
+ public function isWriteMode() {
return false;
}
/**
* Indicates whether this module must be called with a POST request
+ * @return bool
*/
public function mustBePosted() {
- return false;
+ return $this->needsToken() !== false;
}
-
/**
- * Profiling: total module execution time
+ * Indicates whether this module is deprecated
+ * @since 1.25
+ * @return bool
*/
- private $mTimeIn = 0, $mModuleTime = 0;
+ public function isDeprecated() {
+ return false;
+ }
/**
- * Start module profiling
+ * Indicates whether this module is "internal"
+ * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
+ * @since 1.25
+ * @return bool
*/
- public function profileIn() {
- if ($this->mTimeIn !== 0)
- ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
- $this->mTimeIn = microtime(true);
- wfProfileIn($this->getModuleProfileName());
+ public function isInternal() {
+ return false;
}
/**
- * End module profiling
+ * Returns the token type this module requires in order to execute.
+ *
+ * Modules are strongly encouraged to use the core 'csrf' type unless they
+ * have specialized security needs. If the token type is not one of the
+ * core types, you must use the ApiQueryTokensRegisterTypes hook to
+ * register it.
+ *
+ * Returning a non-falsey value here will force the addition of an
+ * appropriate 'token' parameter in self::getFinalParams(). Also,
+ * self::mustBePosted() must return true when tokens are used.
+ *
+ * In previous versions of MediaWiki, true was a valid return value.
+ * Returning true will generate errors indicating that the API module needs
+ * updating.
+ *
+ * @return string|false
*/
- public function profileOut() {
- if ($this->mTimeIn === 0)
- ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
- if ($this->mDBTimeIn !== 0)
- ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
-
- $this->mModuleTime += microtime(true) - $this->mTimeIn;
- $this->mTimeIn = 0;
- wfProfileOut($this->getModuleProfileName());
+ public function needsToken() {
+ return false;
}
/**
- * When modules crash, sometimes it is needed to do a profileOut() regardless
- * of the profiling state the module was in. This method does such cleanup.
+ * Fetch the salt used in the Web UI corresponding to this module.
+ *
+ * Only override this if the Web UI uses a token with a non-constant salt.
+ *
+ * @since 1.24
+ * @param array $params All supplied parameters for the module
+ * @return string|array|null
*/
- public function safeProfileOut() {
- if ($this->mTimeIn !== 0) {
- if ($this->mDBTimeIn !== 0)
- $this->profileDBOut();
- $this->profileOut();
- }
+ protected function getWebUITokenSalt( array $params ) {
+ return null;
}
/**
- * Total time the module was executed
+ * Returns data for HTTP conditional request mechanisms.
+ *
+ * @since 1.26
+ * @param string $condition Condition being queried:
+ * - last-modified: Return a timestamp representing the maximum of the
+ * last-modified dates for all resources involved in the request. See
+ * RFC 7232 § 2.2 for semantics.
+ * - etag: Return an entity-tag representing the state of all resources involved
+ * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
+ * @return string|bool|null As described above, or null if no value is available.
*/
- public function getProfileTime() {
- if ($this->mTimeIn !== 0)
- ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
- return $this->mModuleTime;
+ public function getConditionalRequestData( $condition ) {
+ return null;
}
- /**
- * Profiling: database execution time
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Data access methods
+ * @{
*/
- private $mDBTimeIn = 0, $mDBTime = 0;
/**
- * Start module profiling
+ * Get the name of the module being executed by this instance
+ * @return string
*/
- public function profileDBIn() {
- if ($this->mTimeIn === 0)
- ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
- if ($this->mDBTimeIn !== 0)
- ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
- $this->mDBTimeIn = microtime(true);
- wfProfileIn($this->getModuleProfileName(true));
+ public function getModuleName() {
+ return $this->mModuleName;
}
/**
- * End database profiling
+ * Get parameter prefix (usually two letters or an empty string).
+ * @return string
*/
- public function profileDBOut() {
- if ($this->mTimeIn === 0)
- ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
- if ($this->mDBTimeIn === 0)
- ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
-
- $time = microtime(true) - $this->mDBTimeIn;
- $this->mDBTimeIn = 0;
-
- $this->mDBTime += $time;
- $this->getMain()->mDBTime += $time;
- wfProfileOut($this->getModuleProfileName(true));
+ public function getModulePrefix() {
+ return $this->mModulePrefix;
}
/**
- * Total time the module used the database
+ * Get the main module
+ * @return ApiMain
*/
- public function getProfileDBTime() {
- if ($this->mDBTimeIn !== 0)
- ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
- return $this->mDBTime;
+ public function getMain() {
+ return $this->mMainModule;
}
- public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
- print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
- var_export($value);
- if ($backtrace)
- print "\n" . wfBacktrace();
- print "\n</pre>\n";
+ /**
+ * Returns true if this module is the main module ($this === $this->mMainModule),
+ * false otherwise.
+ * @return bool
+ */
+ public function isMain() {
+ return $this === $this->mMainModule;
}
-
/**
- * Returns a String that identifies the version of this class.
+ * Get the parent of this module
+ * @since 1.25
+ * @return ApiBase|null
*/
- public static function getBaseVersion() {
- return __CLASS__ . ': $Id: ApiBase.php 47041 2009-02-09 14:39:41Z catrope $';
+ public function getParent() {
+ return $this->isMain() ? null : $this->getMain();
}
+
+ /**
+ * Returns true if the current request breaks the same-origin policy.
+ *
+ * For example, json with callbacks.
+ *
+ * https://en.wikipedia.org/wiki/Same-origin_policy
+ *
+ * @since 1.25
+ * @return bool
+ */
+ public function lacksSameOriginSecurity() {
+ // Main module has this method overridden
+ // Safety - avoid infinite loop:
+ if ( $this->isMain() ) {
+ self::dieDebug( __METHOD__, 'base method was called on main module.' );
+ }
+
+ return $this->getMain()->lacksSameOriginSecurity();
+ }
+
+ /**
+ * Get the path to this module
+ *
+ * @since 1.25
+ * @return string
+ */
+ public function getModulePath() {
+ if ( $this->isMain() ) {
+ return 'main';
+ } elseif ( $this->getParent()->isMain() ) {
+ return $this->getModuleName();
+ } else {
+ return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
+ }
+ }
+
+ /**
+ * Get a module from its module path
+ *
+ * @since 1.25
+ * @param string $path
+ * @return ApiBase|null
+ * @throws ApiUsageException
+ */
+ public function getModuleFromPath( $path ) {
+ $module = $this->getMain();
+ if ( $path === 'main' ) {
+ return $module;
+ }
+
+ $parts = explode( '+', $path );
+ if ( count( $parts ) === 1 ) {
+ // In case the '+' was typed into URL, it resolves as a space
+ $parts = explode( ' ', $path );
+ }
+
+ $count = count( $parts );
+ for ( $i = 0; $i < $count; $i++ ) {
+ $parent = $module;
+ $manager = $parent->getModuleManager();
+ if ( $manager === null ) {
+ $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
+ $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
+ }
+ $module = $manager->getModule( $parts[$i] );
+
+ if ( $module === null ) {
+ $errorPath = $i ? implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
+ $this->dieWithError(
+ [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
+ 'badmodule'
+ );
+ }
+ }
+
+ return $module;
+ }
+
+ /**
+ * Get the result object
+ * @return ApiResult
+ */
+ public function getResult() {
+ // Main module has getResult() method overridden
+ // Safety - avoid infinite loop:
+ if ( $this->isMain() ) {
+ self::dieDebug( __METHOD__, 'base method was called on main module. ' );
+ }
+
+ return $this->getMain()->getResult();
+ }
+
+ /**
+ * Get the error formatter
+ * @return ApiErrorFormatter
+ */
+ public function getErrorFormatter() {
+ // Main module has getErrorFormatter() method overridden
+ // Safety - avoid infinite loop:
+ if ( $this->isMain() ) {
+ self::dieDebug( __METHOD__, 'base method was called on main module. ' );
+ }
+
+ return $this->getMain()->getErrorFormatter();
+ }
+
+ /**
+ * Gets a default replica DB connection object
+ * @return IDatabase
+ */
+ protected function getDB() {
+ if ( !isset( $this->mSlaveDB ) ) {
+ $this->mSlaveDB = wfGetDB( DB_REPLICA, 'api' );
+ }
+
+ return $this->mSlaveDB;
+ }
+
+ /**
+ * Get the continuation manager
+ * @return ApiContinuationManager|null
+ */
+ public function getContinuationManager() {
+ // Main module has getContinuationManager() method overridden
+ // Safety - avoid infinite loop:
+ if ( $this->isMain() ) {
+ self::dieDebug( __METHOD__, 'base method was called on main module. ' );
+ }
+
+ return $this->getMain()->getContinuationManager();
+ }
+
+ /**
+ * Set the continuation manager
+ * @param ApiContinuationManager|null $manager
+ */
+ public function setContinuationManager( $manager ) {
+ // Main module has setContinuationManager() method overridden
+ // Safety - avoid infinite loop:
+ if ( $this->isMain() ) {
+ self::dieDebug( __METHOD__, 'base method was called on main module. ' );
+ }
+
+ $this->getMain()->setContinuationManager( $manager );
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Parameter handling
+ * @{
+ */
+
+ /**
+ * Indicate if the module supports dynamically-determined parameters that
+ * cannot be included in self::getAllowedParams().
+ * @return string|array|Message|null Return null if the module does not
+ * support additional dynamic parameters, otherwise return a message
+ * describing them.
+ */
+ public function dynamicParameterDocumentation() {
+ return null;
+ }
+
+ /**
+ * This method mangles parameter name based on the prefix supplied to the constructor.
+ * Override this method to change parameter name during runtime
+ * @param string|string[] $paramName Parameter name
+ * @return string|string[] Prefixed parameter name
+ * @since 1.29 accepts an array of strings
+ */
+ public function encodeParamName( $paramName ) {
+ if ( is_array( $paramName ) ) {
+ return array_map( function ( $name ) {
+ return $this->mModulePrefix . $name;
+ }, $paramName );
+ } else {
+ return $this->mModulePrefix . $paramName;
+ }
+ }
+
+ /**
+ * 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. limits will not be
+ * parsed if $parseLimit is set to false; use this when the max
+ * limit is not definitive yet, e.g. when getting revisions.
+ * @param bool $parseLimit True by default
+ * @return array
+ */
+ public function extractRequestParams( $parseLimit = true ) {
+ // Cache parameters, for performance and to avoid T26564.
+ if ( !isset( $this->mParamCache[$parseLimit] ) ) {
+ $params = $this->getFinalParams();
+ $results = [];
+
+ if ( $params ) { // getFinalParams() can return false
+ foreach ( $params as $paramName => $paramSettings ) {
+ $results[$paramName] = $this->getParameterFromSettings(
+ $paramName, $paramSettings, $parseLimit );
+ }
+ }
+ $this->mParamCache[$parseLimit] = $results;
+ }
+
+ return $this->mParamCache[$parseLimit];
+ }
+
+ /**
+ * Get a value for the given parameter
+ * @param string $paramName Parameter name
+ * @param bool $parseLimit See extractRequestParams()
+ * @return mixed Parameter value
+ */
+ protected function getParameter( $paramName, $parseLimit = true ) {
+ $paramSettings = $this->getFinalParams()[$paramName];
+
+ return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
+ }
+
+ /**
+ * Die if none or more than one of a certain set of parameters is set and not false.
+ *
+ * @param array $params User provided set of parameters, as from $this->extractRequestParams()
+ * @param string $required,... Names of parameters of which exactly one must be set
+ */
+ public function requireOnlyOneParameter( $params, $required /*...*/ ) {
+ $required = func_get_args();
+ array_shift( $required );
+
+ $intersection = array_intersect( array_keys( array_filter( $params,
+ [ $this, 'parameterNotEmpty' ] ) ), $required );
+
+ if ( count( $intersection ) > 1 ) {
+ $this->dieWithError( [
+ 'apierror-invalidparammix',
+ Message::listParam( array_map(
+ function ( $p ) {
+ return '<var>' . $this->encodeParamName( $p ) . '</var>';
+ },
+ array_values( $intersection )
+ ) ),
+ count( $intersection ),
+ ] );
+ } elseif ( count( $intersection ) == 0 ) {
+ $this->dieWithError( [
+ 'apierror-missingparam-one-of',
+ Message::listParam( array_map(
+ function ( $p ) {
+ return '<var>' . $this->encodeParamName( $p ) . '</var>';
+ },
+ array_values( $required )
+ ) ),
+ count( $required ),
+ ], 'missingparam' );
+ }
+ }
+
+ /**
+ * Die if more than one of a certain set of parameters is set and not false.
+ *
+ * @param array $params User provided set of parameters, as from $this->extractRequestParams()
+ * @param string $required,... Names of parameters of which at most one must be set
+ */
+ public function requireMaxOneParameter( $params, $required /*...*/ ) {
+ $required = func_get_args();
+ array_shift( $required );
+
+ $intersection = array_intersect( array_keys( array_filter( $params,
+ [ $this, 'parameterNotEmpty' ] ) ), $required );
+
+ if ( count( $intersection ) > 1 ) {
+ $this->dieWithError( [
+ 'apierror-invalidparammix',
+ Message::listParam( array_map(
+ function ( $p ) {
+ return '<var>' . $this->encodeParamName( $p ) . '</var>';
+ },
+ array_values( $intersection )
+ ) ),
+ count( $intersection ),
+ ] );
+ }
+ }
+
+ /**
+ * Die if none of a certain set of parameters is set and not false.
+ *
+ * @since 1.23
+ * @param array $params User provided set of parameters, as from $this->extractRequestParams()
+ * @param string $required,... Names of parameters of which at least one must be set
+ */
+ public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
+ $required = func_get_args();
+ array_shift( $required );
+
+ $intersection = array_intersect(
+ array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
+ $required
+ );
+
+ if ( count( $intersection ) == 0 ) {
+ $this->dieWithError( [
+ 'apierror-missingparam-at-least-one-of',
+ Message::listParam( array_map(
+ function ( $p ) {
+ return '<var>' . $this->encodeParamName( $p ) . '</var>';
+ },
+ array_values( $required )
+ ) ),
+ count( $required ),
+ ], 'missingparam' );
+ }
+ }
+
+ /**
+ * Die if any of the specified parameters were found in the query part of
+ * the URL rather than the post body.
+ * @since 1.28
+ * @param string[] $params Parameters to check
+ * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
+ */
+ public function requirePostedParameters( $params, $prefix = 'prefix' ) {
+ // Skip if $wgDebugAPI is set or we're in internal mode
+ if ( $this->getConfig()->get( 'DebugAPI' ) || $this->getMain()->isInternalMode() ) {
+ return;
+ }
+
+ $queryValues = $this->getRequest()->getQueryValues();
+ $badParams = [];
+ foreach ( $params as $param ) {
+ if ( $prefix !== 'noprefix' ) {
+ $param = $this->encodeParamName( $param );
+ }
+ if ( array_key_exists( $param, $queryValues ) ) {
+ $badParams[] = $param;
+ }
+ }
+
+ if ( $badParams ) {
+ $this->dieWithError(
+ [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
+ );
+ }
+ }
+
+ /**
+ * Callback function used in requireOnlyOneParameter to check whether required parameters are set
+ *
+ * @param object $x Parameter to check is not null/false
+ * @return bool
+ */
+ private function parameterNotEmpty( $x ) {
+ return !is_null( $x ) && $x !== false;
+ }
+
+ /**
+ * Get a WikiPage object from a title or pageid param, if possible.
+ * Can die, if no param is set or if the title or page id is not valid.
+ *
+ * @param array $params User provided set of parameters, as from $this->extractRequestParams()
+ * @param bool|string $load Whether load the object's state from the database:
+ * - false: don't load (if the pageid is given, it will still be loaded)
+ * - 'fromdb': load from a replica DB
+ * - 'fromdbmaster': load from the master database
+ * @return WikiPage
+ */
+ public function getTitleOrPageId( $params, $load = false ) {
+ $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
+
+ $pageObj = null;
+ if ( isset( $params['title'] ) ) {
+ $titleObj = Title::newFromText( $params['title'] );
+ if ( !$titleObj || $titleObj->isExternal() ) {
+ $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
+ }
+ if ( !$titleObj->canExist() ) {
+ $this->dieWithError( 'apierror-pagecannotexist' );
+ }
+ $pageObj = WikiPage::factory( $titleObj );
+ if ( $load !== false ) {
+ $pageObj->loadPageData( $load );
+ }
+ } elseif ( isset( $params['pageid'] ) ) {
+ if ( $load === false ) {
+ $load = 'fromdb';
+ }
+ $pageObj = WikiPage::newFromID( $params['pageid'], $load );
+ if ( !$pageObj ) {
+ $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
+ }
+ }
+
+ return $pageObj;
+ }
+
+ /**
+ * Get a Title object from a title or pageid param, if possible.
+ * Can die, if no param is set or if the title or page id is not valid.
+ *
+ * @since 1.29
+ * @param array $params User provided set of parameters, as from $this->extractRequestParams()
+ * @return Title
+ */
+ public function getTitleFromTitleOrPageId( $params ) {
+ $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
+
+ $titleObj = null;
+ if ( isset( $params['title'] ) ) {
+ $titleObj = Title::newFromText( $params['title'] );
+ if ( !$titleObj || $titleObj->isExternal() ) {
+ $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
+ }
+ return $titleObj;
+ } elseif ( isset( $params['pageid'] ) ) {
+ $titleObj = Title::newFromID( $params['pageid'] );
+ if ( !$titleObj ) {
+ $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
+ }
+ }
+
+ return $titleObj;
+ }
+
+ /**
+ * Return true if we're to watch the page, false if not, null if no change.
+ * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
+ * @param Title $titleObj The page under consideration
+ * @param string $userOption The user option to consider when $watchlist=preferences.
+ * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
+ * @return bool
+ */
+ protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
+ $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
+
+ switch ( $watchlist ) {
+ case 'watch':
+ return true;
+
+ case 'unwatch':
+ return false;
+
+ case 'preferences':
+ # If the user is already watching, don't bother checking
+ if ( $userWatching ) {
+ return true;
+ }
+ # If no user option was passed, use watchdefault and watchcreations
+ if ( is_null( $userOption ) ) {
+ return $this->getUser()->getBoolOption( 'watchdefault' ) ||
+ $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
+ }
+
+ # Watch the article based on the user preference
+ return $this->getUser()->getBoolOption( $userOption );
+
+ case 'nochange':
+ return $userWatching;
+
+ default:
+ return $userWatching;
+ }
+ }
+
+ /**
+ * Using the settings determine the value for the given parameter
+ *
+ * @param string $paramName Parameter name
+ * @param array|mixed $paramSettings Default value or an array of settings
+ * using PARAM_* constants.
+ * @param bool $parseLimit Parse limit?
+ * @return mixed Parameter value
+ */
+ protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
+ // Some classes may decide to change parameter names
+ $encParamName = $this->encodeParamName( $paramName );
+
+ // Shorthand
+ if ( !is_array( $paramSettings ) ) {
+ $paramSettings = [
+ self::PARAM_DFLT => $paramSettings,
+ ];
+ }
+
+ $default = isset( $paramSettings[self::PARAM_DFLT] )
+ ? $paramSettings[self::PARAM_DFLT]
+ : null;
+ $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
+ ? $paramSettings[self::PARAM_ISMULTI]
+ : false;
+ $multiLimit1 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT1] )
+ ? $paramSettings[self::PARAM_ISMULTI_LIMIT1]
+ : null;
+ $multiLimit2 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT2] )
+ ? $paramSettings[self::PARAM_ISMULTI_LIMIT2]
+ : null;
+ $type = isset( $paramSettings[self::PARAM_TYPE] )
+ ? $paramSettings[self::PARAM_TYPE]
+ : null;
+ $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
+ ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
+ : false;
+ $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
+ ? $paramSettings[self::PARAM_DEPRECATED]
+ : false;
+ $deprecatedValues = isset( $paramSettings[self::PARAM_DEPRECATED_VALUES] )
+ ? $paramSettings[self::PARAM_DEPRECATED_VALUES]
+ : [];
+ $required = isset( $paramSettings[self::PARAM_REQUIRED] )
+ ? $paramSettings[self::PARAM_REQUIRED]
+ : false;
+ $allowAll = isset( $paramSettings[self::PARAM_ALL] )
+ ? $paramSettings[self::PARAM_ALL]
+ : false;
+
+ // When type is not given, and no choices, the type is the same as $default
+ if ( !isset( $type ) ) {
+ if ( isset( $default ) ) {
+ $type = gettype( $default );
+ } else {
+ $type = 'NULL'; // allow everything
+ }
+ }
+
+ if ( $type == 'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
+ $this->getMain()->markParamsSensitive( $encParamName );
+ }
+
+ if ( $type == 'boolean' ) {
+ if ( isset( $default ) && $default !== false ) {
+ // Having a default value of anything other than 'false' is not allowed
+ self::dieDebug(
+ __METHOD__,
+ "Boolean param $encParamName's default is set to '$default'. " .
+ 'Boolean parameters must default to false.'
+ );
+ }
+
+ $value = $this->getMain()->getCheck( $encParamName );
+ } elseif ( $type == 'upload' ) {
+ if ( isset( $default ) ) {
+ // Having a default value is not allowed
+ self::dieDebug(
+ __METHOD__,
+ "File upload param $encParamName's default is set to " .
+ "'$default'. File upload parameters may not have a default." );
+ }
+ if ( $multi ) {
+ self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
+ }
+ $value = $this->getMain()->getUpload( $encParamName );
+ if ( !$value->exists() ) {
+ // This will get the value without trying to normalize it
+ // (because trying to normalize a large binary file
+ // accidentally uploaded as a field fails spectacularly)
+ $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
+ if ( $value !== null ) {
+ $this->dieWithError(
+ [ 'apierror-badupload', $encParamName ],
+ "badupload_{$encParamName}"
+ );
+ }
+ }
+ } else {
+ $value = $this->getMain()->getVal( $encParamName, $default );
+
+ if ( isset( $value ) && $type == 'namespace' ) {
+ $type = MWNamespace::getValidNamespaces();
+ if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
+ is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
+ ) {
+ $type = array_merge( $type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
+ }
+ // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
+ // all namespaces.
+ $allowAll = true;
+ }
+ if ( isset( $value ) && $type == 'submodule' ) {
+ if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
+ $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
+ } else {
+ $type = $this->getModuleManager()->getNames( $paramName );
+ }
+ }
+
+ $request = $this->getMain()->getRequest();
+ $rawValue = $request->getRawVal( $encParamName );
+ if ( $rawValue === null ) {
+ $rawValue = $default;
+ }
+
+ // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
+ if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
+ if ( $multi ) {
+ // This loses the potential $wgContLang->checkTitleEncoding() transformation
+ // done by WebRequest for $_GET. Let's call that a feature.
+ $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
+ } else {
+ $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
+ }
+ }
+
+ // Check for NFC normalization, and warn
+ if ( $rawValue !== $value ) {
+ $this->handleParamNormalization( $paramName, $value, $rawValue );
+ }
+ }
+
+ $allSpecifier = ( is_string( $allowAll ) ? $allowAll : self::ALL_DEFAULT_STRING );
+ if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
+ self::dieDebug(
+ __METHOD__,
+ "For param $encParamName, PARAM_ALL collides with a possible value" );
+ }
+ if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
+ $value = $this->parseMultiValue(
+ $encParamName,
+ $value,
+ $multi,
+ is_array( $type ) ? $type : null,
+ $allowAll ? $allSpecifier : null,
+ $multiLimit1,
+ $multiLimit2
+ );
+ }
+
+ // More validation only when choices were not given
+ // choices were validated in parseMultiValue()
+ if ( isset( $value ) ) {
+ if ( !is_array( $type ) ) {
+ switch ( $type ) {
+ case 'NULL': // nothing to do
+ break;
+ case 'string':
+ case 'text':
+ case 'password':
+ if ( $required && $value === '' ) {
+ $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
+ }
+ break;
+ case 'integer': // Force everything using intval() and optionally validate limits
+ $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
+ $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
+ $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
+ ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
+
+ if ( is_array( $value ) ) {
+ $value = array_map( 'intval', $value );
+ if ( !is_null( $min ) || !is_null( $max ) ) {
+ foreach ( $value as &$v ) {
+ $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
+ }
+ }
+ } else {
+ $value = intval( $value );
+ if ( !is_null( $min ) || !is_null( $max ) ) {
+ $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
+ }
+ }
+ break;
+ case 'limit':
+ if ( !$parseLimit ) {
+ // Don't do any validation whatsoever
+ break;
+ }
+ if ( !isset( $paramSettings[self::PARAM_MAX] )
+ || !isset( $paramSettings[self::PARAM_MAX2] )
+ ) {
+ self::dieDebug(
+ __METHOD__,
+ "MAX1 or MAX2 are not defined for the limit $encParamName"
+ );
+ }
+ if ( $multi ) {
+ self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
+ }
+ $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
+ if ( $value == 'max' ) {
+ $value = $this->getMain()->canApiHighLimits()
+ ? $paramSettings[self::PARAM_MAX2]
+ : $paramSettings[self::PARAM_MAX];
+ $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
+ } else {
+ $value = intval( $value );
+ $this->validateLimit(
+ $paramName,
+ $value,
+ $min,
+ $paramSettings[self::PARAM_MAX],
+ $paramSettings[self::PARAM_MAX2]
+ );
+ }
+ break;
+ case 'boolean':
+ if ( $multi ) {
+ self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
+ }
+ break;
+ case 'timestamp':
+ if ( is_array( $value ) ) {
+ foreach ( $value as $key => $val ) {
+ $value[$key] = $this->validateTimestamp( $val, $encParamName );
+ }
+ } else {
+ $value = $this->validateTimestamp( $value, $encParamName );
+ }
+ break;
+ case 'user':
+ if ( is_array( $value ) ) {
+ foreach ( $value as $key => $val ) {
+ $value[$key] = $this->validateUser( $val, $encParamName );
+ }
+ } else {
+ $value = $this->validateUser( $value, $encParamName );
+ }
+ break;
+ case 'upload': // nothing to do
+ break;
+ case 'tags':
+ // If change tagging was requested, check that the tags are valid.
+ if ( !is_array( $value ) && !$multi ) {
+ $value = [ $value ];
+ }
+ $tagsStatus = ChangeTags::canAddTagsAccompanyingChange( $value );
+ if ( !$tagsStatus->isGood() ) {
+ $this->dieStatus( $tagsStatus );
+ }
+ break;
+ default:
+ self::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
+ }
+ }
+
+ // Throw out duplicates if requested
+ if ( !$dupes && is_array( $value ) ) {
+ $value = array_unique( $value );
+ }
+
+ // Set a warning if a deprecated parameter has been passed
+ if ( $deprecated && $value !== false ) {
+ $feature = $encParamName;
+ $m = $this;
+ while ( !$m->isMain() ) {
+ $p = $m->getParent();
+ $name = $m->getModuleName();
+ $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
+ $feature = "{$param}={$name}&{$feature}";
+ $m = $p;
+ }
+ $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
+ }
+
+ // Set a warning if a deprecated parameter value has been passed
+ $usedDeprecatedValues = $deprecatedValues && $value !== false
+ ? array_intersect( array_keys( $deprecatedValues ), (array)$value )
+ : [];
+ if ( $usedDeprecatedValues ) {
+ $feature = "$encParamName=";
+ $m = $this;
+ while ( !$m->isMain() ) {
+ $p = $m->getParent();
+ $name = $m->getModuleName();
+ $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
+ $feature = "{$param}={$name}&{$feature}";
+ $m = $p;
+ }
+ foreach ( $usedDeprecatedValues as $v ) {
+ $msg = $deprecatedValues[$v];
+ if ( $msg === true ) {
+ $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
+ }
+ $this->addDeprecation( $msg, "$feature$v" );
+ }
+ }
+ } elseif ( $required ) {
+ $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
+ }
+
+ return $value;
+ }
+
+ /**
+ * Handle when a parameter was Unicode-normalized
+ * @since 1.28
+ * @param string $paramName Unprefixed parameter name
+ * @param string $value Input that will be used.
+ * @param string $rawValue Input before normalization.
+ */
+ protected function handleParamNormalization( $paramName, $value, $rawValue ) {
+ $encParamName = $this->encodeParamName( $paramName );
+ $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
+ }
+
+ /**
+ * Split a multi-valued parameter string, like explode()
+ * @since 1.28
+ * @param string $value
+ * @param int $limit
+ * @return string[]
+ */
+ protected function explodeMultiValue( $value, $limit ) {
+ if ( substr( $value, 0, 1 ) === "\x1f" ) {
+ $sep = "\x1f";
+ $value = substr( $value, 1 );
+ } else {
+ $sep = '|';
+ }
+
+ return explode( $sep, $value, $limit );
+ }
+
+ /**
+ * Return an array of values that were given in a 'a|b|c' notation,
+ * after it optionally validates them against the list allowed values.
+ *
+ * @param string $valueName The name of the parameter (for error
+ * reporting)
+ * @param mixed $value The value being parsed
+ * @param bool $allowMultiple Can $value contain more than one value
+ * separated by '|'?
+ * @param string[]|null $allowedValues An array of values to check against. If
+ * null, all values are accepted.
+ * @param string|null $allSpecifier String to use to specify all allowed values, or null
+ * if this behavior should not be allowed
+ * @param int|null $limit1 Maximum number of values, for normal users.
+ * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
+ * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
+ */
+ protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
+ $allSpecifier = null, $limit1 = null, $limit2 = null
+ ) {
+ if ( ( trim( $value ) === '' || trim( $value ) === "\x1f" ) && $allowMultiple ) {
+ return [];
+ }
+ $limit1 = $limit1 ?: self::LIMIT_SML1;
+ $limit2 = $limit2 ?: self::LIMIT_SML2;
+
+ // This is a bit awkward, but we want to avoid calling canApiHighLimits()
+ // because it unstubs $wgUser
+ $valuesList = $this->explodeMultiValue( $value, $limit2 + 1 );
+ $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule->canApiHighLimits()
+ ? $limit2
+ : $limit1;
+
+ if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
+ count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
+ ) {
+ return $allowedValues;
+ }
+
+ if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
+ $this->addDeprecation(
+ [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
+ "too-many-$valueName-for-{$this->getModulePath()}"
+ );
+ }
+
+ if ( !$allowMultiple && count( $valuesList ) != 1 ) {
+ // T35482 - Allow entries with | in them for non-multiple values
+ if ( in_array( $value, $allowedValues, true ) ) {
+ return $value;
+ }
+
+ if ( is_array( $allowedValues ) ) {
+ $values = array_map( function ( $v ) {
+ return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
+ }, $allowedValues );
+ $this->dieWithError( [
+ 'apierror-multival-only-one-of',
+ $valueName,
+ Message::listParam( $values ),
+ count( $values ),
+ ], "multival_$valueName" );
+ } else {
+ $this->dieWithError( [
+ 'apierror-multival-only-one',
+ $valueName,
+ ], "multival_$valueName" );
+ }
+ }
+
+ if ( is_array( $allowedValues ) ) {
+ // Check for unknown values
+ $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
+ if ( count( $unknown ) ) {
+ if ( $allowMultiple ) {
+ $this->addWarning( [
+ 'apiwarn-unrecognizedvalues',
+ $valueName,
+ Message::listParam( $unknown, 'comma' ),
+ count( $unknown ),
+ ] );
+ } else {
+ $this->dieWithError(
+ [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
+ "unknown_$valueName"
+ );
+ }
+ }
+ // Now throw them out
+ $valuesList = array_intersect( $valuesList, $allowedValues );
+ }
+
+ return $allowMultiple ? $valuesList : $valuesList[0];
+ }
+
+ /**
+ * Validate the value against the minimum and user/bot maximum limits.
+ * Prints usage info on failure.
+ * @param string $paramName Parameter name
+ * @param int &$value Parameter value
+ * @param int|null $min Minimum value
+ * @param int|null $max Maximum value for users
+ * @param int $botMax Maximum value for sysops/bots
+ * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
+ */
+ protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
+ $enforceLimits = false
+ ) {
+ if ( !is_null( $min ) && $value < $min ) {
+ $msg = ApiMessage::create(
+ [ 'apierror-integeroutofrange-belowminimum',
+ $this->encodeParamName( $paramName ), $min, $value ],
+ 'integeroutofrange',
+ [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
+ );
+ $this->warnOrDie( $msg, $enforceLimits );
+ $value = $min;
+ }
+
+ // Minimum is always validated, whereas maximum is checked only if not
+ // running in internal call mode
+ if ( $this->getMain()->isInternalMode() ) {
+ return;
+ }
+
+ // Optimization: do not check user's bot status unless really needed -- skips db query
+ // assumes $botMax >= $max
+ if ( !is_null( $max ) && $value > $max ) {
+ if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
+ if ( $value > $botMax ) {
+ $msg = ApiMessage::create(
+ [ 'apierror-integeroutofrange-abovebotmax',
+ $this->encodeParamName( $paramName ), $botMax, $value ],
+ 'integeroutofrange',
+ [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
+ );
+ $this->warnOrDie( $msg, $enforceLimits );
+ $value = $botMax;
+ }
+ } else {
+ $msg = ApiMessage::create(
+ [ 'apierror-integeroutofrange-abovemax',
+ $this->encodeParamName( $paramName ), $max, $value ],
+ 'integeroutofrange',
+ [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
+ );
+ $this->warnOrDie( $msg, $enforceLimits );
+ $value = $max;
+ }
+ }
+ }
+
+ /**
+ * Validate and normalize of parameters of type 'timestamp'
+ * @param string $value Parameter value
+ * @param string $encParamName Parameter name
+ * @return string Validated and normalized parameter
+ */
+ protected function validateTimestamp( $value, $encParamName ) {
+ // Confusing synonyms for the current time accepted by wfTimestamp()
+ // (wfTimestamp() also accepts various non-strings and the string of 14
+ // ASCII NUL bytes, but those can't get here)
+ if ( !$value ) {
+ $this->addDeprecation(
+ [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
+ 'unclear-"now"-timestamp'
+ );
+ return wfTimestamp( TS_MW );
+ }
+
+ // Explicit synonym for the current time
+ if ( $value === 'now' ) {
+ return wfTimestamp( TS_MW );
+ }
+
+ $unixTimestamp = wfTimestamp( TS_UNIX, $value );
+ if ( $unixTimestamp === false ) {
+ $this->dieWithError(
+ [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
+ "badtimestamp_{$encParamName}"
+ );
+ }
+
+ return wfTimestamp( TS_MW, $unixTimestamp );
+ }
+
+ /**
+ * Validate the supplied token.
+ *
+ * @since 1.24
+ * @param string $token Supplied token
+ * @param array $params All supplied parameters for the module
+ * @return bool
+ * @throws MWException
+ */
+ final public function validateToken( $token, array $params ) {
+ $tokenType = $this->needsToken();
+ $salts = ApiQueryTokens::getTokenTypeSalts();
+ if ( !isset( $salts[$tokenType] ) ) {
+ throw new MWException(
+ "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
+ 'without registering it'
+ );
+ }
+
+ $tokenObj = ApiQueryTokens::getToken(
+ $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
+ );
+ if ( $tokenObj->match( $token ) ) {
+ return true;
+ }
+
+ $webUiSalt = $this->getWebUITokenSalt( $params );
+ if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
+ $token,
+ $webUiSalt,
+ $this->getRequest()
+ ) ) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Validate and normalize of parameters of type 'user'
+ * @param string $value Parameter value
+ * @param string $encParamName Parameter name
+ * @return string Validated and normalized parameter
+ */
+ private function validateUser( $value, $encParamName ) {
+ $title = Title::makeTitleSafe( NS_USER, $value );
+ if ( $title === null || $title->hasFragment() ) {
+ $this->dieWithError(
+ [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
+ "baduser_{$encParamName}"
+ );
+ }
+
+ return $title->getText();
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Utility methods
+ * @{
+ */
+
+ /**
+ * Set a watch (or unwatch) based the based on a watchlist parameter.
+ * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
+ * @param Title $titleObj The article's title to change
+ * @param string $userOption The user option to consider when $watch=preferences
+ */
+ protected function setWatch( $watch, $titleObj, $userOption = null ) {
+ $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
+ if ( $value === null ) {
+ return;
+ }
+
+ WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
+ }
+
+ /**
+ * Truncate an array to a certain length.
+ * @param array &$arr Array to truncate
+ * @param int $limit Maximum length
+ * @return bool True if the array was truncated, false otherwise
+ */
+ public static function truncateArray( &$arr, $limit ) {
+ $modified = false;
+ while ( count( $arr ) > $limit ) {
+ array_pop( $arr );
+ $modified = true;
+ }
+
+ return $modified;
+ }
+
+ /**
+ * Gets the user for whom to get the watchlist
+ *
+ * @param array $params
+ * @return User
+ */
+ public function getWatchlistUser( $params ) {
+ if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
+ $user = User::newFromName( $params['owner'], false );
+ if ( !( $user && $user->getId() ) ) {
+ $this->dieWithError(
+ [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
+ );
+ }
+ $token = $user->getOption( 'watchlisttoken' );
+ if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
+ $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
+ }
+ } else {
+ if ( !$this->getUser()->isLoggedIn() ) {
+ $this->dieWithError( 'watchlistanontext', 'notloggedin' );
+ }
+ $this->checkUserRightsAny( 'viewmywatchlist' );
+ $user = $this->getUser();
+ }
+
+ return $user;
+ }
+
+ /**
+ * A subset of wfEscapeWikiText for BC texts
+ *
+ * @since 1.25
+ * @param string|array $v
+ * @return string|array
+ */
+ private static function escapeWikiText( $v ) {
+ if ( is_array( $v ) ) {
+ return array_map( 'self::escapeWikiText', $v );
+ } else {
+ return strtr( $v, [
+ '__' => '__', '{' => '{', '}' => '}',
+ '[[Category:' => '[[:Category:',
+ '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
+ ] );
+ }
+ }
+
+ /**
+ * Create a Message from a string or array
+ *
+ * A string is used as a message key. An array has the message key as the
+ * first value and message parameters as subsequent values.
+ *
+ * @since 1.25
+ * @param string|array|Message $msg
+ * @param IContextSource $context
+ * @param array $params
+ * @return Message|null
+ */
+ public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
+ if ( is_string( $msg ) ) {
+ $msg = wfMessage( $msg );
+ } elseif ( is_array( $msg ) ) {
+ $msg = call_user_func_array( 'wfMessage', $msg );
+ }
+ if ( !$msg instanceof Message ) {
+ return null;
+ }
+
+ $msg->setContext( $context );
+ if ( $params ) {
+ $msg->params( $params );
+ }
+
+ return $msg;
+ }
+
+ /**
+ * Turn an array of message keys or key+param arrays into a Status
+ * @since 1.29
+ * @param array $errors
+ * @param User|null $user
+ * @return Status
+ */
+ public function errorArrayToStatus( array $errors, User $user = null ) {
+ if ( $user === null ) {
+ $user = $this->getUser();
+ }
+
+ $status = Status::newGood();
+ foreach ( $errors as $error ) {
+ if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
+ $status->fatal( ApiMessage::create(
+ 'apierror-blocked',
+ 'blocked',
+ [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
+ ) );
+ } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
+ $status->fatal( ApiMessage::create(
+ 'apierror-autoblocked',
+ 'autoblocked',
+ [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
+ ) );
+ } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
+ $status->fatal( ApiMessage::create(
+ 'apierror-systemblocked',
+ 'blocked',
+ [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
+ ) );
+ } else {
+ call_user_func_array( [ $status, 'fatal' ], (array)$error );
+ }
+ }
+ return $status;
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Warning and error reporting
+ * @{
+ */
+
+ /**
+ * Add a warning for this module.
+ *
+ * Users should monitor this section to notice any changes in API. Multiple
+ * calls to this function will result in multiple warning messages.
+ *
+ * If $msg is not an ApiMessage, the message code will be derived from the
+ * message key by stripping any "apiwarn-" or "apierror-" prefix.
+ *
+ * @since 1.29
+ * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
+ * @param string|null $code See ApiErrorFormatter::addWarning()
+ * @param array|null $data See ApiErrorFormatter::addWarning()
+ */
+ public function addWarning( $msg, $code = null, $data = null ) {
+ $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
+ }
+
+ /**
+ * Add a deprecation warning for this module.
+ *
+ * A combination of $this->addWarning() and $this->logFeatureUsage()
+ *
+ * @since 1.29
+ * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
+ * @param string|null $feature See ApiBase::logFeatureUsage()
+ * @param array|null $data See ApiErrorFormatter::addWarning()
+ */
+ public function addDeprecation( $msg, $feature, $data = [] ) {
+ $data = (array)$data;
+ if ( $feature !== null ) {
+ $data['feature'] = $feature;
+ $this->logFeatureUsage( $feature );
+ }
+ $this->addWarning( $msg, 'deprecation', $data );
+
+ // No real need to deduplicate here, ApiErrorFormatter does that for
+ // us (assuming the hook is deterministic).
+ $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
+ Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
+ if ( count( $msgs ) > 1 ) {
+ $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
+ $msg = ( new RawMessage( $key ) )->params( $msgs );
+ } else {
+ $msg = reset( $msgs );
+ }
+ $this->getMain()->addWarning( $msg, 'deprecation-help' );
+ }
+
+ /**
+ * Add an error for this module without aborting
+ *
+ * If $msg is not an ApiMessage, the message code will be derived from the
+ * message key by stripping any "apiwarn-" or "apierror-" prefix.
+ *
+ * @note If you want to abort processing, use self::dieWithError() instead.
+ * @since 1.29
+ * @param string|array|Message $msg See ApiErrorFormatter::addError()
+ * @param string|null $code See ApiErrorFormatter::addError()
+ * @param array|null $data See ApiErrorFormatter::addError()
+ */
+ public function addError( $msg, $code = null, $data = null ) {
+ $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
+ }
+
+ /**
+ * Add warnings and/or errors from a Status
+ *
+ * @note If you want to abort processing, use self::dieStatus() instead.
+ * @since 1.29
+ * @param StatusValue $status
+ * @param string[] $types 'warning' and/or 'error'
+ */
+ public function addMessagesFromStatus( StatusValue $status, $types = [ 'warning', 'error' ] ) {
+ $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
+ }
+
+ /**
+ * Abort execution with an error
+ *
+ * If $msg is not an ApiMessage, the message code will be derived from the
+ * message key by stripping any "apiwarn-" or "apierror-" prefix.
+ *
+ * @since 1.29
+ * @param string|array|Message $msg See ApiErrorFormatter::addError()
+ * @param string|null $code See ApiErrorFormatter::addError()
+ * @param array|null $data See ApiErrorFormatter::addError()
+ * @param int|null $httpCode HTTP error code to use
+ * @throws ApiUsageException always
+ */
+ public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
+ throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
+ }
+
+ /**
+ * Abort execution with an error derived from an exception
+ *
+ * @since 1.29
+ * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
+ * @param array $options See ApiErrorFormatter::getMessageFromException()
+ * @throws ApiUsageException always
+ */
+ public function dieWithException( $exception, array $options = [] ) {
+ $this->dieWithError(
+ $this->getErrorFormatter()->getMessageFromException( $exception, $options )
+ );
+ }
+
+ /**
+ * Adds a warning to the output, else dies
+ *
+ * @param ApiMessage $msg Message to show as a warning, or error message if dying
+ * @param bool $enforceLimits Whether this is an enforce (die)
+ */
+ private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
+ if ( $enforceLimits ) {
+ $this->dieWithError( $msg );
+ } else {
+ $this->addWarning( $msg );
+ }
+ }
+
+ /**
+ * Throw an ApiUsageException, which will (if uncaught) call the main module's
+ * error handler and die with an error message including block info.
+ *
+ * @since 1.27
+ * @param Block $block The block used to generate the ApiUsageException
+ * @throws ApiUsageException always
+ */
+ public function dieBlocked( Block $block ) {
+ // Die using the appropriate message depending on block type
+ if ( $block->getType() == Block::TYPE_AUTO ) {
+ $this->dieWithError(
+ 'apierror-autoblocked',
+ 'autoblocked',
+ [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
+ );
+ } else {
+ $this->dieWithError(
+ 'apierror-blocked',
+ 'blocked',
+ [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
+ );
+ }
+ }
+
+ /**
+ * Throw an ApiUsageException based on the Status object.
+ *
+ * @since 1.22
+ * @since 1.29 Accepts a StatusValue
+ * @param StatusValue $status
+ * @throws ApiUsageException always
+ */
+ public function dieStatus( StatusValue $status ) {
+ if ( $status->isGood() ) {
+ throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
+ }
+
+ // ApiUsageException needs a fatal status, but this method has
+ // historically accepted any non-good status. Convert it if necessary.
+ $status->setOK( false );
+ if ( !$status->getErrorsByType( 'error' ) ) {
+ $newStatus = Status::newGood();
+ foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
+ call_user_func_array(
+ [ $newStatus, 'fatal' ],
+ array_merge( [ $err['message'] ], $err['params'] )
+ );
+ }
+ if ( !$newStatus->getErrorsByType( 'error' ) ) {
+ $newStatus->fatal( 'unknownerror-nocode' );
+ }
+ $status = $newStatus;
+ }
+
+ throw new ApiUsageException( $this, $status );
+ }
+
+ /**
+ * Helper function for readonly errors
+ *
+ * @throws ApiUsageException always
+ */
+ public function dieReadOnly() {
+ $this->dieWithError(
+ 'apierror-readonly',
+ 'readonly',
+ [ 'readonlyreason' => wfReadOnlyReason() ]
+ );
+ }
+
+ /**
+ * Helper function for permission-denied errors
+ * @since 1.29
+ * @param string|string[] $rights
+ * @param User|null $user
+ * @throws ApiUsageException if the user doesn't have any of the rights.
+ * The error message is based on $rights[0].
+ */
+ public function checkUserRightsAny( $rights, $user = null ) {
+ if ( !$user ) {
+ $user = $this->getUser();
+ }
+ $rights = (array)$rights;
+ if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
+ $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
+ }
+ }
+
+ /**
+ * Helper function for permission-denied errors
+ * @since 1.29
+ * @param Title $title
+ * @param string|string[] $actions
+ * @param User|null $user
+ * @throws ApiUsageException if the user doesn't have all of the rights.
+ */
+ public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
+ if ( !$user ) {
+ $user = $this->getUser();
+ }
+
+ $errors = [];
+ foreach ( (array)$actions as $action ) {
+ $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
+ }
+ if ( $errors ) {
+ $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
+ }
+ }
+
+ /**
+ * Will only set a warning instead of failing if the global $wgDebugAPI
+ * is set to true. Otherwise behaves exactly as self::dieWithError().
+ *
+ * @since 1.29
+ * @param string|array|Message $msg
+ * @param string|null $code
+ * @param array|null $data
+ * @param int|null $httpCode
+ * @throws ApiUsageException
+ */
+ public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
+ if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
+ $this->dieWithError( $msg, $code, $data, $httpCode );
+ } else {
+ $this->addWarning( $msg, $code, $data );
+ }
+ }
+
+ /**
+ * Die with the 'badcontinue' error.
+ *
+ * This call is common enough to make it into the base method.
+ *
+ * @param bool $condition Will only die if this value is true
+ * @throws ApiUsageException
+ * @since 1.21
+ */
+ protected function dieContinueUsageIf( $condition ) {
+ if ( $condition ) {
+ $this->dieWithError( 'apierror-badcontinue' );
+ }
+ }
+
+ /**
+ * Internal code errors should be reported with this method
+ * @param string $method Method or function name
+ * @param string $message Error message
+ * @throws MWException always
+ */
+ protected static function dieDebug( $method, $message ) {
+ throw new MWException( "Internal error in $method: $message" );
+ }
+
+ /**
+ * Write logging information for API features to a debug log, for usage
+ * analysis.
+ * @note Consider using $this->addDeprecation() instead to both warn and log.
+ * @param string $feature Feature being used.
+ */
+ public function logFeatureUsage( $feature ) {
+ $request = $this->getRequest();
+ $s = '"' . addslashes( $feature ) . '"' .
+ ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
+ ' "' . $request->getIP() . '"' .
+ ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
+ ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
+ wfDebugLog( 'api-feature-usage', $s, 'private' );
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Help message generation
+ * @{
+ */
+
+ /**
+ * Return the summary message.
+ *
+ * This is a one-line description of the module, suitable for display in a
+ * list of modules.
+ *
+ * @since 1.30
+ * @return string|array|Message
+ */
+ protected function getSummaryMessage() {
+ return "apihelp-{$this->getModulePath()}-summary";
+ }
+
+ /**
+ * Return the extended help text message.
+ *
+ * This is additional text to display at the top of the help section, below
+ * the summary.
+ *
+ * @since 1.30
+ * @return string|array|Message
+ */
+ protected function getExtendedDescription() {
+ return [ [
+ "apihelp-{$this->getModulePath()}-extended-description",
+ 'api-help-no-extended-description',
+ ] ];
+ }
+
+ /**
+ * Get final module summary
+ *
+ * Ideally this will just be the getSummaryMessage(). However, for
+ * backwards compatibility, if that message does not exist then the first
+ * line of wikitext from the description message will be used instead.
+ *
+ * @since 1.30
+ * @return Message
+ */
+ public function getFinalSummary() {
+ $msg = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
+ $this->getModulePrefix(),
+ $this->getModuleName(),
+ $this->getModulePath(),
+ ] );
+ if ( !$msg->exists() ) {
+ wfDeprecated( 'API help "description" messages', '1.30' );
+ $msg = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
+ $this->getModulePrefix(),
+ $this->getModuleName(),
+ $this->getModulePath(),
+ ] );
+ $msg = self::makeMessage( 'rawmessage', $this->getContext(), [
+ preg_replace( '/\n.*/s', '', $msg->text() )
+ ] );
+ }
+ return $msg;
+ }
+
+ /**
+ * Get final module description, after hooks have had a chance to tweak it as
+ * needed.
+ *
+ * @since 1.25, returns Message[] rather than string[]
+ * @return Message[]
+ */
+ public function getFinalDescription() {
+ $desc = $this->getDescription();
+
+ // Avoid PHP 7.1 warning of passing $this by reference
+ $apiModule = $this;
+ Hooks::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
+ $desc = self::escapeWikiText( $desc );
+ if ( is_array( $desc ) ) {
+ $desc = implode( "\n", $desc );
+ } else {
+ $desc = (string)$desc;
+ }
+
+ $summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
+ $this->getModulePrefix(),
+ $this->getModuleName(),
+ $this->getModulePath(),
+ ] );
+ $extendedDescription = self::makeMessage(
+ $this->getExtendedDescription(), $this->getContext(), [
+ $this->getModulePrefix(),
+ $this->getModuleName(),
+ $this->getModulePath(),
+ ]
+ );
+
+ if ( $summary->exists() ) {
+ $msgs = [ $summary, $extendedDescription ];
+ } else {
+ wfDeprecated( 'API help "description" messages', '1.30' );
+ $description = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
+ $this->getModulePrefix(),
+ $this->getModuleName(),
+ $this->getModulePath(),
+ ] );
+ if ( !$description->exists() ) {
+ $description = $this->msg( 'api-help-fallback-description', $desc );
+ }
+ $msgs = [ $description ];
+ }
+
+ Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
+
+ return $msgs;
+ }
+
+ /**
+ * Get final list of parameters, after hooks have had a chance to
+ * tweak it as needed.
+ *
+ * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
+ * @return array|bool False on no parameters
+ * @since 1.21 $flags param added
+ */
+ public function getFinalParams( $flags = 0 ) {
+ $params = $this->getAllowedParams( $flags );
+ if ( !$params ) {
+ $params = [];
+ }
+
+ if ( $this->needsToken() ) {
+ $params['token'] = [
+ self::PARAM_TYPE => 'string',
+ self::PARAM_REQUIRED => true,
+ self::PARAM_SENSITIVE => true,
+ self::PARAM_HELP_MSG => [
+ 'api-help-param-token',
+ $this->needsToken(),
+ ],
+ ] + ( isset( $params['token'] ) ? $params['token'] : [] );
+ }
+
+ // Avoid PHP 7.1 warning of passing $this by reference
+ $apiModule = $this;
+ Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
+
+ return $params;
+ }
+
+ /**
+ * Get final parameter descriptions, after hooks have had a chance to tweak it as
+ * needed.
+ *
+ * @since 1.25, returns array of Message[] rather than array of string[]
+ * @return array Keys are parameter names, values are arrays of Message objects
+ */
+ public function getFinalParamDescription() {
+ $prefix = $this->getModulePrefix();
+ $name = $this->getModuleName();
+ $path = $this->getModulePath();
+
+ $desc = $this->getParamDescription();
+
+ // Avoid PHP 7.1 warning of passing $this by reference
+ $apiModule = $this;
+ Hooks::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
+
+ if ( !$desc ) {
+ $desc = [];
+ }
+ $desc = self::escapeWikiText( $desc );
+
+ $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
+ $msgs = [];
+ foreach ( $params as $param => $settings ) {
+ if ( !is_array( $settings ) ) {
+ $settings = [];
+ }
+
+ $d = isset( $desc[$param] ) ? $desc[$param] : '';
+ if ( is_array( $d ) ) {
+ // Special handling for prop parameters
+ $d = array_map( function ( $line ) {
+ if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
+ $line = "\n;{$m[1]}:{$m[2]}";
+ }
+ return $line;
+ }, $d );
+ $d = implode( ' ', $d );
+ }
+
+ if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
+ $msg = $settings[self::PARAM_HELP_MSG];
+ } else {
+ $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
+ if ( !$msg->exists() ) {
+ $msg = $this->msg( 'api-help-fallback-parameter', $d );
+ }
+ }
+ $msg = self::makeMessage( $msg, $this->getContext(),
+ [ $prefix, $param, $name, $path ] );
+ if ( !$msg ) {
+ self::dieDebug( __METHOD__,
+ 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
+ }
+ $msgs[$param] = [ $msg ];
+
+ if ( isset( $settings[self::PARAM_TYPE] ) &&
+ $settings[self::PARAM_TYPE] === 'submodule'
+ ) {
+ if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
+ $map = $settings[self::PARAM_SUBMODULE_MAP];
+ } else {
+ $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
+ $map = [];
+ foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
+ $map[$submoduleName] = $prefix . $submoduleName;
+ }
+ }
+ ksort( $map );
+ $submodules = [];
+ $deprecatedSubmodules = [];
+ foreach ( $map as $v => $m ) {
+ $arr = &$submodules;
+ $isDeprecated = false;
+ $summary = null;
+ try {
+ $submod = $this->getModuleFromPath( $m );
+ if ( $submod ) {
+ $summary = $submod->getFinalSummary();
+ $isDeprecated = $submod->isDeprecated();
+ if ( $isDeprecated ) {
+ $arr = &$deprecatedSubmodules;
+ }
+ }
+ } catch ( ApiUsageException $ex ) {
+ // Ignore
+ }
+ if ( $summary ) {
+ $key = $summary->getKey();
+ $params = $summary->getParams();
+ } else {
+ $key = 'api-help-undocumented-module';
+ $params = [ $m ];
+ }
+ $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
+ $arr[] = $m->setContext( $this->getContext() );
+ }
+ $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
+ } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
+ if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
+ self::dieDebug( __METHOD__,
+ 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
+ }
+ if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
+ self::dieDebug( __METHOD__,
+ 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
+ 'ApiBase::PARAM_TYPE is an array' );
+ }
+
+ $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
+ $deprecatedValues = isset( $settings[self::PARAM_DEPRECATED_VALUES] )
+ ? $settings[self::PARAM_DEPRECATED_VALUES]
+ : [];
+
+ foreach ( $settings[self::PARAM_TYPE] as $value ) {
+ if ( isset( $valueMsgs[$value] ) ) {
+ $msg = $valueMsgs[$value];
+ } else {
+ $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
+ }
+ $m = self::makeMessage( $msg, $this->getContext(),
+ [ $prefix, $param, $name, $path, $value ] );
+ if ( $m ) {
+ $m = new ApiHelpParamValueMessage(
+ $value,
+ [ $m->getKey(), 'api-help-param-no-description' ],
+ $m->getParams(),
+ isset( $deprecatedValues[$value] )
+ );
+ $msgs[$param][] = $m->setContext( $this->getContext() );
+ } else {
+ self::dieDebug( __METHOD__,
+ "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
+ }
+ }
+ }
+
+ if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
+ if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
+ self::dieDebug( __METHOD__,
+ 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
+ }
+ foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
+ $m = self::makeMessage( $m, $this->getContext(),
+ [ $prefix, $param, $name, $path ] );
+ if ( $m ) {
+ $msgs[$param][] = $m;
+ } else {
+ self::dieDebug( __METHOD__,
+ 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
+ }
+ }
+ }
+ }
+
+ Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
+
+ return $msgs;
+ }
+
+ /**
+ * Generates the list of flags for the help screen and for action=paraminfo
+ *
+ * Corresponding messages: api-help-flag-deprecated,
+ * api-help-flag-internal, api-help-flag-readrights,
+ * api-help-flag-writerights, api-help-flag-mustbeposted
+ *
+ * @return string[]
+ */
+ protected function getHelpFlags() {
+ $flags = [];
+
+ if ( $this->isDeprecated() ) {
+ $flags[] = 'deprecated';
+ }
+ if ( $this->isInternal() ) {
+ $flags[] = 'internal';
+ }
+ if ( $this->isReadMode() ) {
+ $flags[] = 'readrights';
+ }
+ if ( $this->isWriteMode() ) {
+ $flags[] = 'writerights';
+ }
+ if ( $this->mustBePosted() ) {
+ $flags[] = 'mustbeposted';
+ }
+
+ return $flags;
+ }
+
+ /**
+ * Returns information about the source of this module, if known
+ *
+ * Returned array is an array with the following keys:
+ * - path: Install path
+ * - name: Extension name, or "MediaWiki" for core
+ * - namemsg: (optional) i18n message key for a display name
+ * - license-name: (optional) Name of license
+ *
+ * @return array|null
+ */
+ protected function getModuleSourceInfo() {
+ global $IP;
+
+ if ( $this->mModuleSource !== false ) {
+ return $this->mModuleSource;
+ }
+
+ // First, try to find where the module comes from...
+ $rClass = new ReflectionClass( $this );
+ $path = $rClass->getFileName();
+ if ( !$path ) {
+ // No path known?
+ $this->mModuleSource = null;
+ return null;
+ }
+ $path = realpath( $path ) ?: $path;
+
+ // Build map of extension directories to extension info
+ if ( self::$extensionInfo === null ) {
+ $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
+ self::$extensionInfo = [
+ realpath( __DIR__ ) ?: __DIR__ => [
+ 'path' => $IP,
+ 'name' => 'MediaWiki',
+ 'license-name' => 'GPL-2.0+',
+ ],
+ realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
+ realpath( $extDir ) ?: $extDir => null,
+ ];
+ $keep = [
+ 'path' => null,
+ 'name' => null,
+ 'namemsg' => null,
+ 'license-name' => null,
+ ];
+ foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
+ foreach ( $group as $ext ) {
+ if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
+ // This shouldn't happen, but does anyway.
+ continue;
+ }
+
+ $extpath = $ext['path'];
+ if ( !is_dir( $extpath ) ) {
+ $extpath = dirname( $extpath );
+ }
+ self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
+ array_intersect_key( $ext, $keep );
+ }
+ }
+ foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
+ $extpath = $ext['path'];
+ if ( !is_dir( $extpath ) ) {
+ $extpath = dirname( $extpath );
+ }
+ self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
+ array_intersect_key( $ext, $keep );
+ }
+ }
+
+ // Now traverse parent directories until we find a match or run out of
+ // parents.
+ do {
+ if ( array_key_exists( $path, self::$extensionInfo ) ) {
+ // Found it!
+ $this->mModuleSource = self::$extensionInfo[$path];
+ return $this->mModuleSource;
+ }
+
+ $oldpath = $path;
+ $path = dirname( $path );
+ } while ( $path !== $oldpath );
+
+ // No idea what extension this might be.
+ $this->mModuleSource = null;
+ return null;
+ }
+
+ /**
+ * 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.
+ *
+ * @param string[] &$help Array of help data
+ * @param array $options Options passed to ApiHelp::getHelp
+ * @param array &$tocData If a TOC is being generated, this array has keys
+ * as anchors in the page and values as for Linker::generateTOC().
+ */
+ public function modifyHelp( array &$help, array $options, array &$tocData ) {
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Deprecated
+ * @{
+ */
+
+ /**
+ * Returns the description string for this module
+ *
+ * Ignored if an i18n message exists for
+ * "apihelp-{$this->getModulePath()}-description".
+ *
+ * @deprecated since 1.25
+ * @return Message|string|array|false
+ */
+ protected function getDescription() {
+ return false;
+ }
+
+ /**
+ * Returns an array of parameter descriptions.
+ *
+ * For each parameter, ignored if an i18n message exists for the parameter.
+ * By default that message is
+ * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
+ * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
+ * self::getFinalParams().
+ *
+ * @deprecated since 1.25
+ * @return array|bool False on no parameter descriptions
+ */
+ protected function getParamDescription() {
+ return [];
+ }
+
+ /**
+ * Returns usage examples for this module.
+ *
+ * Return value as an array is either:
+ * - numeric keys with partial URLs ("api.php?" plus a query string) as
+ * values
+ * - sequential numeric keys with even-numbered keys being display-text
+ * and odd-numbered keys being partial urls
+ * - partial URLs as keys with display-text (string or array-to-be-joined)
+ * as values
+ * Return value as a string is the same as an array with a numeric key and
+ * that value, and boolean false means "no examples".
+ *
+ * @deprecated since 1.25, use getExamplesMessages() instead
+ * @return bool|string|array
+ */
+ protected function getExamples() {
+ return false;
+ }
+
+ /**
+ * @deprecated since 1.25, always returns empty string
+ * @param IDatabase|bool $db
+ * @return string
+ */
+ public function getModuleProfileName( $db = false ) {
+ wfDeprecated( __METHOD__, '1.25' );
+ return '';
+ }
+
+ /**
+ * @deprecated since 1.25
+ */
+ public function profileIn() {
+ // No wfDeprecated() yet because extensions call this and might need to
+ // keep doing so for BC.
+ }
+
+ /**
+ * @deprecated since 1.25
+ */
+ public function profileOut() {
+ // No wfDeprecated() yet because extensions call this and might need to
+ // keep doing so for BC.
+ }
+
+ /**
+ * @deprecated since 1.25
+ */
+ public function safeProfileOut() {
+ wfDeprecated( __METHOD__, '1.25' );
+ }
+
+ /**
+ * @deprecated since 1.25, always returns 0
+ * @return float
+ */
+ public function getProfileTime() {
+ wfDeprecated( __METHOD__, '1.25' );
+ return 0;
+ }
+
+ /**
+ * @deprecated since 1.25
+ */
+ public function profileDBIn() {
+ wfDeprecated( __METHOD__, '1.25' );
+ }
+
+ /**
+ * @deprecated since 1.25
+ */
+ public function profileDBOut() {
+ wfDeprecated( __METHOD__, '1.25' );
+ }
+
+ /**
+ * @deprecated since 1.25, always returns 0
+ * @return float
+ */
+ public function getProfileDBTime() {
+ wfDeprecated( __METHOD__, '1.25' );
+ return 0;
+ }
+
+ /**
+ * Call wfTransactionalTimeLimit() if this request was POSTed
+ * @since 1.26
+ */
+ protected function useTransactionalTimeLimit() {
+ if ( $this->getRequest()->wasPosted() ) {
+ wfTransactionalTimeLimit();
+ }
+ }
+
+ /**
+ * @deprecated since 1.29, use ApiBase::addWarning() instead
+ * @param string $warning Warning message
+ */
+ public function setWarning( $warning ) {
+ wfDeprecated( __METHOD__, '1.29' );
+ $msg = new ApiRawMessage( $warning, 'warning' );
+ $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
+ }
+
+ /**
+ * Throw an ApiUsageException, which will (if uncaught) call the main module's
+ * error handler and die with an error message.
+ *
+ * @deprecated since 1.29, use self::dieWithError() instead
+ * @param string $description One-line human-readable description of the
+ * error condition, e.g., "The API requires a valid action parameter"
+ * @param string $errorCode Brief, arbitrary, stable string to allow easy
+ * automated identification of the error, e.g., 'unknown_action'
+ * @param int $httpRespCode HTTP response code
+ * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
+ * @throws ApiUsageException always
+ */
+ public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
+ wfDeprecated( __METHOD__, '1.29' );
+ $this->dieWithError(
+ new RawMessage( '$1', [ $description ] ),
+ $errorCode,
+ $extradata,
+ $httpRespCode
+ );
+ }
+
+ /**
+ * Get error (as code, string) from a Status object.
+ *
+ * @since 1.23
+ * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
+ * @param Status $status
+ * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
+ * @return array Array of code and error string
+ * @throws MWException
+ */
+ public function getErrorFromStatus( $status, &$extraData = null ) {
+ wfDeprecated( __METHOD__, '1.29' );
+ if ( $status->isGood() ) {
+ throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
+ }
+
+ $errors = $status->getErrorsByType( 'error' );
+ if ( !$errors ) {
+ // No errors? Assume the warnings should be treated as errors
+ $errors = $status->getErrorsByType( 'warning' );
+ }
+ if ( !$errors ) {
+ // Still no errors? Punt
+ $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
+ }
+
+ if ( $errors[0]['message'] instanceof MessageSpecifier ) {
+ $msg = $errors[0]['message'];
+ } else {
+ $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
+ }
+ if ( !$msg instanceof IApiMessage ) {
+ $key = $msg->getKey();
+ $params = $msg->getParams();
+ array_unshift( $params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
+ $msg = ApiMessage::create( $params );
+ }
+
+ return [
+ $msg->getApiCode(),
+ ApiErrorFormatter::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
+ ];
+ }
+
+ /**
+ * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
+ * arbitrary strings (often message keys used elsewhere in MediaWiki) to
+ * API codes and message texts, and a few interfaces required poking
+ * something in here. Now we're repurposing it to map those same strings
+ * to i18n messages, and declaring that any interface that requires poking
+ * at this is broken and needs replacing ASAP.
+ */
+ private static $messageMap = [
+ 'unknownerror' => 'apierror-unknownerror',
+ 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
+ 'ns-specialprotected' => 'ns-specialprotected',
+ 'protectedinterface' => 'protectedinterface',
+ 'namespaceprotected' => 'namespaceprotected',
+ 'customcssprotected' => 'customcssprotected',
+ 'customjsprotected' => 'customjsprotected',
+ 'cascadeprotected' => 'cascadeprotected',
+ 'protectedpagetext' => 'protectedpagetext',
+ 'protect-cantedit' => 'protect-cantedit',
+ 'deleteprotected' => 'deleteprotected',
+ 'badaccess-group0' => 'badaccess-group0',
+ 'badaccess-groups' => 'badaccess-groups',
+ 'titleprotected' => 'titleprotected',
+ 'nocreate-loggedin' => 'nocreate-loggedin',
+ 'nocreatetext' => 'nocreatetext',
+ 'movenologintext' => 'movenologintext',
+ 'movenotallowed' => 'movenotallowed',
+ 'confirmedittext' => 'confirmedittext',
+ 'blockedtext' => 'apierror-blocked',
+ 'autoblockedtext' => 'apierror-autoblocked',
+ 'systemblockedtext' => 'apierror-systemblocked',
+ 'actionthrottledtext' => 'apierror-ratelimited',
+ 'alreadyrolled' => 'alreadyrolled',
+ 'cantrollback' => 'cantrollback',
+ 'readonlytext' => 'readonlytext',
+ 'sessionfailure' => 'sessionfailure',
+ 'cannotdelete' => 'cannotdelete',
+ 'notanarticle' => 'apierror-missingtitle',
+ 'selfmove' => 'selfmove',
+ 'immobile_namespace' => 'apierror-immobilenamespace',
+ 'articleexists' => 'articleexists',
+ 'hookaborted' => 'hookaborted',
+ 'cantmove-titleprotected' => 'cantmove-titleprotected',
+ 'imagenocrossnamespace' => 'imagenocrossnamespace',
+ 'imagetypemismatch' => 'imagetypemismatch',
+ 'ip_range_invalid' => 'ip_range_invalid',
+ 'range_block_disabled' => 'range_block_disabled',
+ 'nosuchusershort' => 'nosuchusershort',
+ 'badipaddress' => 'badipaddress',
+ 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
+ 'ipb_already_blocked' => 'ipb_already_blocked',
+ 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
+ 'ipb_cant_unblock' => 'ipb_cant_unblock',
+ 'mailnologin' => 'apierror-cantsend',
+ 'ipbblocked' => 'ipbblocked',
+ 'ipbnounblockself' => 'ipbnounblockself',
+ 'usermaildisabled' => 'usermaildisabled',
+ 'blockedemailuser' => 'apierror-blockedfrommail',
+ 'notarget' => 'apierror-notarget',
+ 'noemail' => 'noemail',
+ 'rcpatroldisabled' => 'rcpatroldisabled',
+ 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
+ 'delete-toobig' => 'delete-toobig',
+ 'movenotallowedfile' => 'movenotallowedfile',
+ 'userrights-no-interwiki' => 'userrights-no-interwiki',
+ 'userrights-nodatabase' => 'userrights-nodatabase',
+ 'nouserspecified' => 'nouserspecified',
+ 'noname' => 'noname',
+ 'summaryrequired' => 'apierror-summaryrequired',
+ 'import-rootpage-invalid' => 'import-rootpage-invalid',
+ 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
+ 'readrequired' => 'apierror-readapidenied',
+ 'writedisabled' => 'apierror-noapiwrite',
+ 'writerequired' => 'apierror-writeapidenied',
+ 'missingparam' => 'apierror-missingparam',
+ 'invalidtitle' => 'apierror-invalidtitle',
+ 'nosuchpageid' => 'apierror-nosuchpageid',
+ 'nosuchrevid' => 'apierror-nosuchrevid',
+ 'nosuchuser' => 'nosuchusershort',
+ 'invaliduser' => 'apierror-invaliduser',
+ 'invalidexpiry' => 'apierror-invalidexpiry',
+ 'pastexpiry' => 'apierror-pastexpiry',
+ 'create-titleexists' => 'apierror-create-titleexists',
+ 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
+ 'cantblock' => 'apierror-cantblock',
+ 'canthide' => 'apierror-canthide',
+ 'cantblock-email' => 'apierror-cantblock-email',
+ 'cantunblock' => 'apierror-permissiondenied-generic',
+ 'cannotundelete' => 'cannotundelete',
+ 'permdenied-undelete' => 'apierror-permissiondenied-generic',
+ 'createonly-exists' => 'apierror-articleexists',
+ 'nocreate-missing' => 'apierror-missingtitle',
+ 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
+ 'nosuchrcid' => 'apierror-nosuchrcid',
+ 'nosuchlogid' => 'apierror-nosuchlogid',
+ 'protect-invalidaction' => 'apierror-protect-invalidaction',
+ 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
+ 'toofewexpiries' => 'apierror-toofewexpiries',
+ 'cantimport' => 'apierror-cantimport',
+ 'cantimport-upload' => 'apierror-cantimport-upload',
+ 'importnofile' => 'importnofile',
+ 'importuploaderrorsize' => 'importuploaderrorsize',
+ 'importuploaderrorpartial' => 'importuploaderrorpartial',
+ 'importuploaderrortemp' => 'importuploaderrortemp',
+ 'importcantopen' => 'importcantopen',
+ 'import-noarticle' => 'import-noarticle',
+ 'importbadinterwiki' => 'importbadinterwiki',
+ 'import-unknownerror' => 'apierror-import-unknownerror',
+ 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
+ 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
+ 'mustbeposted' => 'apierror-mustbeposted',
+ 'show' => 'apierror-show',
+ 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
+ 'invalidoldimage' => 'apierror-invalidoldimage',
+ 'nodeleteablefile' => 'apierror-nodeleteablefile',
+ 'fileexists-forbidden' => 'fileexists-forbidden',
+ 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
+ 'filerevert-badversion' => 'filerevert-badversion',
+ 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
+ 'noimageredirect-logged' => 'apierror-noimageredirect',
+ 'spamdetected' => 'apierror-spamdetected',
+ 'contenttoobig' => 'apierror-contenttoobig',
+ 'noedit-anon' => 'apierror-noedit-anon',
+ 'noedit' => 'apierror-noedit',
+ 'wasdeleted' => 'apierror-pagedeleted',
+ 'blankpage' => 'apierror-emptypage',
+ 'editconflict' => 'editconflict',
+ 'hashcheckfailed' => 'apierror-badmd5',
+ 'missingtext' => 'apierror-notext',
+ 'emptynewsection' => 'apierror-emptynewsection',
+ 'revwrongpage' => 'apierror-revwrongpage',
+ 'undo-failure' => 'undo-failure',
+ 'content-not-allowed-here' => 'content-not-allowed-here',
+ 'edit-hook-aborted' => 'edit-hook-aborted',
+ 'edit-gone-missing' => 'edit-gone-missing',
+ 'edit-conflict' => 'edit-conflict',
+ 'edit-already-exists' => 'edit-already-exists',
+ 'invalid-file-key' => 'apierror-invalid-file-key',
+ 'nouploadmodule' => 'apierror-nouploadmodule',
+ 'uploaddisabled' => 'uploaddisabled',
+ 'copyuploaddisabled' => 'copyuploaddisabled',
+ 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
+ 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
+ 'filename-tooshort' => 'filename-tooshort',
+ 'filename-toolong' => 'filename-toolong',
+ 'illegal-filename' => 'illegal-filename',
+ 'filetype-missing' => 'filetype-missing',
+ 'mustbeloggedin' => 'apierror-mustbeloggedin',
+ ];
+
+ /**
+ * @deprecated do not use
+ * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
+ * @return ApiMessage
+ */
+ private function parseMsgInternal( $error ) {
+ $msg = Message::newFromSpecifier( $error );
+ if ( !$msg instanceof IApiMessage ) {
+ $key = $msg->getKey();
+ if ( isset( self::$messageMap[$key] ) ) {
+ $params = $msg->getParams();
+ array_unshift( $params, self::$messageMap[$key] );
+ } else {
+ $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
+ }
+ $msg = ApiMessage::create( $params );
+ }
+ return $msg;
+ }
+
+ /**
+ * Return the error message related to a certain array
+ * @deprecated since 1.29
+ * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
+ * @return array [ 'code' => code, 'info' => info ]
+ */
+ public function parseMsg( $error ) {
+ wfDeprecated( __METHOD__, '1.29' );
+ // Check whether someone passed the whole array, instead of one element as
+ // documented. This breaks if it's actually an array of fallback keys, but
+ // that's long-standing misbehavior introduced in r87627 to incorrectly
+ // fix T30797.
+ if ( is_array( $error ) ) {
+ $first = reset( $error );
+ if ( is_array( $first ) ) {
+ wfDebug( __METHOD__ . ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
+ $error = $first;
+ }
+ }
+
+ $msg = $this->parseMsgInternal( $error );
+ return [
+ 'code' => $msg->getApiCode(),
+ 'info' => ApiErrorFormatter::stripMarkup(
+ $msg->inLanguage( 'en' )->useDatabase( false )->text()
+ ),
+ 'data' => $msg->getApiData()
+ ];
+ }
+
+ /**
+ * Output the error message related to a certain array
+ * @deprecated since 1.29, use ApiBase::dieWithError() instead
+ * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
+ * @throws ApiUsageException always
+ */
+ public function dieUsageMsg( $error ) {
+ wfDeprecated( __METHOD__, '1.29' );
+ $this->dieWithError( $this->parseMsgInternal( $error ) );
+ }
+
+ /**
+ * Will only set a warning instead of failing if the global $wgDebugAPI
+ * is set to true. Otherwise behaves exactly as dieUsageMsg().
+ * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
+ * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
+ * @throws ApiUsageException
+ * @since 1.21
+ */
+ public function dieUsageMsgOrDebug( $error ) {
+ wfDeprecated( __METHOD__, '1.29' );
+ $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
+ }
+
+ /**
+ * Return the description message.
+ *
+ * This is additional text to display on the help page after the summary.
+ *
+ * @deprecated since 1.30
+ * @return string|array|Message
+ */
+ protected function getDescriptionMessage() {
+ return [ [
+ "apihelp-{$this->getModulePath()}-description",
+ "apihelp-{$this->getModulePath()}-summary",
+ ] ];
+ }
+
+ /**@}*/
}
+
+/**
+ * For really cool vim folding this needs to be at the end:
+ * vim: foldmarker=@{,@} foldmethod=marker
+ */