MediaWiki  REL1_20
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 
00069         private $mMainModule, $mModuleName, $mModulePrefix;
00070         private $mParamCache = array();
00071 
00078         public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
00079                 $this->mMainModule = $mainModule;
00080                 $this->mModuleName = $moduleName;
00081                 $this->mModulePrefix = $modulePrefix;
00082 
00083                 if ( !$this->isMain() ) {
00084                         $this->setContext( $mainModule->getContext() );
00085                 }
00086         }
00087 
00088         /*****************************************************************************
00089          * ABSTRACT METHODS                                                          *
00090          *****************************************************************************/
00091 
00108         public abstract function execute();
00109 
00116         public abstract function getVersion();
00117 
00122         public function getModuleName() {
00123                 return $this->mModuleName;
00124         }
00125 
00130         public function getModulePrefix() {
00131                 return $this->mModulePrefix;
00132         }
00133 
00141         public function getModuleProfileName( $db = false ) {
00142                 if ( $db ) {
00143                         return 'API:' . $this->mModuleName . '-DB';
00144                 } else {
00145                         return 'API:' . $this->mModuleName;
00146                 }
00147         }
00148 
00153         public function getMain() {
00154                 return $this->mMainModule;
00155         }
00156 
00162         public function isMain() {
00163                 return $this === $this->mMainModule;
00164         }
00165 
00170         public function getResult() {
00171                 // Main module has getResult() method overriden
00172                 // Safety - avoid infinite loop:
00173                 if ( $this->isMain() ) {
00174                         ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
00175                 }
00176                 return $this->getMain()->getResult();
00177         }
00178 
00183         public function getResultData() {
00184                 return $this->getResult()->getData();
00185         }
00186 
00196         public function createContext() {
00197                 wfDeprecated( __METHOD__, '1.19' );
00198                 return new DerivativeContext( $this->getContext() );
00199         }
00200 
00208         public function setWarning( $warning ) {
00209                 $result = $this->getResult();
00210                 $data = $result->getData();
00211                 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
00212                         // Don't add duplicate warnings
00213                         $warn_regex = preg_quote( $warning, '/' );
00214                         if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) {
00215                                 return;
00216                         }
00217                         $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
00218                         // If there is a warning already, append it to the existing one
00219                         $warning = "$oldwarning\n$warning";
00220                         $result->unsetValue( 'warnings', $this->getModuleName() );
00221                 }
00222                 $msg = array();
00223                 ApiResult::setContent( $msg, $warning );
00224                 $result->disableSizeCheck();
00225                 $result->addValue( 'warnings', $this->getModuleName(), $msg );
00226                 $result->enableSizeCheck();
00227         }
00228 
00235         public function getCustomPrinter() {
00236                 return null;
00237         }
00238 
00243         public function makeHelpMsg() {
00244                 static $lnPrfx = "\n  ";
00245 
00246                 $msg = $this->getFinalDescription();
00247 
00248                 if ( $msg !== false ) {
00249 
00250                         if ( !is_array( $msg ) ) {
00251                                 $msg = array(
00252                                         $msg
00253                                 );
00254                         }
00255                         $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
00256 
00257                         if ( $this->isReadMode() ) {
00258                                 $msg .= "\nThis module requires read rights";
00259                         }
00260                         if ( $this->isWriteMode() ) {
00261                                 $msg .= "\nThis module requires write rights";
00262                         }
00263                         if ( $this->mustBePosted() ) {
00264                                 $msg .= "\nThis module only accepts POST requests";
00265                         }
00266                         if ( $this->isReadMode() || $this->isWriteMode() ||
00267                                         $this->mustBePosted() ) {
00268                                 $msg .= "\n";
00269                         }
00270 
00271                         // Parameters
00272                         $paramsMsg = $this->makeHelpMsgParameters();
00273                         if ( $paramsMsg !== false ) {
00274                                 $msg .= "Parameters:\n$paramsMsg";
00275                         }
00276 
00277                         $examples = $this->getExamples();
00278                         if ( $examples !== false && $examples !== '' ) {
00279                                 if ( !is_array( $examples ) ) {
00280                                         $examples = array(
00281                                                 $examples
00282                                         );
00283                                 }
00284                                 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
00285                                 foreach( $examples as $k => $v ) {
00286 
00287                                         if ( is_numeric( $k ) ) {
00288                                                 $msg .= "  $v\n";
00289                                         } else {
00290                                                 if ( is_array( $v ) ) {
00291                                                         $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
00292                                                 } else {
00293                                                         $msgExample = "  $v";
00294                                                 }
00295                                                 $msgExample .= ":";
00296                                                 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n    $k\n";
00297                                         }
00298                                 }
00299                         }
00300 
00301                         $msg .= $this->makeHelpArrayToString( $lnPrfx, "Help page", $this->getHelpUrls() );
00302 
00303                         if ( $this->getMain()->getShowVersions() ) {
00304                                 $versions = $this->getVersion();
00305                                 $pattern = '/(\$.*) ([0-9a-z_]+\.php) (.*\$)/i';
00306                                 $callback = array( $this, 'makeHelpMsg_callback' );
00307 
00308                                 if ( is_array( $versions ) ) {
00309                                         foreach ( $versions as &$v ) {
00310                                                 $v = preg_replace_callback( $pattern, $callback, $v );
00311                                         }
00312                                         $versions = implode( "\n  ", $versions );
00313                                 } else {
00314                                         $versions = preg_replace_callback( $pattern, $callback, $versions );
00315                                 }
00316 
00317                                 $msg .= "Version:\n  $versions\n";
00318                         }
00319                 }
00320 
00321                 return $msg;
00322         }
00323 
00328         private function indentExampleText( $item ) {
00329                 return "  " . $item;
00330         }
00331 
00338         protected function makeHelpArrayToString( $prefix, $title, $input ) {
00339                 if ( $input === false ) {
00340                         return '';
00341                 }
00342                 if ( !is_array( $input ) ) {
00343                         $input = array(
00344                                 $input
00345                         );
00346                 }
00347 
00348                 if ( count( $input ) > 0 ) {
00349                         $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n  ";
00350                         $msg .= implode( $prefix, $input ) . "\n";
00351                         return $msg;
00352                 }
00353                 return '';
00354         }
00355 
00361         public function makeHelpMsgParameters() {
00362                 $params = $this->getFinalParams();
00363                 if ( $params ) {
00364 
00365                         $paramsDescription = $this->getFinalParamDescription();
00366                         $msg = '';
00367                         $paramPrefix = "\n" . str_repeat( ' ', 24 );
00368                         $descWordwrap = "\n" . str_repeat( ' ', 28 );
00369                         foreach ( $params as $paramName => $paramSettings ) {
00370                                 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
00371                                 if ( is_array( $desc ) ) {
00372                                         $desc = implode( $paramPrefix, $desc );
00373                                 }
00374 
00375                                 //handle shorthand
00376                                 if ( !is_array( $paramSettings ) ) {
00377                                         $paramSettings = array(
00378                                                 self::PARAM_DFLT => $paramSettings,
00379                                         );
00380                                 }
00381 
00382                                 //handle missing type
00383                                 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
00384                                         $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] ) ? $paramSettings[ApiBase::PARAM_DFLT] : null;
00385                                         if ( is_bool( $dflt ) ) {
00386                                                 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
00387                                         } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
00388                                                 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
00389                                         } elseif ( is_int( $dflt ) ) {
00390                                                 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
00391                                         }
00392                                 }
00393 
00394                                 if ( isset( $paramSettings[self::PARAM_DEPRECATED] ) && $paramSettings[self::PARAM_DEPRECATED] ) {
00395                                         $desc = "DEPRECATED! $desc";
00396                                 }
00397 
00398                                 if ( isset( $paramSettings[self::PARAM_REQUIRED] ) && $paramSettings[self::PARAM_REQUIRED] ) {
00399                                         $desc .= $paramPrefix . "This parameter is required";
00400                                 }
00401 
00402                                 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
00403                                 if ( isset( $type ) ) {
00404                                         $hintPipeSeparated = true;
00405                                         $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
00406                                         if ( $multi ) {
00407                                                 $prompt = 'Values (separate with \'|\'): ';
00408                                         } else {
00409                                                 $prompt = 'One value: ';
00410                                         }
00411 
00412                                         if ( is_array( $type ) ) {
00413                                                 $choices = array();
00414                                                 $nothingPrompt = '';
00415                                                 foreach ( $type as $t ) {
00416                                                         if ( $t === '' ) {
00417                                                                 $nothingPrompt = 'Can be empty, or ';
00418                                                         } else {
00419                                                                 $choices[] =  $t;
00420                                                         }
00421                                                 }
00422                                                 $desc .= $paramPrefix . $nothingPrompt . $prompt;
00423                                                 $choicesstring = implode( ', ', $choices );
00424                                                 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
00425                                                 $hintPipeSeparated = false;
00426                                         } else {
00427                                                 switch ( $type ) {
00428                                                         case 'namespace':
00429                                                                 // Special handling because namespaces are type-limited, yet they are not given
00430                                                                 $desc .= $paramPrefix . $prompt;
00431                                                                 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
00432                                                                         100, $descWordwrap );
00433                                                                 $hintPipeSeparated = false;
00434                                                                 break;
00435                                                         case 'limit':
00436                                                                 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
00437                                                                 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
00438                                                                         $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
00439                                                                 }
00440                                                                 $desc .= ' allowed';
00441                                                                 break;
00442                                                         case 'integer':
00443                                                                 $s = $multi ? 's' : '';
00444                                                                 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
00445                                                                 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
00446                                                                 if ( $hasMin || $hasMax ) {
00447                                                                         if ( !$hasMax ) {
00448                                                                                 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
00449                                                                         } elseif ( !$hasMin ) {
00450                                                                                 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
00451                                                                         } else {
00452                                                                                 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
00453                                                                         }
00454 
00455                                                                         $desc .= $paramPrefix . $intRangeStr;
00456                                                                 }
00457                                                                 break;
00458                                                 }
00459                                         }
00460 
00461                                         if ( $multi ) {
00462                                                 if ( $hintPipeSeparated ) {
00463                                                         $desc .= $paramPrefix . "Separate values with '|'";
00464                                                 }
00465 
00466                                                 $isArray = is_array( $type );
00467                                                 if ( !$isArray
00468                                                                 || $isArray && count( $type ) > self::LIMIT_SML1 ) {
00469                                                         $desc .= $paramPrefix . "Maximum number of values " .
00470                                                                         self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
00471                                                 }
00472                                         }
00473                                 }
00474 
00475                                 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
00476                                 if ( !is_null( $default ) && $default !== false ) {
00477                                         $desc .= $paramPrefix . "Default: $default";
00478                                 }
00479 
00480                                 $msg .= sprintf( "  %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
00481                         }
00482                         return $msg;
00483 
00484                 } else {
00485                         return false;
00486                 }
00487         }
00488 
00496         public function makeHelpMsg_callback( $matches ) {
00497                 global $wgAutoloadClasses, $wgAutoloadLocalClasses;
00498 
00499                 $file = '';
00500                 if ( isset( $wgAutoloadLocalClasses[get_class( $this )] ) ) {
00501                         $file = $wgAutoloadLocalClasses[get_class( $this )];
00502                 } elseif ( isset( $wgAutoloadClasses[get_class( $this )] ) ) {
00503                         $file = $wgAutoloadClasses[get_class( $this )];
00504                 }
00505 
00506                 // Do some guesswork here
00507                 $path = strstr( $file, 'includes/api/' );
00508                 if ( $path === false ) {
00509                         $path = strstr( $file, 'extensions/' );
00510                 } else {
00511                         $path = 'phase3/' . $path;
00512                 }
00513 
00514                 // Get the filename from $matches[2] instead of $file
00515                 // If they're not the same file, they're assumed to be in the
00516                 // same directory
00517                 // This is necessary to make stuff like ApiMain::getVersion()
00518                 // returning the version string for ApiBase work
00519                 if ( $path ) {
00520                         return "{$matches[0]}\n   https://svn.wikimedia.org/" .
00521                                         "viewvc/mediawiki/trunk/" . dirname( $path ) .
00522                                         "/{$matches[2]}";
00523                 }
00524                 return $matches[0];
00525         }
00526 
00531         protected function getDescription() {
00532                 return false;
00533         }
00534 
00539         protected function getExamples() {
00540                 return false;
00541         }
00542 
00550         protected function getAllowedParams() {
00551                 return false;
00552         }
00553 
00560         protected function getParamDescription() {
00561                 return false;
00562         }
00563 
00570         public function getFinalParams() {
00571                 $params = $this->getAllowedParams();
00572                 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
00573                 return $params;
00574         }
00575 
00582         public function getFinalParamDescription() {
00583                 $desc = $this->getParamDescription();
00584                 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
00585                 return $desc;
00586         }
00587 
00604         protected function getResultProperties() {
00605                 return false;
00606         }
00607 
00614         public function getFinalResultProperties() {
00615                 $properties = $this->getResultProperties();
00616                 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
00617                 return $properties;
00618         }
00619 
00624         protected static function addTokenProperties( &$props, $tokenFunctions ) {
00625                 foreach ( array_keys( $tokenFunctions ) as $token ) {
00626                         $props[''][$token . 'token'] = array(
00627                                 ApiBase::PROP_TYPE => 'string',
00628                                 ApiBase::PROP_NULLABLE => true
00629                         );
00630                 }
00631         }
00632 
00639         public function getFinalDescription() {
00640                 $desc = $this->getDescription();
00641                 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
00642                 return $desc;
00643         }
00644 
00651         public function encodeParamName( $paramName ) {
00652                 return $this->mModulePrefix . $paramName;
00653         }
00654 
00664         public function extractRequestParams( $parseLimit = true ) {
00665                 // Cache parameters, for performance and to avoid bug 24564.
00666                 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
00667                         $params = $this->getFinalParams();
00668                         $results = array();
00669 
00670                         if ( $params ) { // getFinalParams() can return false
00671                                 foreach ( $params as $paramName => $paramSettings ) {
00672                                         $results[$paramName] = $this->getParameterFromSettings(
00673                                                 $paramName, $paramSettings, $parseLimit );
00674                                 }
00675                         }
00676                         $this->mParamCache[$parseLimit] = $results;
00677                 }
00678                 return $this->mParamCache[$parseLimit];
00679         }
00680 
00687         protected function getParameter( $paramName, $parseLimit = true ) {
00688                 $params = $this->getFinalParams();
00689                 $paramSettings = $params[$paramName];
00690                 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
00691         }
00692 
00697         public function requireOnlyOneParameter( $params ) {
00698                 $required = func_get_args();
00699                 array_shift( $required );
00700                 $p = $this->getModulePrefix();
00701 
00702                 $intersection = array_intersect( array_keys( array_filter( $params,
00703                         array( $this, "parameterNotEmpty" ) ) ), $required );
00704 
00705                 if ( count( $intersection ) > 1 ) {
00706                         $this->dieUsage( "The parameters {$p}" . implode( ", {$p}",  $intersection ) . ' can not be used together', "{$p}invalidparammix" );
00707                 } elseif ( count( $intersection ) == 0 ) {
00708                         $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
00709                 }
00710         }
00711 
00718         public function getRequireOnlyOneParameterErrorMessages( $params ) {
00719                 $p = $this->getModulePrefix();
00720                 $params = implode( ", {$p}", $params );
00721 
00722                 return array(
00723                         array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
00724                         array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
00725                 );
00726         }
00727 
00733         public function requireMaxOneParameter( $params ) {
00734                 $required = func_get_args();
00735                 array_shift( $required );
00736                 $p = $this->getModulePrefix();
00737 
00738                 $intersection = array_intersect( array_keys( array_filter( $params,
00739                         array( $this, "parameterNotEmpty" ) ) ), $required );
00740 
00741                 if ( count( $intersection ) > 1 ) {
00742                         $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
00743                 }
00744         }
00745 
00752         public function getRequireMaxOneParameterErrorMessages( $params ) {
00753                 $p = $this->getModulePrefix();
00754                 $params = implode( ", {$p}", $params );
00755 
00756                 return array(
00757                         array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
00758                 );
00759         }
00760 
00769         public function getTitleOrPageId( $params, $load = false ) {
00770                 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
00771 
00772                 $pageObj = null;
00773                 if ( isset( $params['title'] ) ) {
00774                         $titleObj = Title::newFromText( $params['title'] );
00775                         if ( !$titleObj ) {
00776                                 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
00777                         }
00778                         $pageObj = WikiPage::factory( $titleObj );
00779                         if ( $load !== false ) {
00780                                 $pageObj->loadPageData( $load );
00781                         }
00782                 } elseif ( isset( $params['pageid'] ) ) {
00783                         if ( $load === false ) {
00784                                 $load = 'fromdb';
00785                         }
00786                         $pageObj = WikiPage::newFromID( $params['pageid'], $load );
00787                         if ( !$pageObj ) {
00788                                 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
00789                         }
00790                 }
00791 
00792                 return $pageObj;
00793         }
00794 
00798         public function getTitleOrPageIdErrorMessage() {
00799                 return array_merge(
00800                         $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
00801                         array(
00802                                 array( 'invalidtitle', 'title' ),
00803                                 array( 'nosuchpageid', 'pageid' ),
00804                         )
00805                 );
00806         }
00807 
00814         private function parameterNotEmpty( $x ) {
00815                 return !is_null( $x ) && $x !== false;
00816         }
00817 
00823         public static function getValidNamespaces() {
00824                 wfDeprecated( __METHOD__, '1.17' );
00825                 return MWNamespace::getValidNamespaces();
00826         }
00827 
00836         protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
00837 
00838                 $userWatching = $this->getUser()->isWatched( $titleObj );
00839 
00840                 switch ( $watchlist ) {
00841                         case 'watch':
00842                                 return true;
00843 
00844                         case 'unwatch':
00845                                 return false;
00846 
00847                         case 'preferences':
00848                                 # If the user is already watching, don't bother checking
00849                                 if ( $userWatching ) {
00850                                         return true;
00851                                 }
00852                                 # If no user option was passed, use watchdefault or watchcreation
00853                                 if ( is_null( $userOption ) ) {
00854                                         $userOption = $titleObj->exists()
00855                                                         ? 'watchdefault' : 'watchcreations';
00856                                 }
00857                                 # Watch the article based on the user preference
00858                                 return (bool)$this->getUser()->getOption( $userOption );
00859 
00860                         case 'nochange':
00861                                 return $userWatching;
00862 
00863                         default:
00864                                 return $userWatching;
00865                 }
00866         }
00867 
00874         protected function setWatch( $watch, $titleObj, $userOption = null ) {
00875                 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
00876                 if ( $value === null ) {
00877                         return;
00878                 }
00879 
00880                 $user = $this->getUser();
00881                 if ( $value ) {
00882                         WatchAction::doWatch( $titleObj, $user );
00883                 } else {
00884                         WatchAction::doUnwatch( $titleObj, $user );
00885                 }
00886         }
00887 
00897         protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
00898                 // Some classes may decide to change parameter names
00899                 $encParamName = $this->encodeParamName( $paramName );
00900 
00901                 if ( !is_array( $paramSettings ) ) {
00902                         $default = $paramSettings;
00903                         $multi = false;
00904                         $type = gettype( $paramSettings );
00905                         $dupes = false;
00906                         $deprecated = false;
00907                         $required = false;
00908                 } else {
00909                         $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
00910                         $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
00911                         $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
00912                         $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false;
00913                         $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false;
00914                         $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? $paramSettings[self::PARAM_REQUIRED] : false;
00915 
00916                         // When type is not given, and no choices, the type is the same as $default
00917                         if ( !isset( $type ) ) {
00918                                 if ( isset( $default ) ) {
00919                                         $type = gettype( $default );
00920                                 } else {
00921                                         $type = 'NULL'; // allow everything
00922                                 }
00923                         }
00924                 }
00925 
00926                 if ( $type == 'boolean' ) {
00927                         if ( isset( $default ) && $default !== false ) {
00928                                 // Having a default value of anything other than 'false' is not allowed
00929                                 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
00930                         }
00931 
00932                         $value = $this->getRequest()->getCheck( $encParamName );
00933                 } else {
00934                         $value = $this->getRequest()->getVal( $encParamName, $default );
00935 
00936                         if ( isset( $value ) && $type == 'namespace' ) {
00937                                 $type = MWNamespace::getValidNamespaces();
00938                         }
00939                 }
00940 
00941                 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
00942                         $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null );
00943                 }
00944 
00945                 // More validation only when choices were not given
00946                 // choices were validated in parseMultiValue()
00947                 if ( isset( $value ) ) {
00948                         if ( !is_array( $type ) ) {
00949                                 switch ( $type ) {
00950                                         case 'NULL': // nothing to do
00951                                                 break;
00952                                         case 'string':
00953                                                 if ( $required && $value === '' ) {
00954                                                         $this->dieUsageMsg( array( 'missingparam', $paramName ) );
00955                                                 }
00956 
00957                                                 break;
00958                                         case 'integer': // Force everything using intval() and optionally validate limits
00959                                                 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
00960                                                 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
00961                                                 $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] )
00962                                                                 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
00963 
00964                                                 if ( is_array( $value ) ) {
00965                                                         $value = array_map( 'intval', $value );
00966                                                         if ( !is_null( $min ) || !is_null( $max ) ) {
00967                                                                 foreach ( $value as &$v ) {
00968                                                                         $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
00969                                                                 }
00970                                                         }
00971                                                 } else {
00972                                                         $value = intval( $value );
00973                                                         if ( !is_null( $min ) || !is_null( $max ) ) {
00974                                                                 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
00975                                                         }
00976                                                 }
00977                                                 break;
00978                                         case 'limit':
00979                                                 if ( !$parseLimit ) {
00980                                                         // Don't do any validation whatsoever
00981                                                         break;
00982                                                 }
00983                                                 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
00984                                                         ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
00985                                                 }
00986                                                 if ( $multi ) {
00987                                                         ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
00988                                                 }
00989                                                 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
00990                                                 if ( $value == 'max' ) {
00991                                                         $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
00992                                                         $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
00993                                                 } else {
00994                                                         $value = intval( $value );
00995                                                         $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
00996                                                 }
00997                                                 break;
00998                                         case 'boolean':
00999                                                 if ( $multi ) {
01000                                                         ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
01001                                                 }
01002                                                 break;
01003                                         case 'timestamp':
01004                                                 if ( is_array( $value ) ) {
01005                                                         foreach ( $value as $key => $val ) {
01006                                                                 $value[$key] = $this->validateTimestamp( $val, $encParamName );
01007                                                         }
01008                                                 } else {
01009                                                         $value = $this->validateTimestamp( $value, $encParamName );
01010                                                 }
01011                                                 break;
01012                                         case 'user':
01013                                                 if ( !is_array( $value ) ) {
01014                                                         $value = array( $value );
01015                                                 }
01016 
01017                                                 foreach ( $value as $key => $val ) {
01018                                                         $title = Title::makeTitleSafe( NS_USER, $val );
01019                                                         if ( is_null( $title ) ) {
01020                                                                 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
01021                                                         }
01022                                                         $value[$key] = $title->getText();
01023                                                 }
01024 
01025                                                 if ( !$multi ) {
01026                                                         $value = $value[0];
01027                                                 }
01028                                                 break;
01029                                         default:
01030                                                 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
01031                                 }
01032                         }
01033 
01034                         // Throw out duplicates if requested
01035                         if ( is_array( $value ) && !$dupes ) {
01036                                 $value = array_unique( $value );
01037                         }
01038 
01039                         // Set a warning if a deprecated parameter has been passed
01040                         if ( $deprecated && $value !== false ) {
01041                                 $this->setWarning( "The $encParamName parameter has been deprecated." );
01042                         }
01043                 } elseif ( $required ) {
01044                         $this->dieUsageMsg( array( 'missingparam', $paramName ) );
01045                 }
01046 
01047                 return $value;
01048         }
01049 
01063         protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
01064                 if ( trim( $value ) === '' && $allowMultiple ) {
01065                         return array();
01066                 }
01067 
01068                 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
01069                 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
01070                 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
01071                                 self::LIMIT_SML2 : self::LIMIT_SML1;
01072 
01073                 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
01074                         $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
01075                 }
01076 
01077                 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
01078                         // Bug 33482 - Allow entries with | in them for non-multiple values
01079                         if ( in_array( $value, $allowedValues ) ) {
01080                                 return $value;
01081                         }
01082 
01083                         $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
01084                         $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
01085                 }
01086 
01087                 if ( is_array( $allowedValues ) ) {
01088                         // Check for unknown values
01089                         $unknown = array_diff( $valuesList, $allowedValues );
01090                         if ( count( $unknown ) ) {
01091                                 if ( $allowMultiple ) {
01092                                         $s = count( $unknown ) > 1 ? 's' : '';
01093                                         $vals = implode( ", ", $unknown );
01094                                         $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
01095                                 } else {
01096                                         $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
01097                                 }
01098                         }
01099                         // Now throw them out
01100                         $valuesList = array_intersect( $valuesList, $allowedValues );
01101                 }
01102 
01103                 return $allowMultiple ? $valuesList : $valuesList[0];
01104         }
01105 
01116         function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
01117                 if ( !is_null( $min ) && $value < $min ) {
01118 
01119                         $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
01120                         $this->warnOrDie( $msg, $enforceLimits );
01121                         $value = $min;
01122                 }
01123 
01124                 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
01125                 if ( $this->getMain()->isInternalMode() ) {
01126                         return;
01127                 }
01128 
01129                 // Optimization: do not check user's bot status unless really needed -- skips db query
01130                 // assumes $botMax >= $max
01131                 if ( !is_null( $max ) && $value > $max ) {
01132                         if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
01133                                 if ( $value > $botMax ) {
01134                                         $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
01135                                         $this->warnOrDie( $msg, $enforceLimits );
01136                                         $value = $botMax;
01137                                 }
01138                         } else {
01139                                 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
01140                                 $this->warnOrDie( $msg, $enforceLimits );
01141                                 $value = $max;
01142                         }
01143                 }
01144         }
01145 
01151         function validateTimestamp( $value, $paramName ) {
01152                 $value = wfTimestamp( TS_UNIX, $value );
01153                 if ( $value === 0 ) {
01154                         $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" );
01155                 }
01156                 return wfTimestamp( TS_MW, $value );
01157         }
01158 
01165         private function warnOrDie( $msg, $enforceLimits = false ) {
01166                 if ( $enforceLimits ) {
01167                         $this->dieUsage( $msg, 'integeroutofrange' );
01168                 } else {
01169                         $this->setWarning( $msg );
01170                 }
01171         }
01172 
01179         public static function truncateArray( &$arr, $limit ) {
01180                 $modified = false;
01181                 while ( count( $arr ) > $limit ) {
01182                         array_pop( $arr );
01183                         $modified = true;
01184                 }
01185                 return $modified;
01186         }
01187 
01200         public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
01201                 Profiler::instance()->close();
01202                 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
01203         }
01204 
01208         public static $messageMap = array(
01209                 // This one MUST be present, or dieUsageMsg() will recurse infinitely
01210                 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
01211                 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
01212 
01213                 // Messages from Title::getUserPermissionsErrors()
01214                 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
01215                 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
01216                 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
01217                 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
01218                 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
01219                 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
01220                 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
01221                 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
01222                 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
01223                 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
01224                 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
01225                 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
01226                 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
01227                 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
01228                 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
01229                 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
01230                 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
01231                 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
01232 
01233                 // Miscellaneous interface messages
01234                 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
01235                 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
01236                 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
01237                 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
01238                 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
01239                 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
01240                 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
01241                 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
01242                 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
01243                 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
01244                 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
01245                 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
01246                 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
01247                 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
01248                 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
01249                 // 'badarticleerror' => shouldn't happen
01250                 // 'badtitletext' => shouldn't happen
01251                 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
01252                 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
01253                 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
01254                 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
01255                 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
01256                 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
01257                 '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." ),
01258                 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
01259                 '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" ),
01260                 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
01261                 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
01262                 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
01263                 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
01264                 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
01265                 '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" ),
01266                 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
01267                 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
01268                 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
01269                 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
01270                 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
01271                 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
01272                 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01273                 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01274                 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
01275                 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
01276                 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
01277 
01278                 // API-specific messages
01279                 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
01280                 '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" ),
01281                 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
01282                 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
01283                 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
01284                 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
01285                 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
01286                 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
01287                 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
01288                 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
01289                 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
01290                 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
01291                 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
01292                 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
01293                 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
01294                 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
01295                 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
01296                 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
01297                 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
01298                 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
01299                 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
01300                 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
01301                 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
01302                 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
01303                 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
01304                 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
01305                 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
01306                 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
01307                 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
01308                 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
01309                 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
01310                 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
01311                 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
01312                 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
01313                 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
01314                 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
01315                 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
01316                 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
01317                 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
01318                 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
01319                 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
01320                 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
01321                 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
01322                 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
01323                 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
01324                 '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.' ),
01325                 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
01326 
01327                 // ApiEditPage messages
01328                 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
01329                 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
01330                 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
01331                 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
01332                 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
01333                 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
01334                 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
01335                 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
01336                 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
01337                 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
01338                 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
01339                 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
01340                 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
01341                 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
01342 
01343                 // Messages from WikiPage::doEit()
01344                 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
01345                 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
01346                 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
01347                 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
01348 
01349                 // uploadMsgs
01350                 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
01351                 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
01352                 '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' ),
01353                 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled.  Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
01354                 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
01355 
01356                 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
01357                 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
01358                 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
01359                 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
01360 
01361                 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
01362         );
01363 
01367         public function dieReadOnly() {
01368                 $parsed = $this->parseMsg( array( 'readonlytext' ) );
01369                 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
01370                         array( 'readonlyreason' => wfReadOnlyReason() ) );
01371         }
01372 
01377         public function dieUsageMsg( $error ) {
01378                 # most of the time we send a 1 element, so we might as well send it as
01379                 # a string and make this an array here.
01380                 if( is_string( $error ) ) {
01381                         $error = array( $error );
01382                 }
01383                 $parsed = $this->parseMsg( $error );
01384                 $this->dieUsage( $parsed['info'], $parsed['code'] );
01385         }
01386 
01392         public function parseMsg( $error ) {
01393                 $error = (array)$error; // It seems strings sometimes make their way in here
01394                 $key = array_shift( $error );
01395 
01396                 // Check whether the error array was nested
01397                 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
01398                 if( is_array( $key ) ){
01399                         $error = $key;
01400                         $key = array_shift( $error );
01401                 }
01402 
01403                 if ( isset( self::$messageMap[$key] ) ) {
01404                         return array(
01405                                 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
01406                                 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
01407                         );
01408                 }
01409 
01410                 // If the key isn't present, throw an "unknown error"
01411                 return $this->parseMsg( array( 'unknownerror', $key ) );
01412         }
01413 
01419         protected static function dieDebug( $method, $message ) {
01420                 wfDebugDieBacktrace( "Internal error in $method: $message" );
01421         }
01422 
01427         public function shouldCheckMaxlag() {
01428                 return true;
01429         }
01430 
01435         public function isReadMode() {
01436                 return true;
01437         }
01442         public function isWriteMode() {
01443                 return false;
01444         }
01445 
01450         public function mustBePosted() {
01451                 return false;
01452         }
01453 
01460         public function needsToken() {
01461                 return false;
01462         }
01463 
01472         public function getTokenSalt() {
01473                 return false;
01474         }
01475 
01482         public function getWatchlistUser( $params ) {
01483                 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
01484                         $user = User::newFromName( $params['owner'], false );
01485                         if ( !($user && $user->getId()) ) {
01486                                 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
01487                         }
01488                         $token = $user->getOption( 'watchlisttoken' );
01489                         if ( $token == '' || $token != $params['token'] ) {
01490                                 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
01491                         }
01492                 } else {
01493                         if ( !$this->getUser()->isLoggedIn() ) {
01494                                 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
01495                         }
01496                         $user = $this->getUser();
01497                 }
01498                 return $user;
01499         }
01500 
01504         public function getHelpUrls() {
01505                 return false;
01506         }
01507 
01512         public function getPossibleErrors() {
01513                 $ret = array();
01514 
01515                 $params = $this->getFinalParams();
01516                 if ( $params ) {
01517                         foreach ( $params as $paramName => $paramSettings ) {
01518                                 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) ) {
01519                                         $ret[] = array( 'missingparam', $paramName );
01520                                 }
01521                         }
01522                 }
01523 
01524                 if ( $this->mustBePosted() ) {
01525                         $ret[] = array( 'mustbeposted', $this->getModuleName() );
01526                 }
01527 
01528                 if ( $this->isReadMode() ) {
01529                         $ret[] = array( 'readrequired' );
01530                 }
01531 
01532                 if ( $this->isWriteMode() ) {
01533                         $ret[] = array( 'writerequired' );
01534                         $ret[] = array( 'writedisabled' );
01535                 }
01536 
01537                 if ( $this->needsToken() ) {
01538                         $ret[] = array( 'missingparam', 'token' );
01539                         $ret[] = array( 'sessionfailure' );
01540                 }
01541 
01542                 return $ret;
01543         }
01544 
01550         public function parseErrors( $errors ) {
01551                 $ret = array();
01552 
01553                 foreach ( $errors as $row ) {
01554                         if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
01555                                 $ret[] = $row;
01556                         } else {
01557                                 $ret[] = $this->parseMsg( $row );
01558                         }
01559                 }
01560                 return $ret;
01561         }
01562 
01566         private $mTimeIn = 0, $mModuleTime = 0;
01567 
01571         public function profileIn() {
01572                 if ( $this->mTimeIn !== 0 ) {
01573                         ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
01574                 }
01575                 $this->mTimeIn = microtime( true );
01576                 wfProfileIn( $this->getModuleProfileName() );
01577         }
01578 
01582         public function profileOut() {
01583                 if ( $this->mTimeIn === 0 ) {
01584                         ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
01585                 }
01586                 if ( $this->mDBTimeIn !== 0 ) {
01587                         ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
01588                 }
01589 
01590                 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
01591                 $this->mTimeIn = 0;
01592                 wfProfileOut( $this->getModuleProfileName() );
01593         }
01594 
01599         public function safeProfileOut() {
01600                 if ( $this->mTimeIn !== 0 ) {
01601                         if ( $this->mDBTimeIn !== 0 ) {
01602                                 $this->profileDBOut();
01603                         }
01604                         $this->profileOut();
01605                 }
01606         }
01607 
01612         public function getProfileTime() {
01613                 if ( $this->mTimeIn !== 0 ) {
01614                         ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
01615                 }
01616                 return $this->mModuleTime;
01617         }
01618 
01622         private $mDBTimeIn = 0, $mDBTime = 0;
01623 
01627         public function profileDBIn() {
01628                 if ( $this->mTimeIn === 0 ) {
01629                         ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
01630                 }
01631                 if ( $this->mDBTimeIn !== 0 ) {
01632                         ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
01633                 }
01634                 $this->mDBTimeIn = microtime( true );
01635                 wfProfileIn( $this->getModuleProfileName( true ) );
01636         }
01637 
01641         public function profileDBOut() {
01642                 if ( $this->mTimeIn === 0 ) {
01643                         ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
01644                 }
01645                 if ( $this->mDBTimeIn === 0 ) {
01646                         ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
01647                 }
01648 
01649                 $time = microtime( true ) - $this->mDBTimeIn;
01650                 $this->mDBTimeIn = 0;
01651 
01652                 $this->mDBTime += $time;
01653                 $this->getMain()->mDBTime += $time;
01654                 wfProfileOut( $this->getModuleProfileName( true ) );
01655         }
01656 
01661         public function getProfileDBTime() {
01662                 if ( $this->mDBTimeIn !== 0 ) {
01663                         ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
01664                 }
01665                 return $this->mDBTime;
01666         }
01667 
01671         protected function getDB() {
01672                 return wfGetDB( DB_SLAVE, 'api' );
01673         }
01674 
01681         public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
01682                 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
01683                 var_export( $value );
01684                 if ( $backtrace ) {
01685                         print "\n" . wfBacktrace();
01686                 }
01687                 print "\n</pre>\n";
01688         }
01689 
01694         public static function getBaseVersion() {
01695                 return __CLASS__ . ': $Id$';
01696         }
01697 }