MediaWiki  REL1_21
ApiBase.php
Go to the documentation of this file.
00001 <?php
00042 abstract class ApiBase extends ContextSource {
00043 
00044         // These constants allow modules to specify exactly how to treat incoming parameters.
00045 
00046         const PARAM_DFLT = 0; // Default value of the parameter
00047         const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
00048         const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
00049         const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
00050         const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
00051         const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
00052         const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
00053         const PARAM_DEPRECATED = 7; // Boolean, is the parameter deprecated (will show a warning)
00055         const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
00057         const PARAM_RANGE_ENFORCE = 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
00058 
00059         const PROP_ROOT = 'ROOT'; // Name of property group that is on the root element of the result, i.e. not part of a list
00060         const PROP_LIST = 'LIST'; // Boolean, is the result multiple items? Defaults to true for query modules, to false for other modules
00061         const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
00062         const PROP_NULLABLE = 1; // Boolean, can the property be not included in the result? Defaults to false
00063 
00064         const LIMIT_BIG1 = 500; // Fast query, std user limit
00065         const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
00066         const LIMIT_SML1 = 50; // Slow query, std user limit
00067         const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
00068 
00074         const GET_VALUES_FOR_HELP = 1;
00075 
00076         private $mMainModule, $mModuleName, $mModulePrefix;
00077         private $mSlaveDB = null;
00078         private $mParamCache = array();
00079 
00086         public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
00087                 $this->mMainModule = $mainModule;
00088                 $this->mModuleName = $moduleName;
00089                 $this->mModulePrefix = $modulePrefix;
00090 
00091                 if ( !$this->isMain() ) {
00092                         $this->setContext( $mainModule->getContext() );
00093                 }
00094         }
00095 
00096         /*****************************************************************************
00097          * ABSTRACT METHODS                                                          *
00098          *****************************************************************************/
00099 
00116         abstract public function execute();
00117 
00125         public function getVersion() {
00126                 wfDeprecated( __METHOD__, '1.21' );
00127                 return '';
00128         }
00129 
00134         public function getModuleName() {
00135                 return $this->mModuleName;
00136         }
00137 
00143         public function getModuleManager() {
00144                 return null;
00145         }
00146 
00151         public function getModulePrefix() {
00152                 return $this->mModulePrefix;
00153         }
00154 
00162         public function getModuleProfileName( $db = false ) {
00163                 if ( $db ) {
00164                         return 'API:' . $this->mModuleName . '-DB';
00165                 } else {
00166                         return 'API:' . $this->mModuleName;
00167                 }
00168         }
00169 
00174         public function getMain() {
00175                 return $this->mMainModule;
00176         }
00177 
00183         public function isMain() {
00184                 return $this === $this->mMainModule;
00185         }
00186 
00191         public function getResult() {
00192                 // Main module has getResult() method overridden
00193                 // Safety - avoid infinite loop:
00194                 if ( $this->isMain() ) {
00195                         ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
00196                 }
00197                 return $this->getMain()->getResult();
00198         }
00199 
00204         public function getResultData() {
00205                 return $this->getResult()->getData();
00206         }
00207 
00217         public function createContext() {
00218                 wfDeprecated( __METHOD__, '1.19' );
00219                 return new DerivativeContext( $this->getContext() );
00220         }
00221 
00229         public function setWarning( $warning ) {
00230                 $result = $this->getResult();
00231                 $data = $result->getData();
00232                 $moduleName = $this->getModuleName();
00233                 if ( isset( $data['warnings'][$moduleName] ) ) {
00234                         // Don't add duplicate warnings
00235                         $oldWarning = $data['warnings'][$moduleName]['*'];
00236                         $warnPos = strpos( $oldWarning, $warning );
00237                         // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
00238                         if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
00239                                 // Check if $warning is followed by "\n" or the end of the $oldWarning
00240                                 $warnPos += strlen( $warning );
00241                                 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
00242                                         return;
00243                                 }
00244                         }
00245                         // If there is a warning already, append it to the existing one
00246                         $warning = "$oldWarning\n$warning";
00247                 }
00248                 $msg = array();
00249                 ApiResult::setContent( $msg, $warning );
00250                 $result->disableSizeCheck();
00251                 $result->addValue( 'warnings', $moduleName,
00252                         $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP );
00253                 $result->enableSizeCheck();
00254         }
00255 
00262         public function getCustomPrinter() {
00263                 return null;
00264         }
00265 
00270         public function makeHelpMsg() {
00271                 static $lnPrfx = "\n  ";
00272 
00273                 $msg = $this->getFinalDescription();
00274 
00275                 if ( $msg !== false ) {
00276 
00277                         if ( !is_array( $msg ) ) {
00278                                 $msg = array(
00279                                         $msg
00280                                 );
00281                         }
00282                         $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
00283 
00284                         $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
00285 
00286                         if ( $this->isReadMode() ) {
00287                                 $msg .= "\nThis module requires read rights";
00288                         }
00289                         if ( $this->isWriteMode() ) {
00290                                 $msg .= "\nThis module requires write rights";
00291                         }
00292                         if ( $this->mustBePosted() ) {
00293                                 $msg .= "\nThis module only accepts POST requests";
00294                         }
00295                         if ( $this->isReadMode() || $this->isWriteMode() ||
00296                                         $this->mustBePosted() ) {
00297                                 $msg .= "\n";
00298                         }
00299 
00300                         // Parameters
00301                         $paramsMsg = $this->makeHelpMsgParameters();
00302                         if ( $paramsMsg !== false ) {
00303                                 $msg .= "Parameters:\n$paramsMsg";
00304                         }
00305 
00306                         $examples = $this->getExamples();
00307                         if ( $examples !== false && $examples !== '' ) {
00308                                 if ( !is_array( $examples ) ) {
00309                                         $examples = array(
00310                                                 $examples
00311                                         );
00312                                 }
00313                                 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
00314                                 foreach( $examples as $k => $v ) {
00315 
00316                                         if ( is_numeric( $k ) ) {
00317                                                 $msg .= "  $v\n";
00318                                         } else {
00319                                                 if ( is_array( $v ) ) {
00320                                                         $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
00321                                                 } else {
00322                                                         $msgExample = "  $v";
00323                                                 }
00324                                                 $msgExample .= ":";
00325                                                 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n    $k\n";
00326                                         }
00327                                 }
00328                         }
00329                 }
00330 
00331                 return $msg;
00332         }
00333 
00338         private function indentExampleText( $item ) {
00339                 return "  " . $item;
00340         }
00341 
00348         protected function makeHelpArrayToString( $prefix, $title, $input ) {
00349                 if ( $input === false ) {
00350                         return '';
00351                 }
00352                 if ( !is_array( $input ) ) {
00353                         $input = array( $input );
00354                 }
00355 
00356                 if ( count( $input ) > 0 ) {
00357                         if ( $title ) {
00358                                 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n  ";
00359                         } else {
00360                                 $msg = '  ';
00361                         }
00362                         $msg .= implode( $prefix, $input ) . "\n";
00363                         return $msg;
00364                 }
00365                 return '';
00366         }
00367 
00373         public function makeHelpMsgParameters() {
00374                 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
00375                 if ( $params ) {
00376 
00377                         $paramsDescription = $this->getFinalParamDescription();
00378                         $msg = '';
00379                         $paramPrefix = "\n" . str_repeat( ' ', 24 );
00380                         $descWordwrap = "\n" . str_repeat( ' ', 28 );
00381                         foreach ( $params as $paramName => $paramSettings ) {
00382                                 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
00383                                 if ( is_array( $desc ) ) {
00384                                         $desc = implode( $paramPrefix, $desc );
00385                                 }
00386 
00387                                 //handle shorthand
00388                                 if ( !is_array( $paramSettings ) ) {
00389                                         $paramSettings = array(
00390                                                 self::PARAM_DFLT => $paramSettings,
00391                                         );
00392                                 }
00393 
00394                                 //handle missing type
00395                                 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
00396                                         $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] ) ? $paramSettings[ApiBase::PARAM_DFLT] : null;
00397                                         if ( is_bool( $dflt ) ) {
00398                                                 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
00399                                         } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
00400                                                 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
00401                                         } elseif ( is_int( $dflt ) ) {
00402                                                 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
00403                                         }
00404                                 }
00405 
00406                                 if ( isset( $paramSettings[self::PARAM_DEPRECATED] ) && $paramSettings[self::PARAM_DEPRECATED] ) {
00407                                         $desc = "DEPRECATED! $desc";
00408                                 }
00409 
00410                                 if ( isset( $paramSettings[self::PARAM_REQUIRED] ) && $paramSettings[self::PARAM_REQUIRED] ) {
00411                                         $desc .= $paramPrefix . "This parameter is required";
00412                                 }
00413 
00414                                 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
00415                                 if ( isset( $type ) ) {
00416                                         $hintPipeSeparated = true;
00417                                         $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
00418                                         if ( $multi ) {
00419                                                 $prompt = 'Values (separate with \'|\'): ';
00420                                         } else {
00421                                                 $prompt = 'One value: ';
00422                                         }
00423 
00424                                         if ( is_array( $type ) ) {
00425                                                 $choices = array();
00426                                                 $nothingPrompt = '';
00427                                                 foreach ( $type as $t ) {
00428                                                         if ( $t === '' ) {
00429                                                                 $nothingPrompt = 'Can be empty, or ';
00430                                                         } else {
00431                                                                 $choices[] = $t;
00432                                                         }
00433                                                 }
00434                                                 $desc .= $paramPrefix . $nothingPrompt . $prompt;
00435                                                 $choicesstring = implode( ', ', $choices );
00436                                                 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
00437                                                 $hintPipeSeparated = false;
00438                                         } else {
00439                                                 switch ( $type ) {
00440                                                         case 'namespace':
00441                                                                 // Special handling because namespaces are type-limited, yet they are not given
00442                                                                 $desc .= $paramPrefix . $prompt;
00443                                                                 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
00444                                                                         100, $descWordwrap );
00445                                                                 $hintPipeSeparated = false;
00446                                                                 break;
00447                                                         case 'limit':
00448                                                                 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
00449                                                                 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
00450                                                                         $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
00451                                                                 }
00452                                                                 $desc .= ' allowed';
00453                                                                 break;
00454                                                         case 'integer':
00455                                                                 $s = $multi ? 's' : '';
00456                                                                 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
00457                                                                 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
00458                                                                 if ( $hasMin || $hasMax ) {
00459                                                                         if ( !$hasMax ) {
00460                                                                                 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
00461                                                                         } elseif ( !$hasMin ) {
00462                                                                                 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
00463                                                                         } else {
00464                                                                                 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
00465                                                                         }
00466 
00467                                                                         $desc .= $paramPrefix . $intRangeStr;
00468                                                                 }
00469                                                                 break;
00470                                                         case 'upload':
00471                                                                 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
00472                                                                 break;
00473                                                 }
00474                                         }
00475 
00476                                         if ( $multi ) {
00477                                                 if ( $hintPipeSeparated ) {
00478                                                         $desc .= $paramPrefix . "Separate values with '|'";
00479                                                 }
00480 
00481                                                 $isArray = is_array( $type );
00482                                                 if ( !$isArray
00483                                                                 || $isArray && count( $type ) > self::LIMIT_SML1 ) {
00484                                                         $desc .= $paramPrefix . "Maximum number of values " .
00485                                                                         self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
00486                                                 }
00487                                         }
00488                                 }
00489 
00490                                 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
00491                                 if ( !is_null( $default ) && $default !== false ) {
00492                                         $desc .= $paramPrefix . "Default: $default";
00493                                 }
00494 
00495                                 $msg .= sprintf( "  %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
00496                         }
00497                         return $msg;
00498 
00499                 } else {
00500                         return false;
00501                 }
00502         }
00503 
00508         protected function getDescription() {
00509                 return false;
00510         }
00511 
00516         protected function getExamples() {
00517                 return false;
00518         }
00519 
00532         protected function getAllowedParams( /* $flags = 0 */ ) {
00533                 // int $flags is not declared because it causes "Strict standards"
00534                 // warning. Most derived classes do not implement it.
00535                 return false;
00536         }
00537 
00544         protected function getParamDescription() {
00545                 return false;
00546         }
00547 
00556         public function getFinalParams( $flags = 0 ) {
00557                 $params = $this->getAllowedParams( $flags );
00558                 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
00559                 return $params;
00560         }
00561 
00568         public function getFinalParamDescription() {
00569                 $desc = $this->getParamDescription();
00570                 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
00571                 return $desc;
00572         }
00573 
00590         protected function getResultProperties() {
00591                 return false;
00592         }
00593 
00600         public function getFinalResultProperties() {
00601                 $properties = $this->getResultProperties();
00602                 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
00603                 return $properties;
00604         }
00605 
00610         protected static function addTokenProperties( &$props, $tokenFunctions ) {
00611                 foreach ( array_keys( $tokenFunctions ) as $token ) {
00612                         $props[''][$token . 'token'] = array(
00613                                 ApiBase::PROP_TYPE => 'string',
00614                                 ApiBase::PROP_NULLABLE => true
00615                         );
00616                 }
00617         }
00618 
00625         public function getFinalDescription() {
00626                 $desc = $this->getDescription();
00627                 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
00628                 return $desc;
00629         }
00630 
00637         public function encodeParamName( $paramName ) {
00638                 return $this->mModulePrefix . $paramName;
00639         }
00640 
00650         public function extractRequestParams( $parseLimit = true ) {
00651                 // Cache parameters, for performance and to avoid bug 24564.
00652                 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
00653                         $params = $this->getFinalParams();
00654                         $results = array();
00655 
00656                         if ( $params ) { // getFinalParams() can return false
00657                                 foreach ( $params as $paramName => $paramSettings ) {
00658                                         $results[$paramName] = $this->getParameterFromSettings(
00659                                                 $paramName, $paramSettings, $parseLimit );
00660                                 }
00661                         }
00662                         $this->mParamCache[$parseLimit] = $results;
00663                 }
00664                 return $this->mParamCache[$parseLimit];
00665         }
00666 
00673         protected function getParameter( $paramName, $parseLimit = true ) {
00674                 $params = $this->getFinalParams();
00675                 $paramSettings = $params[$paramName];
00676                 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
00677         }
00678 
00683         public function requireOnlyOneParameter( $params ) {
00684                 $required = func_get_args();
00685                 array_shift( $required );
00686                 $p = $this->getModulePrefix();
00687 
00688                 $intersection = array_intersect( array_keys( array_filter( $params,
00689                         array( $this, "parameterNotEmpty" ) ) ), $required );
00690 
00691                 if ( count( $intersection ) > 1 ) {
00692                         $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
00693                 } elseif ( count( $intersection ) == 0 ) {
00694                         $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
00695                 }
00696         }
00697 
00704         public function getRequireOnlyOneParameterErrorMessages( $params ) {
00705                 $p = $this->getModulePrefix();
00706                 $params = implode( ", {$p}", $params );
00707 
00708                 return array(
00709                         array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
00710                         array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
00711                 );
00712         }
00713 
00719         public function requireMaxOneParameter( $params ) {
00720                 $required = func_get_args();
00721                 array_shift( $required );
00722                 $p = $this->getModulePrefix();
00723 
00724                 $intersection = array_intersect( array_keys( array_filter( $params,
00725                         array( $this, "parameterNotEmpty" ) ) ), $required );
00726 
00727                 if ( count( $intersection ) > 1 ) {
00728                         $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
00729                 }
00730         }
00731 
00738         public function getRequireMaxOneParameterErrorMessages( $params ) {
00739                 $p = $this->getModulePrefix();
00740                 $params = implode( ", {$p}", $params );
00741 
00742                 return array(
00743                         array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
00744                 );
00745         }
00746 
00755         public function getTitleOrPageId( $params, $load = false ) {
00756                 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
00757 
00758                 $pageObj = null;
00759                 if ( isset( $params['title'] ) ) {
00760                         $titleObj = Title::newFromText( $params['title'] );
00761                         if ( !$titleObj || $titleObj->isExternal() ) {
00762                                 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
00763                         }
00764                         if ( !$titleObj->canExist() ) {
00765                                 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
00766                         }
00767                         $pageObj = WikiPage::factory( $titleObj );
00768                         if ( $load !== false ) {
00769                                 $pageObj->loadPageData( $load );
00770                         }
00771                 } elseif ( isset( $params['pageid'] ) ) {
00772                         if ( $load === false ) {
00773                                 $load = 'fromdb';
00774                         }
00775                         $pageObj = WikiPage::newFromID( $params['pageid'], $load );
00776                         if ( !$pageObj ) {
00777                                 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
00778                         }
00779                 }
00780 
00781                 return $pageObj;
00782         }
00783 
00787         public function getTitleOrPageIdErrorMessage() {
00788                 return array_merge(
00789                         $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
00790                         array(
00791                                 array( 'invalidtitle', 'title' ),
00792                                 array( 'nosuchpageid', 'pageid' ),
00793                         )
00794                 );
00795         }
00796 
00803         private function parameterNotEmpty( $x ) {
00804                 return !is_null( $x ) && $x !== false;
00805         }
00806 
00812         public static function getValidNamespaces() {
00813                 wfDeprecated( __METHOD__, '1.17' );
00814                 return MWNamespace::getValidNamespaces();
00815         }
00816 
00825         protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
00826 
00827                 $userWatching = $this->getUser()->isWatched( $titleObj );
00828 
00829                 switch ( $watchlist ) {
00830                         case 'watch':
00831                                 return true;
00832 
00833                         case 'unwatch':
00834                                 return false;
00835 
00836                         case 'preferences':
00837                                 # If the user is already watching, don't bother checking
00838                                 if ( $userWatching ) {
00839                                         return true;
00840                                 }
00841                                 # If no user option was passed, use watchdefault or watchcreations
00842                                 if ( is_null( $userOption ) ) {
00843                                         $userOption = $titleObj->exists()
00844                                                         ? 'watchdefault' : 'watchcreations';
00845                                 }
00846                                 # Watch the article based on the user preference
00847                                 return $this->getUser()->getBoolOption( $userOption );
00848 
00849                         case 'nochange':
00850                                 return $userWatching;
00851 
00852                         default:
00853                                 return $userWatching;
00854                 }
00855         }
00856 
00863         protected function setWatch( $watch, $titleObj, $userOption = null ) {
00864                 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
00865                 if ( $value === null ) {
00866                         return;
00867                 }
00868 
00869                 $user = $this->getUser();
00870                 if ( $value ) {
00871                         WatchAction::doWatch( $titleObj, $user );
00872                 } else {
00873                         WatchAction::doUnwatch( $titleObj, $user );
00874                 }
00875         }
00876 
00886         protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
00887                 // Some classes may decide to change parameter names
00888                 $encParamName = $this->encodeParamName( $paramName );
00889 
00890                 if ( !is_array( $paramSettings ) ) {
00891                         $default = $paramSettings;
00892                         $multi = false;
00893                         $type = gettype( $paramSettings );
00894                         $dupes = false;
00895                         $deprecated = false;
00896                         $required = false;
00897                 } else {
00898                         $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
00899                         $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
00900                         $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
00901                         $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false;
00902                         $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false;
00903                         $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? $paramSettings[self::PARAM_REQUIRED] : false;
00904 
00905                         // When type is not given, and no choices, the type is the same as $default
00906                         if ( !isset( $type ) ) {
00907                                 if ( isset( $default ) ) {
00908                                         $type = gettype( $default );
00909                                 } else {
00910                                         $type = 'NULL'; // allow everything
00911                                 }
00912                         }
00913                 }
00914 
00915                 if ( $type == 'boolean' ) {
00916                         if ( isset( $default ) && $default !== false ) {
00917                                 // Having a default value of anything other than 'false' is not allowed
00918                                 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
00919                         }
00920 
00921                         $value = $this->getMain()->getCheck( $encParamName );
00922                 } elseif ( $type == 'upload' ) {
00923                         if ( isset( $default ) ) {
00924                                 // Having a default value is not allowed
00925                                 ApiBase::dieDebug( __METHOD__, "File upload param $encParamName's default is set to '$default'. File upload parameters may not have a default." );
00926                         }
00927                         if ( $multi ) {
00928                                 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
00929                         }
00930                         $value = $this->getMain()->getUpload( $encParamName );
00931                         if ( !$value->exists() ) {
00932                                 // This will get the value without trying to normalize it
00933                                 // (because trying to normalize a large binary file
00934                                 // accidentally uploaded as a field fails spectacularly)
00935                                 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
00936                                 if ( $value !== null ) {
00937                                         $this->dieUsage(
00938                                                 "File upload param $encParamName is not a file upload; " .
00939                                                 "be sure to use multipart/form-data for your POST and include " .
00940                                                 "a filename in the Content-Disposition header.",
00941                                                 "badupload_{$encParamName}"
00942                                         );
00943                                 }
00944                         }
00945                 } else {
00946                         $value = $this->getMain()->getVal( $encParamName, $default );
00947 
00948                         if ( isset( $value ) && $type == 'namespace' ) {
00949                                 $type = MWNamespace::getValidNamespaces();
00950                         }
00951                 }
00952 
00953                 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
00954                         $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null );
00955                 }
00956 
00957                 // More validation only when choices were not given
00958                 // choices were validated in parseMultiValue()
00959                 if ( isset( $value ) ) {
00960                         if ( !is_array( $type ) ) {
00961                                 switch ( $type ) {
00962                                         case 'NULL': // nothing to do
00963                                                 break;
00964                                         case 'string':
00965                                                 if ( $required && $value === '' ) {
00966                                                         $this->dieUsageMsg( array( 'missingparam', $paramName ) );
00967                                                 }
00968                                                 break;
00969                                         case 'integer': // Force everything using intval() and optionally validate limits
00970                                                 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
00971                                                 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
00972                                                 $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] )
00973                                                                 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
00974 
00975                                                 if ( is_array( $value ) ) {
00976                                                         $value = array_map( 'intval', $value );
00977                                                         if ( !is_null( $min ) || !is_null( $max ) ) {
00978                                                                 foreach ( $value as &$v ) {
00979                                                                         $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
00980                                                                 }
00981                                                         }
00982                                                 } else {
00983                                                         $value = intval( $value );
00984                                                         if ( !is_null( $min ) || !is_null( $max ) ) {
00985                                                                 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
00986                                                         }
00987                                                 }
00988                                                 break;
00989                                         case 'limit':
00990                                                 if ( !$parseLimit ) {
00991                                                         // Don't do any validation whatsoever
00992                                                         break;
00993                                                 }
00994                                                 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
00995                                                         ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
00996                                                 }
00997                                                 if ( $multi ) {
00998                                                         ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
00999                                                 }
01000                                                 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
01001                                                 if ( $value == 'max' ) {
01002                                                         $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
01003                                                         $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
01004                                                 } else {
01005                                                         $value = intval( $value );
01006                                                         $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
01007                                                 }
01008                                                 break;
01009                                         case 'boolean':
01010                                                 if ( $multi ) {
01011                                                         ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
01012                                                 }
01013                                                 break;
01014                                         case 'timestamp':
01015                                                 if ( is_array( $value ) ) {
01016                                                         foreach ( $value as $key => $val ) {
01017                                                                 $value[$key] = $this->validateTimestamp( $val, $encParamName );
01018                                                         }
01019                                                 } else {
01020                                                         $value = $this->validateTimestamp( $value, $encParamName );
01021                                                 }
01022                                                 break;
01023                                         case 'user':
01024                                                 if ( is_array( $value ) ) {
01025                                                         foreach ( $value as $key => $val ) {
01026                                                                 $value[$key] = $this->validateUser( $val, $encParamName );
01027                                                         }
01028                                                 } else {
01029                                                         $value = $this->validateUser( $value, $encParamName );
01030                                                 }
01031                                                 break;
01032                                         case 'upload': // nothing to do
01033                                                 break;
01034                                         default:
01035                                                 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
01036                                 }
01037                         }
01038 
01039                         // Throw out duplicates if requested
01040                         if ( !$dupes && is_array( $value ) ) {
01041                                 $value = array_unique( $value );
01042                         }
01043 
01044                         // Set a warning if a deprecated parameter has been passed
01045                         if ( $deprecated && $value !== false ) {
01046                                 $this->setWarning( "The $encParamName parameter has been deprecated." );
01047                         }
01048                 } elseif ( $required ) {
01049                         $this->dieUsageMsg( array( 'missingparam', $paramName ) );
01050                 }
01051 
01052                 return $value;
01053         }
01054 
01068         protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
01069                 if ( trim( $value ) === '' && $allowMultiple ) {
01070                         return array();
01071                 }
01072 
01073                 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
01074                 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
01075                 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
01076                                 self::LIMIT_SML2 : self::LIMIT_SML1;
01077 
01078                 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
01079                         $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
01080                 }
01081 
01082                 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
01083                         // Bug 33482 - Allow entries with | in them for non-multiple values
01084                         if ( in_array( $value, $allowedValues ) ) {
01085                                 return $value;
01086                         }
01087 
01088                         $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
01089                         $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
01090                 }
01091 
01092                 if ( is_array( $allowedValues ) ) {
01093                         // Check for unknown values
01094                         $unknown = array_diff( $valuesList, $allowedValues );
01095                         if ( count( $unknown ) ) {
01096                                 if ( $allowMultiple ) {
01097                                         $s = count( $unknown ) > 1 ? 's' : '';
01098                                         $vals = implode( ", ", $unknown );
01099                                         $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
01100                                 } else {
01101                                         $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
01102                                 }
01103                         }
01104                         // Now throw them out
01105                         $valuesList = array_intersect( $valuesList, $allowedValues );
01106                 }
01107 
01108                 return $allowMultiple ? $valuesList : $valuesList[0];
01109         }
01110 
01121         function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
01122                 if ( !is_null( $min ) && $value < $min ) {
01123 
01124                         $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
01125                         $this->warnOrDie( $msg, $enforceLimits );
01126                         $value = $min;
01127                 }
01128 
01129                 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
01130                 if ( $this->getMain()->isInternalMode() ) {
01131                         return;
01132                 }
01133 
01134                 // Optimization: do not check user's bot status unless really needed -- skips db query
01135                 // assumes $botMax >= $max
01136                 if ( !is_null( $max ) && $value > $max ) {
01137                         if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
01138                                 if ( $value > $botMax ) {
01139                                         $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
01140                                         $this->warnOrDie( $msg, $enforceLimits );
01141                                         $value = $botMax;
01142                                 }
01143                         } else {
01144                                 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
01145                                 $this->warnOrDie( $msg, $enforceLimits );
01146                                 $value = $max;
01147                         }
01148                 }
01149         }
01150 
01157         function validateTimestamp( $value, $encParamName ) {
01158                 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
01159                 if ( $unixTimestamp === false ) {
01160                         $this->dieUsage( "Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}" );
01161                 }
01162                 return wfTimestamp( TS_MW, $unixTimestamp );
01163         }
01164 
01171         private function validateUser( $value, $encParamName ) {
01172                 $title = Title::makeTitleSafe( NS_USER, $value );
01173                 if ( $title === null ) {
01174                         $this->dieUsage( "Invalid value '$value' for user parameter $encParamName", "baduser_{$encParamName}" );
01175                 }
01176                 return $title->getText();
01177         }
01178 
01185         private function warnOrDie( $msg, $enforceLimits = false ) {
01186                 if ( $enforceLimits ) {
01187                         $this->dieUsage( $msg, 'integeroutofrange' );
01188                 } else {
01189                         $this->setWarning( $msg );
01190                 }
01191         }
01192 
01199         public static function truncateArray( &$arr, $limit ) {
01200                 $modified = false;
01201                 while ( count( $arr ) > $limit ) {
01202                         array_pop( $arr );
01203                         $modified = true;
01204                 }
01205                 return $modified;
01206         }
01207 
01220         public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
01221                 Profiler::instance()->close();
01222                 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
01223         }
01224 
01228         public static $messageMap = array(
01229                 // This one MUST be present, or dieUsageMsg() will recurse infinitely
01230                 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
01231                 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
01232 
01233                 // Messages from Title::getUserPermissionsErrors()
01234                 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
01235                 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
01236                 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
01237                 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
01238                 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
01239                 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
01240                 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
01241                 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
01242                 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
01243                 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
01244                 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
01245                 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
01246                 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
01247                 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
01248                 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
01249                 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your email address before you can edit" ),
01250                 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
01251                 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
01252 
01253                 // Miscellaneous interface messages
01254                 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
01255                 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
01256                 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
01257                 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
01258                 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
01259                 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
01260                 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
01261                 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
01262                 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
01263                 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
01264                 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
01265                 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
01266                 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
01267                 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
01268                 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
01269                 // 'badarticleerror' => shouldn't happen
01270                 // 'badtitletext' => shouldn't happen
01271                 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
01272                 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
01273                 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
01274                 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
01275                 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
01276                 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
01277                 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole." ),
01278                 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
01279                 'mailnologin' => array( 'code' => 'cantsend', 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email" ),
01280                 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
01281                 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
01282                 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
01283                 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending email" ),
01284                 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
01285                 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users" ),
01286                 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
01287                 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
01288                 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
01289                 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
01290                 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
01291                 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
01292                 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01293                 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01294                 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
01295                 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
01296                 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
01297 
01298                 // API-specific messages
01299                 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
01300                 'writedisabled' => array( 'code' => 'noapiwrite', 'info' => "Editing of this wiki through the API is disabled. Make sure the \$wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file" ),
01301                 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
01302                 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
01303                 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
01304                 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
01305                 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
01306                 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
01307                 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01308                 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
01309                 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
01310                 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
01311                 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
01312                 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
01313                 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
01314                 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending email through the wiki" ),
01315                 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
01316                 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
01317                 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
01318                 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
01319                 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
01320                 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
01321                 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
01322                 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
01323                 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
01324                 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
01325                 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
01326                 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
01327                 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
01328                 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
01329                 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
01330                 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
01331                 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
01332                 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
01333                 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
01334                 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
01335                 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
01336                 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
01337                 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
01338                 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
01339                 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
01340                 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
01341                 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
01342                 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
01343                 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
01344                 'fileexists-shared-forbidden' => array( 'code' => 'fileexists-shared-forbidden', 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.' ),
01345                 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
01346 
01347                 // ApiEditPage messages
01348                 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
01349                 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
01350                 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
01351                 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
01352                 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
01353                 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
01354                 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
01355                 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
01356                 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
01357                 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
01358                 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
01359                 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
01360                 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
01361                 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
01362 
01363                 // Messages from WikiPage::doEit()
01364                 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
01365                 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
01366                 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
01367                 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
01368 
01369                 // uploadMsgs
01370                 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
01371                 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
01372                 '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' ),
01373                 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
01374                 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
01375 
01376                 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
01377                 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
01378                 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
01379                 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
01380 
01381                 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
01382         );
01383 
01387         public function dieReadOnly() {
01388                 $parsed = $this->parseMsg( array( 'readonlytext' ) );
01389                 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
01390                         array( 'readonlyreason' => wfReadOnlyReason() ) );
01391         }
01392 
01397         public function dieUsageMsg( $error ) {
01398                 # most of the time we send a 1 element, so we might as well send it as
01399                 # a string and make this an array here.
01400                 if( is_string( $error ) ) {
01401                         $error = array( $error );
01402                 }
01403                 $parsed = $this->parseMsg( $error );
01404                 $this->dieUsage( $parsed['info'], $parsed['code'] );
01405         }
01406 
01413         public function dieUsageMsgOrDebug( $error ) {
01414                 global $wgDebugAPI;
01415                 if( $wgDebugAPI !== true ) {
01416                         $this->dieUsageMsg( $error );
01417                 } else {
01418                         if( is_string( $error ) ) {
01419                                 $error = array( $error );
01420                         }
01421                         $parsed = $this->parseMsg( $error );
01422                         $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
01423                                 . ' - ' . $parsed['info'] );
01424                 }
01425         }
01426 
01432         protected function dieContinueUsageIf( $condition ) {
01433                 if ( $condition ) {
01434                         $this->dieUsage(
01435                                 'Invalid continue param. You should pass the original value returned by the previous query',
01436                                 'badcontinue' );
01437                 }
01438         }
01439 
01445         public function parseMsg( $error ) {
01446                 $error = (array)$error; // It seems strings sometimes make their way in here
01447                 $key = array_shift( $error );
01448 
01449                 // Check whether the error array was nested
01450                 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
01451                 if( is_array( $key ) ) {
01452                         $error = $key;
01453                         $key = array_shift( $error );
01454                 }
01455 
01456                 if ( isset( self::$messageMap[$key] ) ) {
01457                         return array(
01458                                 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
01459                                 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
01460                         );
01461                 }
01462 
01463                 // If the key isn't present, throw an "unknown error"
01464                 return $this->parseMsg( array( 'unknownerror', $key ) );
01465         }
01466 
01472         protected static function dieDebug( $method, $message ) {
01473                 wfDebugDieBacktrace( "Internal error in $method: $message" );
01474         }
01475 
01480         public function shouldCheckMaxlag() {
01481                 return true;
01482         }
01483 
01488         public function isReadMode() {
01489                 return true;
01490         }
01495         public function isWriteMode() {
01496                 return false;
01497         }
01498 
01503         public function mustBePosted() {
01504                 return false;
01505         }
01506 
01513         public function needsToken() {
01514                 return false;
01515         }
01516 
01525         public function getTokenSalt() {
01526                 return false;
01527         }
01528 
01535         public function getWatchlistUser( $params ) {
01536                 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
01537                         $user = User::newFromName( $params['owner'], false );
01538                         if ( !($user && $user->getId()) ) {
01539                                 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
01540                         }
01541                         $token = $user->getOption( 'watchlisttoken' );
01542                         if ( $token == '' || $token != $params['token'] ) {
01543                                 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
01544                         }
01545                 } else {
01546                         if ( !$this->getUser()->isLoggedIn() ) {
01547                                 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
01548                         }
01549                         $user = $this->getUser();
01550                 }
01551                 return $user;
01552         }
01553 
01557         public function getHelpUrls() {
01558                 return false;
01559         }
01560 
01565         public function getPossibleErrors() {
01566                 $ret = array();
01567 
01568                 $params = $this->getFinalParams();
01569                 if ( $params ) {
01570                         foreach ( $params as $paramName => $paramSettings ) {
01571                                 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) && $paramSettings[ApiBase::PARAM_REQUIRED] ) {
01572                                         $ret[] = array( 'missingparam', $paramName );
01573                                 }
01574                         }
01575                         if ( array_key_exists( 'continue', $params ) ) {
01576                                 $ret[] = array(
01577                                         array(
01578                                                 'code' => 'badcontinue',
01579                                                 'info' => 'Invalid continue param. You should pass the original value returned by the previous query'
01580                                         ) );
01581                         }
01582                 }
01583 
01584                 if ( $this->mustBePosted() ) {
01585                         $ret[] = array( 'mustbeposted', $this->getModuleName() );
01586                 }
01587 
01588                 if ( $this->isReadMode() ) {
01589                         $ret[] = array( 'readrequired' );
01590                 }
01591 
01592                 if ( $this->isWriteMode() ) {
01593                         $ret[] = array( 'writerequired' );
01594                         $ret[] = array( 'writedisabled' );
01595                 }
01596 
01597                 if ( $this->needsToken() ) {
01598                         $ret[] = array( 'missingparam', 'token' );
01599                         $ret[] = array( 'sessionfailure' );
01600                 }
01601 
01602                 return $ret;
01603         }
01604 
01610         public function parseErrors( $errors ) {
01611                 $ret = array();
01612 
01613                 foreach ( $errors as $row ) {
01614                         if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
01615                                 $ret[] = $row;
01616                         } else {
01617                                 $ret[] = $this->parseMsg( $row );
01618                         }
01619                 }
01620                 return $ret;
01621         }
01622 
01626         private $mTimeIn = 0, $mModuleTime = 0;
01627 
01631         public function profileIn() {
01632                 if ( $this->mTimeIn !== 0 ) {
01633                         ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
01634                 }
01635                 $this->mTimeIn = microtime( true );
01636                 wfProfileIn( $this->getModuleProfileName() );
01637         }
01638 
01642         public function profileOut() {
01643                 if ( $this->mTimeIn === 0 ) {
01644                         ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
01645                 }
01646                 if ( $this->mDBTimeIn !== 0 ) {
01647                         ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
01648                 }
01649 
01650                 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
01651                 $this->mTimeIn = 0;
01652                 wfProfileOut( $this->getModuleProfileName() );
01653         }
01654 
01659         public function safeProfileOut() {
01660                 if ( $this->mTimeIn !== 0 ) {
01661                         if ( $this->mDBTimeIn !== 0 ) {
01662                                 $this->profileDBOut();
01663                         }
01664                         $this->profileOut();
01665                 }
01666         }
01667 
01672         public function getProfileTime() {
01673                 if ( $this->mTimeIn !== 0 ) {
01674                         ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
01675                 }
01676                 return $this->mModuleTime;
01677         }
01678 
01682         private $mDBTimeIn = 0, $mDBTime = 0;
01683 
01687         public function profileDBIn() {
01688                 if ( $this->mTimeIn === 0 ) {
01689                         ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
01690                 }
01691                 if ( $this->mDBTimeIn !== 0 ) {
01692                         ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
01693                 }
01694                 $this->mDBTimeIn = microtime( true );
01695                 wfProfileIn( $this->getModuleProfileName( true ) );
01696         }
01697 
01701         public function profileDBOut() {
01702                 if ( $this->mTimeIn === 0 ) {
01703                         ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
01704                 }
01705                 if ( $this->mDBTimeIn === 0 ) {
01706                         ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
01707                 }
01708 
01709                 $time = microtime( true ) - $this->mDBTimeIn;
01710                 $this->mDBTimeIn = 0;
01711 
01712                 $this->mDBTime += $time;
01713                 $this->getMain()->mDBTime += $time;
01714                 wfProfileOut( $this->getModuleProfileName( true ) );
01715         }
01716 
01721         public function getProfileDBTime() {
01722                 if ( $this->mDBTimeIn !== 0 ) {
01723                         ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
01724                 }
01725                 return $this->mDBTime;
01726         }
01727 
01732         protected function getDB() {
01733                 if ( !isset( $this->mSlaveDB ) ) {
01734                         $this->profileDBIn();
01735                         $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
01736                         $this->profileDBOut();
01737                 }
01738                 return $this->mSlaveDB;
01739         }
01740 
01747         public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
01748                 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
01749                 var_export( $value );
01750                 if ( $backtrace ) {
01751                         print "\n" . wfBacktrace();
01752                 }
01753                 print "\n</pre>\n";
01754         }
01755 }