[ Index ] |
PHP Cross Reference of MediaWiki-1.24.0 |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * 4 * 5 * Created on Sep 5, 2006 6 * 7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com" 8 * 9 * This program is free software; you can redistribute it and/or modify 10 * it under the terms of the GNU General Public License as published by 11 * the Free Software Foundation; either version 2 of the License, or 12 * (at your option) any later version. 13 * 14 * This program is distributed in the hope that it will be useful, 15 * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 * GNU General Public License for more details. 18 * 19 * You should have received a copy of the GNU General Public License along 20 * with this program; if not, write to the Free Software Foundation, Inc., 21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 22 * http://www.gnu.org/copyleft/gpl.html 23 * 24 * @file 25 */ 26 27 /** 28 * This abstract class implements many basic API functions, and is the base of 29 * all API classes. 30 * The class functions are divided into several areas of functionality: 31 * 32 * Module parameters: Derived classes can define getAllowedParams() to specify 33 * which parameters to expect, how to parse and validate them. 34 * 35 * Profiling: various methods to allow keeping tabs on various tasks and their 36 * time costs 37 * 38 * Self-documentation: code to allow the API to document its own state 39 * 40 * @ingroup API 41 */ 42 abstract class ApiBase extends ContextSource { 43 // These constants allow modules to specify exactly how to treat incoming parameters. 44 45 // Default value of the parameter 46 const PARAM_DFLT = 0; 47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)? 48 const PARAM_ISMULTI = 1; 49 // Can be either a string type (e.g.: 'integer') or an array of allowed values 50 const PARAM_TYPE = 2; 51 // Max value allowed for a parameter. Only applies if TYPE='integer' 52 const PARAM_MAX = 3; 53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer' 54 const PARAM_MAX2 = 4; 55 // Lowest value allowed for a parameter. Only applies if TYPE='integer' 56 const PARAM_MIN = 5; 57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true 58 const PARAM_ALLOW_DUPLICATES = 6; 59 // Boolean, is the parameter deprecated (will show a warning) 60 const PARAM_DEPRECATED = 7; 61 /// @since 1.17 62 const PARAM_REQUIRED = 8; // Boolean, is the parameter required? 63 /// @since 1.17 64 // Boolean, if MIN/MAX are set, enforce (die) these? 65 // Only applies if TYPE='integer' Use with extreme caution 66 const PARAM_RANGE_ENFORCE = 9; 67 68 const LIMIT_BIG1 = 500; // Fast query, std user limit 69 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit 70 const LIMIT_SML1 = 50; // Slow query, std user limit 71 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit 72 73 /** 74 * getAllowedParams() flag: When set, the result could take longer to generate, 75 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension 76 * @since 1.21 77 */ 78 const GET_VALUES_FOR_HELP = 1; 79 80 /** @var ApiMain */ 81 private $mMainModule; 82 /** @var string */ 83 private $mModuleName, $mModulePrefix; 84 private $mSlaveDB = null; 85 private $mParamCache = array(); 86 87 /** 88 * @param ApiMain $mainModule 89 * @param string $moduleName Name of this module 90 * @param string $modulePrefix Prefix to use for parameter names 91 */ 92 public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) { 93 $this->mMainModule = $mainModule; 94 $this->mModuleName = $moduleName; 95 $this->mModulePrefix = $modulePrefix; 96 97 if ( !$this->isMain() ) { 98 $this->setContext( $mainModule->getContext() ); 99 } 100 } 101 102 103 /************************************************************************//** 104 * @name Methods to implement 105 * @{ 106 */ 107 108 /** 109 * Evaluates the parameters, performs the requested query, and sets up 110 * the result. Concrete implementations of ApiBase must override this 111 * method to provide whatever functionality their module offers. 112 * Implementations must not produce any output on their own and are not 113 * expected to handle any errors. 114 * 115 * The execute() method will be invoked directly by ApiMain immediately 116 * before the result of the module is output. Aside from the 117 * constructor, implementations should assume that no other methods 118 * will be called externally on the module before the result is 119 * processed. 120 * 121 * The result data should be stored in the ApiResult object available 122 * through getResult(). 123 */ 124 abstract public function execute(); 125 126 /** 127 * Get the module manager, or null if this module has no sub-modules 128 * @since 1.21 129 * @return ApiModuleManager 130 */ 131 public function getModuleManager() { 132 return null; 133 } 134 135 /** 136 * If the module may only be used with a certain format module, 137 * it should override this method to return an instance of that formatter. 138 * A value of null means the default format will be used. 139 * @return mixed Instance of a derived class of ApiFormatBase, or null 140 */ 141 public function getCustomPrinter() { 142 return null; 143 } 144 145 /** 146 * Returns the description string for this module 147 * @return string|array 148 */ 149 protected function getDescription() { 150 return false; 151 } 152 153 /** 154 * Returns usage examples for this module. Return false if no examples are available. 155 * @return bool|string|array 156 */ 157 protected function getExamples() { 158 return false; 159 } 160 161 /** 162 * @return bool|string|array Returns a false if the module has no help URL, 163 * else returns a (array of) string 164 */ 165 public function getHelpUrls() { 166 return false; 167 } 168 169 /** 170 * Returns an array of allowed parameters (parameter name) => (default 171 * value) or (parameter name) => (array with PARAM_* constants as keys) 172 * Don't call this function directly: use getFinalParams() to allow 173 * hooks to modify parameters as needed. 174 * 175 * Some derived classes may choose to handle an integer $flags parameter 176 * in the overriding methods. Callers of this method can pass zero or 177 * more OR-ed flags like GET_VALUES_FOR_HELP. 178 * 179 * @return array|bool 180 */ 181 protected function getAllowedParams( /* $flags = 0 */ ) { 182 // int $flags is not declared because it causes "Strict standards" 183 // warning. Most derived classes do not implement it. 184 return false; 185 } 186 187 /** 188 * Returns an array of parameter descriptions. 189 * Don't call this function directly: use getFinalParamDescription() to 190 * allow hooks to modify descriptions as needed. 191 * @return array|bool False on no parameter descriptions 192 */ 193 protected function getParamDescription() { 194 return false; 195 } 196 197 /** 198 * Indicates if this module needs maxlag to be checked 199 * @return bool 200 */ 201 public function shouldCheckMaxlag() { 202 return true; 203 } 204 205 /** 206 * Indicates whether this module requires read rights 207 * @return bool 208 */ 209 public function isReadMode() { 210 return true; 211 } 212 213 /** 214 * Indicates whether this module requires write mode 215 * @return bool 216 */ 217 public function isWriteMode() { 218 return false; 219 } 220 221 /** 222 * Indicates whether this module must be called with a POST request 223 * @return bool 224 */ 225 public function mustBePosted() { 226 return $this->needsToken() !== false; 227 } 228 229 /** 230 * Returns the token type this module requires in order to execute. 231 * 232 * Modules are strongly encouraged to use the core 'csrf' type unless they 233 * have specialized security needs. If the token type is not one of the 234 * core types, you must use the ApiQueryTokensRegisterTypes hook to 235 * register it. 236 * 237 * Returning a non-falsey value here will cause self::getFinalParams() to 238 * return a required string 'token' parameter and 239 * self::getFinalParamDescription() to ensure there is standardized 240 * documentation for it. Also, self::mustBePosted() must return true when 241 * tokens are used. 242 * 243 * In previous versions of MediaWiki, true was a valid return value. 244 * Returning true will generate errors indicating that the API module needs 245 * updating. 246 * 247 * @return string|false 248 */ 249 public function needsToken() { 250 return false; 251 } 252 253 /** 254 * Fetch the salt used in the Web UI corresponding to this module. 255 * 256 * Only override this if the Web UI uses a token with a non-constant salt. 257 * 258 * @since 1.24 259 * @param array $params All supplied parameters for the module 260 * @return string|array|null 261 */ 262 protected function getWebUITokenSalt( array $params ) { 263 return null; 264 } 265 266 /**@}*/ 267 268 /************************************************************************//** 269 * @name Data access methods 270 * @{ 271 */ 272 273 /** 274 * Get the name of the module being executed by this instance 275 * @return string 276 */ 277 public function getModuleName() { 278 return $this->mModuleName; 279 } 280 281 /** 282 * Get parameter prefix (usually two letters or an empty string). 283 * @return string 284 */ 285 public function getModulePrefix() { 286 return $this->mModulePrefix; 287 } 288 289 /** 290 * Get the main module 291 * @return ApiMain 292 */ 293 public function getMain() { 294 return $this->mMainModule; 295 } 296 297 /** 298 * Returns true if this module is the main module ($this === $this->mMainModule), 299 * false otherwise. 300 * @return bool 301 */ 302 public function isMain() { 303 return $this === $this->mMainModule; 304 } 305 306 /** 307 * Get the result object 308 * @return ApiResult 309 */ 310 public function getResult() { 311 // Main module has getResult() method overridden 312 // Safety - avoid infinite loop: 313 if ( $this->isMain() ) { 314 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' ); 315 } 316 317 return $this->getMain()->getResult(); 318 } 319 320 /** 321 * Get the result data array (read-only) 322 * @return array 323 */ 324 public function getResultData() { 325 return $this->getResult()->getData(); 326 } 327 328 /** 329 * Gets a default slave database connection object 330 * @return DatabaseBase 331 */ 332 protected function getDB() { 333 if ( !isset( $this->mSlaveDB ) ) { 334 $this->profileDBIn(); 335 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' ); 336 $this->profileDBOut(); 337 } 338 339 return $this->mSlaveDB; 340 } 341 342 /** 343 * Get final module description, after hooks have had a chance to tweak it as 344 * needed. 345 * 346 * @return array|bool False on no parameters 347 */ 348 public function getFinalDescription() { 349 $desc = $this->getDescription(); 350 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) ); 351 352 return $desc; 353 } 354 355 /** 356 * Get final list of parameters, after hooks have had a chance to 357 * tweak it as needed. 358 * 359 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP 360 * @return array|bool False on no parameters 361 * @since 1.21 $flags param added 362 */ 363 public function getFinalParams( $flags = 0 ) { 364 $params = $this->getAllowedParams( $flags ); 365 366 if ( $this->needsToken() ) { 367 $params['token'] = array( 368 ApiBase::PARAM_TYPE => 'string', 369 ApiBase::PARAM_REQUIRED => true, 370 ); 371 } 372 373 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) ); 374 375 return $params; 376 } 377 378 /** 379 * Get final parameter descriptions, after hooks have had a chance to tweak it as 380 * needed. 381 * 382 * @return array|bool False on no parameter descriptions 383 */ 384 public function getFinalParamDescription() { 385 $desc = $this->getParamDescription(); 386 387 $tokenType = $this->needsToken(); 388 if ( $tokenType ) { 389 if ( !isset( $desc['token'] ) ) { 390 $desc['token'] = array(); 391 } elseif ( !is_array( $desc['token'] ) ) { 392 // We ignore a plain-string token, because it's probably an 393 // extension that is supplying the string for BC. 394 $desc['token'] = array(); 395 } 396 array_unshift( $desc['token'], 397 "A '$tokenType' token retrieved from action=query&meta=tokens" 398 ); 399 } 400 401 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) ); 402 403 return $desc; 404 } 405 406 /**@}*/ 407 408 /************************************************************************//** 409 * @name Parameter handling 410 * @{ 411 */ 412 413 /** 414 * This method mangles parameter name based on the prefix supplied to the constructor. 415 * Override this method to change parameter name during runtime 416 * @param string $paramName Parameter name 417 * @return string Prefixed parameter name 418 */ 419 public function encodeParamName( $paramName ) { 420 return $this->mModulePrefix . $paramName; 421 } 422 423 /** 424 * Using getAllowedParams(), this function makes an array of the values 425 * provided by the user, with key being the name of the variable, and 426 * value - validated value from user or default. limits will not be 427 * parsed if $parseLimit is set to false; use this when the max 428 * limit is not definitive yet, e.g. when getting revisions. 429 * @param bool $parseLimit True by default 430 * @return array 431 */ 432 public function extractRequestParams( $parseLimit = true ) { 433 // Cache parameters, for performance and to avoid bug 24564. 434 if ( !isset( $this->mParamCache[$parseLimit] ) ) { 435 $params = $this->getFinalParams(); 436 $results = array(); 437 438 if ( $params ) { // getFinalParams() can return false 439 foreach ( $params as $paramName => $paramSettings ) { 440 $results[$paramName] = $this->getParameterFromSettings( 441 $paramName, $paramSettings, $parseLimit ); 442 } 443 } 444 $this->mParamCache[$parseLimit] = $results; 445 } 446 447 return $this->mParamCache[$parseLimit]; 448 } 449 450 /** 451 * Get a value for the given parameter 452 * @param string $paramName Parameter name 453 * @param bool $parseLimit See extractRequestParams() 454 * @return mixed Parameter value 455 */ 456 protected function getParameter( $paramName, $parseLimit = true ) { 457 $params = $this->getFinalParams(); 458 $paramSettings = $params[$paramName]; 459 460 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit ); 461 } 462 463 /** 464 * Die if none or more than one of a certain set of parameters is set and not false. 465 * 466 * @param array $params User provided set of parameters, as from $this->extractRequestParams() 467 * @param string $required,... Names of parameters of which exactly one must be set 468 */ 469 public function requireOnlyOneParameter( $params, $required /*...*/ ) { 470 $required = func_get_args(); 471 array_shift( $required ); 472 $p = $this->getModulePrefix(); 473 474 $intersection = array_intersect( array_keys( array_filter( $params, 475 array( $this, "parameterNotEmpty" ) ) ), $required ); 476 477 if ( count( $intersection ) > 1 ) { 478 $this->dieUsage( 479 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', 480 'invalidparammix' ); 481 } elseif ( count( $intersection ) == 0 ) { 482 $this->dieUsage( 483 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', 484 'missingparam' 485 ); 486 } 487 } 488 489 /** 490 * Die if more than one of a certain set of parameters is set and not false. 491 * 492 * @param array $params User provided set of parameters, as from $this->extractRequestParams() 493 * @param string $required,... Names of parameters of which at most one must be set 494 */ 495 public function requireMaxOneParameter( $params, $required /*...*/ ) { 496 $required = func_get_args(); 497 array_shift( $required ); 498 $p = $this->getModulePrefix(); 499 500 $intersection = array_intersect( array_keys( array_filter( $params, 501 array( $this, "parameterNotEmpty" ) ) ), $required ); 502 503 if ( count( $intersection ) > 1 ) { 504 $this->dieUsage( 505 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', 506 'invalidparammix' 507 ); 508 } 509 } 510 511 /** 512 * Die if none of a certain set of parameters is set and not false. 513 * 514 * @since 1.23 515 * @param array $params User provided set of parameters, as from $this->extractRequestParams() 516 * @param string $required,... Names of parameters of which at least one must be set 517 */ 518 public function requireAtLeastOneParameter( $params, $required /*...*/ ) { 519 $required = func_get_args(); 520 array_shift( $required ); 521 $p = $this->getModulePrefix(); 522 523 $intersection = array_intersect( 524 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ), 525 $required 526 ); 527 528 if ( count( $intersection ) == 0 ) { 529 $this->dieUsage( "At least one of the parameters {$p}" . 530 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" ); 531 } 532 } 533 534 /** 535 * Callback function used in requireOnlyOneParameter to check whether required parameters are set 536 * 537 * @param object $x Parameter to check is not null/false 538 * @return bool 539 */ 540 private function parameterNotEmpty( $x ) { 541 return !is_null( $x ) && $x !== false; 542 } 543 544 /** 545 * Get a WikiPage object from a title or pageid param, if possible. 546 * Can die, if no param is set or if the title or page id is not valid. 547 * 548 * @param array $params 549 * @param bool|string $load Whether load the object's state from the database: 550 * - false: don't load (if the pageid is given, it will still be loaded) 551 * - 'fromdb': load from a slave database 552 * - 'fromdbmaster': load from the master database 553 * @return WikiPage 554 */ 555 public function getTitleOrPageId( $params, $load = false ) { 556 $this->requireOnlyOneParameter( $params, 'title', 'pageid' ); 557 558 $pageObj = null; 559 if ( isset( $params['title'] ) ) { 560 $titleObj = Title::newFromText( $params['title'] ); 561 if ( !$titleObj || $titleObj->isExternal() ) { 562 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) ); 563 } 564 if ( !$titleObj->canExist() ) { 565 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' ); 566 } 567 $pageObj = WikiPage::factory( $titleObj ); 568 if ( $load !== false ) { 569 $pageObj->loadPageData( $load ); 570 } 571 } elseif ( isset( $params['pageid'] ) ) { 572 if ( $load === false ) { 573 $load = 'fromdb'; 574 } 575 $pageObj = WikiPage::newFromID( $params['pageid'], $load ); 576 if ( !$pageObj ) { 577 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) ); 578 } 579 } 580 581 return $pageObj; 582 } 583 584 /** 585 * Return true if we're to watch the page, false if not, null if no change. 586 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange' 587 * @param Title $titleObj The page under consideration 588 * @param string $userOption The user option to consider when $watchlist=preferences. 589 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist. 590 * @return bool 591 */ 592 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) { 593 594 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS ); 595 596 switch ( $watchlist ) { 597 case 'watch': 598 return true; 599 600 case 'unwatch': 601 return false; 602 603 case 'preferences': 604 # If the user is already watching, don't bother checking 605 if ( $userWatching ) { 606 return true; 607 } 608 # If no user option was passed, use watchdefault and watchcreations 609 if ( is_null( $userOption ) ) { 610 return $this->getUser()->getBoolOption( 'watchdefault' ) || 611 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists(); 612 } 613 614 # Watch the article based on the user preference 615 return $this->getUser()->getBoolOption( $userOption ); 616 617 case 'nochange': 618 return $userWatching; 619 620 default: 621 return $userWatching; 622 } 623 } 624 625 /** 626 * Using the settings determine the value for the given parameter 627 * 628 * @param string $paramName Parameter name 629 * @param array|mixed $paramSettings Default value or an array of settings 630 * using PARAM_* constants. 631 * @param bool $parseLimit Parse limit? 632 * @return mixed Parameter value 633 */ 634 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) { 635 // Some classes may decide to change parameter names 636 $encParamName = $this->encodeParamName( $paramName ); 637 638 if ( !is_array( $paramSettings ) ) { 639 $default = $paramSettings; 640 $multi = false; 641 $type = gettype( $paramSettings ); 642 $dupes = false; 643 $deprecated = false; 644 $required = false; 645 } else { 646 $default = isset( $paramSettings[self::PARAM_DFLT] ) 647 ? $paramSettings[self::PARAM_DFLT] 648 : null; 649 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) 650 ? $paramSettings[self::PARAM_ISMULTI] 651 : false; 652 $type = isset( $paramSettings[self::PARAM_TYPE] ) 653 ? $paramSettings[self::PARAM_TYPE] 654 : null; 655 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) 656 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] 657 : false; 658 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) 659 ? $paramSettings[self::PARAM_DEPRECATED] 660 : false; 661 $required = isset( $paramSettings[self::PARAM_REQUIRED] ) 662 ? $paramSettings[self::PARAM_REQUIRED] 663 : false; 664 665 // When type is not given, and no choices, the type is the same as $default 666 if ( !isset( $type ) ) { 667 if ( isset( $default ) ) { 668 $type = gettype( $default ); 669 } else { 670 $type = 'NULL'; // allow everything 671 } 672 } 673 } 674 675 if ( $type == 'boolean' ) { 676 if ( isset( $default ) && $default !== false ) { 677 // Having a default value of anything other than 'false' is not allowed 678 ApiBase::dieDebug( 679 __METHOD__, 680 "Boolean param $encParamName's default is set to '$default'. " . 681 "Boolean parameters must default to false." 682 ); 683 } 684 685 $value = $this->getMain()->getCheck( $encParamName ); 686 } elseif ( $type == 'upload' ) { 687 if ( isset( $default ) ) { 688 // Having a default value is not allowed 689 ApiBase::dieDebug( 690 __METHOD__, 691 "File upload param $encParamName's default is set to " . 692 "'$default'. File upload parameters may not have a default." ); 693 } 694 if ( $multi ) { 695 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" ); 696 } 697 $value = $this->getMain()->getUpload( $encParamName ); 698 if ( !$value->exists() ) { 699 // This will get the value without trying to normalize it 700 // (because trying to normalize a large binary file 701 // accidentally uploaded as a field fails spectacularly) 702 $value = $this->getMain()->getRequest()->unsetVal( $encParamName ); 703 if ( $value !== null ) { 704 $this->dieUsage( 705 "File upload param $encParamName is not a file upload; " . 706 "be sure to use multipart/form-data for your POST and include " . 707 "a filename in the Content-Disposition header.", 708 "badupload_{$encParamName}" 709 ); 710 } 711 } 712 } else { 713 $value = $this->getMain()->getVal( $encParamName, $default ); 714 715 if ( isset( $value ) && $type == 'namespace' ) { 716 $type = MWNamespace::getValidNamespaces(); 717 } 718 if ( isset( $value ) && $type == 'submodule' ) { 719 $type = $this->getModuleManager()->getNames( $paramName ); 720 } 721 } 722 723 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) { 724 $value = $this->parseMultiValue( 725 $encParamName, 726 $value, 727 $multi, 728 is_array( $type ) ? $type : null 729 ); 730 } 731 732 // More validation only when choices were not given 733 // choices were validated in parseMultiValue() 734 if ( isset( $value ) ) { 735 if ( !is_array( $type ) ) { 736 switch ( $type ) { 737 case 'NULL': // nothing to do 738 break; 739 case 'string': 740 if ( $required && $value === '' ) { 741 $this->dieUsageMsg( array( 'missingparam', $paramName ) ); 742 } 743 break; 744 case 'integer': // Force everything using intval() and optionally validate limits 745 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null; 746 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null; 747 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] ) 748 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false; 749 750 if ( is_array( $value ) ) { 751 $value = array_map( 'intval', $value ); 752 if ( !is_null( $min ) || !is_null( $max ) ) { 753 foreach ( $value as &$v ) { 754 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits ); 755 } 756 } 757 } else { 758 $value = intval( $value ); 759 if ( !is_null( $min ) || !is_null( $max ) ) { 760 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits ); 761 } 762 } 763 break; 764 case 'limit': 765 if ( !$parseLimit ) { 766 // Don't do any validation whatsoever 767 break; 768 } 769 if ( !isset( $paramSettings[self::PARAM_MAX] ) 770 || !isset( $paramSettings[self::PARAM_MAX2] ) 771 ) { 772 ApiBase::dieDebug( 773 __METHOD__, 774 "MAX1 or MAX2 are not defined for the limit $encParamName" 775 ); 776 } 777 if ( $multi ) { 778 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" ); 779 } 780 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0; 781 if ( $value == 'max' ) { 782 $value = $this->getMain()->canApiHighLimits() 783 ? $paramSettings[self::PARAM_MAX2] 784 : $paramSettings[self::PARAM_MAX]; 785 $this->getResult()->setParsedLimit( $this->getModuleName(), $value ); 786 } else { 787 $value = intval( $value ); 788 $this->validateLimit( 789 $paramName, 790 $value, 791 $min, 792 $paramSettings[self::PARAM_MAX], 793 $paramSettings[self::PARAM_MAX2] 794 ); 795 } 796 break; 797 case 'boolean': 798 if ( $multi ) { 799 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" ); 800 } 801 break; 802 case 'timestamp': 803 if ( is_array( $value ) ) { 804 foreach ( $value as $key => $val ) { 805 $value[$key] = $this->validateTimestamp( $val, $encParamName ); 806 } 807 } else { 808 $value = $this->validateTimestamp( $value, $encParamName ); 809 } 810 break; 811 case 'user': 812 if ( is_array( $value ) ) { 813 foreach ( $value as $key => $val ) { 814 $value[$key] = $this->validateUser( $val, $encParamName ); 815 } 816 } else { 817 $value = $this->validateUser( $value, $encParamName ); 818 } 819 break; 820 case 'upload': // nothing to do 821 break; 822 default: 823 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" ); 824 } 825 } 826 827 // Throw out duplicates if requested 828 if ( !$dupes && is_array( $value ) ) { 829 $value = array_unique( $value ); 830 } 831 832 // Set a warning if a deprecated parameter has been passed 833 if ( $deprecated && $value !== false ) { 834 $this->setWarning( "The $encParamName parameter has been deprecated." ); 835 } 836 } elseif ( $required ) { 837 $this->dieUsageMsg( array( 'missingparam', $paramName ) ); 838 } 839 840 return $value; 841 } 842 843 /** 844 * Return an array of values that were given in a 'a|b|c' notation, 845 * after it optionally validates them against the list allowed values. 846 * 847 * @param string $valueName The name of the parameter (for error 848 * reporting) 849 * @param mixed $value The value being parsed 850 * @param bool $allowMultiple Can $value contain more than one value 851 * separated by '|'? 852 * @param string[]|null $allowedValues An array of values to check against. If 853 * null, all values are accepted. 854 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value) 855 */ 856 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) { 857 if ( trim( $value ) === '' && $allowMultiple ) { 858 return array(); 859 } 860 861 // This is a bit awkward, but we want to avoid calling canApiHighLimits() 862 // because it unstubs $wgUser 863 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 ); 864 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() 865 ? self::LIMIT_SML2 866 : self::LIMIT_SML1; 867 868 if ( self::truncateArray( $valuesList, $sizeLimit ) ) { 869 $this->setWarning( "Too many values supplied for parameter '$valueName': " . 870 "the limit is $sizeLimit" ); 871 } 872 873 if ( !$allowMultiple && count( $valuesList ) != 1 ) { 874 // Bug 33482 - Allow entries with | in them for non-multiple values 875 if ( in_array( $value, $allowedValues, true ) ) { 876 return $value; 877 } 878 879 $possibleValues = is_array( $allowedValues ) 880 ? "of '" . implode( "', '", $allowedValues ) . "'" 881 : ''; 882 $this->dieUsage( 883 "Only one $possibleValues is allowed for parameter '$valueName'", 884 "multival_$valueName" 885 ); 886 } 887 888 if ( is_array( $allowedValues ) ) { 889 // Check for unknown values 890 $unknown = array_diff( $valuesList, $allowedValues ); 891 if ( count( $unknown ) ) { 892 if ( $allowMultiple ) { 893 $s = count( $unknown ) > 1 ? 's' : ''; 894 $vals = implode( ", ", $unknown ); 895 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" ); 896 } else { 897 $this->dieUsage( 898 "Unrecognized value for parameter '$valueName': {$valuesList[0]}", 899 "unknown_$valueName" 900 ); 901 } 902 } 903 // Now throw them out 904 $valuesList = array_intersect( $valuesList, $allowedValues ); 905 } 906 907 return $allowMultiple ? $valuesList : $valuesList[0]; 908 } 909 910 /** 911 * Validate the value against the minimum and user/bot maximum limits. 912 * Prints usage info on failure. 913 * @param string $paramName Parameter name 914 * @param int $value Parameter value 915 * @param int|null $min Minimum value 916 * @param int|null $max Maximum value for users 917 * @param int $botMax Maximum value for sysops/bots 918 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits 919 */ 920 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) { 921 if ( !is_null( $min ) && $value < $min ) { 922 923 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)"; 924 $this->warnOrDie( $msg, $enforceLimits ); 925 $value = $min; 926 } 927 928 // Minimum is always validated, whereas maximum is checked only if not 929 // running in internal call mode 930 if ( $this->getMain()->isInternalMode() ) { 931 return; 932 } 933 934 // Optimization: do not check user's bot status unless really needed -- skips db query 935 // assumes $botMax >= $max 936 if ( !is_null( $max ) && $value > $max ) { 937 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) { 938 if ( $value > $botMax ) { 939 $msg = $this->encodeParamName( $paramName ) . 940 " may not be over $botMax (set to $value) for bots or sysops"; 941 $this->warnOrDie( $msg, $enforceLimits ); 942 $value = $botMax; 943 } 944 } else { 945 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users"; 946 $this->warnOrDie( $msg, $enforceLimits ); 947 $value = $max; 948 } 949 } 950 } 951 952 /** 953 * Validate and normalize of parameters of type 'timestamp' 954 * @param string $value Parameter value 955 * @param string $encParamName Parameter name 956 * @return string Validated and normalized parameter 957 */ 958 protected function validateTimestamp( $value, $encParamName ) { 959 $unixTimestamp = wfTimestamp( TS_UNIX, $value ); 960 if ( $unixTimestamp === false ) { 961 $this->dieUsage( 962 "Invalid value '$value' for timestamp parameter $encParamName", 963 "badtimestamp_{$encParamName}" 964 ); 965 } 966 967 return wfTimestamp( TS_MW, $unixTimestamp ); 968 } 969 970 /** 971 * Validate the supplied token. 972 * 973 * @since 1.24 974 * @param string $token Supplied token 975 * @param array $params All supplied parameters for the module 976 * @return bool 977 */ 978 public final function validateToken( $token, array $params ) { 979 $tokenType = $this->needsToken(); 980 $salts = ApiQueryTokens::getTokenTypeSalts(); 981 if ( !isset( $salts[$tokenType] ) ) { 982 throw new MWException( 983 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " . 984 'without registering it' 985 ); 986 } 987 988 if ( $this->getUser()->matchEditToken( 989 $token, 990 $salts[$tokenType], 991 $this->getRequest() 992 ) ) { 993 return true; 994 } 995 996 $webUiSalt = $this->getWebUITokenSalt( $params ); 997 if ( $webUiSalt !== null && $this->getUser()->matchEditToken( 998 $token, 999 $webUiSalt, 1000 $this->getRequest() 1001 ) ) { 1002 return true; 1003 } 1004 1005 return false; 1006 } 1007 1008 /** 1009 * Validate and normalize of parameters of type 'user' 1010 * @param string $value Parameter value 1011 * @param string $encParamName Parameter name 1012 * @return string Validated and normalized parameter 1013 */ 1014 private function validateUser( $value, $encParamName ) { 1015 $title = Title::makeTitleSafe( NS_USER, $value ); 1016 if ( $title === null ) { 1017 $this->dieUsage( 1018 "Invalid value '$value' for user parameter $encParamName", 1019 "baduser_{$encParamName}" 1020 ); 1021 } 1022 1023 return $title->getText(); 1024 } 1025 1026 /**@}*/ 1027 1028 /************************************************************************//** 1029 * @name Utility methods 1030 * @{ 1031 */ 1032 1033 /** 1034 * Set a watch (or unwatch) based the based on a watchlist parameter. 1035 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange' 1036 * @param Title $titleObj The article's title to change 1037 * @param string $userOption The user option to consider when $watch=preferences 1038 */ 1039 protected function setWatch( $watch, $titleObj, $userOption = null ) { 1040 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption ); 1041 if ( $value === null ) { 1042 return; 1043 } 1044 1045 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() ); 1046 } 1047 1048 /** 1049 * Truncate an array to a certain length. 1050 * @param array $arr Array to truncate 1051 * @param int $limit Maximum length 1052 * @return bool True if the array was truncated, false otherwise 1053 */ 1054 public static function truncateArray( &$arr, $limit ) { 1055 $modified = false; 1056 while ( count( $arr ) > $limit ) { 1057 array_pop( $arr ); 1058 $modified = true; 1059 } 1060 1061 return $modified; 1062 } 1063 1064 /** 1065 * Gets the user for whom to get the watchlist 1066 * 1067 * @param array $params 1068 * @return User 1069 */ 1070 public function getWatchlistUser( $params ) { 1071 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) { 1072 $user = User::newFromName( $params['owner'], false ); 1073 if ( !( $user && $user->getId() ) ) { 1074 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' ); 1075 } 1076 $token = $user->getOption( 'watchlisttoken' ); 1077 if ( $token == '' || $token != $params['token'] ) { 1078 $this->dieUsage( 1079 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 1080 'bad_wltoken' 1081 ); 1082 } 1083 } else { 1084 if ( !$this->getUser()->isLoggedIn() ) { 1085 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' ); 1086 } 1087 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) { 1088 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' ); 1089 } 1090 $user = $this->getUser(); 1091 } 1092 1093 return $user; 1094 } 1095 1096 /**@}*/ 1097 1098 /************************************************************************//** 1099 * @name Warning and error reporting 1100 * @{ 1101 */ 1102 1103 /** 1104 * Set warning section for this module. Users should monitor this 1105 * section to notice any changes in API. Multiple calls to this 1106 * function will result in the warning messages being separated by 1107 * newlines 1108 * @param string $warning Warning message 1109 */ 1110 public function setWarning( $warning ) { 1111 $result = $this->getResult(); 1112 $data = $result->getData(); 1113 $moduleName = $this->getModuleName(); 1114 if ( isset( $data['warnings'][$moduleName] ) ) { 1115 // Don't add duplicate warnings 1116 $oldWarning = $data['warnings'][$moduleName]['*']; 1117 $warnPos = strpos( $oldWarning, $warning ); 1118 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n" 1119 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) { 1120 // Check if $warning is followed by "\n" or the end of the $oldWarning 1121 $warnPos += strlen( $warning ); 1122 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) { 1123 return; 1124 } 1125 } 1126 // If there is a warning already, append it to the existing one 1127 $warning = "$oldWarning\n$warning"; 1128 } 1129 $msg = array(); 1130 ApiResult::setContent( $msg, $warning ); 1131 $result->addValue( 'warnings', $moduleName, 1132 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK ); 1133 } 1134 1135 /** 1136 * Adds a warning to the output, else dies 1137 * 1138 * @param string $msg Message to show as a warning, or error message if dying 1139 * @param bool $enforceLimits Whether this is an enforce (die) 1140 */ 1141 private function warnOrDie( $msg, $enforceLimits = false ) { 1142 if ( $enforceLimits ) { 1143 $this->dieUsage( $msg, 'integeroutofrange' ); 1144 } 1145 1146 $this->setWarning( $msg ); 1147 } 1148 1149 /** 1150 * Throw a UsageException, which will (if uncaught) call the main module's 1151 * error handler and die with an error message. 1152 * 1153 * @param string $description One-line human-readable description of the 1154 * error condition, e.g., "The API requires a valid action parameter" 1155 * @param string $errorCode Brief, arbitrary, stable string to allow easy 1156 * automated identification of the error, e.g., 'unknown_action' 1157 * @param int $httpRespCode HTTP response code 1158 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format 1159 * @throws UsageException 1160 */ 1161 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) { 1162 Profiler::instance()->close(); 1163 throw new UsageException( 1164 $description, 1165 $this->encodeParamName( $errorCode ), 1166 $httpRespCode, 1167 $extradata 1168 ); 1169 } 1170 1171 /** 1172 * Get error (as code, string) from a Status object. 1173 * 1174 * @since 1.23 1175 * @param Status $status 1176 * @return array Array of code and error string 1177 */ 1178 public function getErrorFromStatus( $status ) { 1179 if ( $status->isGood() ) { 1180 throw new MWException( 'Successful status passed to ApiBase::dieStatus' ); 1181 } 1182 1183 $errors = $status->getErrorsArray(); 1184 if ( !$errors ) { 1185 // No errors? Assume the warnings should be treated as errors 1186 $errors = $status->getWarningsArray(); 1187 } 1188 if ( !$errors ) { 1189 // Still no errors? Punt 1190 $errors = array( array( 'unknownerror-nocode' ) ); 1191 } 1192 1193 // Cannot use dieUsageMsg() because extensions might return custom 1194 // error messages. 1195 if ( $errors[0] instanceof Message ) { 1196 $msg = $errors[0]; 1197 $code = $msg->getKey(); 1198 } else { 1199 $code = array_shift( $errors[0] ); 1200 $msg = wfMessage( $code, $errors[0] ); 1201 } 1202 if ( isset( ApiBase::$messageMap[$code] ) ) { 1203 // Translate message to code, for backwards compatibility 1204 $code = ApiBase::$messageMap[$code]['code']; 1205 } 1206 1207 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() ); 1208 } 1209 1210 /** 1211 * Throw a UsageException based on the errors in the Status object. 1212 * 1213 * @since 1.22 1214 * @param Status $status 1215 * @throws MWException 1216 */ 1217 public function dieStatus( $status ) { 1218 1219 list( $code, $msg ) = $this->getErrorFromStatus( $status ); 1220 $this->dieUsage( $msg, $code ); 1221 } 1222 1223 // @codingStandardsIgnoreStart Allow long lines. Cannot split these. 1224 /** 1225 * Array that maps message keys to error messages. $1 and friends are replaced. 1226 */ 1227 public static $messageMap = array( 1228 // This one MUST be present, or dieUsageMsg() will recurse infinitely 1229 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ), 1230 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ), 1231 1232 // Messages from Title::getUserPermissionsErrors() 1233 'ns-specialprotected' => array( 1234 'code' => 'unsupportednamespace', 1235 'info' => "Pages in the Special namespace can't be edited" 1236 ), 1237 'protectedinterface' => array( 1238 'code' => 'protectednamespace-interface', 1239 'info' => "You're not allowed to edit interface messages" 1240 ), 1241 'namespaceprotected' => array( 1242 'code' => 'protectednamespace', 1243 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" 1244 ), 1245 'customcssprotected' => array( 1246 'code' => 'customcssprotected', 1247 'info' => "You're not allowed to edit custom CSS pages" 1248 ), 1249 'customjsprotected' => array( 1250 'code' => 'customjsprotected', 1251 'info' => "You're not allowed to edit custom JavaScript pages" 1252 ), 1253 'cascadeprotected' => array( 1254 'code' => 'cascadeprotected', 1255 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" 1256 ), 1257 'protectedpagetext' => array( 1258 'code' => 'protectedpage', 1259 'info' => "The \"\$1\" right is required to edit this page" 1260 ), 1261 'protect-cantedit' => array( 1262 'code' => 'cantedit', 1263 'info' => "You can't protect this page because you can't edit it" 1264 ), 1265 'deleteprotected' => array( 1266 'code' => 'cantedit', 1267 'info' => "You can't delete this page because it has been protected" 1268 ), 1269 'badaccess-group0' => array( 1270 'code' => 'permissiondenied', 1271 'info' => "Permission denied" 1272 ), // Generic permission denied message 1273 'badaccess-groups' => array( 1274 'code' => 'permissiondenied', 1275 'info' => "Permission denied" 1276 ), 1277 'titleprotected' => array( 1278 'code' => 'protectedtitle', 1279 'info' => "This title has been protected from creation" 1280 ), 1281 'nocreate-loggedin' => array( 1282 'code' => 'cantcreate', 1283 'info' => "You don't have permission to create new pages" 1284 ), 1285 'nocreatetext' => array( 1286 'code' => 'cantcreate-anon', 1287 'info' => "Anonymous users can't create new pages" 1288 ), 1289 'movenologintext' => array( 1290 'code' => 'cantmove-anon', 1291 'info' => "Anonymous users can't move pages" 1292 ), 1293 'movenotallowed' => array( 1294 'code' => 'cantmove', 1295 'info' => "You don't have permission to move pages" 1296 ), 1297 'confirmedittext' => array( 1298 'code' => 'confirmemail', 1299 'info' => "You must confirm your email address before you can edit" 1300 ), 1301 'blockedtext' => array( 1302 'code' => 'blocked', 1303 'info' => "You have been blocked from editing" 1304 ), 1305 'autoblockedtext' => array( 1306 'code' => 'autoblocked', 1307 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" 1308 ), 1309 1310 // Miscellaneous interface messages 1311 'actionthrottledtext' => array( 1312 'code' => 'ratelimited', 1313 'info' => "You've exceeded your rate limit. Please wait some time and try again" 1314 ), 1315 'alreadyrolled' => array( 1316 'code' => 'alreadyrolled', 1317 'info' => "The page you tried to rollback was already rolled back" 1318 ), 1319 'cantrollback' => array( 1320 'code' => 'onlyauthor', 1321 'info' => "The page you tried to rollback only has one author" 1322 ), 1323 'readonlytext' => array( 1324 'code' => 'readonly', 1325 'info' => "The wiki is currently in read-only mode" 1326 ), 1327 'sessionfailure' => array( 1328 'code' => 'badtoken', 1329 'info' => "Invalid token" ), 1330 'cannotdelete' => array( 1331 'code' => 'cantdelete', 1332 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" 1333 ), 1334 'notanarticle' => array( 1335 'code' => 'missingtitle', 1336 'info' => "The page you requested doesn't exist" 1337 ), 1338 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" 1339 ), 1340 'immobile_namespace' => array( 1341 'code' => 'immobilenamespace', 1342 'info' => "You tried to move pages from or to a namespace that is protected from moving" 1343 ), 1344 'articleexists' => array( 1345 'code' => 'articleexists', 1346 'info' => "The destination article already exists and is not a redirect to the source article" 1347 ), 1348 'protectedpage' => array( 1349 'code' => 'protectedpage', 1350 'info' => "You don't have permission to perform this move" 1351 ), 1352 'hookaborted' => array( 1353 'code' => 'hookaborted', 1354 'info' => "The modification you tried to make was aborted by an extension hook" 1355 ), 1356 'cantmove-titleprotected' => array( 1357 'code' => 'protectedtitle', 1358 'info' => "The destination article has been protected from creation" 1359 ), 1360 'imagenocrossnamespace' => array( 1361 'code' => 'nonfilenamespace', 1362 'info' => "Can't move a file to a non-file namespace" 1363 ), 1364 'imagetypemismatch' => array( 1365 'code' => 'filetypemismatch', 1366 'info' => "The new file extension doesn't match its type" 1367 ), 1368 // 'badarticleerror' => shouldn't happen 1369 // 'badtitletext' => shouldn't happen 1370 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ), 1371 'range_block_disabled' => array( 1372 'code' => 'rangedisabled', 1373 'info' => "Blocking IP ranges has been disabled" 1374 ), 1375 'nosuchusershort' => array( 1376 'code' => 'nosuchuser', 1377 'info' => "The user you specified doesn't exist" 1378 ), 1379 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ), 1380 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ), 1381 'ipb_already_blocked' => array( 1382 'code' => 'alreadyblocked', 1383 'info' => "The user you tried to block was already blocked" 1384 ), 1385 'ipb_blocked_as_range' => array( 1386 'code' => 'blockedasrange', 1387 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole." 1388 ), 1389 'ipb_cant_unblock' => array( 1390 'code' => 'cantunblock', 1391 'info' => "The block you specified was not found. It may have been unblocked already" 1392 ), 1393 'mailnologin' => array( 1394 'code' => 'cantsend', 1395 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email" 1396 ), 1397 'ipbblocked' => array( 1398 'code' => 'ipbblocked', 1399 'info' => 'You cannot block or unblock users while you are yourself blocked' 1400 ), 1401 'ipbnounblockself' => array( 1402 'code' => 'ipbnounblockself', 1403 'info' => 'You are not allowed to unblock yourself' 1404 ), 1405 'usermaildisabled' => array( 1406 'code' => 'usermaildisabled', 1407 'info' => "User email has been disabled" 1408 ), 1409 'blockedemailuser' => array( 1410 'code' => 'blockedfrommail', 1411 'info' => "You have been blocked from sending email" 1412 ), 1413 'notarget' => array( 1414 'code' => 'notarget', 1415 'info' => "You have not specified a valid target for this action" 1416 ), 1417 'noemail' => array( 1418 'code' => 'noemail', 1419 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users" 1420 ), 1421 'rcpatroldisabled' => array( 1422 'code' => 'patroldisabled', 1423 'info' => "Patrolling is disabled on this wiki" 1424 ), 1425 'markedaspatrollederror-noautopatrol' => array( 1426 'code' => 'noautopatrol', 1427 'info' => "You don't have permission to patrol your own changes" 1428 ), 1429 'delete-toobig' => array( 1430 'code' => 'bigdelete', 1431 'info' => "You can't delete this page because it has more than \$1 revisions" 1432 ), 1433 'movenotallowedfile' => array( 1434 'code' => 'cantmovefile', 1435 'info' => "You don't have permission to move files" 1436 ), 1437 'userrights-no-interwiki' => array( 1438 'code' => 'nointerwikiuserrights', 1439 'info' => "You don't have permission to change user rights on other wikis" 1440 ), 1441 'userrights-nodatabase' => array( 1442 'code' => 'nosuchdatabase', 1443 'info' => "Database \"\$1\" does not exist or is not local" 1444 ), 1445 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ), 1446 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ), 1447 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ), 1448 'import-rootpage-invalid' => array( 1449 'code' => 'import-rootpage-invalid', 1450 'info' => 'Root page is an invalid title' 1451 ), 1452 'import-rootpage-nosubpage' => array( 1453 'code' => 'import-rootpage-nosubpage', 1454 'info' => 'Namespace "$1" of the root page does not allow subpages' 1455 ), 1456 1457 // API-specific messages 1458 'readrequired' => array( 1459 'code' => 'readapidenied', 1460 'info' => "You need read permission to use this module" 1461 ), 1462 'writedisabled' => array( 1463 'code' => 'noapiwrite', 1464 '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" 1465 ), 1466 'writerequired' => array( 1467 'code' => 'writeapidenied', 1468 'info' => "You're not allowed to edit this wiki through the API" 1469 ), 1470 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ), 1471 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ), 1472 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ), 1473 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ), 1474 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ), 1475 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ), 1476 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ), 1477 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ), 1478 'create-titleexists' => array( 1479 'code' => 'create-titleexists', 1480 'info' => "Existing titles can't be protected with 'create'" 1481 ), 1482 'missingtitle-createonly' => array( 1483 'code' => 'missingtitle-createonly', 1484 'info' => "Missing titles can only be protected with 'create'" 1485 ), 1486 'cantblock' => array( 'code' => 'cantblock', 1487 'info' => "You don't have permission to block users" 1488 ), 1489 'canthide' => array( 1490 'code' => 'canthide', 1491 'info' => "You don't have permission to hide user names from the block log" 1492 ), 1493 'cantblock-email' => array( 1494 'code' => 'cantblock-email', 1495 'info' => "You don't have permission to block users from sending email through the wiki" 1496 ), 1497 'unblock-notarget' => array( 1498 'code' => 'notarget', 1499 'info' => "Either the id or the user parameter must be set" 1500 ), 1501 'unblock-idanduser' => array( 1502 'code' => 'idanduser', 1503 'info' => "The id and user parameters can't be used together" 1504 ), 1505 'cantunblock' => array( 1506 'code' => 'permissiondenied', 1507 'info' => "You don't have permission to unblock users" 1508 ), 1509 'cannotundelete' => array( 1510 'code' => 'cantundelete', 1511 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" 1512 ), 1513 'permdenied-undelete' => array( 1514 'code' => 'permissiondenied', 1515 'info' => "You don't have permission to restore deleted revisions" 1516 ), 1517 'createonly-exists' => array( 1518 'code' => 'articleexists', 1519 'info' => "The article you tried to create has been created already" 1520 ), 1521 'nocreate-missing' => array( 1522 'code' => 'missingtitle', 1523 'info' => "The article you tried to edit doesn't exist" 1524 ), 1525 'cantchangecontentmodel' => array( 1526 'code' => 'cantchangecontentmodel', 1527 'info' => "You don't have permission to change the content model of a page" 1528 ), 1529 'nosuchrcid' => array( 1530 'code' => 'nosuchrcid', 1531 'info' => "There is no change with rcid \"\$1\"" 1532 ), 1533 'protect-invalidaction' => array( 1534 'code' => 'protect-invalidaction', 1535 'info' => "Invalid protection type \"\$1\"" 1536 ), 1537 'protect-invalidlevel' => array( 1538 'code' => 'protect-invalidlevel', 1539 'info' => "Invalid protection level \"\$1\"" 1540 ), 1541 'toofewexpiries' => array( 1542 'code' => 'toofewexpiries', 1543 'info' => "\$1 expiry timestamps were provided where \$2 were needed" 1544 ), 1545 'cantimport' => array( 1546 'code' => 'cantimport', 1547 'info' => "You don't have permission to import pages" 1548 ), 1549 'cantimport-upload' => array( 1550 'code' => 'cantimport-upload', 1551 'info' => "You don't have permission to import uploaded pages" 1552 ), 1553 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ), 1554 'importuploaderrorsize' => array( 1555 'code' => 'filetoobig', 1556 'info' => 'The file you uploaded is bigger than the maximum upload size' 1557 ), 1558 'importuploaderrorpartial' => array( 1559 'code' => 'partialupload', 1560 'info' => 'The file was only partially uploaded' 1561 ), 1562 'importuploaderrortemp' => array( 1563 'code' => 'notempdir', 1564 'info' => 'The temporary upload directory is missing' 1565 ), 1566 'importcantopen' => array( 1567 'code' => 'cantopenfile', 1568 'info' => "Couldn't open the uploaded file" 1569 ), 1570 'import-noarticle' => array( 1571 'code' => 'badinterwiki', 1572 'info' => 'Invalid interwiki title specified' 1573 ), 1574 'importbadinterwiki' => array( 1575 'code' => 'badinterwiki', 1576 'info' => 'Invalid interwiki title specified' 1577 ), 1578 'import-unknownerror' => array( 1579 'code' => 'import-unknownerror', 1580 'info' => "Unknown error on import: \"\$1\"" 1581 ), 1582 'cantoverwrite-sharedfile' => array( 1583 'code' => 'cantoverwrite-sharedfile', 1584 'info' => 'The target file exists on a shared repository and you do not have permission to override it' 1585 ), 1586 'sharedfile-exists' => array( 1587 'code' => 'fileexists-sharedrepo-perm', 1588 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' 1589 ), 1590 'mustbeposted' => array( 1591 'code' => 'mustbeposted', 1592 'info' => "The \$1 module requires a POST request" 1593 ), 1594 'show' => array( 1595 'code' => 'show', 1596 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' 1597 ), 1598 'specialpage-cantexecute' => array( 1599 'code' => 'specialpage-cantexecute', 1600 'info' => "You don't have permission to view the results of this special page" 1601 ), 1602 'invalidoldimage' => array( 1603 'code' => 'invalidoldimage', 1604 'info' => 'The oldimage parameter has invalid format' 1605 ), 1606 'nodeleteablefile' => array( 1607 'code' => 'nodeleteablefile', 1608 'info' => 'No such old version of the file' 1609 ), 1610 'fileexists-forbidden' => array( 1611 'code' => 'fileexists-forbidden', 1612 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' 1613 ), 1614 'fileexists-shared-forbidden' => array( 1615 'code' => 'fileexists-shared-forbidden', 1616 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.' 1617 ), 1618 'filerevert-badversion' => array( 1619 'code' => 'filerevert-badversion', 1620 'info' => 'There is no previous local version of this file with the provided timestamp.' 1621 ), 1622 1623 // ApiEditPage messages 1624 'noimageredirect-anon' => array( 1625 'code' => 'noimageredirect-anon', 1626 'info' => "Anonymous users can't create image redirects" 1627 ), 1628 'noimageredirect-logged' => array( 1629 'code' => 'noimageredirect', 1630 'info' => "You don't have permission to create image redirects" 1631 ), 1632 'spamdetected' => array( 1633 'code' => 'spamdetected', 1634 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" 1635 ), 1636 'contenttoobig' => array( 1637 'code' => 'contenttoobig', 1638 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" 1639 ), 1640 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ), 1641 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ), 1642 'wasdeleted' => array( 1643 'code' => 'pagedeleted', 1644 'info' => "The page has been deleted since you fetched its timestamp" 1645 ), 1646 'blankpage' => array( 1647 'code' => 'emptypage', 1648 'info' => "Creating new, empty pages is not allowed" 1649 ), 1650 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ), 1651 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ), 1652 'missingtext' => array( 1653 'code' => 'notext', 1654 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" 1655 ), 1656 'emptynewsection' => array( 1657 'code' => 'emptynewsection', 1658 'info' => 'Creating empty new sections is not possible.' 1659 ), 1660 'revwrongpage' => array( 1661 'code' => 'revwrongpage', 1662 'info' => "r\$1 is not a revision of \"\$2\"" 1663 ), 1664 'undo-failure' => array( 1665 'code' => 'undofailure', 1666 'info' => 'Undo failed due to conflicting intermediate edits' 1667 ), 1668 'content-not-allowed-here' => array( 1669 'code' => 'contentnotallowedhere', 1670 'info' => 'Content model "$1" is not allowed at title "$2"' 1671 ), 1672 1673 // Messages from WikiPage::doEit() 1674 'edit-hook-aborted' => array( 1675 'code' => 'edit-hook-aborted', 1676 'info' => "Your edit was aborted by an ArticleSave hook" 1677 ), 1678 'edit-gone-missing' => array( 1679 'code' => 'edit-gone-missing', 1680 'info' => "The page you tried to edit doesn't seem to exist anymore" 1681 ), 1682 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ), 1683 'edit-already-exists' => array( 1684 'code' => 'edit-already-exists', 1685 'info' => 'It seems the page you tried to create already exist' 1686 ), 1687 1688 // uploadMsgs 1689 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ), 1690 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ), 1691 'uploaddisabled' => array( 1692 'code' => 'uploaddisabled', 1693 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true' 1694 ), 1695 'copyuploaddisabled' => array( 1696 'code' => 'copyuploaddisabled', 1697 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' 1698 ), 1699 'copyuploadbaddomain' => array( 1700 'code' => 'copyuploadbaddomain', 1701 'info' => 'Uploads by URL are not allowed from this domain.' 1702 ), 1703 'copyuploadbadurl' => array( 1704 'code' => 'copyuploadbadurl', 1705 'info' => 'Upload not allowed from this URL.' 1706 ), 1707 1708 'filename-tooshort' => array( 1709 'code' => 'filename-tooshort', 1710 'info' => 'The filename is too short' 1711 ), 1712 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ), 1713 'illegal-filename' => array( 1714 'code' => 'illegal-filename', 1715 'info' => 'The filename is not allowed' 1716 ), 1717 'filetype-missing' => array( 1718 'code' => 'filetype-missing', 1719 'info' => 'The file is missing an extension' 1720 ), 1721 1722 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' ) 1723 ); 1724 // @codingStandardsIgnoreEnd 1725 1726 /** 1727 * Helper function for readonly errors 1728 */ 1729 public function dieReadOnly() { 1730 $parsed = $this->parseMsg( array( 'readonlytext' ) ); 1731 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0, 1732 array( 'readonlyreason' => wfReadOnlyReason() ) ); 1733 } 1734 1735 /** 1736 * Output the error message related to a certain array 1737 * @param array|string $error Element of a getUserPermissionsErrors()-style array 1738 */ 1739 public function dieUsageMsg( $error ) { 1740 # most of the time we send a 1 element, so we might as well send it as 1741 # a string and make this an array here. 1742 if ( is_string( $error ) ) { 1743 $error = array( $error ); 1744 } 1745 $parsed = $this->parseMsg( $error ); 1746 $this->dieUsage( $parsed['info'], $parsed['code'] ); 1747 } 1748 1749 /** 1750 * Will only set a warning instead of failing if the global $wgDebugAPI 1751 * is set to true. Otherwise behaves exactly as dieUsageMsg(). 1752 * @param array|string $error Element of a getUserPermissionsErrors()-style array 1753 * @since 1.21 1754 */ 1755 public function dieUsageMsgOrDebug( $error ) { 1756 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) { 1757 $this->dieUsageMsg( $error ); 1758 } 1759 1760 if ( is_string( $error ) ) { 1761 $error = array( $error ); 1762 } 1763 $parsed = $this->parseMsg( $error ); 1764 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] ); 1765 } 1766 1767 /** 1768 * Die with the $prefix.'badcontinue' error. This call is common enough to 1769 * make it into the base method. 1770 * @param bool $condition Will only die if this value is true 1771 * @since 1.21 1772 */ 1773 protected function dieContinueUsageIf( $condition ) { 1774 if ( $condition ) { 1775 $this->dieUsage( 1776 'Invalid continue param. You should pass the original value returned by the previous query', 1777 'badcontinue' ); 1778 } 1779 } 1780 1781 /** 1782 * Return the error message related to a certain array 1783 * @param array $error Element of a getUserPermissionsErrors()-style array 1784 * @return array('code' => code, 'info' => info) 1785 */ 1786 public function parseMsg( $error ) { 1787 $error = (array)$error; // It seems strings sometimes make their way in here 1788 $key = array_shift( $error ); 1789 1790 // Check whether the error array was nested 1791 // array( array( <code>, <params> ), array( <another_code>, <params> ) ) 1792 if ( is_array( $key ) ) { 1793 $error = $key; 1794 $key = array_shift( $error ); 1795 } 1796 1797 if ( isset( self::$messageMap[$key] ) ) { 1798 return array( 1799 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ), 1800 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error ) 1801 ); 1802 } 1803 1804 // If the key isn't present, throw an "unknown error" 1805 return $this->parseMsg( array( 'unknownerror', $key ) ); 1806 } 1807 1808 /** 1809 * Internal code errors should be reported with this method 1810 * @param string $method Method or function name 1811 * @param string $message Error message 1812 * @throws MWException 1813 */ 1814 protected static function dieDebug( $method, $message ) { 1815 throw new MWException( "Internal error in $method: $message" ); 1816 } 1817 1818 /**@}*/ 1819 1820 /************************************************************************//** 1821 * @name Help message generation 1822 * @{ 1823 */ 1824 1825 /** 1826 * Generates help message for this module, or false if there is no description 1827 * @return string|bool 1828 */ 1829 public function makeHelpMsg() { 1830 static $lnPrfx = "\n "; 1831 1832 $msg = $this->getFinalDescription(); 1833 1834 if ( $msg !== false ) { 1835 1836 if ( !is_array( $msg ) ) { 1837 $msg = array( 1838 $msg 1839 ); 1840 } 1841 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n"; 1842 1843 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() ); 1844 1845 if ( $this->isReadMode() ) { 1846 $msg .= "\nThis module requires read rights"; 1847 } 1848 if ( $this->isWriteMode() ) { 1849 $msg .= "\nThis module requires write rights"; 1850 } 1851 if ( $this->mustBePosted() ) { 1852 $msg .= "\nThis module only accepts POST requests"; 1853 } 1854 if ( $this->isReadMode() || $this->isWriteMode() || 1855 $this->mustBePosted() 1856 ) { 1857 $msg .= "\n"; 1858 } 1859 1860 // Parameters 1861 $paramsMsg = $this->makeHelpMsgParameters(); 1862 if ( $paramsMsg !== false ) { 1863 $msg .= "Parameters:\n$paramsMsg"; 1864 } 1865 1866 $examples = $this->getExamples(); 1867 if ( $examples ) { 1868 if ( !is_array( $examples ) ) { 1869 $examples = array( 1870 $examples 1871 ); 1872 } 1873 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n"; 1874 foreach ( $examples as $k => $v ) { 1875 if ( is_numeric( $k ) ) { 1876 $msg .= " $v\n"; 1877 } else { 1878 if ( is_array( $v ) ) { 1879 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) ); 1880 } else { 1881 $msgExample = " $v"; 1882 } 1883 $msgExample .= ":"; 1884 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n"; 1885 } 1886 } 1887 } 1888 } 1889 1890 return $msg; 1891 } 1892 1893 /** 1894 * @param string $item 1895 * @return string 1896 */ 1897 private function indentExampleText( $item ) { 1898 return " " . $item; 1899 } 1900 1901 /** 1902 * @param string $prefix Text to split output items 1903 * @param string $title What is being output 1904 * @param string|array $input 1905 * @return string 1906 */ 1907 protected function makeHelpArrayToString( $prefix, $title, $input ) { 1908 if ( $input === false ) { 1909 return ''; 1910 } 1911 if ( !is_array( $input ) ) { 1912 $input = array( $input ); 1913 } 1914 1915 if ( count( $input ) > 0 ) { 1916 if ( $title ) { 1917 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n "; 1918 } else { 1919 $msg = ' '; 1920 } 1921 $msg .= implode( $prefix, $input ) . "\n"; 1922 1923 return $msg; 1924 } 1925 1926 return ''; 1927 } 1928 1929 /** 1930 * Generates the parameter descriptions for this module, to be displayed in the 1931 * module's help. 1932 * @return string|bool 1933 */ 1934 public function makeHelpMsgParameters() { 1935 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP ); 1936 if ( $params ) { 1937 1938 $paramsDescription = $this->getFinalParamDescription(); 1939 $msg = ''; 1940 $paramPrefix = "\n" . str_repeat( ' ', 24 ); 1941 $descWordwrap = "\n" . str_repeat( ' ', 28 ); 1942 foreach ( $params as $paramName => $paramSettings ) { 1943 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : ''; 1944 if ( is_array( $desc ) ) { 1945 $desc = implode( $paramPrefix, $desc ); 1946 } 1947 1948 //handle shorthand 1949 if ( !is_array( $paramSettings ) ) { 1950 $paramSettings = array( 1951 self::PARAM_DFLT => $paramSettings, 1952 ); 1953 } 1954 1955 //handle missing type 1956 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) { 1957 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] ) 1958 ? $paramSettings[ApiBase::PARAM_DFLT] 1959 : null; 1960 if ( is_bool( $dflt ) ) { 1961 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean'; 1962 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) { 1963 $paramSettings[ApiBase::PARAM_TYPE] = 'string'; 1964 } elseif ( is_int( $dflt ) ) { 1965 $paramSettings[ApiBase::PARAM_TYPE] = 'integer'; 1966 } 1967 } 1968 1969 if ( isset( $paramSettings[self::PARAM_DEPRECATED] ) 1970 && $paramSettings[self::PARAM_DEPRECATED] 1971 ) { 1972 $desc = "DEPRECATED! $desc"; 1973 } 1974 1975 if ( isset( $paramSettings[self::PARAM_REQUIRED] ) 1976 && $paramSettings[self::PARAM_REQUIRED] 1977 ) { 1978 $desc .= $paramPrefix . "This parameter is required"; 1979 } 1980 1981 $type = isset( $paramSettings[self::PARAM_TYPE] ) 1982 ? $paramSettings[self::PARAM_TYPE] 1983 : null; 1984 if ( isset( $type ) ) { 1985 $hintPipeSeparated = true; 1986 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) 1987 ? $paramSettings[self::PARAM_ISMULTI] 1988 : false; 1989 if ( $multi ) { 1990 $prompt = 'Values (separate with \'|\'): '; 1991 } else { 1992 $prompt = 'One value: '; 1993 } 1994 1995 if ( $type === 'submodule' ) { 1996 $type = $this->getModuleManager()->getNames( $paramName ); 1997 sort( $type ); 1998 } 1999 if ( is_array( $type ) ) { 2000 $choices = array(); 2001 $nothingPrompt = ''; 2002 foreach ( $type as $t ) { 2003 if ( $t === '' ) { 2004 $nothingPrompt = 'Can be empty, or '; 2005 } else { 2006 $choices[] = $t; 2007 } 2008 } 2009 $desc .= $paramPrefix . $nothingPrompt . $prompt; 2010 $choicesstring = implode( ', ', $choices ); 2011 $desc .= wordwrap( $choicesstring, 100, $descWordwrap ); 2012 $hintPipeSeparated = false; 2013 } else { 2014 switch ( $type ) { 2015 case 'namespace': 2016 // Special handling because namespaces are 2017 // type-limited, yet they are not given 2018 $desc .= $paramPrefix . $prompt; 2019 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ), 2020 100, $descWordwrap ); 2021 $hintPipeSeparated = false; 2022 break; 2023 case 'limit': 2024 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}"; 2025 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) { 2026 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)"; 2027 } 2028 $desc .= ' allowed'; 2029 break; 2030 case 'integer': 2031 $s = $multi ? 's' : ''; 2032 $hasMin = isset( $paramSettings[self::PARAM_MIN] ); 2033 $hasMax = isset( $paramSettings[self::PARAM_MAX] ); 2034 if ( $hasMin || $hasMax ) { 2035 if ( !$hasMax ) { 2036 $intRangeStr = "The value$s must be no less than " . 2037 "{$paramSettings[self::PARAM_MIN]}"; 2038 } elseif ( !$hasMin ) { 2039 $intRangeStr = "The value$s must be no more than " . 2040 "{$paramSettings[self::PARAM_MAX]}"; 2041 } else { 2042 $intRangeStr = "The value$s must be between " . 2043 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}"; 2044 } 2045 2046 $desc .= $paramPrefix . $intRangeStr; 2047 } 2048 break; 2049 case 'upload': 2050 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data"; 2051 break; 2052 } 2053 } 2054 2055 if ( $multi ) { 2056 if ( $hintPipeSeparated ) { 2057 $desc .= $paramPrefix . "Separate values with '|'"; 2058 } 2059 2060 $isArray = is_array( $type ); 2061 if ( !$isArray 2062 || $isArray && count( $type ) > self::LIMIT_SML1 2063 ) { 2064 $desc .= $paramPrefix . "Maximum number of values " . 2065 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)"; 2066 } 2067 } 2068 } 2069 2070 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null; 2071 if ( !is_null( $default ) && $default !== false ) { 2072 $desc .= $paramPrefix . "Default: $default"; 2073 } 2074 2075 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc ); 2076 } 2077 2078 return $msg; 2079 } 2080 2081 return false; 2082 } 2083 2084 /**@}*/ 2085 2086 /************************************************************************//** 2087 * @name Profiling 2088 * @{ 2089 */ 2090 2091 /** 2092 * Profiling: total module execution time 2093 */ 2094 private $mTimeIn = 0, $mModuleTime = 0; 2095 2096 /** 2097 * Get the name of the module as shown in the profiler log 2098 * 2099 * @param DatabaseBase|bool $db 2100 * 2101 * @return string 2102 */ 2103 public function getModuleProfileName( $db = false ) { 2104 if ( $db ) { 2105 return 'API:' . $this->mModuleName . '-DB'; 2106 } 2107 2108 return 'API:' . $this->mModuleName; 2109 } 2110 2111 /** 2112 * Start module profiling 2113 */ 2114 public function profileIn() { 2115 if ( $this->mTimeIn !== 0 ) { 2116 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' ); 2117 } 2118 $this->mTimeIn = microtime( true ); 2119 wfProfileIn( $this->getModuleProfileName() ); 2120 } 2121 2122 /** 2123 * End module profiling 2124 */ 2125 public function profileOut() { 2126 if ( $this->mTimeIn === 0 ) { 2127 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' ); 2128 } 2129 if ( $this->mDBTimeIn !== 0 ) { 2130 ApiBase::dieDebug( 2131 __METHOD__, 2132 'Must be called after database profiling is done with profileDBOut()' 2133 ); 2134 } 2135 2136 $this->mModuleTime += microtime( true ) - $this->mTimeIn; 2137 $this->mTimeIn = 0; 2138 wfProfileOut( $this->getModuleProfileName() ); 2139 } 2140 2141 /** 2142 * When modules crash, sometimes it is needed to do a profileOut() regardless 2143 * of the profiling state the module was in. This method does such cleanup. 2144 */ 2145 public function safeProfileOut() { 2146 if ( $this->mTimeIn !== 0 ) { 2147 if ( $this->mDBTimeIn !== 0 ) { 2148 $this->profileDBOut(); 2149 } 2150 $this->profileOut(); 2151 } 2152 } 2153 2154 /** 2155 * Total time the module was executed 2156 * @return float 2157 */ 2158 public function getProfileTime() { 2159 if ( $this->mTimeIn !== 0 ) { 2160 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' ); 2161 } 2162 2163 return $this->mModuleTime; 2164 } 2165 2166 /** 2167 * Profiling: database execution time 2168 */ 2169 private $mDBTimeIn = 0, $mDBTime = 0; 2170 2171 /** 2172 * Start module profiling 2173 */ 2174 public function profileDBIn() { 2175 if ( $this->mTimeIn === 0 ) { 2176 ApiBase::dieDebug( 2177 __METHOD__, 2178 'Must be called while profiling the entire module with profileIn()' 2179 ); 2180 } 2181 if ( $this->mDBTimeIn !== 0 ) { 2182 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' ); 2183 } 2184 $this->mDBTimeIn = microtime( true ); 2185 wfProfileIn( $this->getModuleProfileName( true ) ); 2186 } 2187 2188 /** 2189 * End database profiling 2190 */ 2191 public function profileDBOut() { 2192 if ( $this->mTimeIn === 0 ) { 2193 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' . 2194 'the entire module with profileIn()' ); 2195 } 2196 if ( $this->mDBTimeIn === 0 ) { 2197 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' ); 2198 } 2199 2200 $time = microtime( true ) - $this->mDBTimeIn; 2201 $this->mDBTimeIn = 0; 2202 2203 $this->mDBTime += $time; 2204 $this->getMain()->mDBTime += $time; 2205 wfProfileOut( $this->getModuleProfileName( true ) ); 2206 } 2207 2208 /** 2209 * Total time the module used the database 2210 * @return float 2211 */ 2212 public function getProfileDBTime() { 2213 if ( $this->mDBTimeIn !== 0 ) { 2214 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' ); 2215 } 2216 2217 return $this->mDBTime; 2218 } 2219 2220 /** 2221 * Write logging information for API features to a debug log, for usage 2222 * analysis. 2223 * @param string $feature Feature being used. 2224 */ 2225 protected function logFeatureUsage( $feature ) { 2226 $request = $this->getRequest(); 2227 $s = '"' . addslashes( $feature ) . '"' . 2228 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' . 2229 ' "' . $request->getIP() . '"' . 2230 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' . 2231 ' "' . addslashes( $request->getHeader( 'User-agent' ) ) . '"'; 2232 wfDebugLog( 'api-feature-usage', $s, 'private' ); 2233 } 2234 2235 /**@}*/ 2236 2237 /************************************************************************//** 2238 * @name Deprecated 2239 * @{ 2240 */ 2241 2242 /// @deprecated since 1.24 2243 const PROP_ROOT = 'ROOT'; 2244 /// @deprecated since 1.24 2245 const PROP_LIST = 'LIST'; 2246 /// @deprecated since 1.24 2247 const PROP_TYPE = 0; 2248 /// @deprecated since 1.24 2249 const PROP_NULLABLE = 1; 2250 2251 /** 2252 * Formerly returned a string that identifies the version of the extending 2253 * class. Typically included the class name, the svn revision, timestamp, 2254 * and last author. Usually done with SVN's Id keyword 2255 * 2256 * @deprecated since 1.21, version string is no longer supported 2257 * @return string 2258 */ 2259 public function getVersion() { 2260 wfDeprecated( __METHOD__, '1.21' ); 2261 return ''; 2262 } 2263 2264 /** 2265 * Formerly used to fetch a list of possible properites in the result, 2266 * somehow organized with respect to the prop parameter that causes them to 2267 * be returned. The specific semantics of the return value was never 2268 * specified. Since this was never possible to be accurately updated, it 2269 * has been removed. 2270 * 2271 * @deprecated since 1.24 2272 * @return array|bool 2273 */ 2274 protected function getResultProperties() { 2275 wfDeprecated( __METHOD__, '1.24' ); 2276 return false; 2277 } 2278 2279 /** 2280 * @see self::getResultProperties() 2281 * @deprecated since 1.24 2282 * @return array|bool 2283 */ 2284 public function getFinalResultProperties() { 2285 wfDeprecated( __METHOD__, '1.24' ); 2286 return array(); 2287 } 2288 2289 /** 2290 * @see self::getResultProperties() 2291 * @deprecated since 1.24 2292 */ 2293 protected static function addTokenProperties( &$props, $tokenFunctions ) { 2294 wfDeprecated( __METHOD__, '1.24' ); 2295 } 2296 2297 /** 2298 * @see self::getPossibleErrors() 2299 * @deprecated since 1.24 2300 * @return array 2301 */ 2302 public function getRequireOnlyOneParameterErrorMessages( $params ) { 2303 wfDeprecated( __METHOD__, '1.24' ); 2304 return array(); 2305 } 2306 2307 /** 2308 * @see self::getPossibleErrors() 2309 * @deprecated since 1.24 2310 * @return array 2311 */ 2312 public function getRequireMaxOneParameterErrorMessages( $params ) { 2313 wfDeprecated( __METHOD__, '1.24' ); 2314 return array(); 2315 } 2316 2317 /** 2318 * @see self::getPossibleErrors() 2319 * @deprecated since 1.24 2320 * @return array 2321 */ 2322 public function getRequireAtLeastOneParameterErrorMessages( $params ) { 2323 wfDeprecated( __METHOD__, '1.24' ); 2324 return array(); 2325 } 2326 2327 /** 2328 * @see self::getPossibleErrors() 2329 * @deprecated since 1.24 2330 * @return array 2331 */ 2332 public function getTitleOrPageIdErrorMessage() { 2333 wfDeprecated( __METHOD__, '1.24' ); 2334 return array(); 2335 } 2336 2337 /** 2338 * This formerly attempted to return a list of all possible errors returned 2339 * by the module. However, this was impossible to maintain in many cases 2340 * since errors could come from other areas of MediaWiki and in some cases 2341 * from arbitrary extension hooks. Since a partial list claiming to be 2342 * comprehensive is unlikely to be useful, it was removed. 2343 * 2344 * @deprecated since 1.24 2345 * @return array 2346 */ 2347 public function getPossibleErrors() { 2348 wfDeprecated( __METHOD__, '1.24' ); 2349 return array(); 2350 } 2351 2352 /** 2353 * @see self::getPossibleErrors() 2354 * @deprecated since 1.24 2355 * @return array 2356 */ 2357 public function getFinalPossibleErrors() { 2358 wfDeprecated( __METHOD__, '1.24' ); 2359 return array(); 2360 } 2361 2362 /** 2363 * @see self::getPossibleErrors() 2364 * @deprecated since 1.24 2365 * @return array 2366 */ 2367 public function parseErrors( $errors ) { 2368 wfDeprecated( __METHOD__, '1.24' ); 2369 return array(); 2370 } 2371 2372 /**@}*/ 2373 } 2374 2375 /** 2376 * For really cool vim folding this needs to be at the end: 2377 * vim: foldmarker=@{,@} foldmethod=marker 2378 */
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Fri Nov 28 14:03:12 2014 | Cross-referenced by PHPXref 0.7.1 |