diff options
author | Pierre Schmitz <pierre@archlinux.de> | 2011-06-22 11:28:20 +0200 |
---|---|---|
committer | Pierre Schmitz <pierre@archlinux.de> | 2011-06-22 11:28:20 +0200 |
commit | 9db190c7e736ec8d063187d4241b59feaf7dc2d1 (patch) | |
tree | 46d1a0dee7febef5c2d57a9f7b972be16a163b3d /includes/api/ApiBase.php | |
parent | 78677c7bbdcc9739f6c10c75935898a20e1acd9e (diff) |
update to MediaWiki 1.17.0
Diffstat (limited to 'includes/api/ApiBase.php')
-rw-r--r-- | includes/api/ApiBase.php | 275 |
1 files changed, 223 insertions, 52 deletions
diff --git a/includes/api/ApiBase.php b/includes/api/ApiBase.php index 708a3a40..175fa6a1 100644 --- a/includes/api/ApiBase.php +++ b/includes/api/ApiBase.php @@ -1,10 +1,9 @@ <?php - /** - * Created on Sep 5, 2006 - * * API for MediaWiki 1.8+ * + * Created on Sep 5, 2006 + * * Copyright © 2006, 2010 Yuri Astrakhan <Firstname><Lastname>@gmail.com * * This program is free software; you can redistribute it and/or modify @@ -19,8 +18,10 @@ * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html + * + * @file */ /** @@ -50,6 +51,8 @@ abstract class ApiBase { const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer' const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true const PARAM_DEPRECATED = 7; // Boolean, is the parameter deprecated (will show a warning) + const PARAM_REQUIRED = 8; // Boolean, is the parameter required? + const PARAM_RANGE_ENFORCE = 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution const LIMIT_BIG1 = 500; // Fast query, std user limit const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit @@ -179,8 +182,7 @@ abstract class ApiBase { if ( isset( $data['warnings'][$this->getModuleName()] ) ) { // Don't add duplicate warnings $warn_regex = preg_quote( $warning, '/' ); - if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) - { + if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) { return; } $oldwarning = $data['warnings'][$this->getModuleName()]['*']; @@ -224,13 +226,13 @@ abstract class ApiBase { $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n"; if ( $this->isReadMode() ) { - $msg .= "\nThis module requires read rights."; + $msg .= "\nThis module requires read rights"; } if ( $this->isWriteMode() ) { - $msg .= "\nThis module requires write rights."; + $msg .= "\nThis module requires write rights"; } if ( $this->mustBePosted() ) { - $msg .= "\nThis module only accepts POST requests."; + $msg .= "\nThis module only accepts POST requests"; } if ( $this->isReadMode() || $this->isWriteMode() || $this->mustBePosted() ) @@ -252,8 +254,11 @@ abstract class ApiBase { $examples ); } - $msg .= 'Example' . ( count( $examples ) > 1 ? 's' : '' ) . ":\n "; - $msg .= implode( $lnPrfx, $examples ) . "\n"; + + if ( count( $examples ) > 0 ) { + $msg .= 'Example' . ( count( $examples ) > 1 ? 's' : '' ) . ":\n "; + $msg .= implode( $lnPrfx, $examples ) . "\n"; + } } if ( $this->getMain()->getShowVersions() ) { @@ -295,12 +300,24 @@ abstract class ApiBase { $desc = implode( $paramPrefix, $desc ); } + if ( !is_array( $paramSettings ) ) { + $paramSettings = array( + self::PARAM_DFLT => $paramSettings, + ); + } + $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false; if ( $deprecated ) { $desc = "DEPRECATED! $desc"; } + $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? + $paramSettings[self::PARAM_REQUIRED] : false; + if ( $required ) { + $desc .= $paramPrefix . "This parameter is required"; + } + $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null; if ( isset( $type ) ) { if ( isset( $paramSettings[self::PARAM_ISMULTI] ) ) { @@ -312,21 +329,26 @@ abstract class ApiBase { if ( is_array( $type ) ) { $choices = array(); $nothingPrompt = false; - foreach ( $type as $t ) + foreach ( $type as $t ) { if ( $t === '' ) { $nothingPrompt = 'Can be empty, or '; } else { $choices[] = $t; } + } $desc .= $paramPrefix . $nothingPrompt . $prompt . implode( ', ', $choices ); } else { switch ( $type ) { case 'namespace': // Special handling because namespaces are type-limited, yet they are not given - $desc .= $paramPrefix . $prompt . implode( ', ', ApiBase::getValidNamespaces() ); + $desc .= $paramPrefix . $prompt . implode( ', ', MWNamespace::getValidNamespaces() ); break; case 'limit': - $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self::PARAM_MAX2]} for bots) allowed."; + $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': $hasMin = isset( $paramSettings[self::PARAM_MIN] ); @@ -344,10 +366,22 @@ abstract class ApiBase { } break; } + + if ( isset( $paramSettings[self::PARAM_ISMULTI] ) ) { + $isArray = is_array( $paramSettings[self::PARAM_TYPE] ); + + if ( !$isArray + || $isArray && count( $paramSettings[self::PARAM_TYPE] ) > self::LIMIT_SML1) { + $desc .= $paramPrefix . "Maximum number of values " . + self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)"; + } + } } } - $default = is_array( $paramSettings ) ? ( isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null ) : $paramSettings; + $default = is_array( $paramSettings ) + ? ( isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null ) + : $paramSettings; if ( !is_null( $default ) && $default !== false ) { $desc .= $paramPrefix . "Default: $default"; } @@ -480,7 +514,7 @@ abstract class ApiBase { if ( $params ) { // getFinalParams() can return false foreach ( $params as $paramName => $paramSettings ) { - $results[$paramName] = $this->getParameterFromSettings( + $results[$paramName] = $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit ); } } @@ -510,8 +544,8 @@ abstract class ApiBase { array_shift( $required ); $intersection = array_intersect( array_keys( array_filter( $params, - create_function( '$x', 'return !is_null($x) && $x !== false;' ) - ) ), $required ); + array( $this, "parameterNotEmpty" ) ) ), $required ); + if ( count( $intersection ) > 1 ) { $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' ); } elseif ( count( $intersection ) == 0 ) { @@ -520,24 +554,81 @@ abstract class ApiBase { } /** - * Returns an array of the namespaces (by integer id) that exist on the - * wiki. Used primarily in help documentation. - * @return array + * Callback function used in requireOnlyOneParameter to check whether reequired parameters are set + * + * @param $x object Parameter to check is not null/false + * @return bool + */ + private function parameterNotEmpty( $x ) { + return !is_null( $x ) && $x !== false; + } + + /** + * @deprecated use MWNamespace::getValidNamespaces() */ public static function getValidNamespaces() { - static $mValidNamespaces = null; - - if ( is_null( $mValidNamespaces ) ) { - global $wgContLang; - $mValidNamespaces = array(); - foreach ( array_keys( $wgContLang->getNamespaces() ) as $ns ) { - if ( $ns >= 0 ) { - $mValidNamespaces[] = $ns; + return MWNamespace::getValidNamespaces(); + } + + /** + * Return true if we're to watch the page, false if not, null if no change. + * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange' + * @param $titleObj Title the page under consideration + * @param $userOption String The user option to consider when $watchlist=preferences. + * If not set will magically default to either watchdefault or watchcreations + * @returns Boolean + */ + protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) { + + $userWatching = $titleObj->userIsWatching(); + + global $wgUser; + 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 or watchcreation + if ( is_null( $userOption ) ) { + $userOption = $titleObj->exists() + ? 'watchdefault' : 'watchcreations'; + } + # Watch the article based on the user preference + return (bool)$wgUser->getOption( $userOption ); + + case 'nochange': + return $userWatching; + + default: + return $userWatching; } + } - return $mValidNamespaces; + /** + * Set a watch (or unwatch) based the based on a watchlist parameter. + * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange' + * @param $titleObj Title the article's title to change + * @param $userOption String 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; + } + + $articleObj = new Article( $titleObj ); + if ( $value ) { + $articleObj->doWatch(); + } else { + $articleObj->doUnwatch(); + } } /** @@ -559,12 +650,14 @@ abstract class ApiBase { $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 ) ) { @@ -587,7 +680,7 @@ abstract class ApiBase { $value = $this->getMain()->getRequest()->getVal( $encParamName, $default ); if ( isset( $value ) && $type == 'namespace' ) { - $type = ApiBase::getValidNamespaces(); + $type = MWNamespace::getValidNamespaces(); } } @@ -602,19 +695,28 @@ abstract class ApiBase { switch ( $type ) { case 'NULL': // nothing to do break; - case 'string': // nothing to do + case 'string': + if ( $required && $value === '' ) { + $this->dieUsageMsg( array( 'missingparam', $paramName ) ); + } + break; case 'integer': // Force everything using intval() and optionally validate limits - - $value = is_array( $value ) ? array_map( 'intval', $value ) : intval( $value ); $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null; $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null; + $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] ) + ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false; if ( !is_null( $min ) || !is_null( $max ) ) { - $values = is_array( $value ) ? $value : array( $value ); - foreach ( $values as &$v ) { - $this->validateLimit( $paramName, $v, $min, $max ); - } + if ( is_array( $value ) ) { + $value = array_map( 'intval', $value ); + foreach ( $value as &$v ) { + $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits ); + } + } else { + $value = intval( $value ); + $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits ); + } } break; case 'limit': @@ -631,15 +733,16 @@ abstract class ApiBase { $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0; if ( $value == 'max' ) { $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX]; - $this->getResult()->addValue( 'limits', $this->getModuleName(), $value ); + $this->getResult()->setParsedLimit( $this->getModuleName(), $value ); } else { $value = intval( $value ); $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] ); } break; case 'boolean': - if ( $multi ) + if ( $multi ) { ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" ); + } break; case 'timestamp': if ( $multi ) { @@ -652,11 +755,21 @@ abstract class ApiBase { $value = wfTimestamp( TS_MW, $value ); break; case 'user': - $title = Title::makeTitleSafe( NS_USER, $value ); - if ( is_null( $title ) ) { - $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" ); + if ( !is_array( $value ) ) { + $value = array( $value ); + } + + foreach ( $value as $key => $val ) { + $title = Title::makeTitleSafe( NS_USER, $val ); + if ( is_null( $title ) ) { + $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" ); + } + $value[$key] = $title->getText(); + } + + if ( !$multi ) { + $value = $value[0]; } - $value = $title->getText(); break; default: ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" ); @@ -672,6 +785,8 @@ abstract class ApiBase { if ( $deprecated && $value !== false ) { $this->setWarning( "The $encParamName parameter has been deprecated." ); } + } else if ( $required ) { + $this->dieUsageMsg( array( 'missingparam', $paramName ) ); } return $value; @@ -736,10 +851,13 @@ abstract class ApiBase { * @param $min int Minimum value * @param $max int Maximum value for users * @param $botMax int Maximum value for sysops/bots + * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits */ - function validateLimit( $paramName, &$value, $min, $max, $botMax = null ) { + function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) { if ( !is_null( $min ) && $value < $min ) { - $this->setWarning( $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)" ); + + $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)"; + $this->warnOrDie( $msg, $enforceLimits ); $value = $min; } @@ -753,17 +871,33 @@ abstract class ApiBase { if ( !is_null( $max ) && $value > $max ) { if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) { if ( $value > $botMax ) { - $this->setWarning( $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops" ); + $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops"; + $this->warnOrDie( $msg, $enforceLimits ); $value = $botMax; } } else { - $this->setWarning( $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users" ); + $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users"; + $this->warnOrDie( $msg, $enforceLimits ); $value = $max; } } } /** + * Adds a warning to the output, else dies + * + * @param $msg String Message to show as a warning, or error message if dying + * @param $enforceLimits Boolean Whether this is an enforce (die) + */ + private function warnOrDie( $msg, $enforceLimits = false ) { + if ( $enforceLimits ) { + $this->dieUsage( $msg, 'integeroutofrange' ); + } else { + $this->setWarning( $msg ); + } + } + + /** * Truncate an array to a certain length. * @param $arr array Array to truncate * @param $limit int Maximum length @@ -772,7 +906,7 @@ abstract class ApiBase { public static function truncateArray( &$arr, $limit ) { $modified = false; while ( count( $arr ) > $limit ) { - $junk = array_pop( $arr ); + array_pop( $arr ); $modified = true; } return $modified; @@ -848,6 +982,8 @@ abstract class ApiBase { 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', 'info' => "IP address ``\$1'' was blocked as part of range ``\$2''. You can't unblock the IP invidually, but you can unblock the range as a whole." ), 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ), 'mailnologin' => array( 'code' => 'cantsend', 'info' => "You are not logged in, you do not have a confirmed e-mail address, or you are not allowed to send e-mail to other users, so you cannot send e-mail" ), + 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ), + 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ), 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ), 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ), 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ), @@ -860,6 +996,7 @@ abstract class ApiBase { 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database ``\$1'' does not exist or is not local" ), 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ), 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ), + 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ), // API-specific messages 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ), @@ -886,7 +1023,6 @@ abstract class ApiBase { 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ), 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ), 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid ``\$1''" ), - 'cantpurge' => array( 'code' => 'cantpurge', 'info' => "Only users with the 'purge' right can purge pages via the API" ), 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type ``\$1''" ), 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level ``\$1''" ), 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ), @@ -927,6 +1063,7 @@ abstract class ApiBase { 'invalid-session-key' => array( 'code' => 'invalid-session-key', 'info' => 'Not a valid session key' ), 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ), 'uploaddisabled' => array( 'code' => 'uploaddisabled', 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true' ), + 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ), ); /** @@ -1022,12 +1159,46 @@ abstract class ApiBase { } /** + * Gets the user for whom to get the watchlist + * + * @returns User + */ + public function getWatchlistUser( $params ) { + global $wgUser; + if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) { + $user = User::newFromName( $params['owner'], false ); + if ( !$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 ( !$wgUser->isLoggedIn() ) { + $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' ); + } + $user = $wgUser; + } + return $user; + } + + /** * Returns a list of all possible errors returned by the module * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... ) */ public function getPossibleErrors() { $ret = array(); + $params = $this->getFinalParams(); + if ( $params ) { + foreach ( $params as $paramName => $paramSettings ) { + if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) ) { + $ret[] = array( 'missingparam', $paramName ); + } + } + } + if ( $this->mustBePosted() ) { $ret[] = array( 'mustbeposted', $this->getModuleName() ); } @@ -1192,6 +1363,6 @@ abstract class ApiBase { * @return string */ public static function getBaseVersion() { - return __CLASS__ . ': $Id: ApiBase.php 79562 2011-01-04 06:15:54Z tstarling $'; + return __CLASS__ . ': $Id: ApiBase.php 82730 2011-02-24 16:03:05Z reedy $'; } } |