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 // Specify additional information tags for the parameter. Value is an array
79 // of arrays, with the first member being the 'tag' for the info and the
80 // remaining members being the values. In the help, this is formatted using
81 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
82 // comma-joined list of values.
83 const PARAM_HELP_MSG_INFO
= 12;
85 // When PARAM_DFLT is an array, this may be an array mapping those values
86 // to page titles which will be linked in the help.
87 const PARAM_VALUE_LINKS
= 13;
89 const LIMIT_BIG1
= 500; // Fast query, std user limit
90 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
91 const LIMIT_SML1
= 50; // Slow query, std user limit
92 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
95 * getAllowedParams() flag: When set, the result could take longer to generate,
96 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
99 const GET_VALUES_FOR_HELP
= 1;
102 private $mMainModule;
104 private $mModuleName, $mModulePrefix;
105 private $mSlaveDB = null;
106 private $mParamCache = array();
109 * @param ApiMain $mainModule
110 * @param string $moduleName Name of this module
111 * @param string $modulePrefix Prefix to use for parameter names
113 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
114 $this->mMainModule
= $mainModule;
115 $this->mModuleName
= $moduleName;
116 $this->mModulePrefix
= $modulePrefix;
118 if ( !$this->isMain() ) {
119 $this->setContext( $mainModule->getContext() );
124 /************************************************************************//**
125 * @name Methods to implement
130 * Evaluates the parameters, performs the requested query, and sets up
131 * the result. Concrete implementations of ApiBase must override this
132 * method to provide whatever functionality their module offers.
133 * Implementations must not produce any output on their own and are not
134 * expected to handle any errors.
136 * The execute() method will be invoked directly by ApiMain immediately
137 * before the result of the module is output. Aside from the
138 * constructor, implementations should assume that no other methods
139 * will be called externally on the module before the result is
142 * The result data should be stored in the ApiResult object available
143 * through getResult().
145 abstract public function execute();
148 * Get the module manager, or null if this module has no sub-modules
150 * @return ApiModuleManager
152 public function getModuleManager() {
157 * If the module may only be used with a certain format module,
158 * it should override this method to return an instance of that formatter.
159 * A value of null means the default format will be used.
160 * @return mixed Instance of a derived class of ApiFormatBase, or null
162 public function getCustomPrinter() {
167 * Returns usage examples for this module.
169 * Return value has query strings as keys, with values being either strings
170 * (message key), arrays (message key + parameter), or Message objects.
172 * Do not call this base class implementation when overriding this method.
177 protected function getExamplesMessages() {
178 // Fall back to old non-localised method
181 $examples = $this->getExamples();
183 if ( !is_array( $examples ) ) {
184 $examples = array( $examples );
185 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
186 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
187 !preg_match( '/^\s*api\.php\?/', $examples[0] )
189 // Fix up the ugly "even numbered elements are description, odd
190 // numbered elemts are the link" format (see doc for self::getExamples)
192 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
193 $tmp[$examples[$i +
1]] = $examples[$i];
198 foreach ( $examples as $k => $v ) {
199 if ( is_numeric( $k ) ) {
204 $msg = self
::escapeWikiText( $v );
205 if ( is_array( $msg ) ) {
206 $msg = join( " ", $msg );
210 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
211 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
219 * Return links to more detailed help pages about the module.
220 * @since 1.25, returning boolean false is deprecated
221 * @return string|array
223 public function getHelpUrls() {
228 * Returns an array of allowed parameters (parameter name) => (default
229 * value) or (parameter name) => (array with PARAM_* constants as keys)
230 * Don't call this function directly: use getFinalParams() to allow
231 * hooks to modify parameters as needed.
233 * Some derived classes may choose to handle an integer $flags parameter
234 * in the overriding methods. Callers of this method can pass zero or
235 * more OR-ed flags like GET_VALUES_FOR_HELP.
239 protected function getAllowedParams( /* $flags = 0 */ ) {
240 // int $flags is not declared because it causes "Strict standards"
241 // warning. Most derived classes do not implement it.
246 * Indicates if this module needs maxlag to be checked
249 public function shouldCheckMaxlag() {
254 * Indicates whether this module requires read rights
257 public function isReadMode() {
262 * Indicates whether this module requires write mode
265 public function isWriteMode() {
270 * Indicates whether this module must be called with a POST request
273 public function mustBePosted() {
274 return $this->needsToken() !== false;
278 * Indicates whether this module is deprecated
282 public function isDeprecated() {
287 * Indicates whether this module is "internal" or unstable
291 public function isInternal() {
296 * Returns the token type this module requires in order to execute.
298 * Modules are strongly encouraged to use the core 'csrf' type unless they
299 * have specialized security needs. If the token type is not one of the
300 * core types, you must use the ApiQueryTokensRegisterTypes hook to
303 * Returning a non-falsey value here will force the addition of an
304 * appropriate 'token' parameter in self::getFinalParams(). Also,
305 * self::mustBePosted() must return true when tokens are used.
307 * In previous versions of MediaWiki, true was a valid return value.
308 * Returning true will generate errors indicating that the API module needs
311 * @return string|false
313 public function needsToken() {
318 * Fetch the salt used in the Web UI corresponding to this module.
320 * Only override this if the Web UI uses a token with a non-constant salt.
323 * @param array $params All supplied parameters for the module
324 * @return string|array|null
326 protected function getWebUITokenSalt( array $params ) {
332 /************************************************************************//**
333 * @name Data access methods
338 * Get the name of the module being executed by this instance
341 public function getModuleName() {
342 return $this->mModuleName
;
346 * Get parameter prefix (usually two letters or an empty string).
349 public function getModulePrefix() {
350 return $this->mModulePrefix
;
354 * Get the main module
357 public function getMain() {
358 return $this->mMainModule
;
362 * Returns true if this module is the main module ($this === $this->mMainModule),
366 public function isMain() {
367 return $this === $this->mMainModule
;
371 * Get the parent of this module
373 * @return ApiBase|null
375 public function getParent() {
376 return $this->isMain() ?
null : $this->getMain();
380 * Get the path to this module
385 public function getModulePath() {
386 if ( $this->isMain() ) {
388 } elseif ( $this->getParent()->isMain() ) {
389 return $this->getModuleName();
391 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
396 * Get a module from its module path
399 * @param string $path
400 * @return ApiBase|null
401 * @throws UsageException
403 public function getModuleFromPath( $path ) {
404 $module = $this->getMain();
405 if ( $path === 'main' ) {
409 $parts = explode( '+', $path );
410 if ( count( $parts ) === 1 ) {
411 // In case the '+' was typed into URL, it resolves as a space
412 $parts = explode( ' ', $path );
415 $count = count( $parts );
416 for ( $i = 0; $i < $count; $i++
) {
418 $manager = $parent->getModuleManager();
419 if ( $manager === null ) {
420 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
421 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
423 $module = $manager->getModule( $parts[$i] );
425 if ( $module === null ) {
426 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
428 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
438 * Get the result object
441 public function getResult() {
442 // Main module has getResult() method overridden
443 // Safety - avoid infinite loop:
444 if ( $this->isMain() ) {
445 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
448 return $this->getMain()->getResult();
452 * Get the result data array (read-only)
455 public function getResultData() {
456 return $this->getResult()->getData();
460 * Gets a default slave database connection object
461 * @return DatabaseBase
463 protected function getDB() {
464 if ( !isset( $this->mSlaveDB
) ) {
465 $this->profileDBIn();
466 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
467 $this->profileDBOut();
470 return $this->mSlaveDB
;
475 /************************************************************************//**
476 * @name Parameter handling
481 * This method mangles parameter name based on the prefix supplied to the constructor.
482 * Override this method to change parameter name during runtime
483 * @param string $paramName Parameter name
484 * @return string Prefixed parameter name
486 public function encodeParamName( $paramName ) {
487 return $this->mModulePrefix
. $paramName;
491 * Using getAllowedParams(), this function makes an array of the values
492 * provided by the user, with key being the name of the variable, and
493 * value - validated value from user or default. limits will not be
494 * parsed if $parseLimit is set to false; use this when the max
495 * limit is not definitive yet, e.g. when getting revisions.
496 * @param bool $parseLimit True by default
499 public function extractRequestParams( $parseLimit = true ) {
500 // Cache parameters, for performance and to avoid bug 24564.
501 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
502 $params = $this->getFinalParams();
505 if ( $params ) { // getFinalParams() can return false
506 foreach ( $params as $paramName => $paramSettings ) {
507 $results[$paramName] = $this->getParameterFromSettings(
508 $paramName, $paramSettings, $parseLimit );
511 $this->mParamCache
[$parseLimit] = $results;
514 return $this->mParamCache
[$parseLimit];
518 * Get a value for the given parameter
519 * @param string $paramName Parameter name
520 * @param bool $parseLimit See extractRequestParams()
521 * @return mixed Parameter value
523 protected function getParameter( $paramName, $parseLimit = true ) {
524 $params = $this->getFinalParams();
525 $paramSettings = $params[$paramName];
527 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
531 * Die if none or more than one of a certain set of parameters is set and not false.
533 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
534 * @param string $required,... Names of parameters of which exactly one must be set
536 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
537 $required = func_get_args();
538 array_shift( $required );
539 $p = $this->getModulePrefix();
541 $intersection = array_intersect( array_keys( array_filter( $params,
542 array( $this, "parameterNotEmpty" ) ) ), $required );
544 if ( count( $intersection ) > 1 ) {
546 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
548 } elseif ( count( $intersection ) == 0 ) {
550 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
557 * Die if more than one of a certain set of parameters is set and not false.
559 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
560 * @param string $required,... Names of parameters of which at most one must be set
562 public function requireMaxOneParameter( $params, $required /*...*/ ) {
563 $required = func_get_args();
564 array_shift( $required );
565 $p = $this->getModulePrefix();
567 $intersection = array_intersect( array_keys( array_filter( $params,
568 array( $this, "parameterNotEmpty" ) ) ), $required );
570 if ( count( $intersection ) > 1 ) {
572 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
579 * Die if none of a certain set of parameters is set and not false.
582 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
583 * @param string $required,... Names of parameters of which at least one must be set
585 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
586 $required = func_get_args();
587 array_shift( $required );
588 $p = $this->getModulePrefix();
590 $intersection = array_intersect(
591 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
595 if ( count( $intersection ) == 0 ) {
596 $this->dieUsage( "At least one of the parameters {$p}" .
597 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
602 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
604 * @param object $x Parameter to check is not null/false
607 private function parameterNotEmpty( $x ) {
608 return !is_null( $x ) && $x !== false;
612 * Get a WikiPage object from a title or pageid param, if possible.
613 * Can die, if no param is set or if the title or page id is not valid.
615 * @param array $params
616 * @param bool|string $load Whether load the object's state from the database:
617 * - false: don't load (if the pageid is given, it will still be loaded)
618 * - 'fromdb': load from a slave database
619 * - 'fromdbmaster': load from the master database
622 public function getTitleOrPageId( $params, $load = false ) {
623 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
626 if ( isset( $params['title'] ) ) {
627 $titleObj = Title
::newFromText( $params['title'] );
628 if ( !$titleObj ||
$titleObj->isExternal() ) {
629 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
631 if ( !$titleObj->canExist() ) {
632 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
634 $pageObj = WikiPage
::factory( $titleObj );
635 if ( $load !== false ) {
636 $pageObj->loadPageData( $load );
638 } elseif ( isset( $params['pageid'] ) ) {
639 if ( $load === false ) {
642 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
644 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
652 * Return true if we're to watch the page, false if not, null if no change.
653 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
654 * @param Title $titleObj The page under consideration
655 * @param string $userOption The user option to consider when $watchlist=preferences.
656 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
659 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
661 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
663 switch ( $watchlist ) {
671 # If the user is already watching, don't bother checking
672 if ( $userWatching ) {
675 # If no user option was passed, use watchdefault and watchcreations
676 if ( is_null( $userOption ) ) {
677 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
678 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
681 # Watch the article based on the user preference
682 return $this->getUser()->getBoolOption( $userOption );
685 return $userWatching;
688 return $userWatching;
693 * Using the settings determine the value for the given parameter
695 * @param string $paramName Parameter name
696 * @param array|mixed $paramSettings Default value or an array of settings
697 * using PARAM_* constants.
698 * @param bool $parseLimit Parse limit?
699 * @return mixed Parameter value
701 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
702 // Some classes may decide to change parameter names
703 $encParamName = $this->encodeParamName( $paramName );
705 if ( !is_array( $paramSettings ) ) {
706 $default = $paramSettings;
708 $type = gettype( $paramSettings );
713 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
714 ?
$paramSettings[self
::PARAM_DFLT
]
716 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
717 ?
$paramSettings[self
::PARAM_ISMULTI
]
719 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
720 ?
$paramSettings[self
::PARAM_TYPE
]
722 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
723 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
725 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
726 ?
$paramSettings[self
::PARAM_DEPRECATED
]
728 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
729 ?
$paramSettings[self
::PARAM_REQUIRED
]
732 // When type is not given, and no choices, the type is the same as $default
733 if ( !isset( $type ) ) {
734 if ( isset( $default ) ) {
735 $type = gettype( $default );
737 $type = 'NULL'; // allow everything
742 if ( $type == 'boolean' ) {
743 if ( isset( $default ) && $default !== false ) {
744 // Having a default value of anything other than 'false' is not allowed
747 "Boolean param $encParamName's default is set to '$default'. " .
748 "Boolean parameters must default to false."
752 $value = $this->getMain()->getCheck( $encParamName );
753 } elseif ( $type == 'upload' ) {
754 if ( isset( $default ) ) {
755 // Having a default value is not allowed
758 "File upload param $encParamName's default is set to " .
759 "'$default'. File upload parameters may not have a default." );
762 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
764 $value = $this->getMain()->getUpload( $encParamName );
765 if ( !$value->exists() ) {
766 // This will get the value without trying to normalize it
767 // (because trying to normalize a large binary file
768 // accidentally uploaded as a field fails spectacularly)
769 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
770 if ( $value !== null ) {
772 "File upload param $encParamName is not a file upload; " .
773 "be sure to use multipart/form-data for your POST and include " .
774 "a filename in the Content-Disposition header.",
775 "badupload_{$encParamName}"
780 $value = $this->getMain()->getVal( $encParamName, $default );
782 if ( isset( $value ) && $type == 'namespace' ) {
783 $type = MWNamespace
::getValidNamespaces();
785 if ( isset( $value ) && $type == 'submodule' ) {
786 $type = $this->getModuleManager()->getNames( $paramName );
790 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
791 $value = $this->parseMultiValue(
795 is_array( $type ) ?
$type : null
799 // More validation only when choices were not given
800 // choices were validated in parseMultiValue()
801 if ( isset( $value ) ) {
802 if ( !is_array( $type ) ) {
804 case 'NULL': // nothing to do
807 if ( $required && $value === '' ) {
808 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
811 case 'integer': // Force everything using intval() and optionally validate limits
812 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
813 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
814 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
815 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
817 if ( is_array( $value ) ) {
818 $value = array_map( 'intval', $value );
819 if ( !is_null( $min ) ||
!is_null( $max ) ) {
820 foreach ( $value as &$v ) {
821 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
825 $value = intval( $value );
826 if ( !is_null( $min ) ||
!is_null( $max ) ) {
827 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
832 if ( !$parseLimit ) {
833 // Don't do any validation whatsoever
836 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
837 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
841 "MAX1 or MAX2 are not defined for the limit $encParamName"
845 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
847 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
848 if ( $value == 'max' ) {
849 $value = $this->getMain()->canApiHighLimits()
850 ?
$paramSettings[self
::PARAM_MAX2
]
851 : $paramSettings[self
::PARAM_MAX
];
852 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
854 $value = intval( $value );
855 $this->validateLimit(
859 $paramSettings[self
::PARAM_MAX
],
860 $paramSettings[self
::PARAM_MAX2
]
866 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
870 if ( is_array( $value ) ) {
871 foreach ( $value as $key => $val ) {
872 $value[$key] = $this->validateTimestamp( $val, $encParamName );
875 $value = $this->validateTimestamp( $value, $encParamName );
879 if ( is_array( $value ) ) {
880 foreach ( $value as $key => $val ) {
881 $value[$key] = $this->validateUser( $val, $encParamName );
884 $value = $this->validateUser( $value, $encParamName );
887 case 'upload': // nothing to do
890 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
894 // Throw out duplicates if requested
895 if ( !$dupes && is_array( $value ) ) {
896 $value = array_unique( $value );
899 // Set a warning if a deprecated parameter has been passed
900 if ( $deprecated && $value !== false ) {
901 $this->setWarning( "The $encParamName parameter has been deprecated." );
903 } elseif ( $required ) {
904 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
911 * Return an array of values that were given in a 'a|b|c' notation,
912 * after it optionally validates them against the list allowed values.
914 * @param string $valueName The name of the parameter (for error
916 * @param mixed $value The value being parsed
917 * @param bool $allowMultiple Can $value contain more than one value
919 * @param string[]|null $allowedValues An array of values to check against. If
920 * null, all values are accepted.
921 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
923 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
924 if ( trim( $value ) === '' && $allowMultiple ) {
928 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
929 // because it unstubs $wgUser
930 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
931 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
935 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
936 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
937 "the limit is $sizeLimit" );
940 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
941 // Bug 33482 - Allow entries with | in them for non-multiple values
942 if ( in_array( $value, $allowedValues, true ) ) {
946 $possibleValues = is_array( $allowedValues )
947 ?
"of '" . implode( "', '", $allowedValues ) . "'"
950 "Only one $possibleValues is allowed for parameter '$valueName'",
951 "multival_$valueName"
955 if ( is_array( $allowedValues ) ) {
956 // Check for unknown values
957 $unknown = array_diff( $valuesList, $allowedValues );
958 if ( count( $unknown ) ) {
959 if ( $allowMultiple ) {
960 $s = count( $unknown ) > 1 ?
's' : '';
961 $vals = implode( ", ", $unknown );
962 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
965 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
970 // Now throw them out
971 $valuesList = array_intersect( $valuesList, $allowedValues );
974 return $allowMultiple ?
$valuesList : $valuesList[0];
978 * Validate the value against the minimum and user/bot maximum limits.
979 * Prints usage info on failure.
980 * @param string $paramName Parameter name
981 * @param int $value Parameter value
982 * @param int|null $min Minimum value
983 * @param int|null $max Maximum value for users
984 * @param int $botMax Maximum value for sysops/bots
985 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
987 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
988 if ( !is_null( $min ) && $value < $min ) {
990 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
991 $this->warnOrDie( $msg, $enforceLimits );
995 // Minimum is always validated, whereas maximum is checked only if not
996 // running in internal call mode
997 if ( $this->getMain()->isInternalMode() ) {
1001 // Optimization: do not check user's bot status unless really needed -- skips db query
1002 // assumes $botMax >= $max
1003 if ( !is_null( $max ) && $value > $max ) {
1004 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1005 if ( $value > $botMax ) {
1006 $msg = $this->encodeParamName( $paramName ) .
1007 " may not be over $botMax (set to $value) for bots or sysops";
1008 $this->warnOrDie( $msg, $enforceLimits );
1012 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1013 $this->warnOrDie( $msg, $enforceLimits );
1020 * Validate and normalize of parameters of type 'timestamp'
1021 * @param string $value Parameter value
1022 * @param string $encParamName Parameter name
1023 * @return string Validated and normalized parameter
1025 protected function validateTimestamp( $value, $encParamName ) {
1026 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1027 if ( $unixTimestamp === false ) {
1029 "Invalid value '$value' for timestamp parameter $encParamName",
1030 "badtimestamp_{$encParamName}"
1034 return wfTimestamp( TS_MW
, $unixTimestamp );
1038 * Validate the supplied token.
1041 * @param string $token Supplied token
1042 * @param array $params All supplied parameters for the module
1045 public final function validateToken( $token, array $params ) {
1046 $tokenType = $this->needsToken();
1047 $salts = ApiQueryTokens
::getTokenTypeSalts();
1048 if ( !isset( $salts[$tokenType] ) ) {
1049 throw new MWException(
1050 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1051 'without registering it'
1055 if ( $this->getUser()->matchEditToken(
1063 $webUiSalt = $this->getWebUITokenSalt( $params );
1064 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1076 * Validate and normalize of parameters of type 'user'
1077 * @param string $value Parameter value
1078 * @param string $encParamName Parameter name
1079 * @return string Validated and normalized parameter
1081 private function validateUser( $value, $encParamName ) {
1082 $title = Title
::makeTitleSafe( NS_USER
, $value );
1083 if ( $title === null ) {
1085 "Invalid value '$value' for user parameter $encParamName",
1086 "baduser_{$encParamName}"
1090 return $title->getText();
1095 /************************************************************************//**
1096 * @name Utility methods
1101 * Set a watch (or unwatch) based the based on a watchlist parameter.
1102 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1103 * @param Title $titleObj The article's title to change
1104 * @param string $userOption The user option to consider when $watch=preferences
1106 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1107 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1108 if ( $value === null ) {
1112 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1116 * Truncate an array to a certain length.
1117 * @param array $arr Array to truncate
1118 * @param int $limit Maximum length
1119 * @return bool True if the array was truncated, false otherwise
1121 public static function truncateArray( &$arr, $limit ) {
1123 while ( count( $arr ) > $limit ) {
1132 * Gets the user for whom to get the watchlist
1134 * @param array $params
1137 public function getWatchlistUser( $params ) {
1138 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1139 $user = User
::newFromName( $params['owner'], false );
1140 if ( !( $user && $user->getId() ) ) {
1141 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1143 $token = $user->getOption( 'watchlisttoken' );
1144 if ( $token == '' ||
$token != $params['token'] ) {
1146 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1151 if ( !$this->getUser()->isLoggedIn() ) {
1152 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1154 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1155 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1157 $user = $this->getUser();
1164 * A subset of wfEscapeWikiText for BC texts
1167 * @param string|array $v
1168 * @return string|array
1170 private static function escapeWikiText( $v ) {
1171 if ( is_array( $v ) ) {
1172 return array_map( 'self::escapeWikiText', $v );
1174 return strtr( $v, array(
1175 '__' => '__', '{' => '{', '}' => '}',
1176 '[[Category:' => '[[:Category:',
1177 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1183 * Create a Message from a string or array
1185 * A string is used as a message key. An array has the message key as the
1186 * first value and message parameters as subsequent values.
1189 * @param string|array|Message $msg
1190 * @param IContextSource $context
1191 * @param array $params
1192 * @return Message|null
1194 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1195 if ( is_string( $msg ) ) {
1196 $msg = wfMessage( $msg );
1197 } elseif ( is_array( $msg ) ) {
1198 $msg = call_user_func_array( 'wfMessage', $msg );
1200 if ( !$msg instanceof Message
) {
1204 $msg->setContext( $context );
1206 $msg->params( $params );
1214 /************************************************************************//**
1215 * @name Warning and error reporting
1220 * Set warning section for this module. Users should monitor this
1221 * section to notice any changes in API. Multiple calls to this
1222 * function will result in the warning messages being separated by
1224 * @param string $warning Warning message
1226 public function setWarning( $warning ) {
1227 $result = $this->getResult();
1228 $data = $result->getData();
1229 $moduleName = $this->getModuleName();
1230 if ( isset( $data['warnings'][$moduleName] ) ) {
1231 // Don't add duplicate warnings
1232 $oldWarning = $data['warnings'][$moduleName]['*'];
1233 $warnPos = strpos( $oldWarning, $warning );
1234 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1235 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
1236 // Check if $warning is followed by "\n" or the end of the $oldWarning
1237 $warnPos +
= strlen( $warning );
1238 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
1242 // If there is a warning already, append it to the existing one
1243 $warning = "$oldWarning\n$warning";
1246 ApiResult
::setContent( $msg, $warning );
1247 $result->addValue( 'warnings', $moduleName,
1248 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
1252 * Adds a warning to the output, else dies
1254 * @param string $msg Message to show as a warning, or error message if dying
1255 * @param bool $enforceLimits Whether this is an enforce (die)
1257 private function warnOrDie( $msg, $enforceLimits = false ) {
1258 if ( $enforceLimits ) {
1259 $this->dieUsage( $msg, 'integeroutofrange' );
1262 $this->setWarning( $msg );
1266 * Throw a UsageException, which will (if uncaught) call the main module's
1267 * error handler and die with an error message.
1269 * @param string $description One-line human-readable description of the
1270 * error condition, e.g., "The API requires a valid action parameter"
1271 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1272 * automated identification of the error, e.g., 'unknown_action'
1273 * @param int $httpRespCode HTTP response code
1274 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1275 * @throws UsageException
1277 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1278 Profiler
::instance()->close();
1279 throw new UsageException(
1281 $this->encodeParamName( $errorCode ),
1288 * Get error (as code, string) from a Status object.
1291 * @param Status $status
1292 * @return array Array of code and error string
1294 public function getErrorFromStatus( $status ) {
1295 if ( $status->isGood() ) {
1296 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1299 $errors = $status->getErrorsArray();
1301 // No errors? Assume the warnings should be treated as errors
1302 $errors = $status->getWarningsArray();
1305 // Still no errors? Punt
1306 $errors = array( array( 'unknownerror-nocode' ) );
1309 // Cannot use dieUsageMsg() because extensions might return custom
1311 if ( $errors[0] instanceof Message
) {
1313 $code = $msg->getKey();
1315 $code = array_shift( $errors[0] );
1316 $msg = wfMessage( $code, $errors[0] );
1318 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1319 // Translate message to code, for backwards compatibility
1320 $code = ApiBase
::$messageMap[$code]['code'];
1323 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1327 * Throw a UsageException based on the errors in the Status object.
1330 * @param Status $status
1331 * @throws MWException
1333 public function dieStatus( $status ) {
1335 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1336 $this->dieUsage( $msg, $code );
1339 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1341 * Array that maps message keys to error messages. $1 and friends are replaced.
1343 public static $messageMap = array(
1344 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1345 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1346 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1348 // Messages from Title::getUserPermissionsErrors()
1349 'ns-specialprotected' => array(
1350 'code' => 'unsupportednamespace',
1351 'info' => "Pages in the Special namespace can't be edited"
1353 'protectedinterface' => array(
1354 'code' => 'protectednamespace-interface',
1355 'info' => "You're not allowed to edit interface messages"
1357 'namespaceprotected' => array(
1358 'code' => 'protectednamespace',
1359 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1361 'customcssprotected' => array(
1362 'code' => 'customcssprotected',
1363 'info' => "You're not allowed to edit custom CSS pages"
1365 'customjsprotected' => array(
1366 'code' => 'customjsprotected',
1367 'info' => "You're not allowed to edit custom JavaScript pages"
1369 'cascadeprotected' => array(
1370 'code' => 'cascadeprotected',
1371 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1373 'protectedpagetext' => array(
1374 'code' => 'protectedpage',
1375 'info' => "The \"\$1\" right is required to edit this page"
1377 'protect-cantedit' => array(
1378 'code' => 'cantedit',
1379 'info' => "You can't protect this page because you can't edit it"
1381 'deleteprotected' => array(
1382 'code' => 'cantedit',
1383 'info' => "You can't delete this page because it has been protected"
1385 'badaccess-group0' => array(
1386 'code' => 'permissiondenied',
1387 'info' => "Permission denied"
1388 ), // Generic permission denied message
1389 'badaccess-groups' => array(
1390 'code' => 'permissiondenied',
1391 'info' => "Permission denied"
1393 'titleprotected' => array(
1394 'code' => 'protectedtitle',
1395 'info' => "This title has been protected from creation"
1397 'nocreate-loggedin' => array(
1398 'code' => 'cantcreate',
1399 'info' => "You don't have permission to create new pages"
1401 'nocreatetext' => array(
1402 'code' => 'cantcreate-anon',
1403 'info' => "Anonymous users can't create new pages"
1405 'movenologintext' => array(
1406 'code' => 'cantmove-anon',
1407 'info' => "Anonymous users can't move pages"
1409 'movenotallowed' => array(
1410 'code' => 'cantmove',
1411 'info' => "You don't have permission to move pages"
1413 'confirmedittext' => array(
1414 'code' => 'confirmemail',
1415 'info' => "You must confirm your email address before you can edit"
1417 'blockedtext' => array(
1418 'code' => 'blocked',
1419 'info' => "You have been blocked from editing"
1421 'autoblockedtext' => array(
1422 'code' => 'autoblocked',
1423 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1426 // Miscellaneous interface messages
1427 'actionthrottledtext' => array(
1428 'code' => 'ratelimited',
1429 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1431 'alreadyrolled' => array(
1432 'code' => 'alreadyrolled',
1433 'info' => "The page you tried to rollback was already rolled back"
1435 'cantrollback' => array(
1436 'code' => 'onlyauthor',
1437 'info' => "The page you tried to rollback only has one author"
1439 'readonlytext' => array(
1440 'code' => 'readonly',
1441 'info' => "The wiki is currently in read-only mode"
1443 'sessionfailure' => array(
1444 'code' => 'badtoken',
1445 'info' => "Invalid token" ),
1446 'cannotdelete' => array(
1447 'code' => 'cantdelete',
1448 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1450 'notanarticle' => array(
1451 'code' => 'missingtitle',
1452 'info' => "The page you requested doesn't exist"
1454 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1456 'immobile_namespace' => array(
1457 'code' => 'immobilenamespace',
1458 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1460 'articleexists' => array(
1461 'code' => 'articleexists',
1462 'info' => "The destination article already exists and is not a redirect to the source article"
1464 'protectedpage' => array(
1465 'code' => 'protectedpage',
1466 'info' => "You don't have permission to perform this move"
1468 'hookaborted' => array(
1469 'code' => 'hookaborted',
1470 'info' => "The modification you tried to make was aborted by an extension hook"
1472 'cantmove-titleprotected' => array(
1473 'code' => 'protectedtitle',
1474 'info' => "The destination article has been protected from creation"
1476 'imagenocrossnamespace' => array(
1477 'code' => 'nonfilenamespace',
1478 'info' => "Can't move a file to a non-file namespace"
1480 'imagetypemismatch' => array(
1481 'code' => 'filetypemismatch',
1482 'info' => "The new file extension doesn't match its type"
1484 // 'badarticleerror' => shouldn't happen
1485 // 'badtitletext' => shouldn't happen
1486 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1487 'range_block_disabled' => array(
1488 'code' => 'rangedisabled',
1489 'info' => "Blocking IP ranges has been disabled"
1491 'nosuchusershort' => array(
1492 'code' => 'nosuchuser',
1493 'info' => "The user you specified doesn't exist"
1495 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1496 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1497 'ipb_already_blocked' => array(
1498 'code' => 'alreadyblocked',
1499 'info' => "The user you tried to block was already blocked"
1501 'ipb_blocked_as_range' => array(
1502 'code' => 'blockedasrange',
1503 '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."
1505 'ipb_cant_unblock' => array(
1506 'code' => 'cantunblock',
1507 'info' => "The block you specified was not found. It may have been unblocked already"
1509 'mailnologin' => array(
1510 'code' => 'cantsend',
1511 '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"
1513 'ipbblocked' => array(
1514 'code' => 'ipbblocked',
1515 'info' => 'You cannot block or unblock users while you are yourself blocked'
1517 'ipbnounblockself' => array(
1518 'code' => 'ipbnounblockself',
1519 'info' => 'You are not allowed to unblock yourself'
1521 'usermaildisabled' => array(
1522 'code' => 'usermaildisabled',
1523 'info' => "User email has been disabled"
1525 'blockedemailuser' => array(
1526 'code' => 'blockedfrommail',
1527 'info' => "You have been blocked from sending email"
1529 'notarget' => array(
1530 'code' => 'notarget',
1531 'info' => "You have not specified a valid target for this action"
1534 'code' => 'noemail',
1535 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1537 'rcpatroldisabled' => array(
1538 'code' => 'patroldisabled',
1539 'info' => "Patrolling is disabled on this wiki"
1541 'markedaspatrollederror-noautopatrol' => array(
1542 'code' => 'noautopatrol',
1543 'info' => "You don't have permission to patrol your own changes"
1545 'delete-toobig' => array(
1546 'code' => 'bigdelete',
1547 'info' => "You can't delete this page because it has more than \$1 revisions"
1549 'movenotallowedfile' => array(
1550 'code' => 'cantmovefile',
1551 'info' => "You don't have permission to move files"
1553 'userrights-no-interwiki' => array(
1554 'code' => 'nointerwikiuserrights',
1555 'info' => "You don't have permission to change user rights on other wikis"
1557 'userrights-nodatabase' => array(
1558 'code' => 'nosuchdatabase',
1559 'info' => "Database \"\$1\" does not exist or is not local"
1561 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1562 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1563 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1564 'import-rootpage-invalid' => array(
1565 'code' => 'import-rootpage-invalid',
1566 'info' => 'Root page is an invalid title'
1568 'import-rootpage-nosubpage' => array(
1569 'code' => 'import-rootpage-nosubpage',
1570 'info' => 'Namespace "$1" of the root page does not allow subpages'
1573 // API-specific messages
1574 'readrequired' => array(
1575 'code' => 'readapidenied',
1576 'info' => "You need read permission to use this module"
1578 'writedisabled' => array(
1579 'code' => 'noapiwrite',
1580 '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"
1582 'writerequired' => array(
1583 'code' => 'writeapidenied',
1584 'info' => "You're not allowed to edit this wiki through the API"
1586 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1587 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1588 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1589 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1590 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1591 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1592 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1593 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1594 'create-titleexists' => array(
1595 'code' => 'create-titleexists',
1596 'info' => "Existing titles can't be protected with 'create'"
1598 'missingtitle-createonly' => array(
1599 'code' => 'missingtitle-createonly',
1600 'info' => "Missing titles can only be protected with 'create'"
1602 'cantblock' => array( 'code' => 'cantblock',
1603 'info' => "You don't have permission to block users"
1605 'canthide' => array(
1606 'code' => 'canthide',
1607 'info' => "You don't have permission to hide user names from the block log"
1609 'cantblock-email' => array(
1610 'code' => 'cantblock-email',
1611 'info' => "You don't have permission to block users from sending email through the wiki"
1613 'unblock-notarget' => array(
1614 'code' => 'notarget',
1615 'info' => "Either the id or the user parameter must be set"
1617 'unblock-idanduser' => array(
1618 'code' => 'idanduser',
1619 'info' => "The id and user parameters can't be used together"
1621 'cantunblock' => array(
1622 'code' => 'permissiondenied',
1623 'info' => "You don't have permission to unblock users"
1625 'cannotundelete' => array(
1626 'code' => 'cantundelete',
1627 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1629 'permdenied-undelete' => array(
1630 'code' => 'permissiondenied',
1631 'info' => "You don't have permission to restore deleted revisions"
1633 'createonly-exists' => array(
1634 'code' => 'articleexists',
1635 'info' => "The article you tried to create has been created already"
1637 'nocreate-missing' => array(
1638 'code' => 'missingtitle',
1639 'info' => "The article you tried to edit doesn't exist"
1641 'nosuchrcid' => array(
1642 'code' => 'nosuchrcid',
1643 'info' => "There is no change with rcid \"\$1\""
1645 'protect-invalidaction' => array(
1646 'code' => 'protect-invalidaction',
1647 'info' => "Invalid protection type \"\$1\""
1649 'protect-invalidlevel' => array(
1650 'code' => 'protect-invalidlevel',
1651 'info' => "Invalid protection level \"\$1\""
1653 'toofewexpiries' => array(
1654 'code' => 'toofewexpiries',
1655 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1657 'cantimport' => array(
1658 'code' => 'cantimport',
1659 'info' => "You don't have permission to import pages"
1661 'cantimport-upload' => array(
1662 'code' => 'cantimport-upload',
1663 'info' => "You don't have permission to import uploaded pages"
1665 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1666 'importuploaderrorsize' => array(
1667 'code' => 'filetoobig',
1668 'info' => 'The file you uploaded is bigger than the maximum upload size'
1670 'importuploaderrorpartial' => array(
1671 'code' => 'partialupload',
1672 'info' => 'The file was only partially uploaded'
1674 'importuploaderrortemp' => array(
1675 'code' => 'notempdir',
1676 'info' => 'The temporary upload directory is missing'
1678 'importcantopen' => array(
1679 'code' => 'cantopenfile',
1680 'info' => "Couldn't open the uploaded file"
1682 'import-noarticle' => array(
1683 'code' => 'badinterwiki',
1684 'info' => 'Invalid interwiki title specified'
1686 'importbadinterwiki' => array(
1687 'code' => 'badinterwiki',
1688 'info' => 'Invalid interwiki title specified'
1690 'import-unknownerror' => array(
1691 'code' => 'import-unknownerror',
1692 'info' => "Unknown error on import: \"\$1\""
1694 'cantoverwrite-sharedfile' => array(
1695 'code' => 'cantoverwrite-sharedfile',
1696 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1698 'sharedfile-exists' => array(
1699 'code' => 'fileexists-sharedrepo-perm',
1700 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1702 'mustbeposted' => array(
1703 'code' => 'mustbeposted',
1704 'info' => "The \$1 module requires a POST request"
1708 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1710 'specialpage-cantexecute' => array(
1711 'code' => 'specialpage-cantexecute',
1712 'info' => "You don't have permission to view the results of this special page"
1714 'invalidoldimage' => array(
1715 'code' => 'invalidoldimage',
1716 'info' => 'The oldimage parameter has invalid format'
1718 'nodeleteablefile' => array(
1719 'code' => 'nodeleteablefile',
1720 'info' => 'No such old version of the file'
1722 'fileexists-forbidden' => array(
1723 'code' => 'fileexists-forbidden',
1724 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1726 'fileexists-shared-forbidden' => array(
1727 'code' => 'fileexists-shared-forbidden',
1728 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1730 'filerevert-badversion' => array(
1731 'code' => 'filerevert-badversion',
1732 'info' => 'There is no previous local version of this file with the provided timestamp.'
1735 // ApiEditPage messages
1736 'noimageredirect-anon' => array(
1737 'code' => 'noimageredirect-anon',
1738 'info' => "Anonymous users can't create image redirects"
1740 'noimageredirect-logged' => array(
1741 'code' => 'noimageredirect',
1742 'info' => "You don't have permission to create image redirects"
1744 'spamdetected' => array(
1745 'code' => 'spamdetected',
1746 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1748 'contenttoobig' => array(
1749 'code' => 'contenttoobig',
1750 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1752 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1753 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1754 'wasdeleted' => array(
1755 'code' => 'pagedeleted',
1756 'info' => "The page has been deleted since you fetched its timestamp"
1758 'blankpage' => array(
1759 'code' => 'emptypage',
1760 'info' => "Creating new, empty pages is not allowed"
1762 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1763 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1764 'missingtext' => array(
1766 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1768 'emptynewsection' => array(
1769 'code' => 'emptynewsection',
1770 'info' => 'Creating empty new sections is not possible.'
1772 'revwrongpage' => array(
1773 'code' => 'revwrongpage',
1774 'info' => "r\$1 is not a revision of \"\$2\""
1776 'undo-failure' => array(
1777 'code' => 'undofailure',
1778 'info' => 'Undo failed due to conflicting intermediate edits'
1780 'content-not-allowed-here' => array(
1781 'code' => 'contentnotallowedhere',
1782 'info' => 'Content model "$1" is not allowed at title "$2"'
1785 // Messages from WikiPage::doEit()
1786 'edit-hook-aborted' => array(
1787 'code' => 'edit-hook-aborted',
1788 'info' => "Your edit was aborted by an ArticleSave hook"
1790 'edit-gone-missing' => array(
1791 'code' => 'edit-gone-missing',
1792 'info' => "The page you tried to edit doesn't seem to exist anymore"
1794 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1795 'edit-already-exists' => array(
1796 'code' => 'edit-already-exists',
1797 'info' => 'It seems the page you tried to create already exist'
1801 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1802 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1803 'uploaddisabled' => array(
1804 'code' => 'uploaddisabled',
1805 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1807 'copyuploaddisabled' => array(
1808 'code' => 'copyuploaddisabled',
1809 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1811 'copyuploadbaddomain' => array(
1812 'code' => 'copyuploadbaddomain',
1813 'info' => 'Uploads by URL are not allowed from this domain.'
1815 'copyuploadbadurl' => array(
1816 'code' => 'copyuploadbadurl',
1817 'info' => 'Upload not allowed from this URL.'
1820 'filename-tooshort' => array(
1821 'code' => 'filename-tooshort',
1822 'info' => 'The filename is too short'
1824 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1825 'illegal-filename' => array(
1826 'code' => 'illegal-filename',
1827 'info' => 'The filename is not allowed'
1829 'filetype-missing' => array(
1830 'code' => 'filetype-missing',
1831 'info' => 'The file is missing an extension'
1834 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1836 // @codingStandardsIgnoreEnd
1839 * Helper function for readonly errors
1841 public function dieReadOnly() {
1842 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1843 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1844 array( 'readonlyreason' => wfReadOnlyReason() ) );
1848 * Output the error message related to a certain array
1849 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1851 public function dieUsageMsg( $error ) {
1852 # most of the time we send a 1 element, so we might as well send it as
1853 # a string and make this an array here.
1854 if ( is_string( $error ) ) {
1855 $error = array( $error );
1857 $parsed = $this->parseMsg( $error );
1858 $this->dieUsage( $parsed['info'], $parsed['code'] );
1862 * Will only set a warning instead of failing if the global $wgDebugAPI
1863 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1864 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1867 public function dieUsageMsgOrDebug( $error ) {
1868 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1869 $this->dieUsageMsg( $error );
1872 if ( is_string( $error ) ) {
1873 $error = array( $error );
1875 $parsed = $this->parseMsg( $error );
1876 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1880 * Die with the $prefix.'badcontinue' error. This call is common enough to
1881 * make it into the base method.
1882 * @param bool $condition Will only die if this value is true
1885 protected function dieContinueUsageIf( $condition ) {
1888 'Invalid continue param. You should pass the original value returned by the previous query',
1894 * Return the error message related to a certain array
1895 * @param array $error Element of a getUserPermissionsErrors()-style array
1896 * @return array('code' => code, 'info' => info)
1898 public function parseMsg( $error ) {
1899 $error = (array)$error; // It seems strings sometimes make their way in here
1900 $key = array_shift( $error );
1902 // Check whether the error array was nested
1903 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1904 if ( is_array( $key ) ) {
1906 $key = array_shift( $error );
1909 if ( isset( self
::$messageMap[$key] ) ) {
1911 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1912 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1916 // If the key isn't present, throw an "unknown error"
1917 return $this->parseMsg( array( 'unknownerror', $key ) );
1921 * Internal code errors should be reported with this method
1922 * @param string $method Method or function name
1923 * @param string $message Error message
1924 * @throws MWException
1926 protected static function dieDebug( $method, $message ) {
1927 throw new MWException( "Internal error in $method: $message" );
1932 /************************************************************************//**
1933 * @name Help message generation
1938 * Return the description message.
1940 * @return string|array|Message
1942 protected function getDescriptionMessage() {
1943 return "apihelp-{$this->getModulePath()}-description";
1947 * Get final module description, after hooks have had a chance to tweak it as
1950 * @since 1.25, returns Message[] rather than string[]
1953 public function getFinalDescription() {
1954 $desc = $this->getDescription();
1955 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
1956 $desc = self
::escapeWikiText( $desc );
1957 if ( is_array( $desc ) ) {
1958 $desc = join( "\n", $desc );
1960 $desc = (string)$desc;
1963 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1964 $this->getModulePrefix(),
1965 $this->getModuleName(),
1966 $this->getModulePath(),
1968 if ( !$msg->exists() ) {
1969 $msg = $this->msg( 'api-help-fallback-description', $desc );
1971 $msgs = array( $msg );
1973 wfRunHooks( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
1979 * Get final list of parameters, after hooks have had a chance to
1980 * tweak it as needed.
1982 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1983 * @return array|bool False on no parameters
1984 * @since 1.21 $flags param added
1986 public function getFinalParams( $flags = 0 ) {
1987 $params = $this->getAllowedParams( $flags );
1992 if ( $this->needsToken() ) {
1993 $params['token'] = array(
1994 ApiBase
::PARAM_TYPE
=> 'string',
1995 ApiBase
::PARAM_REQUIRED
=> true,
1996 ApiBase
::PARAM_HELP_MSG
=> array(
1997 'api-help-param-token',
1998 $this->needsToken(),
2000 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2003 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2009 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2012 * @since 1.25, returns array of Message[] rather than array of string[]
2013 * @return array Keys are parameter names, values are arrays of Message objects
2015 public function getFinalParamDescription() {
2016 $desc = $this->getParamDescription();
2017 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
2022 $desc = self
::escapeWikiText( $desc );
2024 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2026 foreach ( $params as $param => $settings ) {
2027 if ( !is_array( $settings ) ) {
2028 $settings = array();
2031 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2032 if ( is_array( $d ) ) {
2033 // Special handling for prop parameters
2034 $d = array_map( function ( $line ) {
2035 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2036 $line = "\n;{$m[1]}:{$m[2]}";
2040 $d = join( ' ', $d );
2043 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2044 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2046 $msg = $this->msg( "apihelp-{$this->getModulePath()}-param-{$param}" );
2047 if ( !$msg->exists() ) {
2048 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2051 $msg = ApiBase
::makeMessage( $msg, $this->getContext(), array(
2052 $this->getModulePrefix(),
2054 $this->getModuleName(),
2055 $this->getModulePath(),
2058 $this->dieDebug( __METHOD__
,
2059 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2061 $msgs[$param] = array( $msg );
2063 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2064 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2065 $this->dieDebug( __METHOD__
,
2066 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2068 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2069 $m = ApiBase
::makeMessage( $m, $this->getContext(), array(
2070 $this->getModulePrefix(),
2072 $this->getModuleName(),
2073 $this->getModulePath(),
2076 $msgs[$param][] = $m;
2078 $this->dieDebug( __METHOD__
,
2079 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2085 wfRunHooks( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2091 * Generates the list of flags for the help screen and for action=paraminfo
2093 * Corresponding messages: api-help-flag-deprecated,
2094 * api-help-flag-internal, api-help-flag-readrights,
2095 * api-help-flag-writerights, api-help-flag-mustbeposted
2099 protected function getHelpFlags() {
2102 if ( $this->isDeprecated() ) {
2103 $flags[] = 'deprecated';
2105 if ( $this->isInternal() ) {
2106 $flags[] = 'internal';
2108 if ( $this->isReadMode() ) {
2109 $flags[] = 'readrights';
2111 if ( $this->isWriteMode() ) {
2112 $flags[] = 'writerights';
2114 if ( $this->mustBePosted() ) {
2115 $flags[] = 'mustbeposted';
2122 * Called from ApiHelp before the pieces are joined together and returned.
2124 * This exists mainly for ApiMain to add the Permissions and Credits
2125 * sections. Other modules probably don't need it.
2127 * @param string[] &$help Array of help data
2128 * @param array $options Options passed to ApiHelp::getHelp
2130 public function modifyHelp( array &$help, array $options ) {
2135 /************************************************************************//**
2141 * Profiling: total module execution time
2143 private $mTimeIn = 0, $mModuleTime = 0;
2146 * Get the name of the module as shown in the profiler log
2148 * @param DatabaseBase|bool $db
2152 public function getModuleProfileName( $db = false ) {
2154 return 'API:' . $this->mModuleName
. '-DB';
2157 return 'API:' . $this->mModuleName
;
2161 * Start module profiling
2163 public function profileIn() {
2164 if ( $this->mTimeIn
!== 0 ) {
2165 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2167 $this->mTimeIn
= microtime( true );
2168 wfProfileIn( $this->getModuleProfileName() );
2172 * End module profiling
2174 public function profileOut() {
2175 if ( $this->mTimeIn
=== 0 ) {
2176 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2178 if ( $this->mDBTimeIn
!== 0 ) {
2181 'Must be called after database profiling is done with profileDBOut()'
2185 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2187 wfProfileOut( $this->getModuleProfileName() );
2191 * When modules crash, sometimes it is needed to do a profileOut() regardless
2192 * of the profiling state the module was in. This method does such cleanup.
2194 public function safeProfileOut() {
2195 if ( $this->mTimeIn
!== 0 ) {
2196 if ( $this->mDBTimeIn
!== 0 ) {
2197 $this->profileDBOut();
2199 $this->profileOut();
2204 * Total time the module was executed
2207 public function getProfileTime() {
2208 if ( $this->mTimeIn
!== 0 ) {
2209 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2212 return $this->mModuleTime
;
2216 * Profiling: database execution time
2218 private $mDBTimeIn = 0, $mDBTime = 0;
2221 * Start module profiling
2223 public function profileDBIn() {
2224 if ( $this->mTimeIn
=== 0 ) {
2227 'Must be called while profiling the entire module with profileIn()'
2230 if ( $this->mDBTimeIn
!== 0 ) {
2231 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2233 $this->mDBTimeIn
= microtime( true );
2234 wfProfileIn( $this->getModuleProfileName( true ) );
2238 * End database profiling
2240 public function profileDBOut() {
2241 if ( $this->mTimeIn
=== 0 ) {
2242 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2243 'the entire module with profileIn()' );
2245 if ( $this->mDBTimeIn
=== 0 ) {
2246 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2249 $time = microtime( true ) - $this->mDBTimeIn
;
2250 $this->mDBTimeIn
= 0;
2252 $this->mDBTime +
= $time;
2253 $this->getMain()->mDBTime +
= $time;
2254 wfProfileOut( $this->getModuleProfileName( true ) );
2258 * Total time the module used the database
2261 public function getProfileDBTime() {
2262 if ( $this->mDBTimeIn
!== 0 ) {
2263 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2266 return $this->mDBTime
;
2270 * Write logging information for API features to a debug log, for usage
2272 * @param string $feature Feature being used.
2274 protected function logFeatureUsage( $feature ) {
2275 $request = $this->getRequest();
2276 $s = '"' . addslashes( $feature ) . '"' .
2277 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2278 ' "' . $request->getIP() . '"' .
2279 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2280 ' "' . addslashes( $request->getHeader( 'User-agent' ) ) . '"';
2281 wfDebugLog( 'api-feature-usage', $s, 'private' );
2286 /************************************************************************//**
2291 /// @deprecated since 1.24
2292 const PROP_ROOT
= 'ROOT';
2293 /// @deprecated since 1.24
2294 const PROP_LIST
= 'LIST';
2295 /// @deprecated since 1.24
2296 const PROP_TYPE
= 0;
2297 /// @deprecated since 1.24
2298 const PROP_NULLABLE
= 1;
2301 * Formerly returned a string that identifies the version of the extending
2302 * class. Typically included the class name, the svn revision, timestamp,
2303 * and last author. Usually done with SVN's Id keyword
2305 * @deprecated since 1.21, version string is no longer supported
2308 public function getVersion() {
2309 wfDeprecated( __METHOD__
, '1.21' );
2314 * Formerly used to fetch a list of possible properites in the result,
2315 * somehow organized with respect to the prop parameter that causes them to
2316 * be returned. The specific semantics of the return value was never
2317 * specified. Since this was never possible to be accurately updated, it
2320 * @deprecated since 1.24
2321 * @return array|bool
2323 protected function getResultProperties() {
2324 wfDeprecated( __METHOD__
, '1.24' );
2329 * @see self::getResultProperties()
2330 * @deprecated since 1.24
2331 * @return array|bool
2333 public function getFinalResultProperties() {
2334 wfDeprecated( __METHOD__
, '1.24' );
2339 * @see self::getResultProperties()
2340 * @deprecated since 1.24
2342 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2343 wfDeprecated( __METHOD__
, '1.24' );
2347 * @see self::getPossibleErrors()
2348 * @deprecated since 1.24
2351 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2352 wfDeprecated( __METHOD__
, '1.24' );
2357 * @see self::getPossibleErrors()
2358 * @deprecated since 1.24
2361 public function getRequireMaxOneParameterErrorMessages( $params ) {
2362 wfDeprecated( __METHOD__
, '1.24' );
2367 * @see self::getPossibleErrors()
2368 * @deprecated since 1.24
2371 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2372 wfDeprecated( __METHOD__
, '1.24' );
2377 * @see self::getPossibleErrors()
2378 * @deprecated since 1.24
2381 public function getTitleOrPageIdErrorMessage() {
2382 wfDeprecated( __METHOD__
, '1.24' );
2387 * This formerly attempted to return a list of all possible errors returned
2388 * by the module. However, this was impossible to maintain in many cases
2389 * since errors could come from other areas of MediaWiki and in some cases
2390 * from arbitrary extension hooks. Since a partial list claiming to be
2391 * comprehensive is unlikely to be useful, it was removed.
2393 * @deprecated since 1.24
2396 public function getPossibleErrors() {
2397 wfDeprecated( __METHOD__
, '1.24' );
2402 * @see self::getPossibleErrors()
2403 * @deprecated since 1.24
2406 public function getFinalPossibleErrors() {
2407 wfDeprecated( __METHOD__
, '1.24' );
2412 * @see self::getPossibleErrors()
2413 * @deprecated since 1.24
2416 public function parseErrors( $errors ) {
2417 wfDeprecated( __METHOD__
, '1.24' );
2422 * Returns the description string for this module
2424 * Ignored if an i18n message exists for
2425 * "apihelp-{$this->getModulePathString()}-description".
2427 * @deprecated since 1.25
2428 * @return Message|string|array
2430 protected function getDescription() {
2435 * Returns an array of parameter descriptions.
2437 * For each parameter, ignored if an i18n message exists for the parameter.
2438 * By default that message is
2439 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2440 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2441 * self::getFinalParams().
2443 * @deprecated since 1.25
2444 * @return array|bool False on no parameter descriptions
2446 protected function getParamDescription() {
2451 * Returns usage examples for this module.
2453 * Return value as an array is either:
2454 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2456 * - sequential numeric keys with even-numbered keys being display-text
2457 * and odd-numbered keys being partial urls
2458 * - partial URLs as keys with display-text (string or array-to-be-joined)
2460 * Return value as a string is the same as an array with a numeric key and
2461 * that value, and boolean false means "no examples".
2463 * @deprecated since 1.25, use getExamplesMessages() instead
2464 * @return bool|string|array
2466 protected function getExamples() {
2471 * Generates help message for this module, or false if there is no description
2472 * @deprecated since 1.25
2473 * @return string|bool
2475 public function makeHelpMsg() {
2476 wfDeprecated( __METHOD__
, '1.25' );
2477 static $lnPrfx = "\n ";
2479 $msg = $this->getFinalDescription();
2481 if ( $msg !== false ) {
2483 if ( !is_array( $msg ) ) {
2488 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2490 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2492 if ( $this->isReadMode() ) {
2493 $msg .= "\nThis module requires read rights";
2495 if ( $this->isWriteMode() ) {
2496 $msg .= "\nThis module requires write rights";
2498 if ( $this->mustBePosted() ) {
2499 $msg .= "\nThis module only accepts POST requests";
2501 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2502 $this->mustBePosted()
2508 $paramsMsg = $this->makeHelpMsgParameters();
2509 if ( $paramsMsg !== false ) {
2510 $msg .= "Parameters:\n$paramsMsg";
2513 $examples = $this->getExamples();
2515 if ( !is_array( $examples ) ) {
2520 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2521 foreach ( $examples as $k => $v ) {
2522 if ( is_numeric( $k ) ) {
2525 if ( is_array( $v ) ) {
2526 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2528 $msgExample = " $v";
2531 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2541 * @deprecated since 1.25
2542 * @param string $item
2545 private function indentExampleText( $item ) {
2550 * @deprecated since 1.25
2551 * @param string $prefix Text to split output items
2552 * @param string $title What is being output
2553 * @param string|array $input
2556 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2557 wfDeprecated( __METHOD__
, '1.25' );
2558 if ( $input === false ) {
2561 if ( !is_array( $input ) ) {
2562 $input = array( $input );
2565 if ( count( $input ) > 0 ) {
2567 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2571 $msg .= implode( $prefix, $input ) . "\n";
2580 * Generates the parameter descriptions for this module, to be displayed in the
2582 * @deprecated since 1.25
2583 * @return string|bool
2585 public function makeHelpMsgParameters() {
2586 wfDeprecated( __METHOD__
, '1.25' );
2587 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2590 $paramsDescription = $this->getFinalParamDescription();
2592 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2593 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2594 foreach ( $params as $paramName => $paramSettings ) {
2595 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2596 if ( is_array( $desc ) ) {
2597 $desc = implode( $paramPrefix, $desc );
2601 if ( !is_array( $paramSettings ) ) {
2602 $paramSettings = array(
2603 self
::PARAM_DFLT
=> $paramSettings,
2607 //handle missing type
2608 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2609 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2610 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2612 if ( is_bool( $dflt ) ) {
2613 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2614 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2615 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2616 } elseif ( is_int( $dflt ) ) {
2617 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2621 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2622 && $paramSettings[self
::PARAM_DEPRECATED
]
2624 $desc = "DEPRECATED! $desc";
2627 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2628 && $paramSettings[self
::PARAM_REQUIRED
]
2630 $desc .= $paramPrefix . "This parameter is required";
2633 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2634 ?
$paramSettings[self
::PARAM_TYPE
]
2636 if ( isset( $type ) ) {
2637 $hintPipeSeparated = true;
2638 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2639 ?
$paramSettings[self
::PARAM_ISMULTI
]
2642 $prompt = 'Values (separate with \'|\'): ';
2644 $prompt = 'One value: ';
2647 if ( $type === 'submodule' ) {
2648 $type = $this->getModuleManager()->getNames( $paramName );
2651 if ( is_array( $type ) ) {
2653 $nothingPrompt = '';
2654 foreach ( $type as $t ) {
2656 $nothingPrompt = 'Can be empty, or ';
2661 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2662 $choicesstring = implode( ', ', $choices );
2663 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2664 $hintPipeSeparated = false;
2668 // Special handling because namespaces are
2669 // type-limited, yet they are not given
2670 $desc .= $paramPrefix . $prompt;
2671 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2672 100, $descWordwrap );
2673 $hintPipeSeparated = false;
2676 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2677 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2678 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2680 $desc .= ' allowed';
2683 $s = $multi ?
's' : '';
2684 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2685 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2686 if ( $hasMin ||
$hasMax ) {
2688 $intRangeStr = "The value$s must be no less than " .
2689 "{$paramSettings[self::PARAM_MIN]}";
2690 } elseif ( !$hasMin ) {
2691 $intRangeStr = "The value$s must be no more than " .
2692 "{$paramSettings[self::PARAM_MAX]}";
2694 $intRangeStr = "The value$s must be between " .
2695 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2698 $desc .= $paramPrefix . $intRangeStr;
2702 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2708 if ( $hintPipeSeparated ) {
2709 $desc .= $paramPrefix . "Separate values with '|'";
2712 $isArray = is_array( $type );
2714 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2716 $desc .= $paramPrefix . "Maximum number of values " .
2717 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2722 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2723 if ( !is_null( $default ) && $default !== false ) {
2724 $desc .= $paramPrefix . "Default: $default";
2727 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2740 * For really cool vim folding this needs to be at the end:
2741 * vim: foldmarker=@{,@} foldmethod=marker