}
}
- /*****************************************************************************
- * ABSTRACT METHODS *
- *****************************************************************************/
+
+ /************************************************************************//**
+ * @name Methods to implement
+ * @{
+ */
/**
* Evaluates the parameters, performs the requested query, and sets up
abstract public function execute();
/**
- * Returns a string that identifies the version of the extending class.
- * Typically includes the class name, the svn revision, timestamp, and
- * last author. Usually done with SVN's Id keyword
- * @return string
- * @deprecated since 1.21, version string is no longer supported
+ * Get the module manager, or null if this module has no sub-modules
+ * @since 1.21
+ * @return ApiModuleManager
*/
- public function getVersion() {
- wfDeprecated( __METHOD__, '1.21' );
+ public function getModuleManager() {
+ return null;
+ }
- return '';
+ /**
+ * 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.
+ * @return mixed Instance of a derived class of ApiFormatBase, or null
+ */
+ public function getCustomPrinter() {
+ return null;
}
/**
- * Get the name of the module being executed by this instance
- * @return string
+ * Returns the description string for this module
+ * @return string|array
*/
- public function getModuleName() {
- return $this->mModuleName;
+ protected function getDescription() {
+ return false;
}
/**
- * Get the module manager, or null if this module has no sub-modules
- * @since 1.21
- * @return ApiModuleManager
+ * Returns usage examples for this module. Return false if no examples are available.
+ * @return bool|string|array
*/
- public function getModuleManager() {
- return null;
+ protected function getExamples() {
+ return false;
}
/**
- * Get parameter prefix (usually two letters or an empty string).
- * @return string
+ * @return bool|string|array Returns a false if the module has no help URL,
+ * else returns a (array of) string
*/
- public function getModulePrefix() {
- return $this->mModulePrefix;
+ public function getHelpUrls() {
+ return false;
}
/**
- * Get the name of the module as shown in the profiler log
+ * 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.
*
- * @param DatabaseBase|bool $db
+ * 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|bool
+ */
+ protected function getAllowedParams( /* $flags = 0 */ ) {
+ // int $flags is not declared because it causes "Strict standards"
+ // warning. Most derived classes do not implement it.
+ return false;
+ }
+
+ /**
+ * Returns an array of parameter descriptions.
+ * Don't call this function directly: use getFinalParamDescription() to
+ * allow hooks to modify descriptions as needed.
+ * @return array|bool False on no parameter descriptions
+ */
+ protected function getParamDescription() {
+ return false;
+ }
+
+ /**
+ * Indicates if this module needs maxlag to be checked
+ * @return bool
+ */
+ public function shouldCheckMaxlag() {
+ return true;
+ }
+
+ /**
+ * Indicates whether this module requires read rights
+ * @return bool
+ */
+ public function isReadMode() {
+ return true;
+ }
+
+ /**
+ * Indicates whether this module requires write mode
+ * @return bool
+ */
+ public function isWriteMode() {
+ return false;
+ }
+
+ /**
+ * Indicates whether this module must be called with a POST request
+ * @return bool
+ */
+ public function mustBePosted() {
+ return $this->needsToken() !== false;
+ }
+
+ /**
+ * 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 cause self::getFinalParams() to
+ * return a required string 'token' parameter and
+ * self::getFinalParamDescription() to ensure there is standardized
+ * documentation for it. 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 needsToken() {
+ return false;
+ }
+
+ /**
+ * 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
+ */
+ protected function getWebUITokenSalt( array $params ) {
+ return null;
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Data access methods
+ * @{
+ */
+
+ /**
+ * Get the name of the module being executed by this instance
* @return string
*/
- public function getModuleProfileName( $db = false ) {
- if ( $db ) {
- return 'API:' . $this->mModuleName . '-DB';
- }
+ public function getModuleName() {
+ return $this->mModuleName;
+ }
- return 'API:' . $this->mModuleName;
+ /**
+ * Get parameter prefix (usually two letters or an empty string).
+ * @return string
+ */
+ public function getModulePrefix() {
+ return $this->mModulePrefix;
}
/**
}
/**
- * Set warning section for this module. Users should monitor this
- * section to notice any changes in API. Multiple calls to this
- * function will result in the warning messages being separated by
- * newlines
- * @param string $warning Warning message
+ * Gets a default slave database connection object
+ * @return DatabaseBase
*/
- public function setWarning( $warning ) {
- $result = $this->getResult();
- $data = $result->getData();
- $moduleName = $this->getModuleName();
- if ( isset( $data['warnings'][$moduleName] ) ) {
- // Don't add duplicate warnings
- $oldWarning = $data['warnings'][$moduleName]['*'];
- $warnPos = strpos( $oldWarning, $warning );
- // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
- if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
- // Check if $warning is followed by "\n" or the end of the $oldWarning
- $warnPos += strlen( $warning );
- if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
- return;
- }
- }
- // If there is a warning already, append it to the existing one
- $warning = "$oldWarning\n$warning";
+ protected function getDB() {
+ if ( !isset( $this->mSlaveDB ) ) {
+ $this->profileDBIn();
+ $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
+ $this->profileDBOut();
}
- $msg = array();
- ApiResult::setContent( $msg, $warning );
- $result->addValue( 'warnings', $moduleName,
- $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
+
+ return $this->mSlaveDB;
}
/**
- * 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.
- * @return mixed Instance of a derived class of ApiFormatBase, or null
+ * Get final module description, after hooks have had a chance to tweak it as
+ * needed.
+ *
+ * @return array|bool False on no parameters
*/
- public function getCustomPrinter() {
- return null;
+ public function getFinalDescription() {
+ $desc = $this->getDescription();
+ wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
+
+ return $desc;
}
/**
- * Generates help message for this module, or false if there is no description
- * @return string|bool
+ * 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 makeHelpMsg() {
- static $lnPrfx = "\n ";
+ public function getFinalParams( $flags = 0 ) {
+ $params = $this->getAllowedParams( $flags );
- $msg = $this->getFinalDescription();
+ if ( $this->needsToken() ) {
+ $params['token'] = array(
+ ApiBase::PARAM_TYPE => 'string',
+ ApiBase::PARAM_REQUIRED => true,
+ );
+ }
- if ( $msg !== false ) {
+ wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
- if ( !is_array( $msg ) ) {
- $msg = array(
- $msg
- );
- }
- $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
+ return $params;
+ }
- $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
+ /**
+ * Get final parameter descriptions, after hooks have had a chance to tweak it as
+ * needed.
+ *
+ * @return array|bool False on no parameter descriptions
+ */
+ public function getFinalParamDescription() {
+ $desc = $this->getParamDescription();
- if ( $this->isReadMode() ) {
- $msg .= "\nThis module requires read rights";
- }
- if ( $this->isWriteMode() ) {
- $msg .= "\nThis module requires write rights";
- }
- if ( $this->mustBePosted() ) {
- $msg .= "\nThis module only accepts POST requests";
- }
- if ( $this->isReadMode() || $this->isWriteMode() ||
- $this->mustBePosted()
- ) {
- $msg .= "\n";
+ $tokenType = $this->needsToken();
+ if ( $tokenType ) {
+ if ( !isset( $desc['token'] ) ) {
+ $desc['token'] = array();
+ } elseif ( !is_array( $desc['token'] ) ) {
+ // We ignore a plain-string token, because it's probably an
+ // extension that is supplying the string for BC.
+ $desc['token'] = array();
}
+ array_unshift( $desc['token'],
+ "A '$tokenType' token retrieved from action=query&meta=tokens"
+ );
+ }
- // Parameters
- $paramsMsg = $this->makeHelpMsgParameters();
- if ( $paramsMsg !== false ) {
- $msg .= "Parameters:\n$paramsMsg";
- }
+ wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
- $examples = $this->getExamples();
- if ( $examples ) {
- if ( !is_array( $examples ) ) {
- $examples = array(
- $examples
- );
- }
- $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
- foreach ( $examples as $k => $v ) {
- if ( is_numeric( $k ) ) {
- $msg .= " $v\n";
- } else {
- if ( is_array( $v ) ) {
- $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
- } else {
- $msgExample = " $v";
- }
- $msgExample .= ":";
- $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
- }
+ return $desc;
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Parameter handling
+ * @{
+ */
+
+ /**
+ * This method mangles parameter name based on the prefix supplied to the constructor.
+ * Override this method to change parameter name during runtime
+ * @param string $paramName Parameter name
+ * @return string Prefixed parameter name
+ */
+ public function encodeParamName( $paramName ) {
+ 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 bug 24564.
+ if ( !isset( $this->mParamCache[$parseLimit] ) ) {
+ $params = $this->getFinalParams();
+ $results = array();
+
+ if ( $params ) { // getFinalParams() can return false
+ foreach ( $params as $paramName => $paramSettings ) {
+ $results[$paramName] = $this->getParameterFromSettings(
+ $paramName, $paramSettings, $parseLimit );
}
}
+ $this->mParamCache[$parseLimit] = $results;
}
- return $msg;
+ return $this->mParamCache[$parseLimit];
}
/**
- * @param string $item
- * @return string
+ * Get a value for the given parameter
+ * @param string $paramName Parameter name
+ * @param bool $parseLimit See extractRequestParams()
+ * @return mixed Parameter value
*/
- private function indentExampleText( $item ) {
- return " " . $item;
+ protected function getParameter( $paramName, $parseLimit = true ) {
+ $params = $this->getFinalParams();
+ $paramSettings = $params[$paramName];
+
+ return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
}
/**
- * @param string $prefix Text to split output items
- * @param string $title What is being output
- * @param string|array $input
- * @return string
+ * 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
*/
- protected function makeHelpArrayToString( $prefix, $title, $input ) {
- if ( $input === false ) {
- return '';
- }
- if ( !is_array( $input ) ) {
- $input = array( $input );
- }
+ public function requireOnlyOneParameter( $params, $required /*...*/ ) {
+ $required = func_get_args();
+ array_shift( $required );
+ $p = $this->getModulePrefix();
- if ( count( $input ) > 0 ) {
- if ( $title ) {
- $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
- } else {
- $msg = ' ';
- }
- $msg .= implode( $prefix, $input ) . "\n";
+ $intersection = array_intersect( array_keys( array_filter( $params,
+ array( $this, "parameterNotEmpty" ) ) ), $required );
- return $msg;
+ if ( count( $intersection ) > 1 ) {
+ $this->dieUsage(
+ "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
+ 'invalidparammix' );
+ } elseif ( count( $intersection ) == 0 ) {
+ $this->dieUsage(
+ "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
+ 'missingparam'
+ );
}
-
- return '';
}
/**
- * Generates the parameter descriptions for this module, to be displayed in the
- * module's help.
- * @return string|bool
+ * 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 makeHelpMsgParameters() {
- $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
- if ( $params ) {
+ public function requireMaxOneParameter( $params, $required /*...*/ ) {
+ $required = func_get_args();
+ array_shift( $required );
+ $p = $this->getModulePrefix();
- $paramsDescription = $this->getFinalParamDescription();
- $msg = '';
- $paramPrefix = "\n" . str_repeat( ' ', 24 );
- $descWordwrap = "\n" . str_repeat( ' ', 28 );
- foreach ( $params as $paramName => $paramSettings ) {
- $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
- if ( is_array( $desc ) ) {
- $desc = implode( $paramPrefix, $desc );
- }
+ $intersection = array_intersect( array_keys( array_filter( $params,
+ array( $this, "parameterNotEmpty" ) ) ), $required );
- //handle shorthand
- if ( !is_array( $paramSettings ) ) {
- $paramSettings = array(
- self::PARAM_DFLT => $paramSettings,
- );
- }
+ if ( count( $intersection ) > 1 ) {
+ $this->dieUsage(
+ "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
+ 'invalidparammix'
+ );
+ }
+ }
- //handle missing type
- if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
- $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
- ? $paramSettings[ApiBase::PARAM_DFLT]
- : null;
- if ( is_bool( $dflt ) ) {
- $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
- } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
- $paramSettings[ApiBase::PARAM_TYPE] = 'string';
- } elseif ( is_int( $dflt ) ) {
- $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
- }
- }
+ /**
+ * 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 );
+ $p = $this->getModulePrefix();
- if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
- && $paramSettings[self::PARAM_DEPRECATED]
- ) {
- $desc = "DEPRECATED! $desc";
- }
+ $intersection = array_intersect(
+ array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
+ $required
+ );
- if ( isset( $paramSettings[self::PARAM_REQUIRED] )
- && $paramSettings[self::PARAM_REQUIRED]
- ) {
- $desc .= $paramPrefix . "This parameter is required";
- }
+ if ( count( $intersection ) == 0 ) {
+ $this->dieUsage( "At least one of the parameters {$p}" .
+ implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
+ }
+ }
- $type = isset( $paramSettings[self::PARAM_TYPE] )
- ? $paramSettings[self::PARAM_TYPE]
- : null;
- if ( isset( $type ) ) {
- $hintPipeSeparated = true;
- $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
- ? $paramSettings[self::PARAM_ISMULTI]
- : false;
- if ( $multi ) {
- $prompt = 'Values (separate with \'|\'): ';
- } else {
- $prompt = 'One value: ';
- }
+ /**
+ * 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;
+ }
- if ( $type === 'submodule' ) {
- $type = $this->getModuleManager()->getNames( $paramName );
- sort( $type );
- }
- if ( is_array( $type ) ) {
- $choices = array();
- $nothingPrompt = '';
- foreach ( $type as $t ) {
- if ( $t === '' ) {
- $nothingPrompt = 'Can be empty, or ';
- } else {
- $choices[] = $t;
- }
- }
- $desc .= $paramPrefix . $nothingPrompt . $prompt;
- $choicesstring = implode( ', ', $choices );
- $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
- $hintPipeSeparated = false;
- } else {
- switch ( $type ) {
- case 'namespace':
- // Special handling because namespaces are
- // type-limited, yet they are not given
- $desc .= $paramPrefix . $prompt;
- $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
- 100, $descWordwrap );
- $hintPipeSeparated = false;
- break;
- case 'limit':
- $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
- if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
- $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
- }
- $desc .= ' allowed';
- break;
- case 'integer':
- $s = $multi ? 's' : '';
- $hasMin = isset( $paramSettings[self::PARAM_MIN] );
- $hasMax = isset( $paramSettings[self::PARAM_MAX] );
- if ( $hasMin || $hasMax ) {
- if ( !$hasMax ) {
- $intRangeStr = "The value$s must be no less than " .
- "{$paramSettings[self::PARAM_MIN]}";
- } elseif ( !$hasMin ) {
- $intRangeStr = "The value$s must be no more than " .
- "{$paramSettings[self::PARAM_MAX]}";
- } else {
- $intRangeStr = "The value$s must be between " .
- "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
- }
-
- $desc .= $paramPrefix . $intRangeStr;
- }
- break;
- case 'upload':
- $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
- break;
- }
- }
-
- if ( $multi ) {
- if ( $hintPipeSeparated ) {
- $desc .= $paramPrefix . "Separate values with '|'";
- }
-
- $isArray = is_array( $type );
- if ( !$isArray
- || $isArray && count( $type ) > self::LIMIT_SML1
- ) {
- $desc .= $paramPrefix . "Maximum number of values " .
- self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
- }
- }
- }
-
- $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
- if ( !is_null( $default ) && $default !== false ) {
- $desc .= $paramPrefix . "Default: $default";
- }
+ /**
+ * 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
+ * @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 slave database
+ * - 'fromdbmaster': load from the master database
+ * @return WikiPage
+ */
+ public function getTitleOrPageId( $params, $load = false ) {
+ $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
- $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
+ $pageObj = null;
+ if ( isset( $params['title'] ) ) {
+ $titleObj = Title::newFromText( $params['title'] );
+ if ( !$titleObj || $titleObj->isExternal() ) {
+ $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
+ }
+ if ( !$titleObj->canExist() ) {
+ $this->dieUsage( "Namespace doesn't allow actual pages", '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->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
}
-
- return $msg;
}
- return false;
+ return $pageObj;
}
/**
- * Returns the description string for this module
- * @return string|array
+ * 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 getDescription() {
- return false;
- }
+ protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
- /**
- * Returns usage examples for this module. Return false if no examples are available.
- * @return bool|string|array
- */
- protected function getExamples() {
- return false;
- }
+ $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
- /**
- * 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|bool
- */
- protected function getAllowedParams( /* $flags = 0 */ ) {
- // int $flags is not declared because it causes "Strict standards"
- // warning. Most derived classes do not implement it.
- return false;
- }
+ switch ( $watchlist ) {
+ case 'watch':
+ return true;
- /**
- * Returns an array of parameter descriptions.
- * Don't call this function directly: use getFinalParamDescription() to
- * allow hooks to modify descriptions as needed.
- * @return array|bool False on no parameter descriptions
- */
- protected function getParamDescription() {
- return false;
- }
+ case 'unwatch':
+ return false;
- /**
- * 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 );
+ 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();
+ }
- if ( $this->needsToken() ) {
- $params['token'] = array(
- ApiBase::PARAM_TYPE => 'string',
- ApiBase::PARAM_REQUIRED => true,
- );
- }
+ # Watch the article based on the user preference
+ return $this->getUser()->getBoolOption( $userOption );
- wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
+ case 'nochange':
+ return $userWatching;
- return $params;
+ default:
+ return $userWatching;
+ }
}
/**
- * Get final parameter descriptions, after hooks have had a chance to tweak it as
- * needed.
+ * Using the settings determine the value for the given parameter
*
- * @return array|bool False on no parameter descriptions
+ * @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
*/
- public function getFinalParamDescription() {
- $desc = $this->getParamDescription();
+ protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
+ // Some classes may decide to change parameter names
+ $encParamName = $this->encodeParamName( $paramName );
- $tokenType = $this->needsToken();
- if ( $tokenType ) {
- if ( !isset( $desc['token'] ) ) {
- $desc['token'] = array();
- } elseif ( !is_array( $desc['token'] ) ) {
- // We ignore a plain-string token, because it's probably an
- // extension that is supplying the string for BC.
- $desc['token'] = array();
+ if ( !is_array( $paramSettings ) ) {
+ $default = $paramSettings;
+ $multi = false;
+ $type = gettype( $paramSettings );
+ $dupes = false;
+ $deprecated = false;
+ $required = 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;
+ $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
+ ? $paramSettings[self::PARAM_DEPRECATED]
+ : false;
+ $required = isset( $paramSettings[self::PARAM_REQUIRED] )
+ ? $paramSettings[self::PARAM_REQUIRED]
+ : 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
+ }
}
- array_unshift( $desc['token'],
- "A '$tokenType' token retrieved from action=query&meta=tokens"
- );
}
- wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
-
- return $desc;
- }
-
- /**
- * Formerly used to fetch a list of possible properites in the result,
- * somehow organized with respect to the prop parameter that causes them to
- * be returned. The specific semantics of the return value was never
- * specified. Since this was never possible to be accurately updated, it
- * has been removed.
- *
- * @deprecated since 1.24
- * @return array|bool
- */
- protected function getResultProperties() {
- wfDeprecated( __METHOD__, '1.24' );
- return false;
- }
-
- /**
- * @see self::getResultProperties()
- * @deprecated since 1.24
- * @return array|bool
- */
- public function getFinalResultProperties() {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
- }
-
- /**
- * @see self::getResultProperties()
- * @deprecated since 1.24
- */
- protected static function addTokenProperties( &$props, $tokenFunctions ) {
- wfDeprecated( __METHOD__, '1.24' );
- }
-
- /**
- * Get final module description, after hooks have had a chance to tweak it as
- * needed.
- *
- * @return array|bool False on no parameters
- */
- public function getFinalDescription() {
- $desc = $this->getDescription();
- wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
-
- return $desc;
- }
-
- /**
- * This method mangles parameter name based on the prefix supplied to the constructor.
- * Override this method to change parameter name during runtime
- * @param string $paramName Parameter name
- * @return string Prefixed parameter name
- */
- public function encodeParamName( $paramName ) {
- 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 bug 24564.
- if ( !isset( $this->mParamCache[$parseLimit] ) ) {
- $params = $this->getFinalParams();
- $results = array();
-
- 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 ) {
- $params = $this->getFinalParams();
- $paramSettings = $params[$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 );
- $p = $this->getModulePrefix();
-
- $intersection = array_intersect( array_keys( array_filter( $params,
- array( $this, "parameterNotEmpty" ) ) ), $required );
-
- if ( count( $intersection ) > 1 ) {
- $this->dieUsage(
- "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
- 'invalidparammix' );
- } elseif ( count( $intersection ) == 0 ) {
- $this->dieUsage(
- "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
- 'missingparam'
- );
- }
- }
-
- /**
- * @see self::getPossibleErrors()
- * @deprecated since 1.24
- * @return array
- */
- public function getRequireOnlyOneParameterErrorMessages( $params ) {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
- }
-
- /**
- * 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 );
- $p = $this->getModulePrefix();
-
- $intersection = array_intersect( array_keys( array_filter( $params,
- array( $this, "parameterNotEmpty" ) ) ), $required );
-
- if ( count( $intersection ) > 1 ) {
- $this->dieUsage(
- "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
- 'invalidparammix'
- );
- }
- }
-
- /**
- * @see self::getPossibleErrors()
- * @deprecated since 1.24
- * @return array
- */
- public function getRequireMaxOneParameterErrorMessages( $params ) {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
- }
-
- /**
- * 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 );
- $p = $this->getModulePrefix();
-
- $intersection = array_intersect(
- array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
- $required
- );
-
- if ( count( $intersection ) == 0 ) {
- $this->dieUsage( "At least one of the parameters {$p}" .
- implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
- }
- }
-
- /**
- * @see self::getPossibleErrors()
- * @deprecated since 1.24
- * @return array
- */
- public function getRequireAtLeastOneParameterErrorMessages( $params ) {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
- }
-
- /**
- * 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
- * @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 slave database
- * - '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->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
- }
- if ( !$titleObj->canExist() ) {
- $this->dieUsage( "Namespace doesn't allow actual pages", '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->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
- }
- }
-
- return $pageObj;
- }
-
- /**
- * @see self::getPossibleErrors()
- * @deprecated since 1.24
- * @return array
- */
- public function getTitleOrPageIdErrorMessage() {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
- }
-
- /**
- * 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;
- }
-
- /**
- * 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, WatchedItem::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;
- }
- }
-
- /**
- * 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() );
- }
-
- /**
- * 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 );
-
- if ( !is_array( $paramSettings ) ) {
- $default = $paramSettings;
- $multi = false;
- $type = gettype( $paramSettings );
- $dupes = false;
- $deprecated = false;
- $required = 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;
- $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
- ? $paramSettings[self::PARAM_DEPRECATED]
- : false;
- $required = isset( $paramSettings[self::PARAM_REQUIRED] )
- ? $paramSettings[self::PARAM_REQUIRED]
- : 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 not allowed
- ApiBase::dieDebug(
- __METHOD__,
- "Boolean param $encParamName's default is set to '$default'. " .
- "Boolean parameters must default to false."
- );
- }
+ if ( $type == 'boolean' ) {
+ if ( isset( $default ) && $default !== false ) {
+ // Having a default value of anything other than 'false' is not allowed
+ ApiBase::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' ) {
* @param int $botMax Maximum value for sysops/bots
* @param bool $enforceLimits Whether to enforce (die) if value is outside limits
*/
- function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
+ protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
if ( !is_null( $min ) && $value < $min ) {
$msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
* @param string $encParamName Parameter name
* @return string Validated and normalized parameter
*/
- function validateTimestamp( $value, $encParamName ) {
+ protected function validateTimestamp( $value, $encParamName ) {
$unixTimestamp = wfTimestamp( TS_UNIX, $value );
if ( $unixTimestamp === false ) {
$this->dieUsage(
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
+ */
+ public final 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'
+ );
+ }
+
+ if ( $this->getUser()->matchEditToken(
+ $token,
+ $salts[$tokenType],
+ $this->getRequest()
+ ) ) {
+ 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
return $title->getText();
}
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Utility methods
+ * @{
+ */
+
/**
- * Adds a warning to the output, else dies
- *
- * @param string $msg Message to show as a warning, or error message if dying
- * @param bool $enforceLimits Whether this is an enforce (die)
+ * 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
*/
- private function warnOrDie( $msg, $enforceLimits = false ) {
- if ( $enforceLimits ) {
- $this->dieUsage( $msg, 'integeroutofrange' );
+ protected function setWatch( $watch, $titleObj, $userOption = null ) {
+ $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
+ if ( $value === null ) {
+ return;
}
- $this->setWarning( $msg );
+ WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
}
/**
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->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
+ }
+ $token = $user->getOption( 'watchlisttoken' );
+ if ( $token == '' || $token != $params['token'] ) {
+ $this->dieUsage(
+ 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
+ 'bad_wltoken'
+ );
+ }
+ } else {
+ if ( !$this->getUser()->isLoggedIn() ) {
+ $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
+ }
+ if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
+ $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
+ }
+ $user = $this->getUser();
+ }
+
+ return $user;
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Warning and error reporting
+ * @{
+ */
+
+ /**
+ * Set warning section for this module. Users should monitor this
+ * section to notice any changes in API. Multiple calls to this
+ * function will result in the warning messages being separated by
+ * newlines
+ * @param string $warning Warning message
+ */
+ public function setWarning( $warning ) {
+ $result = $this->getResult();
+ $data = $result->getData();
+ $moduleName = $this->getModuleName();
+ if ( isset( $data['warnings'][$moduleName] ) ) {
+ // Don't add duplicate warnings
+ $oldWarning = $data['warnings'][$moduleName]['*'];
+ $warnPos = strpos( $oldWarning, $warning );
+ // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
+ if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
+ // Check if $warning is followed by "\n" or the end of the $oldWarning
+ $warnPos += strlen( $warning );
+ if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
+ return;
+ }
+ }
+ // If there is a warning already, append it to the existing one
+ $warning = "$oldWarning\n$warning";
+ }
+ $msg = array();
+ ApiResult::setContent( $msg, $warning );
+ $result->addValue( 'warnings', $moduleName,
+ $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
+ }
+
+ /**
+ * Adds a warning to the output, else dies
+ *
+ * @param string $msg Message to show as a warning, or error message if dying
+ * @param bool $enforceLimits Whether this is an enforce (die)
+ */
+ private function warnOrDie( $msg, $enforceLimits = false ) {
+ if ( $enforceLimits ) {
+ $this->dieUsage( $msg, 'integeroutofrange' );
+ }
+
+ $this->setWarning( $msg );
+ }
+
/**
* Throw a UsageException, which will (if uncaught) call the main module's
* error handler and die with an error message.
}
/**
- * Return the error message related to a certain array
- * @param array $error Element of a getUserPermissionsErrors()-style array
- * @return array('code' => code, 'info' => 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 ) {
+ $error = (array)$error; // It seems strings sometimes make their way in here
+ $key = array_shift( $error );
+
+ // Check whether the error array was nested
+ // array( array( <code>, <params> ), array( <another_code>, <params> ) )
+ if ( is_array( $key ) ) {
+ $error = $key;
+ $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 ) );
+ }
+
+ /**
+ * Internal code errors should be reported with this method
+ * @param string $method Method or function name
+ * @param string $message Error message
+ * @throws MWException
+ */
+ protected static function dieDebug( $method, $message ) {
+ throw new MWException( "Internal error in $method: $message" );
+ }
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Help message generation
+ * @{
+ */
+
+ /**
+ * Generates help message for this module, or false if there is no description
+ * @return string|bool
+ */
+ public function makeHelpMsg() {
+ static $lnPrfx = "\n ";
+
+ $msg = $this->getFinalDescription();
+
+ if ( $msg !== false ) {
+
+ if ( !is_array( $msg ) ) {
+ $msg = array(
+ $msg
+ );
+ }
+ $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
+
+ $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
+
+ if ( $this->isReadMode() ) {
+ $msg .= "\nThis module requires read rights";
+ }
+ if ( $this->isWriteMode() ) {
+ $msg .= "\nThis module requires write rights";
+ }
+ if ( $this->mustBePosted() ) {
+ $msg .= "\nThis module only accepts POST requests";
+ }
+ if ( $this->isReadMode() || $this->isWriteMode() ||
+ $this->mustBePosted()
+ ) {
+ $msg .= "\n";
+ }
+
+ // Parameters
+ $paramsMsg = $this->makeHelpMsgParameters();
+ if ( $paramsMsg !== false ) {
+ $msg .= "Parameters:\n$paramsMsg";
+ }
+
+ $examples = $this->getExamples();
+ if ( $examples ) {
+ if ( !is_array( $examples ) ) {
+ $examples = array(
+ $examples
+ );
+ }
+ $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
+ foreach ( $examples as $k => $v ) {
+ if ( is_numeric( $k ) ) {
+ $msg .= " $v\n";
+ } else {
+ if ( is_array( $v ) ) {
+ $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
+ } else {
+ $msgExample = " $v";
+ }
+ $msgExample .= ":";
+ $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
+ }
+ }
+ }
+ }
+
+ return $msg;
+ }
+
+ /**
+ * @param string $item
+ * @return string
*/
- public function parseMsg( $error ) {
- $error = (array)$error; // It seems strings sometimes make their way in here
- $key = array_shift( $error );
+ private function indentExampleText( $item ) {
+ return " " . $item;
+ }
- // Check whether the error array was nested
- // array( array( <code>, <params> ), array( <another_code>, <params> ) )
- if ( is_array( $key ) ) {
- $error = $key;
- $key = array_shift( $error );
+ /**
+ * @param string $prefix Text to split output items
+ * @param string $title What is being output
+ * @param string|array $input
+ * @return string
+ */
+ protected function makeHelpArrayToString( $prefix, $title, $input ) {
+ if ( $input === false ) {
+ return '';
+ }
+ if ( !is_array( $input ) ) {
+ $input = array( $input );
}
- if ( isset( self::$messageMap[$key] ) ) {
- return array(
- 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
- 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
- );
+ if ( count( $input ) > 0 ) {
+ if ( $title ) {
+ $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
+ } else {
+ $msg = ' ';
+ }
+ $msg .= implode( $prefix, $input ) . "\n";
+
+ return $msg;
}
- // If the key isn't present, throw an "unknown error"
- return $this->parseMsg( array( 'unknownerror', $key ) );
+ return '';
}
/**
- * Internal code errors should be reported with this method
- * @param string $method Method or function name
- * @param string $message Error message
- * @throws MWException
+ * Generates the parameter descriptions for this module, to be displayed in the
+ * module's help.
+ * @return string|bool
*/
- protected static function dieDebug( $method, $message ) {
- throw new MWException( "Internal error in $method: $message" );
- }
+ public function makeHelpMsgParameters() {
+ $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
+ if ( $params ) {
- /**
- * Indicates if this module needs maxlag to be checked
- * @return bool
- */
- public function shouldCheckMaxlag() {
- return true;
- }
+ $paramsDescription = $this->getFinalParamDescription();
+ $msg = '';
+ $paramPrefix = "\n" . str_repeat( ' ', 24 );
+ $descWordwrap = "\n" . str_repeat( ' ', 28 );
+ foreach ( $params as $paramName => $paramSettings ) {
+ $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
+ if ( is_array( $desc ) ) {
+ $desc = implode( $paramPrefix, $desc );
+ }
- /**
- * Indicates whether this module requires read rights
- * @return bool
- */
- public function isReadMode() {
- return true;
- }
+ //handle shorthand
+ if ( !is_array( $paramSettings ) ) {
+ $paramSettings = array(
+ self::PARAM_DFLT => $paramSettings,
+ );
+ }
- /**
- * Indicates whether this module requires write mode
- * @return bool
- */
- public function isWriteMode() {
- return false;
- }
+ //handle missing type
+ if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
+ $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
+ ? $paramSettings[ApiBase::PARAM_DFLT]
+ : null;
+ if ( is_bool( $dflt ) ) {
+ $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
+ } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
+ $paramSettings[ApiBase::PARAM_TYPE] = 'string';
+ } elseif ( is_int( $dflt ) ) {
+ $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
+ }
+ }
- /**
- * Indicates whether this module must be called with a POST request
- * @return bool
- */
- public function mustBePosted() {
- return $this->needsToken() !== false;
- }
+ if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
+ && $paramSettings[self::PARAM_DEPRECATED]
+ ) {
+ $desc = "DEPRECATED! $desc";
+ }
- /**
- * 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 cause self::getFinalParams() to
- * return a required string 'token' parameter and
- * self::getFinalParamDescription() to ensure there is standardized
- * documentation for it. 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 needsToken() {
- return false;
- }
+ if ( isset( $paramSettings[self::PARAM_REQUIRED] )
+ && $paramSettings[self::PARAM_REQUIRED]
+ ) {
+ $desc .= $paramPrefix . "This parameter is required";
+ }
- /**
- * Validate the supplied token.
- *
- * @since 1.24
- * @param string $token Supplied token
- * @param array $params All supplied parameters for the module
- * @return bool
- */
- public final 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'
- );
- }
+ $type = isset( $paramSettings[self::PARAM_TYPE] )
+ ? $paramSettings[self::PARAM_TYPE]
+ : null;
+ if ( isset( $type ) ) {
+ $hintPipeSeparated = true;
+ $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
+ ? $paramSettings[self::PARAM_ISMULTI]
+ : false;
+ if ( $multi ) {
+ $prompt = 'Values (separate with \'|\'): ';
+ } else {
+ $prompt = 'One value: ';
+ }
+
+ if ( $type === 'submodule' ) {
+ $type = $this->getModuleManager()->getNames( $paramName );
+ sort( $type );
+ }
+ if ( is_array( $type ) ) {
+ $choices = array();
+ $nothingPrompt = '';
+ foreach ( $type as $t ) {
+ if ( $t === '' ) {
+ $nothingPrompt = 'Can be empty, or ';
+ } else {
+ $choices[] = $t;
+ }
+ }
+ $desc .= $paramPrefix . $nothingPrompt . $prompt;
+ $choicesstring = implode( ', ', $choices );
+ $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
+ $hintPipeSeparated = false;
+ } else {
+ switch ( $type ) {
+ case 'namespace':
+ // Special handling because namespaces are
+ // type-limited, yet they are not given
+ $desc .= $paramPrefix . $prompt;
+ $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
+ 100, $descWordwrap );
+ $hintPipeSeparated = false;
+ break;
+ case 'limit':
+ $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
+ if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
+ $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
+ }
+ $desc .= ' allowed';
+ break;
+ case 'integer':
+ $s = $multi ? 's' : '';
+ $hasMin = isset( $paramSettings[self::PARAM_MIN] );
+ $hasMax = isset( $paramSettings[self::PARAM_MAX] );
+ if ( $hasMin || $hasMax ) {
+ if ( !$hasMax ) {
+ $intRangeStr = "The value$s must be no less than " .
+ "{$paramSettings[self::PARAM_MIN]}";
+ } elseif ( !$hasMin ) {
+ $intRangeStr = "The value$s must be no more than " .
+ "{$paramSettings[self::PARAM_MAX]}";
+ } else {
+ $intRangeStr = "The value$s must be between " .
+ "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
+ }
+
+ $desc .= $paramPrefix . $intRangeStr;
+ }
+ break;
+ case 'upload':
+ $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
+ break;
+ }
+ }
+
+ if ( $multi ) {
+ if ( $hintPipeSeparated ) {
+ $desc .= $paramPrefix . "Separate values with '|'";
+ }
+
+ $isArray = is_array( $type );
+ if ( !$isArray
+ || $isArray && count( $type ) > self::LIMIT_SML1
+ ) {
+ $desc .= $paramPrefix . "Maximum number of values " .
+ self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
+ }
+ }
+ }
+
+ $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
+ if ( !is_null( $default ) && $default !== false ) {
+ $desc .= $paramPrefix . "Default: $default";
+ }
- if ( $this->getUser()->matchEditToken(
- $token,
- $salts[$tokenType],
- $this->getRequest()
- ) ) {
- return true;
- }
+ $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
+ }
- $webUiSalt = $this->getWebUITokenSalt( $params );
- if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
- $token,
- $webUiSalt,
- $this->getRequest()
- ) ) {
- return true;
+ return $msg;
}
return false;
}
- /**
- * 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
- */
- protected function getWebUITokenSalt( array $params ) {
- return null;
- }
+ /**@}*/
- /**
- * Gets the user for whom to get the watchlist
- *
- * @param array $params
- * @return User
+ /************************************************************************//**
+ * @name Profiling
+ * @{
*/
- public function getWatchlistUser( $params ) {
- if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
- $user = User::newFromName( $params['owner'], false );
- if ( !( $user && $user->getId() ) ) {
- $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
- }
- $token = $user->getOption( 'watchlisttoken' );
- if ( $token == '' || $token != $params['token'] ) {
- $this->dieUsage(
- 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
- 'bad_wltoken'
- );
- }
- } else {
- if ( !$this->getUser()->isLoggedIn() ) {
- $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
- }
- if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
- $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
- }
- $user = $this->getUser();
- }
-
- return $user;
- }
/**
- * @return bool|string|array Returns a false if the module has no help URL,
- * else returns a (array of) string
+ * Profiling: total module execution time
*/
- public function getHelpUrls() {
- return false;
- }
+ private $mTimeIn = 0, $mModuleTime = 0;
/**
- * This formerly attempted to return a list of all possible errors returned
- * by the module. However, this was impossible to maintain in many cases
- * since errors could come from other areas of MediaWiki and in some cases
- * from arbitrary extension hooks. Since a partial list claiming to be
- * comprehensive is unlikely to be useful, it was removed.
+ * Get the name of the module as shown in the profiler log
*
- * @deprecated since 1.24
- * @return array
- */
- public function getPossibleErrors() {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
- }
-
- /**
- * @see self::getPossibleErrors()
- * @deprecated since 1.24
- * @return array
+ * @param DatabaseBase|bool $db
+ *
+ * @return string
*/
- public function getFinalPossibleErrors() {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
- }
+ public function getModuleProfileName( $db = false ) {
+ if ( $db ) {
+ return 'API:' . $this->mModuleName . '-DB';
+ }
- /**
- * @see self::getPossibleErrors()
- * @deprecated since 1.24
- * @return array
- */
- public function parseErrors( $errors ) {
- wfDeprecated( __METHOD__, '1.24' );
- return array();
+ return 'API:' . $this->mModuleName;
}
- /**
- * Profiling: total module execution time
- */
- private $mTimeIn = 0, $mModuleTime = 0;
-
/**
* Start module profiling
*/
return $this->mDBTime;
}
- /**
- * Gets a default slave database connection object
- * @return DatabaseBase
- */
- protected function getDB() {
- if ( !isset( $this->mSlaveDB ) ) {
- $this->profileDBIn();
- $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
- $this->profileDBOut();
- }
-
- return $this->mSlaveDB;
- }
-
- /**
- * Debugging function that prints a value and an optional backtrace
- * @param mixed $value Value to print
- * @param string $name Description of the printed value
- * @param bool $backtrace If true, print a backtrace
- */
- public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
- print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
- var_export( $value );
- if ( $backtrace ) {
- print "\n" . wfBacktrace();
- }
- print "\n</pre>\n";
- }
-
/**
* Write logging information for API features to a debug log, for usage
* analysis.
' "' . addslashes( $request->getHeader( 'User-agent' ) ) . '"';
wfDebugLog( 'api-feature-usage', $s, 'private' );
}
+
+ /**@}*/
+
+ /************************************************************************//**
+ * @name Deprecated
+ * @{
+ */
+
+ /**
+ * Formerly returned a string that identifies the version of the extending
+ * class. Typically included the class name, the svn revision, timestamp,
+ * and last author. Usually done with SVN's Id keyword
+ *
+ * @deprecated since 1.21, version string is no longer supported
+ * @return string
+ */
+ public function getVersion() {
+ wfDeprecated( __METHOD__, '1.21' );
+ return '';
+ }
+
+ /**
+ * Formerly used to fetch a list of possible properites in the result,
+ * somehow organized with respect to the prop parameter that causes them to
+ * be returned. The specific semantics of the return value was never
+ * specified. Since this was never possible to be accurately updated, it
+ * has been removed.
+ *
+ * @deprecated since 1.24
+ * @return array|bool
+ */
+ protected function getResultProperties() {
+ wfDeprecated( __METHOD__, '1.24' );
+ return false;
+ }
+
+ /**
+ * @see self::getResultProperties()
+ * @deprecated since 1.24
+ * @return array|bool
+ */
+ public function getFinalResultProperties() {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**
+ * @see self::getResultProperties()
+ * @deprecated since 1.24
+ */
+ protected static function addTokenProperties( &$props, $tokenFunctions ) {
+ wfDeprecated( __METHOD__, '1.24' );
+ }
+
+ /**
+ * @see self::getPossibleErrors()
+ * @deprecated since 1.24
+ * @return array
+ */
+ public function getRequireOnlyOneParameterErrorMessages( $params ) {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**
+ * @see self::getPossibleErrors()
+ * @deprecated since 1.24
+ * @return array
+ */
+ public function getRequireMaxOneParameterErrorMessages( $params ) {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**
+ * @see self::getPossibleErrors()
+ * @deprecated since 1.24
+ * @return array
+ */
+ public function getRequireAtLeastOneParameterErrorMessages( $params ) {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**
+ * @see self::getPossibleErrors()
+ * @deprecated since 1.24
+ * @return array
+ */
+ public function getTitleOrPageIdErrorMessage() {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**
+ * This formerly attempted to return a list of all possible errors returned
+ * by the module. However, this was impossible to maintain in many cases
+ * since errors could come from other areas of MediaWiki and in some cases
+ * from arbitrary extension hooks. Since a partial list claiming to be
+ * comprehensive is unlikely to be useful, it was removed.
+ *
+ * @deprecated since 1.24
+ * @return array
+ */
+ public function getPossibleErrors() {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**
+ * @see self::getPossibleErrors()
+ * @deprecated since 1.24
+ * @return array
+ */
+ public function getFinalPossibleErrors() {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**
+ * @see self::getPossibleErrors()
+ * @deprecated since 1.24
+ * @return array
+ */
+ public function parseErrors( $errors ) {
+ wfDeprecated( __METHOD__, '1.24' );
+ return array();
+ }
+
+ /**@}*/
}
+
+/**
+ * For really cool vim folding this needs to be at the end:
+ * vim: foldmarker=@{,@} foldmethod=marker
+ */