a214f2ebb3e49943804257f4ddf1f1225c01c1f6
5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
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
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
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;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
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;
68 // Specify an alternative i18n message for this help parameter.
69 // Value can be a string key, an array giving key and parameters, or a
71 const PARAM_HELP_MSG
= 10;
73 // Specify additional i18n messages to append to the normal message. Value
74 // is an array of any of strings giving the message key, arrays giving key and
75 // parameters, or Message objects.
76 const PARAM_HELP_MSG_APPEND
= 11;
78 const LIMIT_BIG1
= 500; // Fast query, std user limit
79 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1
= 50; // Slow query, std user limit
81 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
88 const GET_VALUES_FOR_HELP
= 1;
93 private $mModuleName, $mModulePrefix;
94 private $mSlaveDB = null;
95 private $mParamCache = array();
98 * @param ApiMain $mainModule
99 * @param string $moduleName Name of this module
100 * @param string $modulePrefix Prefix to use for parameter names
102 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
103 $this->mMainModule
= $mainModule;
104 $this->mModuleName
= $moduleName;
105 $this->mModulePrefix
= $modulePrefix;
107 if ( !$this->isMain() ) {
108 $this->setContext( $mainModule->getContext() );
113 /************************************************************************//**
114 * @name Methods to implement
119 * Evaluates the parameters, performs the requested query, and sets up
120 * the result. Concrete implementations of ApiBase must override this
121 * method to provide whatever functionality their module offers.
122 * Implementations must not produce any output on their own and are not
123 * expected to handle any errors.
125 * The execute() method will be invoked directly by ApiMain immediately
126 * before the result of the module is output. Aside from the
127 * constructor, implementations should assume that no other methods
128 * will be called externally on the module before the result is
131 * The result data should be stored in the ApiResult object available
132 * through getResult().
134 abstract public function execute();
137 * Get the module manager, or null if this module has no sub-modules
139 * @return ApiModuleManager
141 public function getModuleManager() {
146 * If the module may only be used with a certain format module,
147 * it should override this method to return an instance of that formatter.
148 * A value of null means the default format will be used.
149 * @return mixed Instance of a derived class of ApiFormatBase, or null
151 public function getCustomPrinter() {
156 * Returns usage examples for this module.
158 * Return value has query strings as keys, with values being either strings
159 * (message key), arrays (message key + parameter), or Message objects.
161 * Do not call this base class implementation when overriding this method.
166 protected function getExamplesMessages() {
167 // Fall back to old non-localised method
170 $examples = $this->getExamples();
172 if ( !is_array( $examples ) ) {
173 $examples = array( $examples );
174 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
175 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
176 !preg_match( '/^\s*api\.php\?/', $examples[0] )
178 // Fix up the ugly "even numbered elements are description, odd
179 // numbered elemts are the link" format (see doc for self::getExamples)
181 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
182 $tmp[$examples[$i +
1]] = $examples[$i];
187 foreach ( $examples as $k => $v ) {
188 if ( is_numeric( $k ) ) {
193 $msg = self
::escapeWikiText( $v );
194 if ( is_array( $msg ) ) {
195 $msg = join( " ", $msg );
199 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
200 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
208 * Return links to more detailed help pages about the module.
209 * @since 1.25, returning boolean false is deprecated
210 * @return string|array
212 public function getHelpUrls() {
217 * Returns an array of allowed parameters (parameter name) => (default
218 * value) or (parameter name) => (array with PARAM_* constants as keys)
219 * Don't call this function directly: use getFinalParams() to allow
220 * hooks to modify parameters as needed.
222 * Some derived classes may choose to handle an integer $flags parameter
223 * in the overriding methods. Callers of this method can pass zero or
224 * more OR-ed flags like GET_VALUES_FOR_HELP.
228 protected function getAllowedParams( /* $flags = 0 */ ) {
229 // int $flags is not declared because it causes "Strict standards"
230 // warning. Most derived classes do not implement it.
235 * Indicates if this module needs maxlag to be checked
238 public function shouldCheckMaxlag() {
243 * Indicates whether this module requires read rights
246 public function isReadMode() {
251 * Indicates whether this module requires write mode
254 public function isWriteMode() {
259 * Indicates whether this module must be called with a POST request
262 public function mustBePosted() {
263 return $this->needsToken() !== false;
267 * Indicates whether this module is deprecated
271 public function isDeprecated() {
276 * Indicates whether this module is "internal" or unstable
280 public function isInternal() {
285 * Returns the token type this module requires in order to execute.
287 * Modules are strongly encouraged to use the core 'csrf' type unless they
288 * have specialized security needs. If the token type is not one of the
289 * core types, you must use the ApiQueryTokensRegisterTypes hook to
292 * Returning a non-falsey value here will force the addition of an
293 * appropriate 'token' parameter in self::getFinalParams(). Also,
294 * self::mustBePosted() must return true when tokens are used.
296 * In previous versions of MediaWiki, true was a valid return value.
297 * Returning true will generate errors indicating that the API module needs
300 * @return string|false
302 public function needsToken() {
307 * Fetch the salt used in the Web UI corresponding to this module.
309 * Only override this if the Web UI uses a token with a non-constant salt.
312 * @param array $params All supplied parameters for the module
313 * @return string|array|null
315 protected function getWebUITokenSalt( array $params ) {
321 /************************************************************************//**
322 * @name Data access methods
327 * Get the name of the module being executed by this instance
330 public function getModuleName() {
331 return $this->mModuleName
;
335 * Get parameter prefix (usually two letters or an empty string).
338 public function getModulePrefix() {
339 return $this->mModulePrefix
;
343 * Get the main module
346 public function getMain() {
347 return $this->mMainModule
;
351 * Returns true if this module is the main module ($this === $this->mMainModule),
355 public function isMain() {
356 return $this === $this->mMainModule
;
360 * Get the parent of this module
362 * @return ApiBase|null
364 public function getParent() {
365 return $this->isMain() ?
null : $this->getMain();
369 * Get the path to this module
374 public function getModulePath() {
375 if ( $this->isMain() ) {
377 } elseif ( $this->getParent()->isMain() ) {
378 return $this->getModuleName();
380 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
385 * Get a module from its module path
388 * @param string $path
389 * @return ApiBase|null
390 * @throws UsageException
392 public function getModuleFromPath( $path ) {
393 $module = $this->getMain();
394 if ( $path === 'main' ) {
398 $parts = explode( '+', $path );
399 if ( count( $parts ) === 1 ) {
400 // In case the '+' was typed into URL, it resolves as a space
401 $parts = explode( ' ', $path );
404 $count = count( $parts );
405 for ( $i = 0; $i < $count; $i++
) {
407 $manager = $parent->getModuleManager();
408 if ( $manager === null ) {
409 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
410 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
412 $module = $manager->getModule( $parts[$i] );
414 if ( $module === null ) {
415 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
417 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
427 * Get the result object
430 public function getResult() {
431 // Main module has getResult() method overridden
432 // Safety - avoid infinite loop:
433 if ( $this->isMain() ) {
434 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
437 return $this->getMain()->getResult();
441 * Get the result data array (read-only)
444 public function getResultData() {
445 return $this->getResult()->getData();
449 * Gets a default slave database connection object
450 * @return DatabaseBase
452 protected function getDB() {
453 if ( !isset( $this->mSlaveDB
) ) {
454 $this->profileDBIn();
455 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
456 $this->profileDBOut();
459 return $this->mSlaveDB
;
464 /************************************************************************//**
465 * @name Parameter handling
470 * This method mangles parameter name based on the prefix supplied to the constructor.
471 * Override this method to change parameter name during runtime
472 * @param string $paramName Parameter name
473 * @return string Prefixed parameter name
475 public function encodeParamName( $paramName ) {
476 return $this->mModulePrefix
. $paramName;
480 * Using getAllowedParams(), this function makes an array of the values
481 * provided by the user, with key being the name of the variable, and
482 * value - validated value from user or default. limits will not be
483 * parsed if $parseLimit is set to false; use this when the max
484 * limit is not definitive yet, e.g. when getting revisions.
485 * @param bool $parseLimit True by default
488 public function extractRequestParams( $parseLimit = true ) {
489 // Cache parameters, for performance and to avoid bug 24564.
490 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
491 $params = $this->getFinalParams();
494 if ( $params ) { // getFinalParams() can return false
495 foreach ( $params as $paramName => $paramSettings ) {
496 $results[$paramName] = $this->getParameterFromSettings(
497 $paramName, $paramSettings, $parseLimit );
500 $this->mParamCache
[$parseLimit] = $results;
503 return $this->mParamCache
[$parseLimit];
507 * Get a value for the given parameter
508 * @param string $paramName Parameter name
509 * @param bool $parseLimit See extractRequestParams()
510 * @return mixed Parameter value
512 protected function getParameter( $paramName, $parseLimit = true ) {
513 $params = $this->getFinalParams();
514 $paramSettings = $params[$paramName];
516 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
520 * Die if none or more than one of a certain set of parameters is set and not false.
522 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
523 * @param string $required,... Names of parameters of which exactly one must be set
525 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
526 $required = func_get_args();
527 array_shift( $required );
528 $p = $this->getModulePrefix();
530 $intersection = array_intersect( array_keys( array_filter( $params,
531 array( $this, "parameterNotEmpty" ) ) ), $required );
533 if ( count( $intersection ) > 1 ) {
535 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
537 } elseif ( count( $intersection ) == 0 ) {
539 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
546 * Die if more than one of a certain set of parameters is set and not false.
548 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
549 * @param string $required,... Names of parameters of which at most one must be set
551 public function requireMaxOneParameter( $params, $required /*...*/ ) {
552 $required = func_get_args();
553 array_shift( $required );
554 $p = $this->getModulePrefix();
556 $intersection = array_intersect( array_keys( array_filter( $params,
557 array( $this, "parameterNotEmpty" ) ) ), $required );
559 if ( count( $intersection ) > 1 ) {
561 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
568 * Die if none of a certain set of parameters is set and not false.
571 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
572 * @param string $required,... Names of parameters of which at least one must be set
574 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
575 $required = func_get_args();
576 array_shift( $required );
577 $p = $this->getModulePrefix();
579 $intersection = array_intersect(
580 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
584 if ( count( $intersection ) == 0 ) {
585 $this->dieUsage( "At least one of the parameters {$p}" .
586 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
591 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
593 * @param object $x Parameter to check is not null/false
596 private function parameterNotEmpty( $x ) {
597 return !is_null( $x ) && $x !== false;
601 * Get a WikiPage object from a title or pageid param, if possible.
602 * Can die, if no param is set or if the title or page id is not valid.
604 * @param array $params
605 * @param bool|string $load Whether load the object's state from the database:
606 * - false: don't load (if the pageid is given, it will still be loaded)
607 * - 'fromdb': load from a slave database
608 * - 'fromdbmaster': load from the master database
611 public function getTitleOrPageId( $params, $load = false ) {
612 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
615 if ( isset( $params['title'] ) ) {
616 $titleObj = Title
::newFromText( $params['title'] );
617 if ( !$titleObj ||
$titleObj->isExternal() ) {
618 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
620 if ( !$titleObj->canExist() ) {
621 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
623 $pageObj = WikiPage
::factory( $titleObj );
624 if ( $load !== false ) {
625 $pageObj->loadPageData( $load );
627 } elseif ( isset( $params['pageid'] ) ) {
628 if ( $load === false ) {
631 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
633 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
641 * Return true if we're to watch the page, false if not, null if no change.
642 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
643 * @param Title $titleObj The page under consideration
644 * @param string $userOption The user option to consider when $watchlist=preferences.
645 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
648 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
650 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
652 switch ( $watchlist ) {
660 # If the user is already watching, don't bother checking
661 if ( $userWatching ) {
664 # If no user option was passed, use watchdefault and watchcreations
665 if ( is_null( $userOption ) ) {
666 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
667 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
670 # Watch the article based on the user preference
671 return $this->getUser()->getBoolOption( $userOption );
674 return $userWatching;
677 return $userWatching;
682 * Using the settings determine the value for the given parameter
684 * @param string $paramName Parameter name
685 * @param array|mixed $paramSettings Default value or an array of settings
686 * using PARAM_* constants.
687 * @param bool $parseLimit Parse limit?
688 * @return mixed Parameter value
690 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
691 // Some classes may decide to change parameter names
692 $encParamName = $this->encodeParamName( $paramName );
694 if ( !is_array( $paramSettings ) ) {
695 $default = $paramSettings;
697 $type = gettype( $paramSettings );
702 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
703 ?
$paramSettings[self
::PARAM_DFLT
]
705 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
706 ?
$paramSettings[self
::PARAM_ISMULTI
]
708 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
709 ?
$paramSettings[self
::PARAM_TYPE
]
711 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
712 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
714 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
715 ?
$paramSettings[self
::PARAM_DEPRECATED
]
717 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
718 ?
$paramSettings[self
::PARAM_REQUIRED
]
721 // When type is not given, and no choices, the type is the same as $default
722 if ( !isset( $type ) ) {
723 if ( isset( $default ) ) {
724 $type = gettype( $default );
726 $type = 'NULL'; // allow everything
731 if ( $type == 'boolean' ) {
732 if ( isset( $default ) && $default !== false ) {
733 // Having a default value of anything other than 'false' is not allowed
736 "Boolean param $encParamName's default is set to '$default'. " .
737 "Boolean parameters must default to false."
741 $value = $this->getMain()->getCheck( $encParamName );
742 } elseif ( $type == 'upload' ) {
743 if ( isset( $default ) ) {
744 // Having a default value is not allowed
747 "File upload param $encParamName's default is set to " .
748 "'$default'. File upload parameters may not have a default." );
751 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
753 $value = $this->getMain()->getUpload( $encParamName );
754 if ( !$value->exists() ) {
755 // This will get the value without trying to normalize it
756 // (because trying to normalize a large binary file
757 // accidentally uploaded as a field fails spectacularly)
758 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
759 if ( $value !== null ) {
761 "File upload param $encParamName is not a file upload; " .
762 "be sure to use multipart/form-data for your POST and include " .
763 "a filename in the Content-Disposition header.",
764 "badupload_{$encParamName}"
769 $value = $this->getMain()->getVal( $encParamName, $default );
771 if ( isset( $value ) && $type == 'namespace' ) {
772 $type = MWNamespace
::getValidNamespaces();
774 if ( isset( $value ) && $type == 'submodule' ) {
775 $type = $this->getModuleManager()->getNames( $paramName );
779 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
780 $value = $this->parseMultiValue(
784 is_array( $type ) ?
$type : null
788 // More validation only when choices were not given
789 // choices were validated in parseMultiValue()
790 if ( isset( $value ) ) {
791 if ( !is_array( $type ) ) {
793 case 'NULL': // nothing to do
796 if ( $required && $value === '' ) {
797 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
800 case 'integer': // Force everything using intval() and optionally validate limits
801 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
802 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
803 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
804 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
806 if ( is_array( $value ) ) {
807 $value = array_map( 'intval', $value );
808 if ( !is_null( $min ) ||
!is_null( $max ) ) {
809 foreach ( $value as &$v ) {
810 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
814 $value = intval( $value );
815 if ( !is_null( $min ) ||
!is_null( $max ) ) {
816 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
821 if ( !$parseLimit ) {
822 // Don't do any validation whatsoever
825 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
826 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
830 "MAX1 or MAX2 are not defined for the limit $encParamName"
834 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
836 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
837 if ( $value == 'max' ) {
838 $value = $this->getMain()->canApiHighLimits()
839 ?
$paramSettings[self
::PARAM_MAX2
]
840 : $paramSettings[self
::PARAM_MAX
];
841 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
843 $value = intval( $value );
844 $this->validateLimit(
848 $paramSettings[self
::PARAM_MAX
],
849 $paramSettings[self
::PARAM_MAX2
]
855 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
859 if ( is_array( $value ) ) {
860 foreach ( $value as $key => $val ) {
861 $value[$key] = $this->validateTimestamp( $val, $encParamName );
864 $value = $this->validateTimestamp( $value, $encParamName );
868 if ( is_array( $value ) ) {
869 foreach ( $value as $key => $val ) {
870 $value[$key] = $this->validateUser( $val, $encParamName );
873 $value = $this->validateUser( $value, $encParamName );
876 case 'upload': // nothing to do
879 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
883 // Throw out duplicates if requested
884 if ( !$dupes && is_array( $value ) ) {
885 $value = array_unique( $value );
888 // Set a warning if a deprecated parameter has been passed
889 if ( $deprecated && $value !== false ) {
890 $this->setWarning( "The $encParamName parameter has been deprecated." );
892 } elseif ( $required ) {
893 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
900 * Return an array of values that were given in a 'a|b|c' notation,
901 * after it optionally validates them against the list allowed values.
903 * @param string $valueName The name of the parameter (for error
905 * @param mixed $value The value being parsed
906 * @param bool $allowMultiple Can $value contain more than one value
908 * @param string[]|null $allowedValues An array of values to check against. If
909 * null, all values are accepted.
910 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
912 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
913 if ( trim( $value ) === '' && $allowMultiple ) {
917 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
918 // because it unstubs $wgUser
919 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
920 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
924 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
925 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
926 "the limit is $sizeLimit" );
929 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
930 // Bug 33482 - Allow entries with | in them for non-multiple values
931 if ( in_array( $value, $allowedValues, true ) ) {
935 $possibleValues = is_array( $allowedValues )
936 ?
"of '" . implode( "', '", $allowedValues ) . "'"
939 "Only one $possibleValues is allowed for parameter '$valueName'",
940 "multival_$valueName"
944 if ( is_array( $allowedValues ) ) {
945 // Check for unknown values
946 $unknown = array_diff( $valuesList, $allowedValues );
947 if ( count( $unknown ) ) {
948 if ( $allowMultiple ) {
949 $s = count( $unknown ) > 1 ?
's' : '';
950 $vals = implode( ", ", $unknown );
951 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
954 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
959 // Now throw them out
960 $valuesList = array_intersect( $valuesList, $allowedValues );
963 return $allowMultiple ?
$valuesList : $valuesList[0];
967 * Validate the value against the minimum and user/bot maximum limits.
968 * Prints usage info on failure.
969 * @param string $paramName Parameter name
970 * @param int $value Parameter value
971 * @param int|null $min Minimum value
972 * @param int|null $max Maximum value for users
973 * @param int $botMax Maximum value for sysops/bots
974 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
976 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
977 if ( !is_null( $min ) && $value < $min ) {
979 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
980 $this->warnOrDie( $msg, $enforceLimits );
984 // Minimum is always validated, whereas maximum is checked only if not
985 // running in internal call mode
986 if ( $this->getMain()->isInternalMode() ) {
990 // Optimization: do not check user's bot status unless really needed -- skips db query
991 // assumes $botMax >= $max
992 if ( !is_null( $max ) && $value > $max ) {
993 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
994 if ( $value > $botMax ) {
995 $msg = $this->encodeParamName( $paramName ) .
996 " may not be over $botMax (set to $value) for bots or sysops";
997 $this->warnOrDie( $msg, $enforceLimits );
1001 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1002 $this->warnOrDie( $msg, $enforceLimits );
1009 * Validate and normalize of parameters of type 'timestamp'
1010 * @param string $value Parameter value
1011 * @param string $encParamName Parameter name
1012 * @return string Validated and normalized parameter
1014 protected function validateTimestamp( $value, $encParamName ) {
1015 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1016 if ( $unixTimestamp === false ) {
1018 "Invalid value '$value' for timestamp parameter $encParamName",
1019 "badtimestamp_{$encParamName}"
1023 return wfTimestamp( TS_MW
, $unixTimestamp );
1027 * Validate the supplied token.
1030 * @param string $token Supplied token
1031 * @param array $params All supplied parameters for the module
1034 public final function validateToken( $token, array $params ) {
1035 $tokenType = $this->needsToken();
1036 $salts = ApiQueryTokens
::getTokenTypeSalts();
1037 if ( !isset( $salts[$tokenType] ) ) {
1038 throw new MWException(
1039 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1040 'without registering it'
1044 if ( $this->getUser()->matchEditToken(
1052 $webUiSalt = $this->getWebUITokenSalt( $params );
1053 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1065 * Validate and normalize of parameters of type 'user'
1066 * @param string $value Parameter value
1067 * @param string $encParamName Parameter name
1068 * @return string Validated and normalized parameter
1070 private function validateUser( $value, $encParamName ) {
1071 $title = Title
::makeTitleSafe( NS_USER
, $value );
1072 if ( $title === null ) {
1074 "Invalid value '$value' for user parameter $encParamName",
1075 "baduser_{$encParamName}"
1079 return $title->getText();
1084 /************************************************************************//**
1085 * @name Utility methods
1090 * Set a watch (or unwatch) based the based on a watchlist parameter.
1091 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1092 * @param Title $titleObj The article's title to change
1093 * @param string $userOption The user option to consider when $watch=preferences
1095 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1096 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1097 if ( $value === null ) {
1101 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1105 * Truncate an array to a certain length.
1106 * @param array $arr Array to truncate
1107 * @param int $limit Maximum length
1108 * @return bool True if the array was truncated, false otherwise
1110 public static function truncateArray( &$arr, $limit ) {
1112 while ( count( $arr ) > $limit ) {
1121 * Gets the user for whom to get the watchlist
1123 * @param array $params
1126 public function getWatchlistUser( $params ) {
1127 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1128 $user = User
::newFromName( $params['owner'], false );
1129 if ( !( $user && $user->getId() ) ) {
1130 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1132 $token = $user->getOption( 'watchlisttoken' );
1133 if ( $token == '' ||
$token != $params['token'] ) {
1135 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1140 if ( !$this->getUser()->isLoggedIn() ) {
1141 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1143 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1144 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1146 $user = $this->getUser();
1153 * A subset of wfEscapeWikiText for BC texts
1156 * @param string|array $v
1157 * @return string|array
1159 private static function escapeWikiText( $v ) {
1160 if ( is_array( $v ) ) {
1161 return array_map( 'self::escapeWikiText', $v );
1163 return strtr( $v, array(
1164 '__' => '__', '{' => '{', '}' => '}',
1165 '[[Category:' => '[[:Category:',
1166 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1172 * Create a Message from a string or array
1174 * A string is used as a message key. An array has the message key as the
1175 * first value and message parameters as subsequent values.
1178 * @param string|array|Message $msg
1179 * @param IContextSource $context
1180 * @param array $params
1181 * @return Message|null
1183 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1184 if ( is_string( $msg ) ) {
1185 $msg = wfMessage( $msg );
1186 } elseif ( is_array( $msg ) ) {
1187 $msg = call_user_func_array( 'wfMessage', $msg );
1189 if ( !$msg instanceof Message
) {
1193 $msg->setContext( $context );
1195 $msg->params( $params );
1203 /************************************************************************//**
1204 * @name Warning and error reporting
1209 * Set warning section for this module. Users should monitor this
1210 * section to notice any changes in API. Multiple calls to this
1211 * function will result in the warning messages being separated by
1213 * @param string $warning Warning message
1215 public function setWarning( $warning ) {
1216 $result = $this->getResult();
1217 $data = $result->getData();
1218 $moduleName = $this->getModuleName();
1219 if ( isset( $data['warnings'][$moduleName] ) ) {
1220 // Don't add duplicate warnings
1221 $oldWarning = $data['warnings'][$moduleName]['*'];
1222 $warnPos = strpos( $oldWarning, $warning );
1223 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1224 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
1225 // Check if $warning is followed by "\n" or the end of the $oldWarning
1226 $warnPos +
= strlen( $warning );
1227 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
1231 // If there is a warning already, append it to the existing one
1232 $warning = "$oldWarning\n$warning";
1235 ApiResult
::setContent( $msg, $warning );
1236 $result->addValue( 'warnings', $moduleName,
1237 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
1241 * Adds a warning to the output, else dies
1243 * @param string $msg Message to show as a warning, or error message if dying
1244 * @param bool $enforceLimits Whether this is an enforce (die)
1246 private function warnOrDie( $msg, $enforceLimits = false ) {
1247 if ( $enforceLimits ) {
1248 $this->dieUsage( $msg, 'integeroutofrange' );
1251 $this->setWarning( $msg );
1255 * Throw a UsageException, which will (if uncaught) call the main module's
1256 * error handler and die with an error message.
1258 * @param string $description One-line human-readable description of the
1259 * error condition, e.g., "The API requires a valid action parameter"
1260 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1261 * automated identification of the error, e.g., 'unknown_action'
1262 * @param int $httpRespCode HTTP response code
1263 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1264 * @throws UsageException
1266 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1267 Profiler
::instance()->close();
1268 throw new UsageException(
1270 $this->encodeParamName( $errorCode ),
1277 * Get error (as code, string) from a Status object.
1280 * @param Status $status
1281 * @return array Array of code and error string
1283 public function getErrorFromStatus( $status ) {
1284 if ( $status->isGood() ) {
1285 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1288 $errors = $status->getErrorsArray();
1290 // No errors? Assume the warnings should be treated as errors
1291 $errors = $status->getWarningsArray();
1294 // Still no errors? Punt
1295 $errors = array( array( 'unknownerror-nocode' ) );
1298 // Cannot use dieUsageMsg() because extensions might return custom
1300 if ( $errors[0] instanceof Message
) {
1302 $code = $msg->getKey();
1304 $code = array_shift( $errors[0] );
1305 $msg = wfMessage( $code, $errors[0] );
1307 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1308 // Translate message to code, for backwards compatibility
1309 $code = ApiBase
::$messageMap[$code]['code'];
1312 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1316 * Throw a UsageException based on the errors in the Status object.
1319 * @param Status $status
1320 * @throws MWException
1322 public function dieStatus( $status ) {
1324 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1325 $this->dieUsage( $msg, $code );
1328 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1330 * Array that maps message keys to error messages. $1 and friends are replaced.
1332 public static $messageMap = array(
1333 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1334 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1335 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1337 // Messages from Title::getUserPermissionsErrors()
1338 'ns-specialprotected' => array(
1339 'code' => 'unsupportednamespace',
1340 'info' => "Pages in the Special namespace can't be edited"
1342 'protectedinterface' => array(
1343 'code' => 'protectednamespace-interface',
1344 'info' => "You're not allowed to edit interface messages"
1346 'namespaceprotected' => array(
1347 'code' => 'protectednamespace',
1348 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1350 'customcssprotected' => array(
1351 'code' => 'customcssprotected',
1352 'info' => "You're not allowed to edit custom CSS pages"
1354 'customjsprotected' => array(
1355 'code' => 'customjsprotected',
1356 'info' => "You're not allowed to edit custom JavaScript pages"
1358 'cascadeprotected' => array(
1359 'code' => 'cascadeprotected',
1360 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1362 'protectedpagetext' => array(
1363 'code' => 'protectedpage',
1364 'info' => "The \"\$1\" right is required to edit this page"
1366 'protect-cantedit' => array(
1367 'code' => 'cantedit',
1368 'info' => "You can't protect this page because you can't edit it"
1370 'deleteprotected' => array(
1371 'code' => 'cantedit',
1372 'info' => "You can't delete this page because it has been protected"
1374 'badaccess-group0' => array(
1375 'code' => 'permissiondenied',
1376 'info' => "Permission denied"
1377 ), // Generic permission denied message
1378 'badaccess-groups' => array(
1379 'code' => 'permissiondenied',
1380 'info' => "Permission denied"
1382 'titleprotected' => array(
1383 'code' => 'protectedtitle',
1384 'info' => "This title has been protected from creation"
1386 'nocreate-loggedin' => array(
1387 'code' => 'cantcreate',
1388 'info' => "You don't have permission to create new pages"
1390 'nocreatetext' => array(
1391 'code' => 'cantcreate-anon',
1392 'info' => "Anonymous users can't create new pages"
1394 'movenologintext' => array(
1395 'code' => 'cantmove-anon',
1396 'info' => "Anonymous users can't move pages"
1398 'movenotallowed' => array(
1399 'code' => 'cantmove',
1400 'info' => "You don't have permission to move pages"
1402 'confirmedittext' => array(
1403 'code' => 'confirmemail',
1404 'info' => "You must confirm your email address before you can edit"
1406 'blockedtext' => array(
1407 'code' => 'blocked',
1408 'info' => "You have been blocked from editing"
1410 'autoblockedtext' => array(
1411 'code' => 'autoblocked',
1412 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1415 // Miscellaneous interface messages
1416 'actionthrottledtext' => array(
1417 'code' => 'ratelimited',
1418 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1420 'alreadyrolled' => array(
1421 'code' => 'alreadyrolled',
1422 'info' => "The page you tried to rollback was already rolled back"
1424 'cantrollback' => array(
1425 'code' => 'onlyauthor',
1426 'info' => "The page you tried to rollback only has one author"
1428 'readonlytext' => array(
1429 'code' => 'readonly',
1430 'info' => "The wiki is currently in read-only mode"
1432 'sessionfailure' => array(
1433 'code' => 'badtoken',
1434 'info' => "Invalid token" ),
1435 'cannotdelete' => array(
1436 'code' => 'cantdelete',
1437 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1439 'notanarticle' => array(
1440 'code' => 'missingtitle',
1441 'info' => "The page you requested doesn't exist"
1443 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1445 'immobile_namespace' => array(
1446 'code' => 'immobilenamespace',
1447 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1449 'articleexists' => array(
1450 'code' => 'articleexists',
1451 'info' => "The destination article already exists and is not a redirect to the source article"
1453 'protectedpage' => array(
1454 'code' => 'protectedpage',
1455 'info' => "You don't have permission to perform this move"
1457 'hookaborted' => array(
1458 'code' => 'hookaborted',
1459 'info' => "The modification you tried to make was aborted by an extension hook"
1461 'cantmove-titleprotected' => array(
1462 'code' => 'protectedtitle',
1463 'info' => "The destination article has been protected from creation"
1465 'imagenocrossnamespace' => array(
1466 'code' => 'nonfilenamespace',
1467 'info' => "Can't move a file to a non-file namespace"
1469 'imagetypemismatch' => array(
1470 'code' => 'filetypemismatch',
1471 'info' => "The new file extension doesn't match its type"
1473 // 'badarticleerror' => shouldn't happen
1474 // 'badtitletext' => shouldn't happen
1475 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1476 'range_block_disabled' => array(
1477 'code' => 'rangedisabled',
1478 'info' => "Blocking IP ranges has been disabled"
1480 'nosuchusershort' => array(
1481 'code' => 'nosuchuser',
1482 'info' => "The user you specified doesn't exist"
1484 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1485 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1486 'ipb_already_blocked' => array(
1487 'code' => 'alreadyblocked',
1488 'info' => "The user you tried to block was already blocked"
1490 'ipb_blocked_as_range' => array(
1491 'code' => 'blockedasrange',
1492 '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."
1494 'ipb_cant_unblock' => array(
1495 'code' => 'cantunblock',
1496 'info' => "The block you specified was not found. It may have been unblocked already"
1498 'mailnologin' => array(
1499 'code' => 'cantsend',
1500 '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"
1502 'ipbblocked' => array(
1503 'code' => 'ipbblocked',
1504 'info' => 'You cannot block or unblock users while you are yourself blocked'
1506 'ipbnounblockself' => array(
1507 'code' => 'ipbnounblockself',
1508 'info' => 'You are not allowed to unblock yourself'
1510 'usermaildisabled' => array(
1511 'code' => 'usermaildisabled',
1512 'info' => "User email has been disabled"
1514 'blockedemailuser' => array(
1515 'code' => 'blockedfrommail',
1516 'info' => "You have been blocked from sending email"
1518 'notarget' => array(
1519 'code' => 'notarget',
1520 'info' => "You have not specified a valid target for this action"
1523 'code' => 'noemail',
1524 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1526 'rcpatroldisabled' => array(
1527 'code' => 'patroldisabled',
1528 'info' => "Patrolling is disabled on this wiki"
1530 'markedaspatrollederror-noautopatrol' => array(
1531 'code' => 'noautopatrol',
1532 'info' => "You don't have permission to patrol your own changes"
1534 'delete-toobig' => array(
1535 'code' => 'bigdelete',
1536 'info' => "You can't delete this page because it has more than \$1 revisions"
1538 'movenotallowedfile' => array(
1539 'code' => 'cantmovefile',
1540 'info' => "You don't have permission to move files"
1542 'userrights-no-interwiki' => array(
1543 'code' => 'nointerwikiuserrights',
1544 'info' => "You don't have permission to change user rights on other wikis"
1546 'userrights-nodatabase' => array(
1547 'code' => 'nosuchdatabase',
1548 'info' => "Database \"\$1\" does not exist or is not local"
1550 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1551 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1552 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1553 'import-rootpage-invalid' => array(
1554 'code' => 'import-rootpage-invalid',
1555 'info' => 'Root page is an invalid title'
1557 'import-rootpage-nosubpage' => array(
1558 'code' => 'import-rootpage-nosubpage',
1559 'info' => 'Namespace "$1" of the root page does not allow subpages'
1562 // API-specific messages
1563 'readrequired' => array(
1564 'code' => 'readapidenied',
1565 'info' => "You need read permission to use this module"
1567 'writedisabled' => array(
1568 'code' => 'noapiwrite',
1569 '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"
1571 'writerequired' => array(
1572 'code' => 'writeapidenied',
1573 'info' => "You're not allowed to edit this wiki through the API"
1575 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1576 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1577 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1578 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1579 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1580 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1581 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1582 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1583 'create-titleexists' => array(
1584 'code' => 'create-titleexists',
1585 'info' => "Existing titles can't be protected with 'create'"
1587 'missingtitle-createonly' => array(
1588 'code' => 'missingtitle-createonly',
1589 'info' => "Missing titles can only be protected with 'create'"
1591 'cantblock' => array( 'code' => 'cantblock',
1592 'info' => "You don't have permission to block users"
1594 'canthide' => array(
1595 'code' => 'canthide',
1596 'info' => "You don't have permission to hide user names from the block log"
1598 'cantblock-email' => array(
1599 'code' => 'cantblock-email',
1600 'info' => "You don't have permission to block users from sending email through the wiki"
1602 'unblock-notarget' => array(
1603 'code' => 'notarget',
1604 'info' => "Either the id or the user parameter must be set"
1606 'unblock-idanduser' => array(
1607 'code' => 'idanduser',
1608 'info' => "The id and user parameters can't be used together"
1610 'cantunblock' => array(
1611 'code' => 'permissiondenied',
1612 'info' => "You don't have permission to unblock users"
1614 'cannotundelete' => array(
1615 'code' => 'cantundelete',
1616 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1618 'permdenied-undelete' => array(
1619 'code' => 'permissiondenied',
1620 'info' => "You don't have permission to restore deleted revisions"
1622 'createonly-exists' => array(
1623 'code' => 'articleexists',
1624 'info' => "The article you tried to create has been created already"
1626 'nocreate-missing' => array(
1627 'code' => 'missingtitle',
1628 'info' => "The article you tried to edit doesn't exist"
1630 'nosuchrcid' => array(
1631 'code' => 'nosuchrcid',
1632 'info' => "There is no change with rcid \"\$1\""
1634 'protect-invalidaction' => array(
1635 'code' => 'protect-invalidaction',
1636 'info' => "Invalid protection type \"\$1\""
1638 'protect-invalidlevel' => array(
1639 'code' => 'protect-invalidlevel',
1640 'info' => "Invalid protection level \"\$1\""
1642 'toofewexpiries' => array(
1643 'code' => 'toofewexpiries',
1644 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1646 'cantimport' => array(
1647 'code' => 'cantimport',
1648 'info' => "You don't have permission to import pages"
1650 'cantimport-upload' => array(
1651 'code' => 'cantimport-upload',
1652 'info' => "You don't have permission to import uploaded pages"
1654 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1655 'importuploaderrorsize' => array(
1656 'code' => 'filetoobig',
1657 'info' => 'The file you uploaded is bigger than the maximum upload size'
1659 'importuploaderrorpartial' => array(
1660 'code' => 'partialupload',
1661 'info' => 'The file was only partially uploaded'
1663 'importuploaderrortemp' => array(
1664 'code' => 'notempdir',
1665 'info' => 'The temporary upload directory is missing'
1667 'importcantopen' => array(
1668 'code' => 'cantopenfile',
1669 'info' => "Couldn't open the uploaded file"
1671 'import-noarticle' => array(
1672 'code' => 'badinterwiki',
1673 'info' => 'Invalid interwiki title specified'
1675 'importbadinterwiki' => array(
1676 'code' => 'badinterwiki',
1677 'info' => 'Invalid interwiki title specified'
1679 'import-unknownerror' => array(
1680 'code' => 'import-unknownerror',
1681 'info' => "Unknown error on import: \"\$1\""
1683 'cantoverwrite-sharedfile' => array(
1684 'code' => 'cantoverwrite-sharedfile',
1685 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1687 'sharedfile-exists' => array(
1688 'code' => 'fileexists-sharedrepo-perm',
1689 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1691 'mustbeposted' => array(
1692 'code' => 'mustbeposted',
1693 'info' => "The \$1 module requires a POST request"
1697 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1699 'specialpage-cantexecute' => array(
1700 'code' => 'specialpage-cantexecute',
1701 'info' => "You don't have permission to view the results of this special page"
1703 'invalidoldimage' => array(
1704 'code' => 'invalidoldimage',
1705 'info' => 'The oldimage parameter has invalid format'
1707 'nodeleteablefile' => array(
1708 'code' => 'nodeleteablefile',
1709 'info' => 'No such old version of the file'
1711 'fileexists-forbidden' => array(
1712 'code' => 'fileexists-forbidden',
1713 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1715 'fileexists-shared-forbidden' => array(
1716 'code' => 'fileexists-shared-forbidden',
1717 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1719 'filerevert-badversion' => array(
1720 'code' => 'filerevert-badversion',
1721 'info' => 'There is no previous local version of this file with the provided timestamp.'
1724 // ApiEditPage messages
1725 'noimageredirect-anon' => array(
1726 'code' => 'noimageredirect-anon',
1727 'info' => "Anonymous users can't create image redirects"
1729 'noimageredirect-logged' => array(
1730 'code' => 'noimageredirect',
1731 'info' => "You don't have permission to create image redirects"
1733 'spamdetected' => array(
1734 'code' => 'spamdetected',
1735 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1737 'contenttoobig' => array(
1738 'code' => 'contenttoobig',
1739 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1741 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1742 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1743 'wasdeleted' => array(
1744 'code' => 'pagedeleted',
1745 'info' => "The page has been deleted since you fetched its timestamp"
1747 'blankpage' => array(
1748 'code' => 'emptypage',
1749 'info' => "Creating new, empty pages is not allowed"
1751 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1752 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1753 'missingtext' => array(
1755 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1757 'emptynewsection' => array(
1758 'code' => 'emptynewsection',
1759 'info' => 'Creating empty new sections is not possible.'
1761 'revwrongpage' => array(
1762 'code' => 'revwrongpage',
1763 'info' => "r\$1 is not a revision of \"\$2\""
1765 'undo-failure' => array(
1766 'code' => 'undofailure',
1767 'info' => 'Undo failed due to conflicting intermediate edits'
1769 'content-not-allowed-here' => array(
1770 'code' => 'contentnotallowedhere',
1771 'info' => 'Content model "$1" is not allowed at title "$2"'
1774 // Messages from WikiPage::doEit()
1775 'edit-hook-aborted' => array(
1776 'code' => 'edit-hook-aborted',
1777 'info' => "Your edit was aborted by an ArticleSave hook"
1779 'edit-gone-missing' => array(
1780 'code' => 'edit-gone-missing',
1781 'info' => "The page you tried to edit doesn't seem to exist anymore"
1783 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1784 'edit-already-exists' => array(
1785 'code' => 'edit-already-exists',
1786 'info' => 'It seems the page you tried to create already exist'
1790 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1791 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1792 'uploaddisabled' => array(
1793 'code' => 'uploaddisabled',
1794 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1796 'copyuploaddisabled' => array(
1797 'code' => 'copyuploaddisabled',
1798 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1800 'copyuploadbaddomain' => array(
1801 'code' => 'copyuploadbaddomain',
1802 'info' => 'Uploads by URL are not allowed from this domain.'
1804 'copyuploadbadurl' => array(
1805 'code' => 'copyuploadbadurl',
1806 'info' => 'Upload not allowed from this URL.'
1809 'filename-tooshort' => array(
1810 'code' => 'filename-tooshort',
1811 'info' => 'The filename is too short'
1813 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1814 'illegal-filename' => array(
1815 'code' => 'illegal-filename',
1816 'info' => 'The filename is not allowed'
1818 'filetype-missing' => array(
1819 'code' => 'filetype-missing',
1820 'info' => 'The file is missing an extension'
1823 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1825 // @codingStandardsIgnoreEnd
1828 * Helper function for readonly errors
1830 public function dieReadOnly() {
1831 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1832 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1833 array( 'readonlyreason' => wfReadOnlyReason() ) );
1837 * Output the error message related to a certain array
1838 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1840 public function dieUsageMsg( $error ) {
1841 # most of the time we send a 1 element, so we might as well send it as
1842 # a string and make this an array here.
1843 if ( is_string( $error ) ) {
1844 $error = array( $error );
1846 $parsed = $this->parseMsg( $error );
1847 $this->dieUsage( $parsed['info'], $parsed['code'] );
1851 * Will only set a warning instead of failing if the global $wgDebugAPI
1852 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1853 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1856 public function dieUsageMsgOrDebug( $error ) {
1857 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1858 $this->dieUsageMsg( $error );
1861 if ( is_string( $error ) ) {
1862 $error = array( $error );
1864 $parsed = $this->parseMsg( $error );
1865 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1869 * Die with the $prefix.'badcontinue' error. This call is common enough to
1870 * make it into the base method.
1871 * @param bool $condition Will only die if this value is true
1874 protected function dieContinueUsageIf( $condition ) {
1877 'Invalid continue param. You should pass the original value returned by the previous query',
1883 * Return the error message related to a certain array
1884 * @param array $error Element of a getUserPermissionsErrors()-style array
1885 * @return array('code' => code, 'info' => info)
1887 public function parseMsg( $error ) {
1888 $error = (array)$error; // It seems strings sometimes make their way in here
1889 $key = array_shift( $error );
1891 // Check whether the error array was nested
1892 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1893 if ( is_array( $key ) ) {
1895 $key = array_shift( $error );
1898 if ( isset( self
::$messageMap[$key] ) ) {
1900 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1901 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1905 // If the key isn't present, throw an "unknown error"
1906 return $this->parseMsg( array( 'unknownerror', $key ) );
1910 * Internal code errors should be reported with this method
1911 * @param string $method Method or function name
1912 * @param string $message Error message
1913 * @throws MWException
1915 protected static function dieDebug( $method, $message ) {
1916 throw new MWException( "Internal error in $method: $message" );
1921 /************************************************************************//**
1922 * @name Help message generation
1927 * Get final module description, after hooks have had a chance to tweak it as
1930 * @since 1.25, returns Message[] rather than string[]
1933 public function getFinalDescription() {
1934 $desc = $this->getDescription();
1935 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
1936 $desc = self
::escapeWikiText( $desc );
1937 if ( is_array( $desc ) ) {
1938 $desc = join( "\n", $desc );
1940 $desc = (string)$desc;
1943 $msg = $this->msg( "apihelp-{$this->getModulePath()}-description", array(
1944 $this->getModulePrefix(),
1945 $this->getModuleName(),
1946 $this->getModulePath(),
1948 if ( !$msg->exists() ) {
1949 $msg = $this->msg( 'api-help-fallback-description', $desc );
1951 $msgs = array( $msg );
1953 wfRunHooks( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
1959 * Get final list of parameters, after hooks have had a chance to
1960 * tweak it as needed.
1962 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1963 * @return array|bool False on no parameters
1964 * @since 1.21 $flags param added
1966 public function getFinalParams( $flags = 0 ) {
1967 $params = $this->getAllowedParams( $flags );
1972 if ( $this->needsToken() ) {
1973 $params['token'] = array(
1974 ApiBase
::PARAM_TYPE
=> 'string',
1975 ApiBase
::PARAM_REQUIRED
=> true,
1976 ApiBase
::PARAM_HELP_MSG
=> array(
1977 'api-help-param-token',
1978 $this->needsToken(),
1980 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
1983 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
1989 * Get final parameter descriptions, after hooks have had a chance to tweak it as
1992 * @since 1.25, returns array of Message[] rather than array of string[]
1993 * @return array Keys are parameter names, values are arrays of Message objects
1995 public function getFinalParamDescription() {
1996 $desc = $this->getParamDescription();
1997 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
2002 $desc = self
::escapeWikiText( $desc );
2004 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2006 foreach ( $params as $param => $settings ) {
2007 if ( !is_array( $settings ) ) {
2008 $settings = array();
2011 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2012 if ( is_array( $d ) ) {
2013 // Special handling for prop parameters
2014 $d = array_map( function ( $line ) {
2015 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2016 $line = "\n;{$m[1]}:{$m[2]}";
2020 $d = join( ' ', $d );
2023 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2024 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2026 $msg = $this->msg( "apihelp-{$this->getModulePath()}-param-{$param}" );
2027 if ( !$msg->exists() ) {
2028 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2031 $msg = ApiBase
::makeMessage( $msg, $this->getContext(), array(
2032 $this->getModulePrefix(),
2034 $this->getModuleName(),
2035 $this->getModulePath(),
2038 $this->dieDebug( __METHOD__
,
2039 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2041 $msgs[$param] = array( $msg );
2043 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2044 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2045 $this->dieDebug( __METHOD__
,
2046 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2048 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2049 $m = ApiBase
::makeMessage( $m, $this->getContext(), array(
2050 $this->getModulePrefix(),
2052 $this->getModuleName(),
2053 $this->getModulePath(),
2056 $msgs[$param][] = $m;
2058 $this->dieDebug( __METHOD__
,
2059 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2065 wfRunHooks( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2071 * Generates the list of flags for the help screen and for action=paraminfo
2073 * Corresponding messages: api-help-flag-deprecated,
2074 * api-help-flag-internal, api-help-flag-readrights,
2075 * api-help-flag-writerights, api-help-flag-mustbeposted
2079 protected function getHelpFlags() {
2082 if ( $this->isDeprecated() ) {
2083 $flags[] = 'deprecated';
2085 if ( $this->isInternal() ) {
2086 $flags[] = 'internal';
2088 if ( $this->isReadMode() ) {
2089 $flags[] = 'readrights';
2091 if ( $this->isWriteMode() ) {
2092 $flags[] = 'writerights';
2094 if ( $this->mustBePosted() ) {
2095 $flags[] = 'mustbeposted';
2102 * Called from ApiHelp before the pieces are joined together and returned.
2104 * This exists mainly for ApiMain to add the Permissions and Credits
2105 * sections. Other modules probably don't need it.
2107 * @param string[] &$help Array of help data
2108 * @param array $options Options passed to ApiHelp::getHelp
2110 public function modifyHelp( array &$help, array $options ) {
2115 /************************************************************************//**
2121 * Profiling: total module execution time
2123 private $mTimeIn = 0, $mModuleTime = 0;
2126 * Get the name of the module as shown in the profiler log
2128 * @param DatabaseBase|bool $db
2132 public function getModuleProfileName( $db = false ) {
2134 return 'API:' . $this->mModuleName
. '-DB';
2137 return 'API:' . $this->mModuleName
;
2141 * Start module profiling
2143 public function profileIn() {
2144 if ( $this->mTimeIn
!== 0 ) {
2145 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2147 $this->mTimeIn
= microtime( true );
2148 wfProfileIn( $this->getModuleProfileName() );
2152 * End module profiling
2154 public function profileOut() {
2155 if ( $this->mTimeIn
=== 0 ) {
2156 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2158 if ( $this->mDBTimeIn
!== 0 ) {
2161 'Must be called after database profiling is done with profileDBOut()'
2165 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2167 wfProfileOut( $this->getModuleProfileName() );
2171 * When modules crash, sometimes it is needed to do a profileOut() regardless
2172 * of the profiling state the module was in. This method does such cleanup.
2174 public function safeProfileOut() {
2175 if ( $this->mTimeIn
!== 0 ) {
2176 if ( $this->mDBTimeIn
!== 0 ) {
2177 $this->profileDBOut();
2179 $this->profileOut();
2184 * Total time the module was executed
2187 public function getProfileTime() {
2188 if ( $this->mTimeIn
!== 0 ) {
2189 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2192 return $this->mModuleTime
;
2196 * Profiling: database execution time
2198 private $mDBTimeIn = 0, $mDBTime = 0;
2201 * Start module profiling
2203 public function profileDBIn() {
2204 if ( $this->mTimeIn
=== 0 ) {
2207 'Must be called while profiling the entire module with profileIn()'
2210 if ( $this->mDBTimeIn
!== 0 ) {
2211 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2213 $this->mDBTimeIn
= microtime( true );
2214 wfProfileIn( $this->getModuleProfileName( true ) );
2218 * End database profiling
2220 public function profileDBOut() {
2221 if ( $this->mTimeIn
=== 0 ) {
2222 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2223 'the entire module with profileIn()' );
2225 if ( $this->mDBTimeIn
=== 0 ) {
2226 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2229 $time = microtime( true ) - $this->mDBTimeIn
;
2230 $this->mDBTimeIn
= 0;
2232 $this->mDBTime +
= $time;
2233 $this->getMain()->mDBTime +
= $time;
2234 wfProfileOut( $this->getModuleProfileName( true ) );
2238 * Total time the module used the database
2241 public function getProfileDBTime() {
2242 if ( $this->mDBTimeIn
!== 0 ) {
2243 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2246 return $this->mDBTime
;
2250 * Write logging information for API features to a debug log, for usage
2252 * @param string $feature Feature being used.
2254 protected function logFeatureUsage( $feature ) {
2255 $request = $this->getRequest();
2256 $s = '"' . addslashes( $feature ) . '"' .
2257 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2258 ' "' . $request->getIP() . '"' .
2259 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2260 ' "' . addslashes( $request->getHeader( 'User-agent' ) ) . '"';
2261 wfDebugLog( 'api-feature-usage', $s, 'private' );
2266 /************************************************************************//**
2271 /// @deprecated since 1.24
2272 const PROP_ROOT
= 'ROOT';
2273 /// @deprecated since 1.24
2274 const PROP_LIST
= 'LIST';
2275 /// @deprecated since 1.24
2276 const PROP_TYPE
= 0;
2277 /// @deprecated since 1.24
2278 const PROP_NULLABLE
= 1;
2281 * Formerly returned a string that identifies the version of the extending
2282 * class. Typically included the class name, the svn revision, timestamp,
2283 * and last author. Usually done with SVN's Id keyword
2285 * @deprecated since 1.21, version string is no longer supported
2288 public function getVersion() {
2289 wfDeprecated( __METHOD__
, '1.21' );
2294 * Formerly used to fetch a list of possible properites in the result,
2295 * somehow organized with respect to the prop parameter that causes them to
2296 * be returned. The specific semantics of the return value was never
2297 * specified. Since this was never possible to be accurately updated, it
2300 * @deprecated since 1.24
2301 * @return array|bool
2303 protected function getResultProperties() {
2304 wfDeprecated( __METHOD__
, '1.24' );
2309 * @see self::getResultProperties()
2310 * @deprecated since 1.24
2311 * @return array|bool
2313 public function getFinalResultProperties() {
2314 wfDeprecated( __METHOD__
, '1.24' );
2319 * @see self::getResultProperties()
2320 * @deprecated since 1.24
2322 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2323 wfDeprecated( __METHOD__
, '1.24' );
2327 * @see self::getPossibleErrors()
2328 * @deprecated since 1.24
2331 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2332 wfDeprecated( __METHOD__
, '1.24' );
2337 * @see self::getPossibleErrors()
2338 * @deprecated since 1.24
2341 public function getRequireMaxOneParameterErrorMessages( $params ) {
2342 wfDeprecated( __METHOD__
, '1.24' );
2347 * @see self::getPossibleErrors()
2348 * @deprecated since 1.24
2351 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2352 wfDeprecated( __METHOD__
, '1.24' );
2357 * @see self::getPossibleErrors()
2358 * @deprecated since 1.24
2361 public function getTitleOrPageIdErrorMessage() {
2362 wfDeprecated( __METHOD__
, '1.24' );
2367 * This formerly attempted to return a list of all possible errors returned
2368 * by the module. However, this was impossible to maintain in many cases
2369 * since errors could come from other areas of MediaWiki and in some cases
2370 * from arbitrary extension hooks. Since a partial list claiming to be
2371 * comprehensive is unlikely to be useful, it was removed.
2373 * @deprecated since 1.24
2376 public function getPossibleErrors() {
2377 wfDeprecated( __METHOD__
, '1.24' );
2382 * @see self::getPossibleErrors()
2383 * @deprecated since 1.24
2386 public function getFinalPossibleErrors() {
2387 wfDeprecated( __METHOD__
, '1.24' );
2392 * @see self::getPossibleErrors()
2393 * @deprecated since 1.24
2396 public function parseErrors( $errors ) {
2397 wfDeprecated( __METHOD__
, '1.24' );
2402 * Returns the description string for this module
2404 * Ignored if an i18n message exists for
2405 * "apihelp-{$this->getModulePathString()}-description".
2407 * @deprecated since 1.25
2408 * @return Message|string|array
2410 protected function getDescription() {
2415 * Returns an array of parameter descriptions.
2417 * For each parameter, ignored if an i18n message exists for the parameter.
2418 * By default that message is
2419 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2420 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2421 * self::getFinalParams().
2423 * @deprecated since 1.25
2424 * @return array|bool False on no parameter descriptions
2426 protected function getParamDescription() {
2431 * Returns usage examples for this module.
2433 * Return value as an array is either:
2434 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2436 * - sequential numeric keys with even-numbered keys being display-text
2437 * and odd-numbered keys being partial urls
2438 * - partial URLs as keys with display-text (string or array-to-be-joined)
2440 * Return value as a string is the same as an array with a numeric key and
2441 * that value, and boolean false means "no examples".
2443 * @deprecated since 1.25, use getExamplesMessages() instead
2444 * @return bool|string|array
2446 protected function getExamples() {
2451 * Generates help message for this module, or false if there is no description
2452 * @deprecated since 1.25
2453 * @return string|bool
2455 public function makeHelpMsg() {
2456 wfDeprecated( __METHOD__
, '1.25' );
2457 static $lnPrfx = "\n ";
2459 $msg = $this->getFinalDescription();
2461 if ( $msg !== false ) {
2463 if ( !is_array( $msg ) ) {
2468 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2470 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2472 if ( $this->isReadMode() ) {
2473 $msg .= "\nThis module requires read rights";
2475 if ( $this->isWriteMode() ) {
2476 $msg .= "\nThis module requires write rights";
2478 if ( $this->mustBePosted() ) {
2479 $msg .= "\nThis module only accepts POST requests";
2481 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2482 $this->mustBePosted()
2488 $paramsMsg = $this->makeHelpMsgParameters();
2489 if ( $paramsMsg !== false ) {
2490 $msg .= "Parameters:\n$paramsMsg";
2493 $examples = $this->getExamples();
2495 if ( !is_array( $examples ) ) {
2500 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2501 foreach ( $examples as $k => $v ) {
2502 if ( is_numeric( $k ) ) {
2505 if ( is_array( $v ) ) {
2506 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2508 $msgExample = " $v";
2511 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2521 * @deprecated since 1.25
2522 * @param string $item
2525 private function indentExampleText( $item ) {
2530 * @deprecated since 1.25
2531 * @param string $prefix Text to split output items
2532 * @param string $title What is being output
2533 * @param string|array $input
2536 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2537 wfDeprecated( __METHOD__
, '1.25' );
2538 if ( $input === false ) {
2541 if ( !is_array( $input ) ) {
2542 $input = array( $input );
2545 if ( count( $input ) > 0 ) {
2547 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2551 $msg .= implode( $prefix, $input ) . "\n";
2560 * Generates the parameter descriptions for this module, to be displayed in the
2562 * @deprecated since 1.25
2563 * @return string|bool
2565 public function makeHelpMsgParameters() {
2566 wfDeprecated( __METHOD__
, '1.25' );
2567 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2570 $paramsDescription = $this->getFinalParamDescription();
2572 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2573 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2574 foreach ( $params as $paramName => $paramSettings ) {
2575 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2576 if ( is_array( $desc ) ) {
2577 $desc = implode( $paramPrefix, $desc );
2581 if ( !is_array( $paramSettings ) ) {
2582 $paramSettings = array(
2583 self
::PARAM_DFLT
=> $paramSettings,
2587 //handle missing type
2588 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2589 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2590 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2592 if ( is_bool( $dflt ) ) {
2593 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2594 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2595 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2596 } elseif ( is_int( $dflt ) ) {
2597 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2601 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2602 && $paramSettings[self
::PARAM_DEPRECATED
]
2604 $desc = "DEPRECATED! $desc";
2607 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2608 && $paramSettings[self
::PARAM_REQUIRED
]
2610 $desc .= $paramPrefix . "This parameter is required";
2613 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2614 ?
$paramSettings[self
::PARAM_TYPE
]
2616 if ( isset( $type ) ) {
2617 $hintPipeSeparated = true;
2618 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2619 ?
$paramSettings[self
::PARAM_ISMULTI
]
2622 $prompt = 'Values (separate with \'|\'): ';
2624 $prompt = 'One value: ';
2627 if ( $type === 'submodule' ) {
2628 $type = $this->getModuleManager()->getNames( $paramName );
2631 if ( is_array( $type ) ) {
2633 $nothingPrompt = '';
2634 foreach ( $type as $t ) {
2636 $nothingPrompt = 'Can be empty, or ';
2641 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2642 $choicesstring = implode( ', ', $choices );
2643 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2644 $hintPipeSeparated = false;
2648 // Special handling because namespaces are
2649 // type-limited, yet they are not given
2650 $desc .= $paramPrefix . $prompt;
2651 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2652 100, $descWordwrap );
2653 $hintPipeSeparated = false;
2656 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2657 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2658 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2660 $desc .= ' allowed';
2663 $s = $multi ?
's' : '';
2664 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2665 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2666 if ( $hasMin ||
$hasMax ) {
2668 $intRangeStr = "The value$s must be no less than " .
2669 "{$paramSettings[self::PARAM_MIN]}";
2670 } elseif ( !$hasMin ) {
2671 $intRangeStr = "The value$s must be no more than " .
2672 "{$paramSettings[self::PARAM_MAX]}";
2674 $intRangeStr = "The value$s must be between " .
2675 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2678 $desc .= $paramPrefix . $intRangeStr;
2682 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2688 if ( $hintPipeSeparated ) {
2689 $desc .= $paramPrefix . "Separate values with '|'";
2692 $isArray = is_array( $type );
2694 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2696 $desc .= $paramPrefix . "Maximum number of values " .
2697 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2702 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2703 if ( !is_null( $default ) && $default !== false ) {
2704 $desc .= $paramPrefix . "Default: $default";
2707 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2720 * For really cool vim folding this needs to be at the end:
2721 * vim: foldmarker=@{,@} foldmethod=marker