MediaWiki
master
|
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 if ( !$titleObj->canExist() ) { 00779 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' ); 00780 } 00781 $pageObj = WikiPage::factory( $titleObj ); 00782 if ( $load !== false ) { 00783 $pageObj->loadPageData( $load ); 00784 } 00785 } elseif ( isset( $params['pageid'] ) ) { 00786 if ( $load === false ) { 00787 $load = 'fromdb'; 00788 } 00789 $pageObj = WikiPage::newFromID( $params['pageid'], $load ); 00790 if ( !$pageObj ) { 00791 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) ); 00792 } 00793 } 00794 00795 return $pageObj; 00796 } 00797 00801 public function getTitleOrPageIdErrorMessage() { 00802 return array_merge( 00803 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ), 00804 array( 00805 array( 'invalidtitle', 'title' ), 00806 array( 'nosuchpageid', 'pageid' ), 00807 ) 00808 ); 00809 } 00810 00817 private function parameterNotEmpty( $x ) { 00818 return !is_null( $x ) && $x !== false; 00819 } 00820 00826 public static function getValidNamespaces() { 00827 wfDeprecated( __METHOD__, '1.17' ); 00828 return MWNamespace::getValidNamespaces(); 00829 } 00830 00839 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) { 00840 00841 $userWatching = $this->getUser()->isWatched( $titleObj ); 00842 00843 switch ( $watchlist ) { 00844 case 'watch': 00845 return true; 00846 00847 case 'unwatch': 00848 return false; 00849 00850 case 'preferences': 00851 # If the user is already watching, don't bother checking 00852 if ( $userWatching ) { 00853 return true; 00854 } 00855 # If no user option was passed, use watchdefault or watchcreation 00856 if ( is_null( $userOption ) ) { 00857 $userOption = $titleObj->exists() 00858 ? 'watchdefault' : 'watchcreations'; 00859 } 00860 # Watch the article based on the user preference 00861 return (bool)$this->getUser()->getOption( $userOption ); 00862 00863 case 'nochange': 00864 return $userWatching; 00865 00866 default: 00867 return $userWatching; 00868 } 00869 } 00870 00877 protected function setWatch( $watch, $titleObj, $userOption = null ) { 00878 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption ); 00879 if ( $value === null ) { 00880 return; 00881 } 00882 00883 $user = $this->getUser(); 00884 if ( $value ) { 00885 WatchAction::doWatch( $titleObj, $user ); 00886 } else { 00887 WatchAction::doUnwatch( $titleObj, $user ); 00888 } 00889 } 00890 00900 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) { 00901 // Some classes may decide to change parameter names 00902 $encParamName = $this->encodeParamName( $paramName ); 00903 00904 if ( !is_array( $paramSettings ) ) { 00905 $default = $paramSettings; 00906 $multi = false; 00907 $type = gettype( $paramSettings ); 00908 $dupes = false; 00909 $deprecated = false; 00910 $required = false; 00911 } else { 00912 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null; 00913 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false; 00914 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null; 00915 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false; 00916 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false; 00917 $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? $paramSettings[self::PARAM_REQUIRED] : false; 00918 00919 // When type is not given, and no choices, the type is the same as $default 00920 if ( !isset( $type ) ) { 00921 if ( isset( $default ) ) { 00922 $type = gettype( $default ); 00923 } else { 00924 $type = 'NULL'; // allow everything 00925 } 00926 } 00927 } 00928 00929 if ( $type == 'boolean' ) { 00930 if ( isset( $default ) && $default !== false ) { 00931 // Having a default value of anything other than 'false' is not allowed 00932 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." ); 00933 } 00934 00935 $value = $this->getMain()->getCheck( $encParamName ); 00936 } else { 00937 $value = $this->getMain()->getVal( $encParamName, $default ); 00938 00939 if ( isset( $value ) && $type == 'namespace' ) { 00940 $type = MWNamespace::getValidNamespaces(); 00941 } 00942 } 00943 00944 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) { 00945 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null ); 00946 } 00947 00948 // More validation only when choices were not given 00949 // choices were validated in parseMultiValue() 00950 if ( isset( $value ) ) { 00951 if ( !is_array( $type ) ) { 00952 switch ( $type ) { 00953 case 'NULL': // nothing to do 00954 break; 00955 case 'string': 00956 if ( $required && $value === '' ) { 00957 $this->dieUsageMsg( array( 'missingparam', $paramName ) ); 00958 } 00959 00960 break; 00961 case 'integer': // Force everything using intval() and optionally validate limits 00962 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null; 00963 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null; 00964 $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] ) 00965 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false; 00966 00967 if ( is_array( $value ) ) { 00968 $value = array_map( 'intval', $value ); 00969 if ( !is_null( $min ) || !is_null( $max ) ) { 00970 foreach ( $value as &$v ) { 00971 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits ); 00972 } 00973 } 00974 } else { 00975 $value = intval( $value ); 00976 if ( !is_null( $min ) || !is_null( $max ) ) { 00977 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits ); 00978 } 00979 } 00980 break; 00981 case 'limit': 00982 if ( !$parseLimit ) { 00983 // Don't do any validation whatsoever 00984 break; 00985 } 00986 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) { 00987 ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" ); 00988 } 00989 if ( $multi ) { 00990 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" ); 00991 } 00992 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0; 00993 if ( $value == 'max' ) { 00994 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX]; 00995 $this->getResult()->setParsedLimit( $this->getModuleName(), $value ); 00996 } else { 00997 $value = intval( $value ); 00998 $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] ); 00999 } 01000 break; 01001 case 'boolean': 01002 if ( $multi ) { 01003 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" ); 01004 } 01005 break; 01006 case 'timestamp': 01007 if ( is_array( $value ) ) { 01008 foreach ( $value as $key => $val ) { 01009 $value[$key] = $this->validateTimestamp( $val, $encParamName ); 01010 } 01011 } else { 01012 $value = $this->validateTimestamp( $value, $encParamName ); 01013 } 01014 break; 01015 case 'user': 01016 if ( !is_array( $value ) ) { 01017 $value = array( $value ); 01018 } 01019 01020 foreach ( $value as $key => $val ) { 01021 $title = Title::makeTitleSafe( NS_USER, $val ); 01022 if ( is_null( $title ) ) { 01023 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" ); 01024 } 01025 $value[$key] = $title->getText(); 01026 } 01027 01028 if ( !$multi ) { 01029 $value = $value[0]; 01030 } 01031 break; 01032 default: 01033 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" ); 01034 } 01035 } 01036 01037 // Throw out duplicates if requested 01038 if ( is_array( $value ) && !$dupes ) { 01039 $value = array_unique( $value ); 01040 } 01041 01042 // Set a warning if a deprecated parameter has been passed 01043 if ( $deprecated && $value !== false ) { 01044 $this->setWarning( "The $encParamName parameter has been deprecated." ); 01045 } 01046 } elseif ( $required ) { 01047 $this->dieUsageMsg( array( 'missingparam', $paramName ) ); 01048 } 01049 01050 return $value; 01051 } 01052 01066 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) { 01067 if ( trim( $value ) === '' && $allowMultiple ) { 01068 return array(); 01069 } 01070 01071 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser 01072 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 ); 01073 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ? 01074 self::LIMIT_SML2 : self::LIMIT_SML1; 01075 01076 if ( self::truncateArray( $valuesList, $sizeLimit ) ) { 01077 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" ); 01078 } 01079 01080 if ( !$allowMultiple && count( $valuesList ) != 1 ) { 01081 // Bug 33482 - Allow entries with | in them for non-multiple values 01082 if ( in_array( $value, $allowedValues ) ) { 01083 return $value; 01084 } 01085 01086 $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : ''; 01087 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" ); 01088 } 01089 01090 if ( is_array( $allowedValues ) ) { 01091 // Check for unknown values 01092 $unknown = array_diff( $valuesList, $allowedValues ); 01093 if ( count( $unknown ) ) { 01094 if ( $allowMultiple ) { 01095 $s = count( $unknown ) > 1 ? 's' : ''; 01096 $vals = implode( ", ", $unknown ); 01097 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" ); 01098 } else { 01099 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" ); 01100 } 01101 } 01102 // Now throw them out 01103 $valuesList = array_intersect( $valuesList, $allowedValues ); 01104 } 01105 01106 return $allowMultiple ? $valuesList : $valuesList[0]; 01107 } 01108 01119 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) { 01120 if ( !is_null( $min ) && $value < $min ) { 01121 01122 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)"; 01123 $this->warnOrDie( $msg, $enforceLimits ); 01124 $value = $min; 01125 } 01126 01127 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode 01128 if ( $this->getMain()->isInternalMode() ) { 01129 return; 01130 } 01131 01132 // Optimization: do not check user's bot status unless really needed -- skips db query 01133 // assumes $botMax >= $max 01134 if ( !is_null( $max ) && $value > $max ) { 01135 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) { 01136 if ( $value > $botMax ) { 01137 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops"; 01138 $this->warnOrDie( $msg, $enforceLimits ); 01139 $value = $botMax; 01140 } 01141 } else { 01142 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users"; 01143 $this->warnOrDie( $msg, $enforceLimits ); 01144 $value = $max; 01145 } 01146 } 01147 } 01148 01154 function validateTimestamp( $value, $paramName ) { 01155 $value = wfTimestamp( TS_UNIX, $value ); 01156 if ( $value === 0 ) { 01157 $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" ); 01158 } 01159 return wfTimestamp( TS_MW, $value ); 01160 } 01161 01168 private function warnOrDie( $msg, $enforceLimits = false ) { 01169 if ( $enforceLimits ) { 01170 $this->dieUsage( $msg, 'integeroutofrange' ); 01171 } else { 01172 $this->setWarning( $msg ); 01173 } 01174 } 01175 01182 public static function truncateArray( &$arr, $limit ) { 01183 $modified = false; 01184 while ( count( $arr ) > $limit ) { 01185 array_pop( $arr ); 01186 $modified = true; 01187 } 01188 return $modified; 01189 } 01190 01203 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) { 01204 Profiler::instance()->close(); 01205 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata ); 01206 } 01207 01211 public static $messageMap = array( 01212 // This one MUST be present, or dieUsageMsg() will recurse infinitely 01213 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ), 01214 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ), 01215 01216 // Messages from Title::getUserPermissionsErrors() 01217 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ), 01218 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ), 01219 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ), 01220 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ), 01221 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ), 01222 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ), 01223 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ), 01224 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ), 01225 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message 01226 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), 01227 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ), 01228 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ), 01229 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ), 01230 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ), 01231 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ), 01232 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ), 01233 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ), 01234 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ), 01235 01236 // Miscellaneous interface messages 01237 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ), 01238 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ), 01239 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ), 01240 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ), 01241 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ), 01242 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ), 01243 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ), 01244 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ), 01245 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ), 01246 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ), 01247 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ), 01248 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ), 01249 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ), 01250 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ), 01251 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ), 01252 // 'badarticleerror' => shouldn't happen 01253 // 'badtitletext' => shouldn't happen 01254 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ), 01255 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ), 01256 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ), 01257 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ), 01258 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ), 01259 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ), 01260 '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." ), 01261 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ), 01262 '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" ), 01263 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ), 01264 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ), 01265 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ), 01266 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ), 01267 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ), 01268 '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" ), 01269 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ), 01270 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ), 01271 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ), 01272 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ), 01273 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ), 01274 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ), 01275 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ), 01276 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ), 01277 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ), 01278 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ), 01279 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ), 01280 01281 // API-specific messages 01282 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ), 01283 '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" ), 01284 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ), 01285 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ), 01286 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ), 01287 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ), 01288 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ), 01289 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ), 01290 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ), 01291 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ), 01292 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ), 01293 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ), 01294 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ), 01295 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ), 01296 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ), 01297 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ), 01298 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ), 01299 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ), 01300 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ), 01301 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ), 01302 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ), 01303 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ), 01304 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ), 01305 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ), 01306 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ), 01307 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ), 01308 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ), 01309 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ), 01310 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ), 01311 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ), 01312 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ), 01313 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ), 01314 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ), 01315 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ), 01316 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ), 01317 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ), 01318 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ), 01319 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ), 01320 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ), 01321 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ), 01322 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ), 01323 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ), 01324 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ), 01325 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ), 01326 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ), 01327 '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.' ), 01328 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ), 01329 01330 // ApiEditPage messages 01331 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ), 01332 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ), 01333 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ), 01334 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ), 01335 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ), 01336 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ), 01337 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ), 01338 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ), 01339 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ), 01340 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ), 01341 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ), 01342 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ), 01343 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ), 01344 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ), 01345 01346 // Messages from WikiPage::doEit() 01347 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ), 01348 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ), 01349 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ), 01350 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ), 01351 01352 // uploadMsgs 01353 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ), 01354 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ), 01355 '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' ), 01356 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ), 01357 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ), 01358 01359 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ), 01360 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ), 01361 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ), 01362 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ), 01363 01364 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' ) 01365 ); 01366 01370 public function dieReadOnly() { 01371 $parsed = $this->parseMsg( array( 'readonlytext' ) ); 01372 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0, 01373 array( 'readonlyreason' => wfReadOnlyReason() ) ); 01374 } 01375 01380 public function dieUsageMsg( $error ) { 01381 # most of the time we send a 1 element, so we might as well send it as 01382 # a string and make this an array here. 01383 if( is_string( $error ) ) { 01384 $error = array( $error ); 01385 } 01386 $parsed = $this->parseMsg( $error ); 01387 $this->dieUsage( $parsed['info'], $parsed['code'] ); 01388 } 01389 01395 public function parseMsg( $error ) { 01396 $error = (array)$error; // It seems strings sometimes make their way in here 01397 $key = array_shift( $error ); 01398 01399 // Check whether the error array was nested 01400 // array( array( <code>, <params> ), array( <another_code>, <params> ) ) 01401 if( is_array( $key ) ){ 01402 $error = $key; 01403 $key = array_shift( $error ); 01404 } 01405 01406 if ( isset( self::$messageMap[$key] ) ) { 01407 return array( 01408 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ), 01409 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error ) 01410 ); 01411 } 01412 01413 // If the key isn't present, throw an "unknown error" 01414 return $this->parseMsg( array( 'unknownerror', $key ) ); 01415 } 01416 01422 protected static function dieDebug( $method, $message ) { 01423 wfDebugDieBacktrace( "Internal error in $method: $message" ); 01424 } 01425 01430 public function shouldCheckMaxlag() { 01431 return true; 01432 } 01433 01438 public function isReadMode() { 01439 return true; 01440 } 01445 public function isWriteMode() { 01446 return false; 01447 } 01448 01453 public function mustBePosted() { 01454 return false; 01455 } 01456 01463 public function needsToken() { 01464 return false; 01465 } 01466 01475 public function getTokenSalt() { 01476 return false; 01477 } 01478 01485 public function getWatchlistUser( $params ) { 01486 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) { 01487 $user = User::newFromName( $params['owner'], false ); 01488 if ( !($user && $user->getId()) ) { 01489 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' ); 01490 } 01491 $token = $user->getOption( 'watchlisttoken' ); 01492 if ( $token == '' || $token != $params['token'] ) { 01493 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' ); 01494 } 01495 } else { 01496 if ( !$this->getUser()->isLoggedIn() ) { 01497 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' ); 01498 } 01499 $user = $this->getUser(); 01500 } 01501 return $user; 01502 } 01503 01507 public function getHelpUrls() { 01508 return false; 01509 } 01510 01515 public function getPossibleErrors() { 01516 $ret = array(); 01517 01518 $params = $this->getFinalParams(); 01519 if ( $params ) { 01520 foreach ( $params as $paramName => $paramSettings ) { 01521 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) ) { 01522 $ret[] = array( 'missingparam', $paramName ); 01523 } 01524 } 01525 } 01526 01527 if ( $this->mustBePosted() ) { 01528 $ret[] = array( 'mustbeposted', $this->getModuleName() ); 01529 } 01530 01531 if ( $this->isReadMode() ) { 01532 $ret[] = array( 'readrequired' ); 01533 } 01534 01535 if ( $this->isWriteMode() ) { 01536 $ret[] = array( 'writerequired' ); 01537 $ret[] = array( 'writedisabled' ); 01538 } 01539 01540 if ( $this->needsToken() ) { 01541 $ret[] = array( 'missingparam', 'token' ); 01542 $ret[] = array( 'sessionfailure' ); 01543 } 01544 01545 return $ret; 01546 } 01547 01553 public function parseErrors( $errors ) { 01554 $ret = array(); 01555 01556 foreach ( $errors as $row ) { 01557 if ( isset( $row['code'] ) && isset( $row['info'] ) ) { 01558 $ret[] = $row; 01559 } else { 01560 $ret[] = $this->parseMsg( $row ); 01561 } 01562 } 01563 return $ret; 01564 } 01565 01569 private $mTimeIn = 0, $mModuleTime = 0; 01570 01574 public function profileIn() { 01575 if ( $this->mTimeIn !== 0 ) { 01576 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' ); 01577 } 01578 $this->mTimeIn = microtime( true ); 01579 wfProfileIn( $this->getModuleProfileName() ); 01580 } 01581 01585 public function profileOut() { 01586 if ( $this->mTimeIn === 0 ) { 01587 ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' ); 01588 } 01589 if ( $this->mDBTimeIn !== 0 ) { 01590 ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' ); 01591 } 01592 01593 $this->mModuleTime += microtime( true ) - $this->mTimeIn; 01594 $this->mTimeIn = 0; 01595 wfProfileOut( $this->getModuleProfileName() ); 01596 } 01597 01602 public function safeProfileOut() { 01603 if ( $this->mTimeIn !== 0 ) { 01604 if ( $this->mDBTimeIn !== 0 ) { 01605 $this->profileDBOut(); 01606 } 01607 $this->profileOut(); 01608 } 01609 } 01610 01615 public function getProfileTime() { 01616 if ( $this->mTimeIn !== 0 ) { 01617 ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' ); 01618 } 01619 return $this->mModuleTime; 01620 } 01621 01625 private $mDBTimeIn = 0, $mDBTime = 0; 01626 01630 public function profileDBIn() { 01631 if ( $this->mTimeIn === 0 ) { 01632 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' ); 01633 } 01634 if ( $this->mDBTimeIn !== 0 ) { 01635 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' ); 01636 } 01637 $this->mDBTimeIn = microtime( true ); 01638 wfProfileIn( $this->getModuleProfileName( true ) ); 01639 } 01640 01644 public function profileDBOut() { 01645 if ( $this->mTimeIn === 0 ) { 01646 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' ); 01647 } 01648 if ( $this->mDBTimeIn === 0 ) { 01649 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' ); 01650 } 01651 01652 $time = microtime( true ) - $this->mDBTimeIn; 01653 $this->mDBTimeIn = 0; 01654 01655 $this->mDBTime += $time; 01656 $this->getMain()->mDBTime += $time; 01657 wfProfileOut( $this->getModuleProfileName( true ) ); 01658 } 01659 01664 public function getProfileDBTime() { 01665 if ( $this->mDBTimeIn !== 0 ) { 01666 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' ); 01667 } 01668 return $this->mDBTime; 01669 } 01670 01674 protected function getDB() { 01675 return wfGetDB( DB_SLAVE, 'api' ); 01676 } 01677 01684 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) { 01685 print "\n\n<pre><b>Debugging value '$name':</b>\n\n"; 01686 var_export( $value ); 01687 if ( $backtrace ) { 01688 print "\n" . wfBacktrace(); 01689 } 01690 print "\n</pre>\n"; 01691 } 01692 01697 public static function getBaseVersion() { 01698 return __CLASS__ . ': $Id$'; 01699 } 01700 }