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 * Self-documentation: code to allow the API to document its own state
39 abstract class ApiBase
extends ContextSource
{
42 * @name Constants for ::getAllowedParams() arrays
43 * These constants are keys in the arrays returned by ::getAllowedParams()
44 * and accepted by ::getParameterFromSettings() that define how the
45 * parameters coming in from the request are to be interpreted.
49 /** (null|boolean|integer|string) Default value of the parameter. */
52 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
53 const PARAM_ISMULTI
= 1;
56 * (string|string[]) Either an array of allowed value strings, or a string
57 * type as described below. If not specified, will be determined from the
60 * Supported string types are:
61 * - boolean: A boolean parameter, returned as false if the parameter is
62 * omitted and true if present (even with a falsey value, i.e. it works
63 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
64 * Cannot be used with PARAM_ISMULTI.
65 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
66 * PARAM_RANGE_ENFORCE.
67 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
68 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
69 * specified. Cannot be used with PARAM_ISMULTI.
70 * - namespace: An integer representing a MediaWiki namespace.
72 * - password: Any non-empty string. Input value is private or sensitive.
73 * <input type="password"> would be an appropriate HTML form field.
74 * - string: Any non-empty string, not expected to be very long or contain newlines.
75 * <input type="text"> would be an appropriate HTML form field.
76 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
77 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
78 * used with PARAM_ISMULTI.
79 * - text: Any non-empty string, expected to be very long or contain newlines.
80 * <textarea> would be an appropriate HTML form field.
81 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
82 * string 'now' representing the current timestamp. Will be returned in
84 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
85 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
86 * Cannot be used with PARAM_ISMULTI.
90 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
94 * (integer) Max value allowed for the parameter for users with the
95 * apihighlimits right, for PARAM_TYPE 'limit'.
99 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
102 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
103 const PARAM_ALLOW_DUPLICATES
= 6;
105 /** (boolean) Is the parameter deprecated (will show a warning)? */
106 const PARAM_DEPRECATED
= 7;
109 * (boolean) Is the parameter required?
112 const PARAM_REQUIRED
= 8;
115 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
118 const PARAM_RANGE_ENFORCE
= 9;
121 * (string|array|Message) Specify an alternative i18n documentation message
122 * for this parameter. Default is apihelp-{$path}-param-{$param}.
125 const PARAM_HELP_MSG
= 10;
128 * ((string|array|Message)[]) Specify additional i18n messages to append to
129 * the normal message for this parameter.
132 const PARAM_HELP_MSG_APPEND
= 11;
135 * (array) Specify additional information tags for the parameter. Value is
136 * an array of arrays, with the first member being the 'tag' for the info
137 * and the remaining members being the values. In the help, this is
138 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
139 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
142 const PARAM_HELP_MSG_INFO
= 12;
145 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
146 * those values to page titles which will be linked in the help.
149 const PARAM_VALUE_LINKS
= 13;
152 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
153 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
154 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
157 const PARAM_HELP_MSG_PER_VALUE
= 14;
160 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
161 * submodule paths. Default is to use all modules in
162 * $this->getModuleManager() in the group matching the parameter name.
165 const PARAM_SUBMODULE_MAP
= 15;
168 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
169 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
172 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
176 /** Fast query, standard limit. */
177 const LIMIT_BIG1
= 500;
178 /** Fast query, apihighlimits limit. */
179 const LIMIT_BIG2
= 5000;
180 /** Slow query, standard limit. */
181 const LIMIT_SML1
= 50;
182 /** Slow query, apihighlimits limit. */
183 const LIMIT_SML2
= 500;
186 * getAllowedParams() flag: When set, the result could take longer to generate,
187 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
190 const GET_VALUES_FOR_HELP
= 1;
192 /** @var array Maps extension paths to info arrays */
193 private static $extensionInfo = null;
196 private $mMainModule;
198 private $mModuleName, $mModulePrefix;
199 private $mSlaveDB = null;
200 private $mParamCache = [];
201 /** @var array|null|bool */
202 private $mModuleSource = false;
205 * @param ApiMain $mainModule
206 * @param string $moduleName Name of this module
207 * @param string $modulePrefix Prefix to use for parameter names
209 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
210 $this->mMainModule
= $mainModule;
211 $this->mModuleName
= $moduleName;
212 $this->mModulePrefix
= $modulePrefix;
214 if ( !$this->isMain() ) {
215 $this->setContext( $mainModule->getContext() );
219 /************************************************************************//**
220 * @name Methods to implement
225 * Evaluates the parameters, performs the requested query, and sets up
226 * the result. Concrete implementations of ApiBase must override this
227 * method to provide whatever functionality their module offers.
228 * Implementations must not produce any output on their own and are not
229 * expected to handle any errors.
231 * The execute() method will be invoked directly by ApiMain immediately
232 * before the result of the module is output. Aside from the
233 * constructor, implementations should assume that no other methods
234 * will be called externally on the module before the result is
237 * The result data should be stored in the ApiResult object available
238 * through getResult().
240 abstract public function execute();
243 * Get the module manager, or null if this module has no sub-modules
245 * @return ApiModuleManager
247 public function getModuleManager() {
252 * If the module may only be used with a certain format module,
253 * it should override this method to return an instance of that formatter.
254 * A value of null means the default format will be used.
255 * @note Do not use this just because you don't want to support non-json
256 * formats. This should be used only when there is a fundamental
257 * requirement for a specific format.
258 * @return mixed Instance of a derived class of ApiFormatBase, or null
260 public function getCustomPrinter() {
265 * Returns usage examples for this module.
267 * Return value has query strings as keys, with values being either strings
268 * (message key), arrays (message key + parameter), or Message objects.
270 * Do not call this base class implementation when overriding this method.
275 protected function getExamplesMessages() {
276 // Fall back to old non-localised method
279 $examples = $this->getExamples();
281 if ( !is_array( $examples ) ) {
282 $examples = [ $examples ];
283 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
284 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
285 !preg_match( '/^\s*api\.php\?/', $examples[0] )
287 // Fix up the ugly "even numbered elements are description, odd
288 // numbered elemts are the link" format (see doc for self::getExamples)
290 $examplesCount = count( $examples );
291 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
292 $tmp[$examples[$i +
1]] = $examples[$i];
297 foreach ( $examples as $k => $v ) {
298 if ( is_numeric( $k ) ) {
303 $msg = self
::escapeWikiText( $v );
304 if ( is_array( $msg ) ) {
305 $msg = implode( ' ', $msg );
309 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
310 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
318 * Return links to more detailed help pages about the module.
319 * @since 1.25, returning boolean false is deprecated
320 * @return string|array
322 public function getHelpUrls() {
327 * Returns an array of allowed parameters (parameter name) => (default
328 * value) or (parameter name) => (array with PARAM_* constants as keys)
329 * Don't call this function directly: use getFinalParams() to allow
330 * hooks to modify parameters as needed.
332 * Some derived classes may choose to handle an integer $flags parameter
333 * in the overriding methods. Callers of this method can pass zero or
334 * more OR-ed flags like GET_VALUES_FOR_HELP.
338 protected function getAllowedParams( /* $flags = 0 */ ) {
339 // int $flags is not declared because it causes "Strict standards"
340 // warning. Most derived classes do not implement it.
345 * Indicates if this module needs maxlag to be checked
348 public function shouldCheckMaxlag() {
353 * Indicates whether this module requires read rights
356 public function isReadMode() {
361 * Indicates whether this module requires write mode
364 public function isWriteMode() {
369 * Indicates whether this module must be called with a POST request
372 public function mustBePosted() {
373 return $this->needsToken() !== false;
377 * Indicates whether this module is deprecated
381 public function isDeprecated() {
386 * Indicates whether this module is "internal"
387 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
391 public function isInternal() {
396 * Returns the token type this module requires in order to execute.
398 * Modules are strongly encouraged to use the core 'csrf' type unless they
399 * have specialized security needs. If the token type is not one of the
400 * core types, you must use the ApiQueryTokensRegisterTypes hook to
403 * Returning a non-falsey value here will force the addition of an
404 * appropriate 'token' parameter in self::getFinalParams(). Also,
405 * self::mustBePosted() must return true when tokens are used.
407 * In previous versions of MediaWiki, true was a valid return value.
408 * Returning true will generate errors indicating that the API module needs
411 * @return string|false
413 public function needsToken() {
418 * Fetch the salt used in the Web UI corresponding to this module.
420 * Only override this if the Web UI uses a token with a non-constant salt.
423 * @param array $params All supplied parameters for the module
424 * @return string|array|null
426 protected function getWebUITokenSalt( array $params ) {
431 * Returns data for HTTP conditional request mechanisms.
434 * @param string $condition Condition being queried:
435 * - last-modified: Return a timestamp representing the maximum of the
436 * last-modified dates for all resources involved in the request. See
437 * RFC 7232 § 2.2 for semantics.
438 * - etag: Return an entity-tag representing the state of all resources involved
439 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
440 * @return string|bool|null As described above, or null if no value is available.
442 public function getConditionalRequestData( $condition ) {
448 /************************************************************************//**
449 * @name Data access methods
454 * Get the name of the module being executed by this instance
457 public function getModuleName() {
458 return $this->mModuleName
;
462 * Get parameter prefix (usually two letters or an empty string).
465 public function getModulePrefix() {
466 return $this->mModulePrefix
;
470 * Get the main module
473 public function getMain() {
474 return $this->mMainModule
;
478 * Returns true if this module is the main module ($this === $this->mMainModule),
482 public function isMain() {
483 return $this === $this->mMainModule
;
487 * Get the parent of this module
489 * @return ApiBase|null
491 public function getParent() {
492 return $this->isMain() ?
null : $this->getMain();
496 * Returns true if the current request breaks the same-origin policy.
498 * For example, json with callbacks.
500 * https://en.wikipedia.org/wiki/Same-origin_policy
505 public function lacksSameOriginSecurity() {
506 // Main module has this method overridden
507 // Safety - avoid infinite loop:
508 if ( $this->isMain() ) {
509 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
512 return $this->getMain()->lacksSameOriginSecurity();
516 * Get the path to this module
521 public function getModulePath() {
522 if ( $this->isMain() ) {
524 } elseif ( $this->getParent()->isMain() ) {
525 return $this->getModuleName();
527 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
532 * Get a module from its module path
535 * @param string $path
536 * @return ApiBase|null
537 * @throws UsageException
539 public function getModuleFromPath( $path ) {
540 $module = $this->getMain();
541 if ( $path === 'main' ) {
545 $parts = explode( '+', $path );
546 if ( count( $parts ) === 1 ) {
547 // In case the '+' was typed into URL, it resolves as a space
548 $parts = explode( ' ', $path );
551 $count = count( $parts );
552 for ( $i = 0; $i < $count; $i++
) {
554 $manager = $parent->getModuleManager();
555 if ( $manager === null ) {
556 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
557 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
559 $module = $manager->getModule( $parts[$i] );
561 if ( $module === null ) {
562 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
564 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
574 * Get the result object
577 public function getResult() {
578 // Main module has getResult() method overridden
579 // Safety - avoid infinite loop:
580 if ( $this->isMain() ) {
581 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
584 return $this->getMain()->getResult();
588 * Get the error formatter
589 * @return ApiErrorFormatter
591 public function getErrorFormatter() {
592 // Main module has getErrorFormatter() method overridden
593 // Safety - avoid infinite loop:
594 if ( $this->isMain() ) {
595 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
598 return $this->getMain()->getErrorFormatter();
602 * Gets a default slave database connection object
603 * @return DatabaseBase
605 protected function getDB() {
606 if ( !isset( $this->mSlaveDB
) ) {
607 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
610 return $this->mSlaveDB
;
614 * Get the continuation manager
615 * @return ApiContinuationManager|null
617 public function getContinuationManager() {
618 // Main module has getContinuationManager() method overridden
619 // Safety - avoid infinite loop:
620 if ( $this->isMain() ) {
621 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
624 return $this->getMain()->getContinuationManager();
628 * Set the continuation manager
629 * @param ApiContinuationManager|null
631 public function setContinuationManager( $manager ) {
632 // Main module has setContinuationManager() method overridden
633 // Safety - avoid infinite loop:
634 if ( $this->isMain() ) {
635 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
638 $this->getMain()->setContinuationManager( $manager );
643 /************************************************************************//**
644 * @name Parameter handling
649 * Indicate if the module supports dynamically-determined parameters that
650 * cannot be included in self::getAllowedParams().
651 * @return string|array|Message|null Return null if the module does not
652 * support additional dynamic parameters, otherwise return a message
655 public function dynamicParameterDocumentation() {
660 * This method mangles parameter name based on the prefix supplied to the constructor.
661 * Override this method to change parameter name during runtime
662 * @param string $paramName Parameter name
663 * @return string Prefixed parameter name
665 public function encodeParamName( $paramName ) {
666 return $this->mModulePrefix
. $paramName;
670 * Using getAllowedParams(), this function makes an array of the values
671 * provided by the user, with key being the name of the variable, and
672 * value - validated value from user or default. limits will not be
673 * parsed if $parseLimit is set to false; use this when the max
674 * limit is not definitive yet, e.g. when getting revisions.
675 * @param bool $parseLimit True by default
678 public function extractRequestParams( $parseLimit = true ) {
679 // Cache parameters, for performance and to avoid bug 24564.
680 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
681 $params = $this->getFinalParams();
684 if ( $params ) { // getFinalParams() can return false
685 foreach ( $params as $paramName => $paramSettings ) {
686 $results[$paramName] = $this->getParameterFromSettings(
687 $paramName, $paramSettings, $parseLimit );
690 $this->mParamCache
[$parseLimit] = $results;
693 return $this->mParamCache
[$parseLimit];
697 * Get a value for the given parameter
698 * @param string $paramName Parameter name
699 * @param bool $parseLimit See extractRequestParams()
700 * @return mixed Parameter value
702 protected function getParameter( $paramName, $parseLimit = true ) {
703 $paramSettings = $this->getFinalParams()[$paramName];
705 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
709 * Die if none or more than one of a certain set of parameters is set and not false.
711 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
712 * @param string $required,... Names of parameters of which exactly one must be set
714 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
715 $required = func_get_args();
716 array_shift( $required );
717 $p = $this->getModulePrefix();
719 $intersection = array_intersect( array_keys( array_filter( $params,
720 [ $this, 'parameterNotEmpty' ] ) ), $required );
722 if ( count( $intersection ) > 1 ) {
724 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
726 } elseif ( count( $intersection ) == 0 ) {
728 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
735 * Die if more than one of a certain set of parameters is set and not false.
737 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
738 * @param string $required,... Names of parameters of which at most one must be set
740 public function requireMaxOneParameter( $params, $required /*...*/ ) {
741 $required = func_get_args();
742 array_shift( $required );
743 $p = $this->getModulePrefix();
745 $intersection = array_intersect( array_keys( array_filter( $params,
746 [ $this, 'parameterNotEmpty' ] ) ), $required );
748 if ( count( $intersection ) > 1 ) {
750 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
757 * Die if none of a certain set of parameters is set and not false.
760 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
761 * @param string $required,... Names of parameters of which at least one must be set
763 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
764 $required = func_get_args();
765 array_shift( $required );
766 $p = $this->getModulePrefix();
768 $intersection = array_intersect(
769 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
773 if ( count( $intersection ) == 0 ) {
774 $this->dieUsage( "At least one of the parameters {$p}" .
775 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
780 * Die if any of the specified parameters were found in the query part of
781 * the URL rather than the post body.
783 * @param string[] $params Parameters to check
784 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
786 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
787 // Skip if $wgDebugAPI is set or we're in internal mode
788 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
792 $queryValues = $this->getRequest()->getQueryValues();
794 foreach ( $params as $param ) {
795 if ( $prefix !== 'noprefix' ) {
796 $param = $this->encodeParamName( $param );
798 if ( array_key_exists( $param, $queryValues ) ) {
799 $badParams[] = $param;
805 'The following parameters were found in the query string, but must be in the POST body: '
806 . join( ', ', $badParams ),
813 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
815 * @param object $x Parameter to check is not null/false
818 private function parameterNotEmpty( $x ) {
819 return !is_null( $x ) && $x !== false;
823 * Get a WikiPage object from a title or pageid param, if possible.
824 * Can die, if no param is set or if the title or page id is not valid.
826 * @param array $params
827 * @param bool|string $load Whether load the object's state from the database:
828 * - false: don't load (if the pageid is given, it will still be loaded)
829 * - 'fromdb': load from a slave database
830 * - 'fromdbmaster': load from the master database
833 public function getTitleOrPageId( $params, $load = false ) {
834 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
837 if ( isset( $params['title'] ) ) {
838 $titleObj = Title
::newFromText( $params['title'] );
839 if ( !$titleObj ||
$titleObj->isExternal() ) {
840 $this->dieUsageMsg( [ 'invalidtitle', $params['title'] ] );
842 if ( !$titleObj->canExist() ) {
843 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
845 $pageObj = WikiPage
::factory( $titleObj );
846 if ( $load !== false ) {
847 $pageObj->loadPageData( $load );
849 } elseif ( isset( $params['pageid'] ) ) {
850 if ( $load === false ) {
853 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
855 $this->dieUsageMsg( [ 'nosuchpageid', $params['pageid'] ] );
863 * Return true if we're to watch the page, false if not, null if no change.
864 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
865 * @param Title $titleObj The page under consideration
866 * @param string $userOption The user option to consider when $watchlist=preferences.
867 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
870 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
872 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
874 switch ( $watchlist ) {
882 # If the user is already watching, don't bother checking
883 if ( $userWatching ) {
886 # If no user option was passed, use watchdefault and watchcreations
887 if ( is_null( $userOption ) ) {
888 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
889 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
892 # Watch the article based on the user preference
893 return $this->getUser()->getBoolOption( $userOption );
896 return $userWatching;
899 return $userWatching;
904 * Using the settings determine the value for the given parameter
906 * @param string $paramName Parameter name
907 * @param array|mixed $paramSettings Default value or an array of settings
908 * using PARAM_* constants.
909 * @param bool $parseLimit Parse limit?
910 * @return mixed Parameter value
912 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
913 // Some classes may decide to change parameter names
914 $encParamName = $this->encodeParamName( $paramName );
916 if ( !is_array( $paramSettings ) ) {
917 $default = $paramSettings;
919 $type = gettype( $paramSettings );
924 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
925 ?
$paramSettings[self
::PARAM_DFLT
]
927 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
928 ?
$paramSettings[self
::PARAM_ISMULTI
]
930 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
931 ?
$paramSettings[self
::PARAM_TYPE
]
933 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
934 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
936 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
937 ?
$paramSettings[self
::PARAM_DEPRECATED
]
939 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
940 ?
$paramSettings[self
::PARAM_REQUIRED
]
943 // When type is not given, and no choices, the type is the same as $default
944 if ( !isset( $type ) ) {
945 if ( isset( $default ) ) {
946 $type = gettype( $default );
948 $type = 'NULL'; // allow everything
953 if ( $type == 'boolean' ) {
954 if ( isset( $default ) && $default !== false ) {
955 // Having a default value of anything other than 'false' is not allowed
958 "Boolean param $encParamName's default is set to '$default'. " .
959 'Boolean parameters must default to false.'
963 $value = $this->getMain()->getCheck( $encParamName );
964 } elseif ( $type == 'upload' ) {
965 if ( isset( $default ) ) {
966 // Having a default value is not allowed
969 "File upload param $encParamName's default is set to " .
970 "'$default'. File upload parameters may not have a default." );
973 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
975 $value = $this->getMain()->getUpload( $encParamName );
976 if ( !$value->exists() ) {
977 // This will get the value without trying to normalize it
978 // (because trying to normalize a large binary file
979 // accidentally uploaded as a field fails spectacularly)
980 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
981 if ( $value !== null ) {
983 "File upload param $encParamName is not a file upload; " .
984 'be sure to use multipart/form-data for your POST and include ' .
985 'a filename in the Content-Disposition header.',
986 "badupload_{$encParamName}"
991 $value = $this->getMain()->getVal( $encParamName, $default );
993 if ( isset( $value ) && $type == 'namespace' ) {
994 $type = MWNamespace
::getValidNamespaces();
996 if ( isset( $value ) && $type == 'submodule' ) {
997 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
998 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1000 $type = $this->getModuleManager()->getNames( $paramName );
1005 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1006 $value = $this->parseMultiValue(
1010 is_array( $type ) ?
$type : null
1014 // More validation only when choices were not given
1015 // choices were validated in parseMultiValue()
1016 if ( isset( $value ) ) {
1017 if ( !is_array( $type ) ) {
1019 case 'NULL': // nothing to do
1024 if ( $required && $value === '' ) {
1025 $this->dieUsageMsg( [ 'missingparam', $paramName ] );
1028 case 'integer': // Force everything using intval() and optionally validate limits
1029 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1030 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1031 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1032 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1034 if ( is_array( $value ) ) {
1035 $value = array_map( 'intval', $value );
1036 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1037 foreach ( $value as &$v ) {
1038 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1042 $value = intval( $value );
1043 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1044 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1049 if ( !$parseLimit ) {
1050 // Don't do any validation whatsoever
1053 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1054 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1058 "MAX1 or MAX2 are not defined for the limit $encParamName"
1062 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1064 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1065 if ( $value == 'max' ) {
1066 $value = $this->getMain()->canApiHighLimits()
1067 ?
$paramSettings[self
::PARAM_MAX2
]
1068 : $paramSettings[self
::PARAM_MAX
];
1069 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1071 $value = intval( $value );
1072 $this->validateLimit(
1076 $paramSettings[self
::PARAM_MAX
],
1077 $paramSettings[self
::PARAM_MAX2
]
1083 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1087 if ( is_array( $value ) ) {
1088 foreach ( $value as $key => $val ) {
1089 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1092 $value = $this->validateTimestamp( $value, $encParamName );
1096 if ( is_array( $value ) ) {
1097 foreach ( $value as $key => $val ) {
1098 $value[$key] = $this->validateUser( $val, $encParamName );
1101 $value = $this->validateUser( $value, $encParamName );
1104 case 'upload': // nothing to do
1107 // If change tagging was requested, check that the tags are valid.
1108 if ( !is_array( $value ) && !$multi ) {
1109 $value = [ $value ];
1111 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1112 if ( !$tagsStatus->isGood() ) {
1113 $this->dieStatus( $tagsStatus );
1117 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1121 // Throw out duplicates if requested
1122 if ( !$dupes && is_array( $value ) ) {
1123 $value = array_unique( $value );
1126 // Set a warning if a deprecated parameter has been passed
1127 if ( $deprecated && $value !== false ) {
1128 $this->setWarning( "The $encParamName parameter has been deprecated." );
1130 $feature = $encParamName;
1132 while ( !$m->isMain() ) {
1133 $p = $m->getParent();
1134 $name = $m->getModuleName();
1135 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1136 $feature = "{$param}={$name}&{$feature}";
1139 $this->logFeatureUsage( $feature );
1141 } elseif ( $required ) {
1142 $this->dieUsageMsg( [ 'missingparam', $paramName ] );
1149 * Return an array of values that were given in a 'a|b|c' notation,
1150 * after it optionally validates them against the list allowed values.
1152 * @param string $valueName The name of the parameter (for error
1154 * @param mixed $value The value being parsed
1155 * @param bool $allowMultiple Can $value contain more than one value
1157 * @param string[]|null $allowedValues An array of values to check against. If
1158 * null, all values are accepted.
1159 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1161 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1162 if ( trim( $value ) === '' && $allowMultiple ) {
1166 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1167 // because it unstubs $wgUser
1168 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1169 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1173 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1174 $this->logFeatureUsage( "too-many-$valueName-for-{$this->getModulePath()}" );
1175 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1176 "the limit is $sizeLimit" );
1179 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1180 // Bug 33482 - Allow entries with | in them for non-multiple values
1181 if ( in_array( $value, $allowedValues, true ) ) {
1185 $possibleValues = is_array( $allowedValues )
1186 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1189 "Only one $possibleValues is allowed for parameter '$valueName'",
1190 "multival_$valueName"
1194 if ( is_array( $allowedValues ) ) {
1195 // Check for unknown values
1196 $unknown = array_diff( $valuesList, $allowedValues );
1197 if ( count( $unknown ) ) {
1198 if ( $allowMultiple ) {
1199 $s = count( $unknown ) > 1 ?
's' : '';
1200 $vals = implode( ', ', $unknown );
1201 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1204 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1205 "unknown_$valueName"
1209 // Now throw them out
1210 $valuesList = array_intersect( $valuesList, $allowedValues );
1213 return $allowMultiple ?
$valuesList : $valuesList[0];
1217 * Validate the value against the minimum and user/bot maximum limits.
1218 * Prints usage info on failure.
1219 * @param string $paramName Parameter name
1220 * @param int $value Parameter value
1221 * @param int|null $min Minimum value
1222 * @param int|null $max Maximum value for users
1223 * @param int $botMax Maximum value for sysops/bots
1224 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1226 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1227 $enforceLimits = false
1229 if ( !is_null( $min ) && $value < $min ) {
1230 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1231 $this->warnOrDie( $msg, $enforceLimits );
1235 // Minimum is always validated, whereas maximum is checked only if not
1236 // running in internal call mode
1237 if ( $this->getMain()->isInternalMode() ) {
1241 // Optimization: do not check user's bot status unless really needed -- skips db query
1242 // assumes $botMax >= $max
1243 if ( !is_null( $max ) && $value > $max ) {
1244 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1245 if ( $value > $botMax ) {
1246 $msg = $this->encodeParamName( $paramName ) .
1247 " may not be over $botMax (set to $value) for bots or sysops";
1248 $this->warnOrDie( $msg, $enforceLimits );
1252 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1253 $this->warnOrDie( $msg, $enforceLimits );
1260 * Validate and normalize of parameters of type 'timestamp'
1261 * @param string $value Parameter value
1262 * @param string $encParamName Parameter name
1263 * @return string Validated and normalized parameter
1265 protected function validateTimestamp( $value, $encParamName ) {
1266 // Confusing synonyms for the current time accepted by wfTimestamp()
1267 // (wfTimestamp() also accepts various non-strings and the string of 14
1268 // ASCII NUL bytes, but those can't get here)
1270 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1272 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1273 ' If for some reason you need to explicitly specify the current time without' .
1274 ' calculating it client-side, use "now".'
1276 return wfTimestamp( TS_MW
);
1279 // Explicit synonym for the current time
1280 if ( $value === 'now' ) {
1281 return wfTimestamp( TS_MW
);
1284 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1285 if ( $unixTimestamp === false ) {
1287 "Invalid value '$value' for timestamp parameter $encParamName",
1288 "badtimestamp_{$encParamName}"
1292 return wfTimestamp( TS_MW
, $unixTimestamp );
1296 * Validate the supplied token.
1299 * @param string $token Supplied token
1300 * @param array $params All supplied parameters for the module
1302 * @throws MWException
1304 final public function validateToken( $token, array $params ) {
1305 $tokenType = $this->needsToken();
1306 $salts = ApiQueryTokens
::getTokenTypeSalts();
1307 if ( !isset( $salts[$tokenType] ) ) {
1308 throw new MWException(
1309 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1310 'without registering it'
1314 $tokenObj = ApiQueryTokens
::getToken(
1315 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1317 if ( $tokenObj->match( $token ) ) {
1321 $webUiSalt = $this->getWebUITokenSalt( $params );
1322 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1334 * Validate and normalize of parameters of type 'user'
1335 * @param string $value Parameter value
1336 * @param string $encParamName Parameter name
1337 * @return string Validated and normalized parameter
1339 private function validateUser( $value, $encParamName ) {
1340 $title = Title
::makeTitleSafe( NS_USER
, $value );
1341 if ( $title === null ||
$title->hasFragment() ) {
1343 "Invalid value '$value' for user parameter $encParamName",
1344 "baduser_{$encParamName}"
1348 return $title->getText();
1353 /************************************************************************//**
1354 * @name Utility methods
1359 * Set a watch (or unwatch) based the based on a watchlist parameter.
1360 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1361 * @param Title $titleObj The article's title to change
1362 * @param string $userOption The user option to consider when $watch=preferences
1364 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1365 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1366 if ( $value === null ) {
1370 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1374 * Truncate an array to a certain length.
1375 * @param array $arr Array to truncate
1376 * @param int $limit Maximum length
1377 * @return bool True if the array was truncated, false otherwise
1379 public static function truncateArray( &$arr, $limit ) {
1381 while ( count( $arr ) > $limit ) {
1390 * Gets the user for whom to get the watchlist
1392 * @param array $params
1395 public function getWatchlistUser( $params ) {
1396 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1397 $user = User
::newFromName( $params['owner'], false );
1398 if ( !( $user && $user->getId() ) ) {
1399 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1401 $token = $user->getOption( 'watchlisttoken' );
1402 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1404 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1409 if ( !$this->getUser()->isLoggedIn() ) {
1410 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1412 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1413 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1415 $user = $this->getUser();
1422 * A subset of wfEscapeWikiText for BC texts
1425 * @param string|array $v
1426 * @return string|array
1428 private static function escapeWikiText( $v ) {
1429 if ( is_array( $v ) ) {
1430 return array_map( 'self::escapeWikiText', $v );
1433 '__' => '__', '{' => '{', '}' => '}',
1434 '[[Category:' => '[[:Category:',
1435 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1441 * Create a Message from a string or array
1443 * A string is used as a message key. An array has the message key as the
1444 * first value and message parameters as subsequent values.
1447 * @param string|array|Message $msg
1448 * @param IContextSource $context
1449 * @param array $params
1450 * @return Message|null
1452 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1453 if ( is_string( $msg ) ) {
1454 $msg = wfMessage( $msg );
1455 } elseif ( is_array( $msg ) ) {
1456 $msg = call_user_func_array( 'wfMessage', $msg );
1458 if ( !$msg instanceof Message
) {
1462 $msg->setContext( $context );
1464 $msg->params( $params );
1472 /************************************************************************//**
1473 * @name Warning and error reporting
1478 * Set warning section for this module. Users should monitor this
1479 * section to notice any changes in API. Multiple calls to this
1480 * function will result in the warning messages being separated by
1482 * @param string $warning Warning message
1484 public function setWarning( $warning ) {
1485 $msg = new ApiRawMessage( $warning, 'warning' );
1486 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1490 * Adds a warning to the output, else dies
1492 * @param string $msg Message to show as a warning, or error message if dying
1493 * @param bool $enforceLimits Whether this is an enforce (die)
1495 private function warnOrDie( $msg, $enforceLimits = false ) {
1496 if ( $enforceLimits ) {
1497 $this->dieUsage( $msg, 'integeroutofrange' );
1500 $this->setWarning( $msg );
1504 * Throw a UsageException, which will (if uncaught) call the main module's
1505 * error handler and die with an error message.
1507 * @param string $description One-line human-readable description of the
1508 * error condition, e.g., "The API requires a valid action parameter"
1509 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1510 * automated identification of the error, e.g., 'unknown_action'
1511 * @param int $httpRespCode HTTP response code
1512 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
1513 * @throws UsageException always
1515 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1516 throw new UsageException(
1518 $this->encodeParamName( $errorCode ),
1525 * Throw a UsageException, which will (if uncaught) call the main module's
1526 * error handler and die with an error message including block info.
1529 * @param Block $block The block used to generate the UsageException
1530 * @throws UsageException always
1532 public function dieBlocked( Block
$block ) {
1533 // Die using the appropriate message depending on block type
1534 if ( $block->getType() == Block
::TYPE_AUTO
) {
1536 'Your IP address has been blocked automatically, because it was used by a blocked user',
1539 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1543 'You have been blocked from editing',
1546 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1552 * Get error (as code, string) from a Status object.
1555 * @param Status $status
1556 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
1557 * @return array Array of code and error string
1558 * @throws MWException
1560 public function getErrorFromStatus( $status, &$extraData = null ) {
1561 if ( $status->isGood() ) {
1562 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1565 $errors = $status->getErrorsByType( 'error' );
1567 // No errors? Assume the warnings should be treated as errors
1568 $errors = $status->getErrorsByType( 'warning' );
1571 // Still no errors? Punt
1572 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
1575 // Cannot use dieUsageMsg() because extensions might return custom
1577 if ( $errors[0]['message'] instanceof Message
) {
1578 $msg = $errors[0]['message'];
1579 if ( $msg instanceof IApiMessage
) {
1580 $extraData = $msg->getApiData();
1581 $code = $msg->getApiCode();
1583 $code = $msg->getKey();
1586 $code = $errors[0]['message'];
1587 $msg = wfMessage( $code, $errors[0]['params'] );
1589 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1590 // Translate message to code, for backwards compatibility
1591 $code = ApiBase
::$messageMap[$code]['code'];
1594 return [ $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() ];
1598 * Throw a UsageException based on the errors in the Status object.
1601 * @param Status $status
1602 * @throws UsageException always
1604 public function dieStatus( $status ) {
1606 list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1607 $this->dieUsage( $msg, $code, 0, $extraData );
1610 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1612 * Array that maps message keys to error messages. $1 and friends are replaced.
1614 public static $messageMap = [
1615 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1616 'unknownerror' => [ 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ],
1617 'unknownerror-nocode' => [ 'code' => 'unknownerror', 'info' => 'Unknown error' ],
1619 // Messages from Title::getUserPermissionsErrors()
1620 'ns-specialprotected' => [
1621 'code' => 'unsupportednamespace',
1622 'info' => "Pages in the Special namespace can't be edited"
1624 'protectedinterface' => [
1625 'code' => 'protectednamespace-interface',
1626 'info' => "You're not allowed to edit interface messages"
1628 'namespaceprotected' => [
1629 'code' => 'protectednamespace',
1630 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1632 'customcssprotected' => [
1633 'code' => 'customcssprotected',
1634 'info' => "You're not allowed to edit custom CSS pages"
1636 'customjsprotected' => [
1637 'code' => 'customjsprotected',
1638 'info' => "You're not allowed to edit custom JavaScript pages"
1640 'cascadeprotected' => [
1641 'code' => 'cascadeprotected',
1642 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1644 'protectedpagetext' => [
1645 'code' => 'protectedpage',
1646 'info' => "The \"\$1\" right is required to edit this page"
1648 'protect-cantedit' => [
1649 'code' => 'cantedit',
1650 'info' => "You can't protect this page because you can't edit it"
1652 'deleteprotected' => [
1653 'code' => 'cantedit',
1654 'info' => "You can't delete this page because it has been protected"
1656 'badaccess-group0' => [
1657 'code' => 'permissiondenied',
1658 'info' => 'Permission denied'
1659 ], // Generic permission denied message
1660 'badaccess-groups' => [
1661 'code' => 'permissiondenied',
1662 'info' => 'Permission denied'
1664 'titleprotected' => [
1665 'code' => 'protectedtitle',
1666 'info' => 'This title has been protected from creation'
1668 'nocreate-loggedin' => [
1669 'code' => 'cantcreate',
1670 'info' => "You don't have permission to create new pages"
1673 'code' => 'cantcreate-anon',
1674 'info' => "Anonymous users can't create new pages"
1676 'movenologintext' => [
1677 'code' => 'cantmove-anon',
1678 'info' => "Anonymous users can't move pages"
1680 'movenotallowed' => [
1681 'code' => 'cantmove',
1682 'info' => "You don't have permission to move pages"
1684 'confirmedittext' => [
1685 'code' => 'confirmemail',
1686 'info' => 'You must confirm your email address before you can edit'
1689 'code' => 'blocked',
1690 'info' => 'You have been blocked from editing'
1692 'autoblockedtext' => [
1693 'code' => 'autoblocked',
1694 'info' => 'Your IP address has been blocked automatically, because it was used by a blocked user'
1697 // Miscellaneous interface messages
1698 'actionthrottledtext' => [
1699 'code' => 'ratelimited',
1700 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1702 'alreadyrolled' => [
1703 'code' => 'alreadyrolled',
1704 'info' => 'The page you tried to rollback was already rolled back'
1707 'code' => 'onlyauthor',
1708 'info' => 'The page you tried to rollback only has one author'
1711 'code' => 'readonly',
1712 'info' => 'The wiki is currently in read-only mode'
1714 'sessionfailure' => [
1715 'code' => 'badtoken',
1716 'info' => 'Invalid token' ],
1718 'code' => 'cantdelete',
1719 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1722 'code' => 'missingtitle',
1723 'info' => "The page you requested doesn't exist"
1725 'selfmove' => [ 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1727 'immobile_namespace' => [
1728 'code' => 'immobilenamespace',
1729 'info' => 'You tried to move pages from or to a namespace that is protected from moving'
1731 'articleexists' => [
1732 'code' => 'articleexists',
1733 'info' => 'The destination article already exists and is not a redirect to the source article'
1735 'protectedpage' => [
1736 'code' => 'protectedpage',
1737 'info' => "You don't have permission to perform this move"
1740 'code' => 'hookaborted',
1741 'info' => 'The modification you tried to make was aborted by an extension hook'
1743 'cantmove-titleprotected' => [
1744 'code' => 'protectedtitle',
1745 'info' => 'The destination article has been protected from creation'
1747 'imagenocrossnamespace' => [
1748 'code' => 'nonfilenamespace',
1749 'info' => "Can't move a file to a non-file namespace"
1751 'imagetypemismatch' => [
1752 'code' => 'filetypemismatch',
1753 'info' => "The new file extension doesn't match its type"
1755 // 'badarticleerror' => shouldn't happen
1756 // 'badtitletext' => shouldn't happen
1757 'ip_range_invalid' => [ 'code' => 'invalidrange', 'info' => 'Invalid IP range' ],
1758 'range_block_disabled' => [
1759 'code' => 'rangedisabled',
1760 'info' => 'Blocking IP ranges has been disabled'
1762 'nosuchusershort' => [
1763 'code' => 'nosuchuser',
1764 'info' => "The user you specified doesn't exist"
1766 'badipaddress' => [ 'code' => 'invalidip', 'info' => 'Invalid IP address specified' ],
1767 'ipb_expiry_invalid' => [ 'code' => 'invalidexpiry', 'info' => 'Invalid expiry time' ],
1768 'ipb_already_blocked' => [
1769 'code' => 'alreadyblocked',
1770 'info' => 'The user you tried to block was already blocked'
1772 'ipb_blocked_as_range' => [
1773 'code' => 'blockedasrange',
1774 '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."
1776 'ipb_cant_unblock' => [
1777 'code' => 'cantunblock',
1778 'info' => 'The block you specified was not found. It may have been unblocked already'
1781 'code' => 'cantsend',
1782 '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'
1785 'code' => 'ipbblocked',
1786 'info' => 'You cannot block or unblock users while you are yourself blocked'
1788 'ipbnounblockself' => [
1789 'code' => 'ipbnounblockself',
1790 'info' => 'You are not allowed to unblock yourself'
1792 'usermaildisabled' => [
1793 'code' => 'usermaildisabled',
1794 'info' => 'User email has been disabled'
1796 'blockedemailuser' => [
1797 'code' => 'blockedfrommail',
1798 'info' => 'You have been blocked from sending email'
1801 'code' => 'notarget',
1802 'info' => 'You have not specified a valid target for this action'
1805 'code' => 'noemail',
1806 'info' => 'The user has not specified a valid email address, or has chosen not to receive email from other users'
1808 'rcpatroldisabled' => [
1809 'code' => 'patroldisabled',
1810 'info' => 'Patrolling is disabled on this wiki'
1812 'markedaspatrollederror-noautopatrol' => [
1813 'code' => 'noautopatrol',
1814 'info' => "You don't have permission to patrol your own changes"
1816 'delete-toobig' => [
1817 'code' => 'bigdelete',
1818 'info' => "You can't delete this page because it has more than \$1 revisions"
1820 'movenotallowedfile' => [
1821 'code' => 'cantmovefile',
1822 'info' => "You don't have permission to move files"
1824 'userrights-no-interwiki' => [
1825 'code' => 'nointerwikiuserrights',
1826 'info' => "You don't have permission to change user rights on other wikis"
1828 'userrights-nodatabase' => [
1829 'code' => 'nosuchdatabase',
1830 'info' => "Database \"\$1\" does not exist or is not local"
1832 'nouserspecified' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1833 'noname' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1834 'summaryrequired' => [ 'code' => 'summaryrequired', 'info' => 'Summary required' ],
1835 'import-rootpage-invalid' => [
1836 'code' => 'import-rootpage-invalid',
1837 'info' => 'Root page is an invalid title'
1839 'import-rootpage-nosubpage' => [
1840 'code' => 'import-rootpage-nosubpage',
1841 'info' => 'Namespace "$1" of the root page does not allow subpages'
1844 // API-specific messages
1846 'code' => 'readapidenied',
1847 'info' => 'You need read permission to use this module'
1849 'writedisabled' => [
1850 'code' => 'noapiwrite',
1851 '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"
1853 'writerequired' => [
1854 'code' => 'writeapidenied',
1855 'info' => "You're not allowed to edit this wiki through the API"
1857 'missingparam' => [ 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ],
1858 'invalidtitle' => [ 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ],
1859 'nosuchpageid' => [ 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ],
1860 'nosuchrevid' => [ 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ],
1861 'nosuchuser' => [ 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ],
1862 'invaliduser' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1863 'invalidexpiry' => [ 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ],
1864 'pastexpiry' => [ 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ],
1865 'create-titleexists' => [
1866 'code' => 'create-titleexists',
1867 'info' => "Existing titles can't be protected with 'create'"
1869 'missingtitle-createonly' => [
1870 'code' => 'missingtitle-createonly',
1871 'info' => "Missing titles can only be protected with 'create'"
1873 'cantblock' => [ 'code' => 'cantblock',
1874 'info' => "You don't have permission to block users"
1877 'code' => 'canthide',
1878 'info' => "You don't have permission to hide user names from the block log"
1880 'cantblock-email' => [
1881 'code' => 'cantblock-email',
1882 'info' => "You don't have permission to block users from sending email through the wiki"
1884 'unblock-notarget' => [
1885 'code' => 'notarget',
1886 'info' => 'Either the id or the user parameter must be set'
1888 'unblock-idanduser' => [
1889 'code' => 'idanduser',
1890 'info' => "The id and user parameters can't be used together"
1893 'code' => 'permissiondenied',
1894 'info' => "You don't have permission to unblock users"
1896 'cannotundelete' => [
1897 'code' => 'cantundelete',
1898 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1900 'permdenied-undelete' => [
1901 'code' => 'permissiondenied',
1902 'info' => "You don't have permission to restore deleted revisions"
1904 'createonly-exists' => [
1905 'code' => 'articleexists',
1906 'info' => 'The article you tried to create has been created already'
1908 'nocreate-missing' => [
1909 'code' => 'missingtitle',
1910 'info' => "The article you tried to edit doesn't exist"
1912 'cantchangecontentmodel' => [
1913 'code' => 'cantchangecontentmodel',
1914 'info' => "You don't have permission to change the content model of a page"
1917 'code' => 'nosuchrcid',
1918 'info' => "There is no change with rcid \"\$1\""
1921 'code' => 'nosuchlogid',
1922 'info' => "There is no log entry with ID \"\$1\""
1924 'protect-invalidaction' => [
1925 'code' => 'protect-invalidaction',
1926 'info' => "Invalid protection type \"\$1\""
1928 'protect-invalidlevel' => [
1929 'code' => 'protect-invalidlevel',
1930 'info' => "Invalid protection level \"\$1\""
1932 'toofewexpiries' => [
1933 'code' => 'toofewexpiries',
1934 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1937 'code' => 'cantimport',
1938 'info' => "You don't have permission to import pages"
1940 'cantimport-upload' => [
1941 'code' => 'cantimport-upload',
1942 'info' => "You don't have permission to import uploaded pages"
1944 'importnofile' => [ 'code' => 'nofile', 'info' => "You didn't upload a file" ],
1945 'importuploaderrorsize' => [
1946 'code' => 'filetoobig',
1947 'info' => 'The file you uploaded is bigger than the maximum upload size'
1949 'importuploaderrorpartial' => [
1950 'code' => 'partialupload',
1951 'info' => 'The file was only partially uploaded'
1953 'importuploaderrortemp' => [
1954 'code' => 'notempdir',
1955 'info' => 'The temporary upload directory is missing'
1957 'importcantopen' => [
1958 'code' => 'cantopenfile',
1959 'info' => "Couldn't open the uploaded file"
1961 'import-noarticle' => [
1962 'code' => 'badinterwiki',
1963 'info' => 'Invalid interwiki title specified'
1965 'importbadinterwiki' => [
1966 'code' => 'badinterwiki',
1967 'info' => 'Invalid interwiki title specified'
1969 'import-unknownerror' => [
1970 'code' => 'import-unknownerror',
1971 'info' => "Unknown error on import: \"\$1\""
1973 'cantoverwrite-sharedfile' => [
1974 'code' => 'cantoverwrite-sharedfile',
1975 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1977 'sharedfile-exists' => [
1978 'code' => 'fileexists-sharedrepo-perm',
1979 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1982 'code' => 'mustbeposted',
1983 'info' => "The \$1 module requires a POST request"
1987 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1989 'specialpage-cantexecute' => [
1990 'code' => 'specialpage-cantexecute',
1991 'info' => "You don't have permission to view the results of this special page"
1993 'invalidoldimage' => [
1994 'code' => 'invalidoldimage',
1995 'info' => 'The oldimage parameter has invalid format'
1997 'nodeleteablefile' => [
1998 'code' => 'nodeleteablefile',
1999 'info' => 'No such old version of the file'
2001 'fileexists-forbidden' => [
2002 'code' => 'fileexists-forbidden',
2003 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
2005 'fileexists-shared-forbidden' => [
2006 'code' => 'fileexists-shared-forbidden',
2007 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
2009 'filerevert-badversion' => [
2010 'code' => 'filerevert-badversion',
2011 'info' => 'There is no previous local version of this file with the provided timestamp.'
2014 // ApiEditPage messages
2015 'noimageredirect-anon' => [
2016 'code' => 'noimageredirect-anon',
2017 'info' => "Anonymous users can't create image redirects"
2019 'noimageredirect-logged' => [
2020 'code' => 'noimageredirect',
2021 'info' => "You don't have permission to create image redirects"
2024 'code' => 'spamdetected',
2025 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
2027 'contenttoobig' => [
2028 'code' => 'contenttoobig',
2029 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
2031 'noedit-anon' => [ 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ],
2032 'noedit' => [ 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ],
2034 'code' => 'pagedeleted',
2035 'info' => 'The page has been deleted since you fetched its timestamp'
2038 'code' => 'emptypage',
2039 'info' => 'Creating new, empty pages is not allowed'
2041 'editconflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2042 'hashcheckfailed' => [ 'code' => 'badmd5', 'info' => 'The supplied MD5 hash was incorrect' ],
2045 'info' => 'One of the text, appendtext, prependtext and undo parameters must be set'
2047 'emptynewsection' => [
2048 'code' => 'emptynewsection',
2049 'info' => 'Creating empty new sections is not possible.'
2052 'code' => 'revwrongpage',
2053 'info' => "r\$1 is not a revision of \"\$2\""
2056 'code' => 'undofailure',
2057 'info' => 'Undo failed due to conflicting intermediate edits'
2059 'content-not-allowed-here' => [
2060 'code' => 'contentnotallowedhere',
2061 'info' => 'Content model "$1" is not allowed at title "$2"'
2064 // Messages from WikiPage::doEit(]
2065 'edit-hook-aborted' => [
2066 'code' => 'edit-hook-aborted',
2067 'info' => 'Your edit was aborted by an ArticleSave hook'
2069 'edit-gone-missing' => [
2070 'code' => 'edit-gone-missing',
2071 'info' => "The page you tried to edit doesn't seem to exist anymore"
2073 'edit-conflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2074 'edit-already-exists' => [
2075 'code' => 'edit-already-exists',
2076 'info' => 'It seems the page you tried to create already exist'
2080 'invalid-file-key' => [ 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ],
2081 'nouploadmodule' => [ 'code' => 'nouploadmodule', 'info' => 'No upload module set' ],
2082 'uploaddisabled' => [
2083 'code' => 'uploaddisabled',
2084 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2086 'copyuploaddisabled' => [
2087 'code' => 'copyuploaddisabled',
2088 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2090 'copyuploadbaddomain' => [
2091 'code' => 'copyuploadbaddomain',
2092 'info' => 'Uploads by URL are not allowed from this domain.'
2094 'copyuploadbadurl' => [
2095 'code' => 'copyuploadbadurl',
2096 'info' => 'Upload not allowed from this URL.'
2099 'filename-tooshort' => [
2100 'code' => 'filename-tooshort',
2101 'info' => 'The filename is too short'
2103 'filename-toolong' => [ 'code' => 'filename-toolong', 'info' => 'The filename is too long' ],
2104 'illegal-filename' => [
2105 'code' => 'illegal-filename',
2106 'info' => 'The filename is not allowed'
2108 'filetype-missing' => [
2109 'code' => 'filetype-missing',
2110 'info' => 'The file is missing an extension'
2113 'mustbeloggedin' => [ 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' ]
2115 // @codingStandardsIgnoreEnd
2118 * Helper function for readonly errors
2120 * @throws UsageException always
2122 public function dieReadOnly() {
2123 $parsed = $this->parseMsg( [ 'readonlytext' ] );
2124 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2125 [ 'readonlyreason' => wfReadOnlyReason() ] );
2129 * Output the error message related to a certain array
2130 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2131 * @throws UsageException always
2133 public function dieUsageMsg( $error ) {
2134 # most of the time we send a 1 element, so we might as well send it as
2135 # a string and make this an array here.
2136 if ( is_string( $error ) ) {
2137 $error = [ $error ];
2139 $parsed = $this->parseMsg( $error );
2140 $extraData = isset( $parsed['data'] ) ?
$parsed['data'] : null;
2141 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2145 * Will only set a warning instead of failing if the global $wgDebugAPI
2146 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2147 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2148 * @throws UsageException
2151 public function dieUsageMsgOrDebug( $error ) {
2152 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2153 $this->dieUsageMsg( $error );
2156 if ( is_string( $error ) ) {
2157 $error = [ $error ];
2159 $parsed = $this->parseMsg( $error );
2160 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2164 * Die with the $prefix.'badcontinue' error. This call is common enough to
2165 * make it into the base method.
2166 * @param bool $condition Will only die if this value is true
2167 * @throws UsageException
2170 protected function dieContinueUsageIf( $condition ) {
2173 'Invalid continue param. You should pass the original value returned by the previous query',
2179 * Return the error message related to a certain array
2180 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2181 * @return [ 'code' => code, 'info' => info ]
2183 public function parseMsg( $error ) {
2184 // Check whether someone passed the whole array, instead of one element as
2185 // documented. This breaks if it's actually an array of fallback keys, but
2186 // that's long-standing misbehavior introduced in r87627 to incorrectly
2188 if ( is_array( $error ) ) {
2189 $first = reset( $error );
2190 if ( is_array( $first ) ) {
2191 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2196 $msg = Message
::newFromSpecifier( $error );
2198 if ( $msg instanceof IApiMessage
) {
2200 'code' => $msg->getApiCode(),
2201 'info' => $msg->inLanguage( 'en' )->useDatabase( false )->text(),
2202 'data' => $msg->getApiData()
2206 $key = $msg->getKey();
2207 if ( isset( self
::$messageMap[$key] ) ) {
2208 $params = $msg->getParams();
2210 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $params ),
2211 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $params )
2215 // If the key isn't present, throw an "unknown error"
2216 return $this->parseMsg( [ 'unknownerror', $key ] );
2220 * Internal code errors should be reported with this method
2221 * @param string $method Method or function name
2222 * @param string $message Error message
2223 * @throws MWException always
2225 protected static function dieDebug( $method, $message ) {
2226 throw new MWException( "Internal error in $method: $message" );
2230 * Write logging information for API features to a debug log, for usage
2232 * @param string $feature Feature being used.
2234 public function logFeatureUsage( $feature ) {
2235 $request = $this->getRequest();
2236 $s = '"' . addslashes( $feature ) . '"' .
2237 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2238 ' "' . $request->getIP() . '"' .
2239 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2240 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2241 wfDebugLog( 'api-feature-usage', $s, 'private' );
2246 /************************************************************************//**
2247 * @name Help message generation
2252 * Return the description message.
2254 * @return string|array|Message
2256 protected function getDescriptionMessage() {
2257 return "apihelp-{$this->getModulePath()}-description";
2261 * Get final module description, after hooks have had a chance to tweak it as
2264 * @since 1.25, returns Message[] rather than string[]
2267 public function getFinalDescription() {
2268 $desc = $this->getDescription();
2269 Hooks
::run( 'APIGetDescription', [ &$this, &$desc ] );
2270 $desc = self
::escapeWikiText( $desc );
2271 if ( is_array( $desc ) ) {
2272 $desc = implode( "\n", $desc );
2274 $desc = (string)$desc;
2277 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2278 $this->getModulePrefix(),
2279 $this->getModuleName(),
2280 $this->getModulePath(),
2282 if ( !$msg->exists() ) {
2283 $msg = $this->msg( 'api-help-fallback-description', $desc );
2287 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2293 * Get final list of parameters, after hooks have had a chance to
2294 * tweak it as needed.
2296 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2297 * @return array|bool False on no parameters
2298 * @since 1.21 $flags param added
2300 public function getFinalParams( $flags = 0 ) {
2301 $params = $this->getAllowedParams( $flags );
2306 if ( $this->needsToken() ) {
2307 $params['token'] = [
2308 ApiBase
::PARAM_TYPE
=> 'string',
2309 ApiBase
::PARAM_REQUIRED
=> true,
2310 ApiBase
::PARAM_HELP_MSG
=> [
2311 'api-help-param-token',
2312 $this->needsToken(),
2314 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2317 Hooks
::run( 'APIGetAllowedParams', [ &$this, &$params, $flags ] );
2323 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2326 * @since 1.25, returns array of Message[] rather than array of string[]
2327 * @return array Keys are parameter names, values are arrays of Message objects
2329 public function getFinalParamDescription() {
2330 $prefix = $this->getModulePrefix();
2331 $name = $this->getModuleName();
2332 $path = $this->getModulePath();
2334 $desc = $this->getParamDescription();
2335 Hooks
::run( 'APIGetParamDescription', [ &$this, &$desc ] );
2340 $desc = self
::escapeWikiText( $desc );
2342 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2344 foreach ( $params as $param => $settings ) {
2345 if ( !is_array( $settings ) ) {
2349 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2350 if ( is_array( $d ) ) {
2351 // Special handling for prop parameters
2352 $d = array_map( function ( $line ) {
2353 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2354 $line = "\n;{$m[1]}:{$m[2]}";
2358 $d = implode( ' ', $d );
2361 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2362 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2364 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2365 if ( !$msg->exists() ) {
2366 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2369 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2370 [ $prefix, $param, $name, $path ] );
2372 self
::dieDebug( __METHOD__
,
2373 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2375 $msgs[$param] = [ $msg ];
2377 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2378 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2379 self
::dieDebug( __METHOD__
,
2380 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2382 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2383 self
::dieDebug( __METHOD__
,
2384 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2385 'ApiBase::PARAM_TYPE is an array' );
2388 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2389 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2390 if ( isset( $valueMsgs[$value] ) ) {
2391 $msg = $valueMsgs[$value];
2393 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2395 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2396 [ $prefix, $param, $name, $path, $value ] );
2398 $m = new ApiHelpParamValueMessage(
2400 [ $m->getKey(), 'api-help-param-no-description' ],
2403 $msgs[$param][] = $m->setContext( $this->getContext() );
2405 self
::dieDebug( __METHOD__
,
2406 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2411 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2412 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2413 self
::dieDebug( __METHOD__
,
2414 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2416 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2417 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2418 [ $prefix, $param, $name, $path ] );
2420 $msgs[$param][] = $m;
2422 self
::dieDebug( __METHOD__
,
2423 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2429 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2435 * Generates the list of flags for the help screen and for action=paraminfo
2437 * Corresponding messages: api-help-flag-deprecated,
2438 * api-help-flag-internal, api-help-flag-readrights,
2439 * api-help-flag-writerights, api-help-flag-mustbeposted
2443 protected function getHelpFlags() {
2446 if ( $this->isDeprecated() ) {
2447 $flags[] = 'deprecated';
2449 if ( $this->isInternal() ) {
2450 $flags[] = 'internal';
2452 if ( $this->isReadMode() ) {
2453 $flags[] = 'readrights';
2455 if ( $this->isWriteMode() ) {
2456 $flags[] = 'writerights';
2458 if ( $this->mustBePosted() ) {
2459 $flags[] = 'mustbeposted';
2466 * Returns information about the source of this module, if known
2468 * Returned array is an array with the following keys:
2469 * - path: Install path
2470 * - name: Extension name, or "MediaWiki" for core
2471 * - namemsg: (optional) i18n message key for a display name
2472 * - license-name: (optional) Name of license
2474 * @return array|null
2476 protected function getModuleSourceInfo() {
2479 if ( $this->mModuleSource
!== false ) {
2480 return $this->mModuleSource
;
2483 // First, try to find where the module comes from...
2484 $rClass = new ReflectionClass( $this );
2485 $path = $rClass->getFileName();
2488 $this->mModuleSource
= null;
2491 $path = realpath( $path ) ?
: $path;
2493 // Build map of extension directories to extension info
2494 if ( self
::$extensionInfo === null ) {
2495 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2496 self
::$extensionInfo = [
2497 realpath( __DIR__
) ?
: __DIR__
=> [
2499 'name' => 'MediaWiki',
2500 'license-name' => 'GPL-2.0+',
2502 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2503 realpath( $extDir ) ?
: $extDir => null,
2509 'license-name' => null,
2511 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2512 foreach ( $group as $ext ) {
2513 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2514 // This shouldn't happen, but does anyway.
2518 $extpath = $ext['path'];
2519 if ( !is_dir( $extpath ) ) {
2520 $extpath = dirname( $extpath );
2522 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2523 array_intersect_key( $ext, $keep );
2526 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2527 $extpath = $ext['path'];
2528 if ( !is_dir( $extpath ) ) {
2529 $extpath = dirname( $extpath );
2531 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2532 array_intersect_key( $ext, $keep );
2536 // Now traverse parent directories until we find a match or run out of
2539 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2541 $this->mModuleSource
= self
::$extensionInfo[$path];
2542 return $this->mModuleSource
;
2546 $path = dirname( $path );
2547 } while ( $path !== $oldpath );
2549 // No idea what extension this might be.
2550 $this->mModuleSource
= null;
2555 * Called from ApiHelp before the pieces are joined together and returned.
2557 * This exists mainly for ApiMain to add the Permissions and Credits
2558 * sections. Other modules probably don't need it.
2560 * @param string[] &$help Array of help data
2561 * @param array $options Options passed to ApiHelp::getHelp
2562 * @param array &$tocData If a TOC is being generated, this array has keys
2563 * as anchors in the page and values as for Linker::generateTOC().
2565 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2570 /************************************************************************//**
2576 * Returns the description string for this module
2578 * Ignored if an i18n message exists for
2579 * "apihelp-{$this->getModulePath()}-description".
2581 * @deprecated since 1.25
2582 * @return Message|string|array
2584 protected function getDescription() {
2589 * Returns an array of parameter descriptions.
2591 * For each parameter, ignored if an i18n message exists for the parameter.
2592 * By default that message is
2593 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2594 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2595 * self::getFinalParams().
2597 * @deprecated since 1.25
2598 * @return array|bool False on no parameter descriptions
2600 protected function getParamDescription() {
2605 * Returns usage examples for this module.
2607 * Return value as an array is either:
2608 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2610 * - sequential numeric keys with even-numbered keys being display-text
2611 * and odd-numbered keys being partial urls
2612 * - partial URLs as keys with display-text (string or array-to-be-joined)
2614 * Return value as a string is the same as an array with a numeric key and
2615 * that value, and boolean false means "no examples".
2617 * @deprecated since 1.25, use getExamplesMessages() instead
2618 * @return bool|string|array
2620 protected function getExamples() {
2625 * Generates help message for this module, or false if there is no description
2626 * @deprecated since 1.25
2627 * @return string|bool
2629 public function makeHelpMsg() {
2630 wfDeprecated( __METHOD__
, '1.25' );
2631 static $lnPrfx = "\n ";
2633 $msg = $this->getFinalDescription();
2635 if ( $msg !== false ) {
2637 if ( !is_array( $msg ) ) {
2642 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2644 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2646 if ( $this->isReadMode() ) {
2647 $msg .= "\nThis module requires read rights";
2649 if ( $this->isWriteMode() ) {
2650 $msg .= "\nThis module requires write rights";
2652 if ( $this->mustBePosted() ) {
2653 $msg .= "\nThis module only accepts POST requests";
2655 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2656 $this->mustBePosted()
2662 $paramsMsg = $this->makeHelpMsgParameters();
2663 if ( $paramsMsg !== false ) {
2664 $msg .= "Parameters:\n$paramsMsg";
2667 $examples = $this->getExamples();
2669 if ( !is_array( $examples ) ) {
2674 $msg .= 'Example' . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2675 foreach ( $examples as $k => $v ) {
2676 if ( is_numeric( $k ) ) {
2679 if ( is_array( $v ) ) {
2680 $msgExample = implode( "\n", array_map( [ $this, 'indentExampleText' ], $v ) );
2682 $msgExample = " $v";
2685 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2695 * @deprecated since 1.25
2696 * @param string $item
2699 private function indentExampleText( $item ) {
2704 * @deprecated since 1.25
2705 * @param string $prefix Text to split output items
2706 * @param string $title What is being output
2707 * @param string|array $input
2710 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2711 wfDeprecated( __METHOD__
, '1.25' );
2712 if ( $input === false ) {
2715 if ( !is_array( $input ) ) {
2716 $input = [ $input ];
2719 if ( count( $input ) > 0 ) {
2721 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2725 $msg .= implode( $prefix, $input ) . "\n";
2734 * Generates the parameter descriptions for this module, to be displayed in the
2736 * @deprecated since 1.25
2737 * @return string|bool
2739 public function makeHelpMsgParameters() {
2740 wfDeprecated( __METHOD__
, '1.25' );
2741 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2743 $paramsDescription = $this->getFinalParamDescription();
2745 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2746 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2747 foreach ( $params as $paramName => $paramSettings ) {
2748 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2749 if ( is_array( $desc ) ) {
2750 $desc = implode( $paramPrefix, $desc );
2754 if ( !is_array( $paramSettings ) ) {
2756 self
::PARAM_DFLT
=> $paramSettings,
2760 // handle missing type
2761 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2762 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2763 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2765 if ( is_bool( $dflt ) ) {
2766 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2767 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2768 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2769 } elseif ( is_int( $dflt ) ) {
2770 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2774 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2775 && $paramSettings[self
::PARAM_DEPRECATED
]
2777 $desc = "DEPRECATED! $desc";
2780 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2781 && $paramSettings[self
::PARAM_REQUIRED
]
2783 $desc .= $paramPrefix . 'This parameter is required';
2786 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2787 ?
$paramSettings[self
::PARAM_TYPE
]
2789 if ( isset( $type ) ) {
2790 $hintPipeSeparated = true;
2791 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2792 ?
$paramSettings[self
::PARAM_ISMULTI
]
2795 $prompt = 'Values (separate with \'|\'): ';
2797 $prompt = 'One value: ';
2800 if ( $type === 'submodule' ) {
2801 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2802 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
2804 $type = $this->getModuleManager()->getNames( $paramName );
2808 if ( is_array( $type ) ) {
2810 $nothingPrompt = '';
2811 foreach ( $type as $t ) {
2813 $nothingPrompt = 'Can be empty, or ';
2818 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2819 $choicesstring = implode( ', ', $choices );
2820 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2821 $hintPipeSeparated = false;
2825 // Special handling because namespaces are
2826 // type-limited, yet they are not given
2827 $desc .= $paramPrefix . $prompt;
2828 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2829 100, $descWordwrap );
2830 $hintPipeSeparated = false;
2833 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2834 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2835 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2837 $desc .= ' allowed';
2840 $s = $multi ?
's' : '';
2841 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2842 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2843 if ( $hasMin ||
$hasMax ) {
2845 $intRangeStr = "The value$s must be no less than " .
2846 "{$paramSettings[self::PARAM_MIN]}";
2847 } elseif ( !$hasMin ) {
2848 $intRangeStr = "The value$s must be no more than " .
2849 "{$paramSettings[self::PARAM_MAX]}";
2851 $intRangeStr = "The value$s must be between " .
2852 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2855 $desc .= $paramPrefix . $intRangeStr;
2859 $desc .= $paramPrefix . 'Must be posted as a file upload using multipart/form-data';
2865 if ( $hintPipeSeparated ) {
2866 $desc .= $paramPrefix . "Separate values with '|'";
2869 $isArray = is_array( $type );
2871 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2873 $desc .= $paramPrefix . 'Maximum number of values ' .
2874 self
::LIMIT_SML1
. ' (' . self
::LIMIT_SML2
. ' for bots)';
2879 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2880 if ( !is_null( $default ) && $default !== false ) {
2881 $desc .= $paramPrefix . "Default: $default";
2884 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2894 * @deprecated since 1.25, always returns empty string
2895 * @param IDatabase|bool $db
2898 public function getModuleProfileName( $db = false ) {
2899 wfDeprecated( __METHOD__
, '1.25' );
2904 * @deprecated since 1.25
2906 public function profileIn() {
2907 // No wfDeprecated() yet because extensions call this and might need to
2908 // keep doing so for BC.
2912 * @deprecated since 1.25
2914 public function profileOut() {
2915 // No wfDeprecated() yet because extensions call this and might need to
2916 // keep doing so for BC.
2920 * @deprecated since 1.25
2922 public function safeProfileOut() {
2923 wfDeprecated( __METHOD__
, '1.25' );
2927 * @deprecated since 1.25, always returns 0
2930 public function getProfileTime() {
2931 wfDeprecated( __METHOD__
, '1.25' );
2936 * @deprecated since 1.25
2938 public function profileDBIn() {
2939 wfDeprecated( __METHOD__
, '1.25' );
2943 * @deprecated since 1.25
2945 public function profileDBOut() {
2946 wfDeprecated( __METHOD__
, '1.25' );
2950 * @deprecated since 1.25, always returns 0
2953 public function getProfileDBTime() {
2954 wfDeprecated( __METHOD__
, '1.25' );
2959 * Get the result data array (read-only)
2960 * @deprecated since 1.25, use $this->getResult() methods instead
2963 public function getResultData() {
2964 wfDeprecated( __METHOD__
, '1.25' );
2965 return $this->getResult()->getData();
2969 * Call wfTransactionalTimeLimit() if this request was POSTed
2972 protected function useTransactionalTimeLimit() {
2973 if ( $this->getRequest()->wasPosted() ) {
2974 wfTransactionalTimeLimit();
2982 * For really cool vim folding this needs to be at the end:
2983 * vim: foldmarker=@{,@} foldmethod=marker