From: Brad Jorsch Date: Wed, 27 Aug 2014 19:41:05 +0000 (-0400) Subject: API: Organize classes X-Git-Tag: 1.31.0-rc.0~14256^2 X-Git-Url: http://git.cyclocoop.org/%24image?a=commitdiff_plain;h=2bb0768d3c15707f801e10d2f608db567a90b0d5;p=lhc%2Fweb%2Fwiklou.git API: Organize classes * Group methods in ApiBase by function * ApiBase::validateLimit and ApiBase::validateTimestamp are now protected; there are no callers in any extensions in Gerrit * Group methods in ApiQueryBase by function * Move ApiFormatFeedWrapper out of ApiFormatBase.php * Deprecate some methods in ApiQueryBase that seem useless and are unused in core or any extensions in Gerrit Change-Id: I32092f13906b6826d2137401724c21ccefa6f670 --- diff --git a/RELEASE-NOTES-1.24 b/RELEASE-NOTES-1.24 index ff9cf83eb5..4ae33e3e8e 100644 --- a/RELEASE-NOTES-1.24 +++ b/RELEASE-NOTES-1.24 @@ -274,6 +274,7 @@ production. APIQueryRecentChangesTokens, APIQueryUsersTokens, and ApiTokensGetTokenTypes are deprecated, but are still called to support backwards-compatible token access. +* ApiBase::validateLimit and ApiBase::validateTimestamp are now protected. * The following methods have been deprecated and may be removed in a future release: * ApiBase::getResultProperties @@ -287,6 +288,10 @@ production. * ApiBase::getFinalPossibleErrors * ApiBase::parseErrors * ApiQuery::setGeneratorContinue + * ApiQueryBase::checkRowCount + * ApiQueryBase::titleToKey + * ApiQueryBase::keyToTitle + * ApiQueryBase::keyPartToTitle * ApiQueryInfo::getTokenFunctions * ApiQueryInfo::resetTokenCache * ApiQueryInfo::getEditToken diff --git a/includes/AutoLoader.php b/includes/AutoLoader.php index 2fb4aa76d3..04802f9e97 100644 --- a/includes/AutoLoader.php +++ b/includes/AutoLoader.php @@ -228,7 +228,7 @@ $wgAutoloadLocalClasses = array( 'ApiFormatBase' => 'includes/api/ApiFormatBase.php', 'ApiFormatDbg' => 'includes/api/ApiFormatDbg.php', 'ApiFormatDump' => 'includes/api/ApiFormatDump.php', - 'ApiFormatFeedWrapper' => 'includes/api/ApiFormatBase.php', + 'ApiFormatFeedWrapper' => 'includes/api/ApiFormatFeedWrapper.php', 'ApiFormatJson' => 'includes/api/ApiFormatJson.php', 'ApiFormatNone' => 'includes/api/ApiFormatNone.php', 'ApiFormatPhp' => 'includes/api/ApiFormatPhp.php', diff --git a/includes/api/ApiBase.php b/includes/api/ApiBase.php index 35943be3fb..6914b02974 100644 --- a/includes/api/ApiBase.php +++ b/includes/api/ApiBase.php @@ -109,9 +109,11 @@ abstract class ApiBase extends ContextSource { } } - /***************************************************************************** - * ABSTRACT METHODS * - *****************************************************************************/ + + /************************************************************************//** + * @name Methods to implement + * @{ + */ /** * Evaluates the parameters, performs the requested query, and sets up @@ -132,56 +134,166 @@ abstract class ApiBase extends ContextSource { 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; } /** @@ -224,773 +336,361 @@ abstract class ApiBase extends ContextSource { } /** - * 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' ) { @@ -1227,7 +927,7 @@ abstract class ApiBase extends ContextSource { * @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)"; @@ -1265,7 +965,7 @@ abstract class ApiBase extends ContextSource { * @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( @@ -1277,6 +977,44 @@ abstract class ApiBase extends ContextSource { 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 @@ -1295,18 +1033,26 @@ abstract class ApiBase extends ContextSource { 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() ); } /** @@ -1325,6 +1071,91 @@ abstract class ApiBase extends ContextSource { 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. @@ -1950,229 +1781,335 @@ abstract class ApiBase extends ContextSource { } /** - * 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( , ), array( , ) ) + 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( , ), array( , ) ) - 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 */ @@ -2282,35 +2219,6 @@ abstract class ApiBase extends ContextSource { 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
Debugging value '$name':\n\n";
-		var_export( $value );
-		if ( $backtrace ) {
-			print "\n" . wfBacktrace();
-		}
-		print "\n
\n"; - } - /** * Write logging information for API features to a debug log, for usage * analysis. @@ -2325,4 +2233,139 @@ abstract class ApiBase extends ContextSource { ' "' . 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 + */ diff --git a/includes/api/ApiFormatBase.php b/includes/api/ApiFormatBase.php index 0e3b6123d9..9165ce8805 100644 --- a/includes/api/ApiFormatBase.php +++ b/includes/api/ApiFormatBase.php @@ -352,79 +352,3 @@ See the complete documentation, $this->setWarning( "format=$name has been deprecated. Please use format=json$fm instead." ); } } - -/** - * This printer is used to wrap an instance of the Feed class - * @ingroup API - */ -class ApiFormatFeedWrapper extends ApiFormatBase { - - public function __construct( ApiMain $main ) { - parent::__construct( $main, 'feed' ); - } - - /** - * Call this method to initialize output data. See execute() - * @param ApiResult $result - * @param object $feed An instance of one of the $wgFeedClasses classes - * @param array $feedItems Array of FeedItem objects - */ - public static function setResult( $result, $feed, $feedItems ) { - // Store output in the Result data. - // This way we can check during execution if any error has occurred - // Disable size checking for this because we can't continue - // cleanly; size checking would cause more problems than it'd - // solve - $result->addValue( null, '_feed', $feed, ApiResult::NO_SIZE_CHECK ); - $result->addValue( null, '_feeditems', $feedItems, ApiResult::NO_SIZE_CHECK ); - } - - /** - * Feed does its own headers - * - * @return null - */ - public function getMimeType() { - return null; - } - - /** - * Optimization - no need to sanitize data that will not be needed - * - * @return bool - */ - public function getNeedsRawData() { - return true; - } - - /** - * ChannelFeed doesn't give us a method to print errors in a friendly - * manner, so just punt errors to the default printer. - * @return bool - */ - public function canPrintErrors() { - return false; - } - - /** - * This class expects the result data to be in a custom format set by self::setResult() - * $result['_feed'] - an instance of one of the $wgFeedClasses classes - * $result['_feeditems'] - an array of FeedItem instances - */ - public function execute() { - $data = $this->getResultData(); - if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) { - $feed = $data['_feed']; - $items = $data['_feeditems']; - - $feed->outHeader(); - foreach ( $items as & $item ) { - $feed->outItem( $item ); - } - $feed->outFooter(); - } else { - // Error has occurred, print something useful - ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' ); - } - } -} diff --git a/includes/api/ApiFormatFeedWrapper.php b/includes/api/ApiFormatFeedWrapper.php new file mode 100644 index 0000000000..92600067f1 --- /dev/null +++ b/includes/api/ApiFormatFeedWrapper.php @@ -0,0 +1,101 @@ +@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 + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * 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., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/gpl.html + * + * @file + */ + +/** + * This printer is used to wrap an instance of the Feed class + * @ingroup API + */ +class ApiFormatFeedWrapper extends ApiFormatBase { + + public function __construct( ApiMain $main ) { + parent::__construct( $main, 'feed' ); + } + + /** + * Call this method to initialize output data. See execute() + * @param ApiResult $result + * @param object $feed An instance of one of the $wgFeedClasses classes + * @param array $feedItems Array of FeedItem objects + */ + public static function setResult( $result, $feed, $feedItems ) { + // Store output in the Result data. + // This way we can check during execution if any error has occurred + // Disable size checking for this because we can't continue + // cleanly; size checking would cause more problems than it'd + // solve + $result->addValue( null, '_feed', $feed, ApiResult::NO_SIZE_CHECK ); + $result->addValue( null, '_feeditems', $feedItems, ApiResult::NO_SIZE_CHECK ); + } + + /** + * Feed does its own headers + * + * @return null + */ + public function getMimeType() { + return null; + } + + /** + * Optimization - no need to sanitize data that will not be needed + * + * @return bool + */ + public function getNeedsRawData() { + return true; + } + + /** + * ChannelFeed doesn't give us a method to print errors in a friendly + * manner, so just punt errors to the default printer. + * @return bool + */ + public function canPrintErrors() { + return false; + } + + /** + * This class expects the result data to be in a custom format set by self::setResult() + * $result['_feed'] - an instance of one of the $wgFeedClasses classes + * $result['_feeditems'] - an array of FeedItem instances + */ + public function execute() { + $data = $this->getResultData(); + if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) { + $feed = $data['_feed']; + $items = $data['_feeditems']; + + $feed->outHeader(); + foreach ( $items as & $item ) { + $feed->outItem( $item ); + } + $feed->outFooter(); + } else { + // Error has occurred, print something useful + ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' ); + } + } +} diff --git a/includes/api/ApiQueryBase.php b/includes/api/ApiQueryBase.php index 6680316390..afb939befe 100644 --- a/includes/api/ApiQueryBase.php +++ b/includes/api/ApiQueryBase.php @@ -47,6 +47,11 @@ abstract class ApiQueryBase extends ApiBase { $this->resetQueryParams(); } + /************************************************************************//** + * @name Methods to implement + * @{ + */ + /** * Get the cache mode for the data generated by this module. Override * this in the module subclass. For possible return values and other @@ -62,6 +67,68 @@ abstract class ApiQueryBase extends ApiBase { return 'private'; } + /** + * Override this method to request extra fields from the pageSet + * using $pageSet->requestField('fieldName') + * @param ApiPageSet $pageSet + */ + public function requestExtraData( $pageSet ) { + } + + /**@}*/ + + /************************************************************************//** + * @name Data access + * @{ + */ + + /** + * Get the main Query module + * @return ApiQuery + */ + public function getQuery() { + return $this->mQueryModule; + } + + /** + * Get the Query database connection (read-only) + * @return DatabaseBase + */ + protected function getDB() { + if ( is_null( $this->mDb ) ) { + $this->mDb = $this->getQuery()->getDB(); + } + + return $this->mDb; + } + + /** + * Selects the query database connection with the given name. + * See ApiQuery::getNamedDB() for more information + * @param string $name Name to assign to the database connection + * @param int $db One of the DB_* constants + * @param array $groups Query groups + * @return DatabaseBase + */ + public function selectNamedDB( $name, $db, $groups ) { + $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups ); + } + + /** + * Get the PageSet object to work on + * @return ApiPageSet + */ + protected function getPageSet() { + return $this->getQuery()->getPageSet(); + } + + /**@}*/ + + /************************************************************************//** + * @name Querying + * @{ + */ + /** * Blank the internal arrays with query parameters */ @@ -305,29 +372,64 @@ abstract class ApiQueryBase extends ApiBase { } /** - * Estimate the row count for the SELECT query that would be run if we - * called select() right now, and check if it's acceptable. - * @return bool True if acceptable, false otherwise + * @param string $query + * @param string $protocol + * @return null|string */ - protected function checkRowCount() { - $db = $this->getDB(); - $this->profileDBIn(); - $rowcount = $db->estimateRowCount( - $this->tables, - $this->fields, - $this->where, - __METHOD__, - $this->options - ); - $this->profileDBOut(); + public function prepareUrlQuerySearchString( $query = null, $protocol = null ) { + $db = $this->getDb(); + if ( !is_null( $query ) || $query != '' ) { + if ( is_null( $protocol ) ) { + $protocol = 'http://'; + } - if ( $rowcount > $this->getConfig()->get( 'APIMaxDBRows' ) ) { - return false; + $likeQuery = LinkFilter::makeLikeArray( $query, $protocol ); + if ( !$likeQuery ) { + $this->dieUsage( 'Invalid query', 'bad_query' ); + } + + $likeQuery = LinkFilter::keepOneWildcard( $likeQuery ); + + return 'el_index ' . $db->buildLike( $likeQuery ); + } elseif ( !is_null( $protocol ) ) { + return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() ); } - return true; + return null; } + /** + * Filters hidden users (where the user doesn't have the right to view them) + * Also adds relevant block information + * + * @param bool $showBlockInfo + * @return void + */ + public function showHiddenUsersAddBlockInfo( $showBlockInfo ) { + $this->addTables( 'ipblocks' ); + $this->addJoinConds( array( + 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ), + ) ); + + $this->addFields( 'ipb_deleted' ); + + if ( $showBlockInfo ) { + $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry' ) ); + } + + // Don't show hidden names + if ( !$this->getUser()->isAllowed( 'hideuser' ) ) { + $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' ); + } + } + + /**@}*/ + + /************************************************************************//** + * @name Utility methods + * @{ + */ + /** * Add information (title and namespace) about a Title object to a * result array @@ -340,22 +442,6 @@ abstract class ApiQueryBase extends ApiBase { $arr[$prefix . 'title'] = $title->getPrefixedText(); } - /** - * Override this method to request extra fields from the pageSet - * using $pageSet->requestField('fieldName') - * @param ApiPageSet $pageSet - */ - public function requestExtraData( $pageSet ) { - } - - /** - * Get the main Query module - * @return ApiQuery - */ - public function getQuery() { - return $this->mQueryModule; - } - /** * Add a sub-element under the page element with the given page ID * @param int $pageId Page ID @@ -405,89 +491,21 @@ abstract class ApiQueryBase extends ApiBase { } /** - * Get the Query database connection (read-only) - * @return DatabaseBase - */ - protected function getDB() { - if ( is_null( $this->mDb ) ) { - $this->mDb = $this->getQuery()->getDB(); - } - - return $this->mDb; - } - - /** - * Selects the query database connection with the given name. - * See ApiQuery::getNamedDB() for more information - * @param string $name Name to assign to the database connection - * @param int $db One of the DB_* constants - * @param array $groups Query groups - * @return DatabaseBase - */ - public function selectNamedDB( $name, $db, $groups ) { - $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups ); - } - - /** - * Get the PageSet object to work on - * @return ApiPageSet - */ - protected function getPageSet() { - return $this->getQuery()->getPageSet(); - } - - /** - * Convert a title to a DB key - * @param string $title Page title with spaces - * @return string Page title with underscores - */ - public function titleToKey( $title ) { - // Don't throw an error if we got an empty string - if ( trim( $title ) == '' ) { - return ''; - } - $t = Title::newFromText( $title ); - if ( !$t ) { - $this->dieUsageMsg( array( 'invalidtitle', $title ) ); - } - - return $t->getPrefixedDBkey(); - } - - /** - * The inverse of titleToKey() - * @param string $key Page title with underscores - * @return string Page title with spaces - */ - public function keyToTitle( $key ) { - // Don't throw an error if we got an empty string - if ( trim( $key ) == '' ) { - return ''; - } - $t = Title::newFromDBkey( $key ); - // This really shouldn't happen but we gotta check anyway - if ( !$t ) { - $this->dieUsageMsg( array( 'invalidtitle', $key ) ); - } - - return $t->getPrefixedText(); - } - - /** - * An alternative to titleToKey() that doesn't trim trailing spaces, and - * does not mangle the input if starts with something that looks like a - * namespace. It is advisable to pass the namespace parameter in order to - * handle per-namespace capitalization settings. - * @param string $titlePart Title part with spaces - * @param int $defaultNamespace Namespace to assume - * @return string Title part with underscores + * Convert an input title or title prefix into a dbkey. + * + * $namespace should always be specified in order to handle per-namespace + * capitalization settings. + * + * @param string $titlePart Title part + * @param int $defaultNamespace Namespace of the title + * @return string DBkey (no namespace prefix) */ - public function titlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) { - $t = Title::makeTitleSafe( $defaultNamespace, $titlePart . 'x' ); + public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) { + $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' ); if ( !$t ) { $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) ); } - if ( $defaultNamespace != $t->getNamespace() || $t->isExternal() ) { + if ( $namespace != $t->getNamespace() || $t->isExternal() ) { // This can happen in two cases. First, if you call titlePartToKey with a title part // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very // difficult to handle such a case. Such cases cannot exist and are therefore treated @@ -499,15 +517,6 @@ abstract class ApiQueryBase extends ApiBase { return substr( $t->getDbKey(), 0, -1 ); } - /** - * An alternative to keyToTitle() that doesn't trim trailing spaces - * @param string $keyPart Key part with spaces - * @return string Key part with underscores - */ - public function keyPartToTitle( $keyPart ) { - return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 ); - } - /** * Gets the personalised direction parameter description * @@ -523,58 +532,6 @@ abstract class ApiQueryBase extends ApiBase { ); } - /** - * @param string $query - * @param string $protocol - * @return null|string - */ - public function prepareUrlQuerySearchString( $query = null, $protocol = null ) { - $db = $this->getDb(); - if ( !is_null( $query ) || $query != '' ) { - if ( is_null( $protocol ) ) { - $protocol = 'http://'; - } - - $likeQuery = LinkFilter::makeLikeArray( $query, $protocol ); - if ( !$likeQuery ) { - $this->dieUsage( 'Invalid query', 'bad_query' ); - } - - $likeQuery = LinkFilter::keepOneWildcard( $likeQuery ); - - return 'el_index ' . $db->buildLike( $likeQuery ); - } elseif ( !is_null( $protocol ) ) { - return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() ); - } - - return null; - } - - /** - * Filters hidden users (where the user doesn't have the right to view them) - * Also adds relevant block information - * - * @param bool $showBlockInfo - * @return void - */ - public function showHiddenUsersAddBlockInfo( $showBlockInfo ) { - $this->addTables( 'ipblocks' ); - $this->addJoinConds( array( - 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ), - ) ); - - $this->addFields( 'ipb_deleted' ); - - if ( $showBlockInfo ) { - $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry' ) ); - } - - // Don't show hidden names - if ( !$this->getUser()->isAllowed( 'hideuser' ) ) { - $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' ); - } - } - /** * @param string $hash * @return bool @@ -604,6 +561,94 @@ abstract class ApiQueryBase extends ApiBase { 'viewsuppressed' ); } + + /**@}*/ + + /************************************************************************//** + * @name Deprecated + * @{ + */ + + /** + * Estimate the row count for the SELECT query that would be run if we + * called select() right now, and check if it's acceptable. + * @deprecated since 1.24 + * @return bool True if acceptable, false otherwise + */ + protected function checkRowCount() { + wfDeprecated( __METHOD__, 1.24 ); + $db = $this->getDB(); + $this->profileDBIn(); + $rowcount = $db->estimateRowCount( + $this->tables, + $this->fields, + $this->where, + __METHOD__, + $this->options + ); + $this->profileDBOut(); + + if ( $rowcount > $this->getConfig()->get( 'APIMaxDBRows' ) ) { + return false; + } + + return true; + } + + /** + * Convert a title to a DB key + * @deprecated since 1.24, past uses of this were always incorrect and should + * have used self::titlePartToKey() instead + * @param string $title Page title with spaces + * @return string Page title with underscores + */ + public function titleToKey( $title ) { + wfDeprecated( __METHOD__, 1.24 ); + // Don't throw an error if we got an empty string + if ( trim( $title ) == '' ) { + return ''; + } + $t = Title::newFromText( $title ); + if ( !$t ) { + $this->dieUsageMsg( array( 'invalidtitle', $title ) ); + } + + return $t->getPrefixedDBkey(); + } + + /** + * The inverse of titleToKey() + * @deprecated since 1.24, unused and probably never needed + * @param string $key Page title with underscores + * @return string Page title with spaces + */ + public function keyToTitle( $key ) { + wfDeprecated( __METHOD__, 1.24 ); + // Don't throw an error if we got an empty string + if ( trim( $key ) == '' ) { + return ''; + } + $t = Title::newFromDBkey( $key ); + // This really shouldn't happen but we gotta check anyway + if ( !$t ) { + $this->dieUsageMsg( array( 'invalidtitle', $key ) ); + } + + return $t->getPrefixedText(); + } + + /** + * Inverse of titlePartToKey() + * @deprecated since 1.24, unused and probably never needed + * @param string $keyPart DBkey, with prefix + * @return string Key part with underscores + */ + public function keyPartToTitle( $keyPart ) { + wfDeprecated( __METHOD__, 1.24 ); + return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 ); + } + + /**@}*/ } /** @@ -641,7 +686,7 @@ abstract class ApiQueryGeneratorBase extends ApiQueryBase { } /** - * Overrides base class to prepend 'g' to every generator parameter + * Overrides ApiBase to prepend 'g' to every generator parameter * @param string $paramName Parameter name * @return string Prefixed parameter name */