MediaWiki  REL1_19
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)
00054         const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
00055         const PARAM_RANGE_ENFORCE = 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
00056 
00057         const LIMIT_BIG1 = 500; // Fast query, std user limit
00058         const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
00059         const LIMIT_SML1 = 50; // Slow query, std user limit
00060         const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
00061 
00062         private $mMainModule, $mModuleName, $mModulePrefix;
00063         private $mParamCache = array();
00064 
00071         public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
00072                 $this->mMainModule = $mainModule;
00073                 $this->mModuleName = $moduleName;
00074                 $this->mModulePrefix = $modulePrefix;
00075 
00076                 if ( !$this->isMain() ) {
00077                         $this->setContext( $mainModule->getContext() );
00078                 }
00079         }
00080 
00081         /*****************************************************************************
00082          * ABSTRACT METHODS                                                          *
00083          *****************************************************************************/
00084 
00101         public abstract function execute();
00102 
00109         public abstract function getVersion();
00110 
00115         public function getModuleName() {
00116                 return $this->mModuleName;
00117         }
00118 
00123         public function getModulePrefix() {
00124                 return $this->mModulePrefix;
00125         }
00126 
00134         public function getModuleProfileName( $db = false ) {
00135                 if ( $db ) {
00136                         return 'API:' . $this->mModuleName . '-DB';
00137                 } else {
00138                         return 'API:' . $this->mModuleName;
00139                 }
00140         }
00141 
00146         public function getMain() {
00147                 return $this->mMainModule;
00148         }
00149 
00155         public function isMain() {
00156                 return $this === $this->mMainModule;
00157         }
00158 
00163         public function getResult() {
00164                 // Main module has getResult() method overriden
00165                 // Safety - avoid infinite loop:
00166                 if ( $this->isMain() ) {
00167                         ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
00168                 }
00169                 return $this->getMain()->getResult();
00170         }
00171 
00176         public function getResultData() {
00177                 return $this->getResult()->getData();
00178         }
00179 
00189         public function createContext() {
00190                 wfDeprecated( __METHOD__, '1.19' );
00191                 return new DerivativeContext( $this->getContext() );
00192         }
00193 
00201         public function setWarning( $warning ) {
00202                 $result = $this->getResult();
00203                 $data = $result->getData();
00204                 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
00205                         // Don't add duplicate warnings
00206                         $warn_regex = preg_quote( $warning, '/' );
00207                         if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) {
00208                                 return;
00209                         }
00210                         $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
00211                         // If there is a warning already, append it to the existing one
00212                         $warning = "$oldwarning\n$warning";
00213                         $result->unsetValue( 'warnings', $this->getModuleName() );
00214                 }
00215                 $msg = array();
00216                 ApiResult::setContent( $msg, $warning );
00217                 $result->disableSizeCheck();
00218                 $result->addValue( 'warnings', $this->getModuleName(), $msg );
00219                 $result->enableSizeCheck();
00220         }
00221 
00228         public function getCustomPrinter() {
00229                 return null;
00230         }
00231 
00236         public function makeHelpMsg() {
00237                 static $lnPrfx = "\n  ";
00238 
00239                 $msg = $this->getFinalDescription();
00240 
00241                 if ( $msg !== false ) {
00242 
00243                         if ( !is_array( $msg ) ) {
00244                                 $msg = array(
00245                                         $msg
00246                                 );
00247                         }
00248                         $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
00249 
00250                         if ( $this->isReadMode() ) {
00251                                 $msg .= "\nThis module requires read rights";
00252                         }
00253                         if ( $this->isWriteMode() ) {
00254                                 $msg .= "\nThis module requires write rights";
00255                         }
00256                         if ( $this->mustBePosted() ) {
00257                                 $msg .= "\nThis module only accepts POST requests";
00258                         }
00259                         if ( $this->isReadMode() || $this->isWriteMode() ||
00260                                         $this->mustBePosted() ) {
00261                                 $msg .= "\n";
00262                         }
00263 
00264                         // Parameters
00265                         $paramsMsg = $this->makeHelpMsgParameters();
00266                         if ( $paramsMsg !== false ) {
00267                                 $msg .= "Parameters:\n$paramsMsg";
00268                         }
00269 
00270                         $examples = $this->getExamples();
00271                         if ( $examples !== false && $examples !== '' ) {
00272                                 if ( !is_array( $examples ) ) {
00273                                         $examples = array(
00274                                                 $examples
00275                                         );
00276                                 }
00277                                 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
00278                                 foreach( $examples as $k => $v ) {
00279 
00280                                         if ( is_numeric( $k ) ) {
00281                                                 $msg .= "  $v\n";
00282                                         } else {
00283                                                 $v .= ":";
00284                                                 if ( is_array( $v ) ) {
00285                                                         $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
00286                                                 } else {
00287                                                         $msgExample = "  $v";
00288                                                 }
00289                                                 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n    $k\n";
00290                                         }
00291                                 }
00292                         }
00293 
00294                         $msg .= $this->makeHelpArrayToString( $lnPrfx, "Help page", $this->getHelpUrls() );
00295 
00296                         if ( $this->getMain()->getShowVersions() ) {
00297                                 $versions = $this->getVersion();
00298                                 $pattern = '/(\$.*) ([0-9a-z_]+\.php) (.*\$)/i';
00299                                 $callback = array( $this, 'makeHelpMsg_callback' );
00300 
00301                                 if ( is_array( $versions ) ) {
00302                                         foreach ( $versions as &$v ) {
00303                                                 $v = preg_replace_callback( $pattern, $callback, $v );
00304                                         }
00305                                         $versions = implode( "\n  ", $versions );
00306                                 } else {
00307                                         $versions = preg_replace_callback( $pattern, $callback, $versions );
00308                                 }
00309 
00310                                 $msg .= "Version:\n  $versions\n";
00311                         }
00312                 }
00313 
00314                 return $msg;
00315         }
00316 
00321         private function indentExampleText( $item ) {
00322                 return "  " . $item;
00323         }
00324 
00331         protected function makeHelpArrayToString( $prefix, $title, $input ) {
00332                 if ( $input === false ) {
00333                         return '';
00334                 }
00335                 if ( !is_array( $input ) ) {
00336                         $input = array(
00337                                 $input
00338                         );
00339                 }
00340 
00341                 if ( count( $input ) > 0 ) {
00342                         $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n  ";
00343                         $msg .= implode( $prefix, $input ) . "\n";
00344                         return $msg;
00345                 }
00346                 return '';
00347         }
00348 
00354         public function makeHelpMsgParameters() {
00355                 $params = $this->getFinalParams();
00356                 if ( $params ) {
00357 
00358                         $paramsDescription = $this->getFinalParamDescription();
00359                         $msg = '';
00360                         $paramPrefix = "\n" . str_repeat( ' ', 24 );
00361                         $descWordwrap = "\n" . str_repeat( ' ', 28 );
00362                         foreach ( $params as $paramName => $paramSettings ) {
00363                                 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
00364                                 if ( is_array( $desc ) ) {
00365                                         $desc = implode( $paramPrefix, $desc );
00366                                 }
00367 
00368                                 if ( !is_array( $paramSettings ) ) {
00369                                         $paramSettings = array(
00370                                                 self::PARAM_DFLT => $paramSettings,
00371                                         );
00372                                 }
00373 
00374                                 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ?
00375                                                 $paramSettings[self::PARAM_DEPRECATED] : false;
00376                                 if ( $deprecated ) {
00377                                         $desc = "DEPRECATED! $desc";
00378                                 }
00379 
00380                                 $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ?
00381                                                 $paramSettings[self::PARAM_REQUIRED] : false;
00382                                 if ( $required ) {
00383                                         $desc .= $paramPrefix . "This parameter is required";
00384                                 }
00385 
00386                                 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
00387                                 if ( isset( $type ) ) {
00388                                         if ( isset( $paramSettings[self::PARAM_ISMULTI] ) && $paramSettings[self::PARAM_ISMULTI] ) {
00389                                                 $prompt = 'Values (separate with \'|\'): ';
00390                                         } else {
00391                                                 $prompt = 'One value: ';
00392                                         }
00393 
00394                                         if ( is_array( $type ) ) {
00395                                                 $choices = array();
00396                                                 $nothingPrompt = false;
00397                                                 foreach ( $type as $t ) {
00398                                                         if ( $t === '' ) {
00399                                                                 $nothingPrompt = 'Can be empty, or ';
00400                                                         } else {
00401                                                                 $choices[] =  $t;
00402                                                         }
00403                                                 }
00404                                                 $desc .= $paramPrefix . $nothingPrompt . $prompt;
00405                                                 $choicesstring = implode( ', ', $choices );
00406                                                 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
00407                                         } else {
00408                                                 switch ( $type ) {
00409                                                         case 'namespace':
00410                                                                 // Special handling because namespaces are type-limited, yet they are not given
00411                                                                 $desc .= $paramPrefix . $prompt;
00412                                                                 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
00413                                                                         100, $descWordwrap );
00414                                                                 break;
00415                                                         case 'limit':
00416                                                                 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
00417                                                                 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
00418                                                                         $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
00419                                                                 }
00420                                                                 $desc .= ' allowed';
00421                                                                 break;
00422                                                         case 'integer':
00423                                                                 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
00424                                                                 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
00425                                                                 if ( $hasMin || $hasMax ) {
00426                                                                         if ( !$hasMax ) {
00427                                                                                 $intRangeStr = "The value must be no less than {$paramSettings[self::PARAM_MIN]}";
00428                                                                         } elseif ( !$hasMin ) {
00429                                                                                 $intRangeStr = "The value must be no more than {$paramSettings[self::PARAM_MAX]}";
00430                                                                         } else {
00431                                                                                 $intRangeStr = "The value must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
00432                                                                         }
00433 
00434                                                                         $desc .= $paramPrefix . $intRangeStr;
00435                                                                 }
00436                                                                 break;
00437                                                 }
00438 
00439                                                 if ( isset( $paramSettings[self::PARAM_ISMULTI] ) ) {
00440                                                         $isArray = is_array( $paramSettings[self::PARAM_TYPE] );
00441 
00442                                                         if ( !$isArray
00443                                                                         || $isArray && count( $paramSettings[self::PARAM_TYPE] ) > self::LIMIT_SML1 ) {
00444                                                                 $desc .= $paramPrefix . "Maximum number of values " .
00445                                                                                 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
00446                                                         }
00447                                                 }
00448                                         }
00449                                 }
00450 
00451                                 $default = is_array( $paramSettings )
00452                                                 ? ( isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null )
00453                                                 : $paramSettings;
00454                                 if ( !is_null( $default ) && $default !== false ) {
00455                                         $desc .= $paramPrefix . "Default: $default";
00456                                 }
00457 
00458                                 $msg .= sprintf( "  %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
00459                         }
00460                         return $msg;
00461 
00462                 } else {
00463                         return false;
00464                 }
00465         }
00466 
00474         public function makeHelpMsg_callback( $matches ) {
00475                 global $wgAutoloadClasses, $wgAutoloadLocalClasses;
00476 
00477                 $file = '';
00478                 if ( isset( $wgAutoloadLocalClasses[get_class( $this )] ) ) {
00479                         $file = $wgAutoloadLocalClasses[get_class( $this )];
00480                 } elseif ( isset( $wgAutoloadClasses[get_class( $this )] ) ) {
00481                         $file = $wgAutoloadClasses[get_class( $this )];
00482                 }
00483 
00484                 // Do some guesswork here
00485                 $path = strstr( $file, 'includes/api/' );
00486                 if ( $path === false ) {
00487                         $path = strstr( $file, 'extensions/' );
00488                 } else {
00489                         $path = 'phase3/' . $path;
00490                 }
00491 
00492                 // Get the filename from $matches[2] instead of $file
00493                 // If they're not the same file, they're assumed to be in the
00494                 // same directory
00495                 // This is necessary to make stuff like ApiMain::getVersion()
00496                 // returning the version string for ApiBase work
00497                 if ( $path ) {
00498                         return "{$matches[0]}\n   https://svn.wikimedia.org/" .
00499                                         "viewvc/mediawiki/trunk/" . dirname( $path ) .
00500                                         "/{$matches[2]}";
00501                 }
00502                 return $matches[0];
00503         }
00504 
00509         protected function getDescription() {
00510                 return false;
00511         }
00512 
00517         protected function getExamples() {
00518                 return false;
00519         }
00520 
00528         protected function getAllowedParams() {
00529                 return false;
00530         }
00531 
00538         protected function getParamDescription() {
00539                 return false;
00540         }
00541 
00548         public function getFinalParams() {
00549                 $params = $this->getAllowedParams();
00550                 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
00551                 return $params;
00552         }
00553 
00560         public function getFinalParamDescription() {
00561                 $desc = $this->getParamDescription();
00562                 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
00563                 return $desc;
00564         }
00565 
00572         public function getFinalDescription() {
00573                 $desc = $this->getDescription();
00574                 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
00575                 return $desc;
00576         }
00577 
00584         public function encodeParamName( $paramName ) {
00585                 return $this->mModulePrefix . $paramName;
00586         }
00587 
00597         public function extractRequestParams( $parseLimit = true ) {
00598                 // Cache parameters, for performance and to avoid bug 24564.
00599                 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
00600                         $params = $this->getFinalParams();
00601                         $results = array();
00602 
00603                         if ( $params ) { // getFinalParams() can return false
00604                                 foreach ( $params as $paramName => $paramSettings ) {
00605                                         $results[$paramName] = $this->getParameterFromSettings(
00606                                                 $paramName, $paramSettings, $parseLimit );
00607                                 }
00608                         }
00609                         $this->mParamCache[$parseLimit] = $results;
00610                 }
00611                 return $this->mParamCache[$parseLimit];
00612         }
00613 
00620         protected function getParameter( $paramName, $parseLimit = true ) {
00621                 $params = $this->getFinalParams();
00622                 $paramSettings = $params[$paramName];
00623                 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
00624         }
00625 
00630         public function requireOnlyOneParameter( $params ) {
00631                 $required = func_get_args();
00632                 array_shift( $required );
00633 
00634                 $intersection = array_intersect( array_keys( array_filter( $params,
00635                         array( $this, "parameterNotEmpty" ) ) ), $required );
00636 
00637                 if ( count( $intersection ) > 1 ) {
00638                         $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
00639                 } elseif ( count( $intersection ) == 0 ) {
00640                         $this->dieUsage( 'One of the parameters ' . implode( ', ', $required ) . ' is required', 'missingparam' );
00641                 }
00642         }
00643 
00650         public function getRequireOnlyOneParameterErrorMessages( $params ) {
00651                 $p = $this->getModulePrefix();
00652                 $params = implode( ", {$p}", $params );
00653 
00654                 return array(
00655                         array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
00656                         array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
00657                 );
00658         }
00659 
00665         public function requireMaxOneParameter( $params ) {
00666                 $required = func_get_args();
00667                 array_shift( $required );
00668 
00669                 $intersection = array_intersect( array_keys( array_filter( $params,
00670                         array( $this, "parameterNotEmpty" ) ) ), $required );
00671 
00672                 if ( count( $intersection ) > 1 ) {
00673                         $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
00674                 }
00675         }
00676 
00683         public function getRequireMaxOneParameterErrorMessages( $params ) {
00684                 $p = $this->getModulePrefix();
00685                 $params = implode( ", {$p}", $params );
00686 
00687                 return array(
00688                         array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
00689                 );
00690         }
00691 
00698         private function parameterNotEmpty( $x ) {
00699                 return !is_null( $x ) && $x !== false;
00700         }
00701 
00707         public static function getValidNamespaces() {
00708                 wfDeprecated( __METHOD__, '1.17' );
00709                 return MWNamespace::getValidNamespaces();
00710         }
00711 
00720         protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
00721 
00722                 $userWatching = $titleObj->userIsWatching();
00723 
00724                 switch ( $watchlist ) {
00725                         case 'watch':
00726                                 return true;
00727 
00728                         case 'unwatch':
00729                                 return false;
00730 
00731                         case 'preferences':
00732                                 # If the user is already watching, don't bother checking
00733                                 if ( $userWatching ) {
00734                                         return true;
00735                                 }
00736                                 # If no user option was passed, use watchdefault or watchcreation
00737                                 if ( is_null( $userOption ) ) {
00738                                         $userOption = $titleObj->exists()
00739                                                         ? 'watchdefault' : 'watchcreations';
00740                                 }
00741                                 # Watch the article based on the user preference
00742                                 return (bool)$this->getUser()->getOption( $userOption );
00743 
00744                         case 'nochange':
00745                                 return $userWatching;
00746 
00747                         default:
00748                                 return $userWatching;
00749                 }
00750         }
00751 
00758         protected function setWatch( $watch, $titleObj, $userOption = null ) {
00759                 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
00760                 if ( $value === null ) {
00761                         return;
00762                 }
00763 
00764                 $user = $this->getUser();
00765                 if ( $value ) {
00766                         WatchAction::doWatch( $titleObj, $user );
00767                 } else {
00768                         WatchAction::doUnwatch( $titleObj, $user );
00769                 }
00770         }
00771 
00781         protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
00782                 // Some classes may decide to change parameter names
00783                 $encParamName = $this->encodeParamName( $paramName );
00784 
00785                 if ( !is_array( $paramSettings ) ) {
00786                         $default = $paramSettings;
00787                         $multi = false;
00788                         $type = gettype( $paramSettings );
00789                         $dupes = false;
00790                         $deprecated = false;
00791                         $required = false;
00792                 } else {
00793                         $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
00794                         $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
00795                         $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
00796                         $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false;
00797                         $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false;
00798                         $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? $paramSettings[self::PARAM_REQUIRED] : false;
00799 
00800                         // When type is not given, and no choices, the type is the same as $default
00801                         if ( !isset( $type ) ) {
00802                                 if ( isset( $default ) ) {
00803                                         $type = gettype( $default );
00804                                 } else {
00805                                         $type = 'NULL'; // allow everything
00806                                 }
00807                         }
00808                 }
00809 
00810                 if ( $type == 'boolean' ) {
00811                         if ( isset( $default ) && $default !== false ) {
00812                                 // Having a default value of anything other than 'false' is pointless
00813                                 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'" );
00814                         }
00815 
00816                         $value = $this->getRequest()->getCheck( $encParamName );
00817                 } else {
00818                         $value = $this->getRequest()->getVal( $encParamName, $default );
00819 
00820                         if ( isset( $value ) && $type == 'namespace' ) {
00821                                 $type = MWNamespace::getValidNamespaces();
00822                         }
00823                 }
00824 
00825                 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
00826                         $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null );
00827                 }
00828 
00829                 // More validation only when choices were not given
00830                 // choices were validated in parseMultiValue()
00831                 if ( isset( $value ) ) {
00832                         if ( !is_array( $type ) ) {
00833                                 switch ( $type ) {
00834                                         case 'NULL': // nothing to do
00835                                                 break;
00836                                         case 'string':
00837                                                 if ( $required && $value === '' ) {
00838                                                         $this->dieUsageMsg( array( 'missingparam', $paramName ) );
00839                                                 }
00840 
00841                                                 break;
00842                                         case 'integer': // Force everything using intval() and optionally validate limits
00843                                                 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
00844                                                 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
00845                                                 $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] )
00846                                                                 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
00847 
00848                                                 if ( is_array( $value ) ) {
00849                                                         $value = array_map( 'intval', $value );
00850                                                         if ( !is_null( $min ) || !is_null( $max ) ) {
00851                                                                 foreach ( $value as &$v ) {
00852                                                                         $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
00853                                                                 }
00854                                                         }
00855                                                 } else {
00856                                                         $value = intval( $value );
00857                                                         if ( !is_null( $min ) || !is_null( $max ) ) {
00858                                                                 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
00859                                                         }
00860                                                 }
00861                                                 break;
00862                                         case 'limit':
00863                                                 if ( !$parseLimit ) {
00864                                                         // Don't do any validation whatsoever
00865                                                         break;
00866                                                 }
00867                                                 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
00868                                                         ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
00869                                                 }
00870                                                 if ( $multi ) {
00871                                                         ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
00872                                                 }
00873                                                 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
00874                                                 if ( $value == 'max' ) {
00875                                                         $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
00876                                                         $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
00877                                                 } else {
00878                                                         $value = intval( $value );
00879                                                         $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
00880                                                 }
00881                                                 break;
00882                                         case 'boolean':
00883                                                 if ( $multi ) {
00884                                                         ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
00885                                                 }
00886                                                 break;
00887                                         case 'timestamp':
00888                                                 if ( is_array( $value ) ) {
00889                                                         foreach ( $value as $key => $val ) {
00890                                                                 $value[$key] = $this->validateTimestamp( $val, $encParamName );
00891                                                         }
00892                                                 } else {
00893                                                         $value = $this->validateTimestamp( $value, $encParamName );
00894                                                 }
00895                                                 break;
00896                                         case 'user':
00897                                                 if ( !is_array( $value ) ) {
00898                                                         $value = array( $value );
00899                                                 }
00900 
00901                                                 foreach ( $value as $key => $val ) {
00902                                                         $title = Title::makeTitleSafe( NS_USER, $val );
00903                                                         if ( is_null( $title ) ) {
00904                                                                 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
00905                                                         }
00906                                                         $value[$key] = $title->getText();
00907                                                 }
00908 
00909                                                 if ( !$multi ) {
00910                                                         $value = $value[0];
00911                                                 }
00912                                                 break;
00913                                         default:
00914                                                 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
00915                                 }
00916                         }
00917 
00918                         // Throw out duplicates if requested
00919                         if ( is_array( $value ) && !$dupes ) {
00920                                 $value = array_unique( $value );
00921                         }
00922 
00923                         // Set a warning if a deprecated parameter has been passed
00924                         if ( $deprecated && $value !== false ) {
00925                                 $this->setWarning( "The $encParamName parameter has been deprecated." );
00926                         }
00927                 } elseif ( $required ) {
00928                         $this->dieUsageMsg( array( 'missingparam', $paramName ) );
00929                 }
00930 
00931                 return $value;
00932         }
00933 
00947         protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
00948                 if ( trim( $value ) === '' && $allowMultiple ) {
00949                         return array();
00950                 }
00951 
00952                 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
00953                 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
00954                 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
00955                                 self::LIMIT_SML2 : self::LIMIT_SML1;
00956 
00957                 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
00958                         $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
00959                 }
00960 
00961                 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
00962                         // Bug 33482 - Allow entries with | in them for non-multiple values
00963                         if ( in_array( $value, $allowedValues ) ) {
00964                                 return $value;
00965                         }
00966 
00967                         $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
00968                         $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
00969                 }
00970 
00971                 if ( is_array( $allowedValues ) ) {
00972                         // Check for unknown values
00973                         $unknown = array_diff( $valuesList, $allowedValues );
00974                         if ( count( $unknown ) ) {
00975                                 if ( $allowMultiple ) {
00976                                         $s = count( $unknown ) > 1 ? 's' : '';
00977                                         $vals = implode( ", ", $unknown );
00978                                         $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
00979                                 } else {
00980                                         $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
00981                                 }
00982                         }
00983                         // Now throw them out
00984                         $valuesList = array_intersect( $valuesList, $allowedValues );
00985                 }
00986 
00987                 return $allowMultiple ? $valuesList : $valuesList[0];
00988         }
00989 
01000         function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
01001                 if ( !is_null( $min ) && $value < $min ) {
01002 
01003                         $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
01004                         $this->warnOrDie( $msg, $enforceLimits );
01005                         $value = $min;
01006                 }
01007 
01008                 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
01009                 if ( $this->getMain()->isInternalMode() ) {
01010                         return;
01011                 }
01012 
01013                 // Optimization: do not check user's bot status unless really needed -- skips db query
01014                 // assumes $botMax >= $max
01015                 if ( !is_null( $max ) && $value > $max ) {
01016                         if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
01017                                 if ( $value > $botMax ) {
01018                                         $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
01019                                         $this->warnOrDie( $msg, $enforceLimits );
01020                                         $value = $botMax;
01021                                 }
01022                         } else {
01023                                 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
01024                                 $this->warnOrDie( $msg, $enforceLimits );
01025                                 $value = $max;
01026                         }
01027                 }
01028         }
01029 
01035         function validateTimestamp( $value, $paramName ) {
01036                 $value = wfTimestamp( TS_UNIX, $value );
01037                 if ( $value === 0 ) {
01038                         $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" );
01039                 }
01040                 return wfTimestamp( TS_MW, $value );
01041         }
01042 
01049         private function warnOrDie( $msg, $enforceLimits = false ) {
01050                 if ( $enforceLimits ) {
01051                         $this->dieUsage( $msg, 'integeroutofrange' );
01052                 } else {
01053                         $this->setWarning( $msg );
01054                 }
01055         }
01056 
01063         public static function truncateArray( &$arr, $limit ) {
01064                 $modified = false;
01065                 while ( count( $arr ) > $limit ) {
01066                         array_pop( $arr );
01067                         $modified = true;
01068                 }
01069                 return $modified;
01070         }
01071 
01083         public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
01084                 Profiler::instance()->close();
01085                 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
01086         }
01087 
01091         public static $messageMap = array(
01092                 // This one MUST be present, or dieUsageMsg() will recurse infinitely
01093                 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
01094                 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
01095 
01096                 // Messages from Title::getUserPermissionsErrors()
01097                 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
01098                 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
01099                 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
01100                 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
01101                 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
01102                 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
01103                 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
01104                 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
01105                 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
01106                 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
01107                 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
01108                 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
01109                 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
01110                 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
01111                 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
01112                 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
01113                 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
01114                 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
01115 
01116                 // Miscellaneous interface messages
01117                 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
01118                 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
01119                 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
01120                 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
01121                 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
01122                 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
01123                 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
01124                 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
01125                 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
01126                 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
01127                 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
01128                 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
01129                 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
01130                 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
01131                 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
01132                 // 'badarticleerror' => shouldn't happen
01133                 // 'badtitletext' => shouldn't happen
01134                 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
01135                 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
01136                 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
01137                 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
01138                 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
01139                 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
01140                 '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." ),
01141                 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
01142                 '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" ),
01143                 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
01144                 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
01145                 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
01146                 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
01147                 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
01148                 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid e-mail address, or has chosen not to receive e-mail from other users" ),
01149                 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
01150                 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
01151                 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
01152                 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
01153                 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
01154                 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
01155                 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01156                 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01157                 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
01158 
01159                 // API-specific messages
01160                 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
01161                 '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" ),
01162                 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
01163                 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
01164                 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
01165                 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
01166                 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
01167                 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
01168                 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01169                 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
01170                 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
01171                 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
01172                 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
01173                 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
01174                 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
01175                 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
01176                 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
01177                 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
01178                 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
01179                 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
01180                 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
01181                 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
01182                 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
01183                 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
01184                 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
01185                 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
01186                 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
01187                 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
01188                 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
01189                 'nouploadmodule' => array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
01190                 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
01191                 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
01192                 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
01193                 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
01194                 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
01195                 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
01196                 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
01197                 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
01198                 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
01199                 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
01200                 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
01201                 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
01202                 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
01203                 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
01204                 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
01205 
01206                 // ApiEditPage messages
01207                 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
01208                 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
01209                 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
01210                 'filtered' => array( 'code' => 'filtered', 'info' => "The filter callback function refused your edit" ),
01211                 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
01212                 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
01213                 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
01214                 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
01215                 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
01216                 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
01217                 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
01218                 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
01219                 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
01220                 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
01221                 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
01222 
01223                 // Messages from WikiPage::doEit()
01224                 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
01225                 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
01226                 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
01227                 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
01228 
01229                 // uploadMsgs
01230                 'invalid-session-key' => array( 'code' => 'invalid-session-key', 'info' => 'Not a valid session key' ),
01231                 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
01232                 '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' ),
01233                 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled.  Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
01234 
01235                 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
01236                 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
01237                 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
01238                 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
01239 
01240                 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
01241         );
01242 
01246         public function dieReadOnly() {
01247                 $parsed = $this->parseMsg( array( 'readonlytext' ) );
01248                 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
01249                         array( 'readonlyreason' => wfReadOnlyReason() ) );
01250         }
01251 
01256         public function dieUsageMsg( $error ) {
01257                 # most of the time we send a 1 element, so we might as well send it as
01258                 # a string and make this an array here.
01259                 if( is_string( $error ) ) {
01260                         $error = array( $error );
01261                 }
01262                 $parsed = $this->parseMsg( $error );
01263                 $this->dieUsage( $parsed['info'], $parsed['code'] );
01264         }
01265 
01271         public function parseMsg( $error ) {
01272                 $error = (array)$error; // It seems strings sometimes make their way in here
01273                 $key = array_shift( $error );
01274 
01275                 // Check whether the error array was nested
01276                 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
01277                 if( is_array( $key ) ){
01278                         $error = $key;
01279                         $key = array_shift( $error );
01280                 }
01281 
01282                 if ( isset( self::$messageMap[$key] ) ) {
01283                         return array( 'code' =>
01284                         wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
01285                                 'info' =>
01286                                 wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
01287                         );
01288                 }
01289 
01290                 // If the key isn't present, throw an "unknown error"
01291                 return $this->parseMsg( array( 'unknownerror', $key ) );
01292         }
01293 
01299         protected static function dieDebug( $method, $message ) {
01300                 wfDebugDieBacktrace( "Internal error in $method: $message" );
01301         }
01302 
01307         public function shouldCheckMaxlag() {
01308                 return true;
01309         }
01310 
01315         public function isReadMode() {
01316                 return true;
01317         }
01322         public function isWriteMode() {
01323                 return false;
01324         }
01325 
01330         public function mustBePosted() {
01331                 return false;
01332         }
01333 
01338         public function needsToken() {
01339                 return false;
01340         }
01341 
01346         public function getTokenSalt() {
01347                 return false;
01348         }
01349 
01356         public function getWatchlistUser( $params ) {
01357                 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
01358                         $user = User::newFromName( $params['owner'], false );
01359                         if ( !($user && $user->getId()) ) {
01360                                 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
01361                         }
01362                         $token = $user->getOption( 'watchlisttoken' );
01363                         if ( $token == '' || $token != $params['token'] ) {
01364                                 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
01365                         }
01366                 } else {
01367                         if ( !$this->getUser()->isLoggedIn() ) {
01368                                 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
01369                         }
01370                         $user = $this->getUser();
01371                 }
01372                 return $user;
01373         }
01374 
01378         public function getHelpUrls() {
01379                 return false;
01380         }
01381 
01386         public function getPossibleErrors() {
01387                 $ret = array();
01388 
01389                 $params = $this->getFinalParams();
01390                 if ( $params ) {
01391                         foreach ( $params as $paramName => $paramSettings ) {
01392                                 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) ) {
01393                                         $ret[] = array( 'missingparam', $paramName );
01394                                 }
01395                         }
01396                 }
01397 
01398                 if ( $this->mustBePosted() ) {
01399                         $ret[] = array( 'mustbeposted', $this->getModuleName() );
01400                 }
01401 
01402                 if ( $this->isReadMode() ) {
01403                         $ret[] = array( 'readrequired' );
01404                 }
01405 
01406                 if ( $this->isWriteMode() ) {
01407                         $ret[] = array( 'writerequired' );
01408                         $ret[] = array( 'writedisabled' );
01409                 }
01410 
01411                 if ( $this->needsToken() ) {
01412                         $ret[] = array( 'missingparam', 'token' );
01413                         $ret[] = array( 'sessionfailure' );
01414                 }
01415 
01416                 return $ret;
01417         }
01418 
01424         public function parseErrors( $errors ) {
01425                 $ret = array();
01426 
01427                 foreach ( $errors as $row ) {
01428                         if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
01429                                 $ret[] = $row;
01430                         } else {
01431                                 $ret[] = $this->parseMsg( $row );
01432                         }
01433                 }
01434                 return $ret;
01435         }
01436 
01440         private $mTimeIn = 0, $mModuleTime = 0;
01441 
01445         public function profileIn() {
01446                 if ( $this->mTimeIn !== 0 ) {
01447                         ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
01448                 }
01449                 $this->mTimeIn = microtime( true );
01450                 wfProfileIn( $this->getModuleProfileName() );
01451         }
01452 
01456         public function profileOut() {
01457                 if ( $this->mTimeIn === 0 ) {
01458                         ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
01459                 }
01460                 if ( $this->mDBTimeIn !== 0 ) {
01461                         ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
01462                 }
01463 
01464                 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
01465                 $this->mTimeIn = 0;
01466                 wfProfileOut( $this->getModuleProfileName() );
01467         }
01468 
01473         public function safeProfileOut() {
01474                 if ( $this->mTimeIn !== 0 ) {
01475                         if ( $this->mDBTimeIn !== 0 ) {
01476                                 $this->profileDBOut();
01477                         }
01478                         $this->profileOut();
01479                 }
01480         }
01481 
01486         public function getProfileTime() {
01487                 if ( $this->mTimeIn !== 0 ) {
01488                         ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
01489                 }
01490                 return $this->mModuleTime;
01491         }
01492 
01496         private $mDBTimeIn = 0, $mDBTime = 0;
01497 
01501         public function profileDBIn() {
01502                 if ( $this->mTimeIn === 0 ) {
01503                         ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
01504                 }
01505                 if ( $this->mDBTimeIn !== 0 ) {
01506                         ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
01507                 }
01508                 $this->mDBTimeIn = microtime( true );
01509                 wfProfileIn( $this->getModuleProfileName( true ) );
01510         }
01511 
01515         public function profileDBOut() {
01516                 if ( $this->mTimeIn === 0 ) {
01517                         ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
01518                 }
01519                 if ( $this->mDBTimeIn === 0 ) {
01520                         ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
01521                 }
01522 
01523                 $time = microtime( true ) - $this->mDBTimeIn;
01524                 $this->mDBTimeIn = 0;
01525 
01526                 $this->mDBTime += $time;
01527                 $this->getMain()->mDBTime += $time;
01528                 wfProfileOut( $this->getModuleProfileName( true ) );
01529         }
01530 
01535         public function getProfileDBTime() {
01536                 if ( $this->mDBTimeIn !== 0 ) {
01537                         ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
01538                 }
01539                 return $this->mDBTime;
01540         }
01541 
01545         protected function getDB() {
01546                 return wfGetDB( DB_SLAVE, 'api' );
01547         }
01548 
01555         public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
01556                 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
01557                 var_export( $value );
01558                 if ( $backtrace ) {
01559                         print "\n" . wfBacktrace();
01560                 }
01561                 print "\n</pre>\n";
01562         }
01563 
01568         public static function getBaseVersion() {
01569                 return __CLASS__ . ': $Id$';
01570         }
01571 }