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. Forces PARAM_ALL = true to
71 * support easily specifying all namespaces.
73 * - password: Any non-empty string. Input value is private or sensitive.
74 * <input type="password"> would be an appropriate HTML form field.
75 * - string: Any non-empty string, not expected to be very long or contain newlines.
76 * <input type="text"> would be an appropriate HTML form field.
77 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
78 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
79 * used with PARAM_ISMULTI.
80 * - text: Any non-empty string, expected to be very long or contain newlines.
81 * <textarea> would be an appropriate HTML form field.
82 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
83 * string 'now' representing the current timestamp. Will be returned in
85 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
86 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
87 * Cannot be used with PARAM_ISMULTI.
91 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
95 * (integer) Max value allowed for the parameter for users with the
96 * apihighlimits right, for PARAM_TYPE 'limit'.
100 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
103 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
104 const PARAM_ALLOW_DUPLICATES
= 6;
106 /** (boolean) Is the parameter deprecated (will show a warning)? */
107 const PARAM_DEPRECATED
= 7;
110 * (boolean) Is the parameter required?
113 const PARAM_REQUIRED
= 8;
116 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
119 const PARAM_RANGE_ENFORCE
= 9;
122 * (string|array|Message) Specify an alternative i18n documentation message
123 * for this parameter. Default is apihelp-{$path}-param-{$param}.
126 const PARAM_HELP_MSG
= 10;
129 * ((string|array|Message)[]) Specify additional i18n messages to append to
130 * the normal message for this parameter.
133 const PARAM_HELP_MSG_APPEND
= 11;
136 * (array) Specify additional information tags for the parameter. Value is
137 * an array of arrays, with the first member being the 'tag' for the info
138 * and the remaining members being the values. In the help, this is
139 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
140 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
143 const PARAM_HELP_MSG_INFO
= 12;
146 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
147 * those values to page titles which will be linked in the help.
150 const PARAM_VALUE_LINKS
= 13;
153 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
154 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
155 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
158 const PARAM_HELP_MSG_PER_VALUE
= 14;
161 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
162 * submodule paths. Default is to use all modules in
163 * $this->getModuleManager() in the group matching the parameter name.
166 const PARAM_SUBMODULE_MAP
= 15;
169 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
170 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
173 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
176 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
177 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
178 * every possible value. If a string is set, it will be used in place of the asterisk.
181 const PARAM_ALL
= 17;
185 const ALL_DEFAULT_STRING
= '*';
187 /** Fast query, standard limit. */
188 const LIMIT_BIG1
= 500;
189 /** Fast query, apihighlimits limit. */
190 const LIMIT_BIG2
= 5000;
191 /** Slow query, standard limit. */
192 const LIMIT_SML1
= 50;
193 /** Slow query, apihighlimits limit. */
194 const LIMIT_SML2
= 500;
197 * getAllowedParams() flag: When set, the result could take longer to generate,
198 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
201 const GET_VALUES_FOR_HELP
= 1;
203 /** @var array Maps extension paths to info arrays */
204 private static $extensionInfo = null;
207 private $mMainModule;
209 private $mModuleName, $mModulePrefix;
210 private $mSlaveDB = null;
211 private $mParamCache = [];
212 /** @var array|null|bool */
213 private $mModuleSource = false;
216 * @param ApiMain $mainModule
217 * @param string $moduleName Name of this module
218 * @param string $modulePrefix Prefix to use for parameter names
220 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
221 $this->mMainModule
= $mainModule;
222 $this->mModuleName
= $moduleName;
223 $this->mModulePrefix
= $modulePrefix;
225 if ( !$this->isMain() ) {
226 $this->setContext( $mainModule->getContext() );
230 /************************************************************************//**
231 * @name Methods to implement
236 * Evaluates the parameters, performs the requested query, and sets up
237 * the result. Concrete implementations of ApiBase must override this
238 * method to provide whatever functionality their module offers.
239 * Implementations must not produce any output on their own and are not
240 * expected to handle any errors.
242 * The execute() method will be invoked directly by ApiMain immediately
243 * before the result of the module is output. Aside from the
244 * constructor, implementations should assume that no other methods
245 * will be called externally on the module before the result is
248 * The result data should be stored in the ApiResult object available
249 * through getResult().
251 abstract public function execute();
254 * Get the module manager, or null if this module has no sub-modules
256 * @return ApiModuleManager
258 public function getModuleManager() {
263 * If the module may only be used with a certain format module,
264 * it should override this method to return an instance of that formatter.
265 * A value of null means the default format will be used.
266 * @note Do not use this just because you don't want to support non-json
267 * formats. This should be used only when there is a fundamental
268 * requirement for a specific format.
269 * @return mixed Instance of a derived class of ApiFormatBase, or null
271 public function getCustomPrinter() {
276 * Returns usage examples for this module.
278 * Return value has query strings as keys, with values being either strings
279 * (message key), arrays (message key + parameter), or Message objects.
281 * Do not call this base class implementation when overriding this method.
286 protected function getExamplesMessages() {
287 // Fall back to old non-localised method
290 $examples = $this->getExamples();
292 if ( !is_array( $examples ) ) {
293 $examples = [ $examples ];
294 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
295 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
296 !preg_match( '/^\s*api\.php\?/', $examples[0] )
298 // Fix up the ugly "even numbered elements are description, odd
299 // numbered elemts are the link" format (see doc for self::getExamples)
301 $examplesCount = count( $examples );
302 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
303 $tmp[$examples[$i +
1]] = $examples[$i];
308 foreach ( $examples as $k => $v ) {
309 if ( is_numeric( $k ) ) {
314 $msg = self
::escapeWikiText( $v );
315 if ( is_array( $msg ) ) {
316 $msg = implode( ' ', $msg );
320 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
321 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
329 * Return links to more detailed help pages about the module.
330 * @since 1.25, returning boolean false is deprecated
331 * @return string|array
333 public function getHelpUrls() {
338 * Returns an array of allowed parameters (parameter name) => (default
339 * value) or (parameter name) => (array with PARAM_* constants as keys)
340 * Don't call this function directly: use getFinalParams() to allow
341 * hooks to modify parameters as needed.
343 * Some derived classes may choose to handle an integer $flags parameter
344 * in the overriding methods. Callers of this method can pass zero or
345 * more OR-ed flags like GET_VALUES_FOR_HELP.
349 protected function getAllowedParams( /* $flags = 0 */ ) {
350 // int $flags is not declared because it causes "Strict standards"
351 // warning. Most derived classes do not implement it.
356 * Indicates if this module needs maxlag to be checked
359 public function shouldCheckMaxlag() {
364 * Indicates whether this module requires read rights
367 public function isReadMode() {
372 * Indicates whether this module requires write mode
375 public function isWriteMode() {
380 * Indicates whether this module must be called with a POST request
383 public function mustBePosted() {
384 return $this->needsToken() !== false;
388 * Indicates whether this module is deprecated
392 public function isDeprecated() {
397 * Indicates whether this module is "internal"
398 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
402 public function isInternal() {
407 * Returns the token type this module requires in order to execute.
409 * Modules are strongly encouraged to use the core 'csrf' type unless they
410 * have specialized security needs. If the token type is not one of the
411 * core types, you must use the ApiQueryTokensRegisterTypes hook to
414 * Returning a non-falsey value here will force the addition of an
415 * appropriate 'token' parameter in self::getFinalParams(). Also,
416 * self::mustBePosted() must return true when tokens are used.
418 * In previous versions of MediaWiki, true was a valid return value.
419 * Returning true will generate errors indicating that the API module needs
422 * @return string|false
424 public function needsToken() {
429 * Fetch the salt used in the Web UI corresponding to this module.
431 * Only override this if the Web UI uses a token with a non-constant salt.
434 * @param array $params All supplied parameters for the module
435 * @return string|array|null
437 protected function getWebUITokenSalt( array $params ) {
442 * Returns data for HTTP conditional request mechanisms.
445 * @param string $condition Condition being queried:
446 * - last-modified: Return a timestamp representing the maximum of the
447 * last-modified dates for all resources involved in the request. See
448 * RFC 7232 § 2.2 for semantics.
449 * - etag: Return an entity-tag representing the state of all resources involved
450 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
451 * @return string|bool|null As described above, or null if no value is available.
453 public function getConditionalRequestData( $condition ) {
459 /************************************************************************//**
460 * @name Data access methods
465 * Get the name of the module being executed by this instance
468 public function getModuleName() {
469 return $this->mModuleName
;
473 * Get parameter prefix (usually two letters or an empty string).
476 public function getModulePrefix() {
477 return $this->mModulePrefix
;
481 * Get the main module
484 public function getMain() {
485 return $this->mMainModule
;
489 * Returns true if this module is the main module ($this === $this->mMainModule),
493 public function isMain() {
494 return $this === $this->mMainModule
;
498 * Get the parent of this module
500 * @return ApiBase|null
502 public function getParent() {
503 return $this->isMain() ?
null : $this->getMain();
507 * Returns true if the current request breaks the same-origin policy.
509 * For example, json with callbacks.
511 * https://en.wikipedia.org/wiki/Same-origin_policy
516 public function lacksSameOriginSecurity() {
517 // Main module has this method overridden
518 // Safety - avoid infinite loop:
519 if ( $this->isMain() ) {
520 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
523 return $this->getMain()->lacksSameOriginSecurity();
527 * Get the path to this module
532 public function getModulePath() {
533 if ( $this->isMain() ) {
535 } elseif ( $this->getParent()->isMain() ) {
536 return $this->getModuleName();
538 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
543 * Get a module from its module path
546 * @param string $path
547 * @return ApiBase|null
548 * @throws UsageException
550 public function getModuleFromPath( $path ) {
551 $module = $this->getMain();
552 if ( $path === 'main' ) {
556 $parts = explode( '+', $path );
557 if ( count( $parts ) === 1 ) {
558 // In case the '+' was typed into URL, it resolves as a space
559 $parts = explode( ' ', $path );
562 $count = count( $parts );
563 for ( $i = 0; $i < $count; $i++
) {
565 $manager = $parent->getModuleManager();
566 if ( $manager === null ) {
567 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
568 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
570 $module = $manager->getModule( $parts[$i] );
572 if ( $module === null ) {
573 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
575 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
585 * Get the result object
588 public function getResult() {
589 // Main module has getResult() method overridden
590 // Safety - avoid infinite loop:
591 if ( $this->isMain() ) {
592 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
595 return $this->getMain()->getResult();
599 * Get the error formatter
600 * @return ApiErrorFormatter
602 public function getErrorFormatter() {
603 // Main module has getErrorFormatter() method overridden
604 // Safety - avoid infinite loop:
605 if ( $this->isMain() ) {
606 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
609 return $this->getMain()->getErrorFormatter();
613 * Gets a default replica DB connection object
616 protected function getDB() {
617 if ( !isset( $this->mSlaveDB
) ) {
618 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
621 return $this->mSlaveDB
;
625 * Get the continuation manager
626 * @return ApiContinuationManager|null
628 public function getContinuationManager() {
629 // Main module has getContinuationManager() method overridden
630 // Safety - avoid infinite loop:
631 if ( $this->isMain() ) {
632 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
635 return $this->getMain()->getContinuationManager();
639 * Set the continuation manager
640 * @param ApiContinuationManager|null
642 public function setContinuationManager( $manager ) {
643 // Main module has setContinuationManager() method overridden
644 // Safety - avoid infinite loop:
645 if ( $this->isMain() ) {
646 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
649 $this->getMain()->setContinuationManager( $manager );
654 /************************************************************************//**
655 * @name Parameter handling
660 * Indicate if the module supports dynamically-determined parameters that
661 * cannot be included in self::getAllowedParams().
662 * @return string|array|Message|null Return null if the module does not
663 * support additional dynamic parameters, otherwise return a message
666 public function dynamicParameterDocumentation() {
671 * This method mangles parameter name based on the prefix supplied to the constructor.
672 * Override this method to change parameter name during runtime
673 * @param string $paramName Parameter name
674 * @return string Prefixed parameter name
676 public function encodeParamName( $paramName ) {
677 return $this->mModulePrefix
. $paramName;
681 * Using getAllowedParams(), this function makes an array of the values
682 * provided by the user, with key being the name of the variable, and
683 * value - validated value from user or default. limits will not be
684 * parsed if $parseLimit is set to false; use this when the max
685 * limit is not definitive yet, e.g. when getting revisions.
686 * @param bool $parseLimit True by default
689 public function extractRequestParams( $parseLimit = true ) {
690 // Cache parameters, for performance and to avoid bug 24564.
691 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
692 $params = $this->getFinalParams();
695 if ( $params ) { // getFinalParams() can return false
696 foreach ( $params as $paramName => $paramSettings ) {
697 $results[$paramName] = $this->getParameterFromSettings(
698 $paramName, $paramSettings, $parseLimit );
701 $this->mParamCache
[$parseLimit] = $results;
704 return $this->mParamCache
[$parseLimit];
708 * Get a value for the given parameter
709 * @param string $paramName Parameter name
710 * @param bool $parseLimit See extractRequestParams()
711 * @return mixed Parameter value
713 protected function getParameter( $paramName, $parseLimit = true ) {
714 $paramSettings = $this->getFinalParams()[$paramName];
716 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
720 * Die if none or more than one of a certain set of parameters is set and not false.
722 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
723 * @param string $required,... Names of parameters of which exactly one must be set
725 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
726 $required = func_get_args();
727 array_shift( $required );
728 $p = $this->getModulePrefix();
730 $intersection = array_intersect( array_keys( array_filter( $params,
731 [ $this, 'parameterNotEmpty' ] ) ), $required );
733 if ( count( $intersection ) > 1 ) {
735 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
737 } elseif ( count( $intersection ) == 0 ) {
739 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
746 * Die if more than one of a certain set of parameters is set and not false.
748 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
749 * @param string $required,... Names of parameters of which at most one must be set
751 public function requireMaxOneParameter( $params, $required /*...*/ ) {
752 $required = func_get_args();
753 array_shift( $required );
754 $p = $this->getModulePrefix();
756 $intersection = array_intersect( array_keys( array_filter( $params,
757 [ $this, 'parameterNotEmpty' ] ) ), $required );
759 if ( count( $intersection ) > 1 ) {
761 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
768 * Die if none of a certain set of parameters is set and not false.
771 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
772 * @param string $required,... Names of parameters of which at least one must be set
774 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
775 $required = func_get_args();
776 array_shift( $required );
777 $p = $this->getModulePrefix();
779 $intersection = array_intersect(
780 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
784 if ( count( $intersection ) == 0 ) {
785 $this->dieUsage( "At least one of the parameters {$p}" .
786 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
791 * Die if any of the specified parameters were found in the query part of
792 * the URL rather than the post body.
794 * @param string[] $params Parameters to check
795 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
797 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
798 // Skip if $wgDebugAPI is set or we're in internal mode
799 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
803 $queryValues = $this->getRequest()->getQueryValues();
805 foreach ( $params as $param ) {
806 if ( $prefix !== 'noprefix' ) {
807 $param = $this->encodeParamName( $param );
809 if ( array_key_exists( $param, $queryValues ) ) {
810 $badParams[] = $param;
816 'The following parameters were found in the query string, but must be in the POST body: '
817 . join( ', ', $badParams ),
824 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
826 * @param object $x Parameter to check is not null/false
829 private function parameterNotEmpty( $x ) {
830 return !is_null( $x ) && $x !== false;
834 * Get a WikiPage object from a title or pageid param, if possible.
835 * Can die, if no param is set or if the title or page id is not valid.
837 * @param array $params
838 * @param bool|string $load Whether load the object's state from the database:
839 * - false: don't load (if the pageid is given, it will still be loaded)
840 * - 'fromdb': load from a replica DB
841 * - 'fromdbmaster': load from the master database
844 public function getTitleOrPageId( $params, $load = false ) {
845 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
848 if ( isset( $params['title'] ) ) {
849 $titleObj = Title
::newFromText( $params['title'] );
850 if ( !$titleObj ||
$titleObj->isExternal() ) {
851 $this->dieUsageMsg( [ 'invalidtitle', $params['title'] ] );
853 if ( !$titleObj->canExist() ) {
854 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
856 $pageObj = WikiPage
::factory( $titleObj );
857 if ( $load !== false ) {
858 $pageObj->loadPageData( $load );
860 } elseif ( isset( $params['pageid'] ) ) {
861 if ( $load === false ) {
864 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
866 $this->dieUsageMsg( [ 'nosuchpageid', $params['pageid'] ] );
874 * Return true if we're to watch the page, false if not, null if no change.
875 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
876 * @param Title $titleObj The page under consideration
877 * @param string $userOption The user option to consider when $watchlist=preferences.
878 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
881 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
883 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
885 switch ( $watchlist ) {
893 # If the user is already watching, don't bother checking
894 if ( $userWatching ) {
897 # If no user option was passed, use watchdefault and watchcreations
898 if ( is_null( $userOption ) ) {
899 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
900 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
903 # Watch the article based on the user preference
904 return $this->getUser()->getBoolOption( $userOption );
907 return $userWatching;
910 return $userWatching;
915 * Using the settings determine the value for the given parameter
917 * @param string $paramName Parameter name
918 * @param array|mixed $paramSettings Default value or an array of settings
919 * using PARAM_* constants.
920 * @param bool $parseLimit Parse limit?
921 * @return mixed Parameter value
923 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
924 // Some classes may decide to change parameter names
925 $encParamName = $this->encodeParamName( $paramName );
927 if ( !is_array( $paramSettings ) ) {
928 $default = $paramSettings;
930 $type = gettype( $paramSettings );
936 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
937 ?
$paramSettings[self
::PARAM_DFLT
]
939 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
940 ?
$paramSettings[self
::PARAM_ISMULTI
]
942 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
943 ?
$paramSettings[self
::PARAM_TYPE
]
945 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
946 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
948 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
949 ?
$paramSettings[self
::PARAM_DEPRECATED
]
951 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
952 ?
$paramSettings[self
::PARAM_REQUIRED
]
954 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
955 ?
$paramSettings[self
::PARAM_ALL
]
958 // When type is not given, and no choices, the type is the same as $default
959 if ( !isset( $type ) ) {
960 if ( isset( $default ) ) {
961 $type = gettype( $default );
963 $type = 'NULL'; // allow everything
968 if ( $type == 'boolean' ) {
969 if ( isset( $default ) && $default !== false ) {
970 // Having a default value of anything other than 'false' is not allowed
973 "Boolean param $encParamName's default is set to '$default'. " .
974 'Boolean parameters must default to false.'
978 $value = $this->getMain()->getCheck( $encParamName );
979 } elseif ( $type == 'upload' ) {
980 if ( isset( $default ) ) {
981 // Having a default value is not allowed
984 "File upload param $encParamName's default is set to " .
985 "'$default'. File upload parameters may not have a default." );
988 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
990 $value = $this->getMain()->getUpload( $encParamName );
991 if ( !$value->exists() ) {
992 // This will get the value without trying to normalize it
993 // (because trying to normalize a large binary file
994 // accidentally uploaded as a field fails spectacularly)
995 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
996 if ( $value !== null ) {
998 "File upload param $encParamName is not a file upload; " .
999 'be sure to use multipart/form-data for your POST and include ' .
1000 'a filename in the Content-Disposition header.',
1001 "badupload_{$encParamName}"
1006 $value = $this->getMain()->getVal( $encParamName, $default );
1008 if ( isset( $value ) && $type == 'namespace' ) {
1009 $type = MWNamespace
::getValidNamespaces();
1010 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1014 if ( isset( $value ) && $type == 'submodule' ) {
1015 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1016 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1018 $type = $this->getModuleManager()->getNames( $paramName );
1022 $request = $this->getMain()->getRequest();
1023 $rawValue = $request->getRawVal( $encParamName );
1024 if ( $rawValue === null ) {
1025 $rawValue = $default;
1028 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1029 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1031 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1032 // done by WebRequest for $_GET. Let's call that a feature.
1033 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1036 "U+001F multi-value separation may only be used for multi-valued parameters.",
1037 'badvalue_notmultivalue'
1042 // Check for NFC normalization, and warn
1043 if ( $rawValue !== $value ) {
1044 $this->handleParamNormalization( $paramName, $value, $rawValue );
1048 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1049 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1052 "For param $encParamName, PARAM_ALL collides with a possible value" );
1054 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1055 $value = $this->parseMultiValue(
1059 is_array( $type ) ?
$type : null,
1060 $allowAll ?
$allSpecifier : null
1064 // More validation only when choices were not given
1065 // choices were validated in parseMultiValue()
1066 if ( isset( $value ) ) {
1067 if ( !is_array( $type ) ) {
1069 case 'NULL': // nothing to do
1074 if ( $required && $value === '' ) {
1075 $this->dieUsageMsg( [ 'missingparam', $paramName ] );
1078 case 'integer': // Force everything using intval() and optionally validate limits
1079 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1080 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1081 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1082 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1084 if ( is_array( $value ) ) {
1085 $value = array_map( 'intval', $value );
1086 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1087 foreach ( $value as &$v ) {
1088 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1092 $value = intval( $value );
1093 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1094 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1099 if ( !$parseLimit ) {
1100 // Don't do any validation whatsoever
1103 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1104 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1108 "MAX1 or MAX2 are not defined for the limit $encParamName"
1112 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1114 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1115 if ( $value == 'max' ) {
1116 $value = $this->getMain()->canApiHighLimits()
1117 ?
$paramSettings[self
::PARAM_MAX2
]
1118 : $paramSettings[self
::PARAM_MAX
];
1119 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1121 $value = intval( $value );
1122 $this->validateLimit(
1126 $paramSettings[self
::PARAM_MAX
],
1127 $paramSettings[self
::PARAM_MAX2
]
1133 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1137 if ( is_array( $value ) ) {
1138 foreach ( $value as $key => $val ) {
1139 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1142 $value = $this->validateTimestamp( $value, $encParamName );
1146 if ( is_array( $value ) ) {
1147 foreach ( $value as $key => $val ) {
1148 $value[$key] = $this->validateUser( $val, $encParamName );
1151 $value = $this->validateUser( $value, $encParamName );
1154 case 'upload': // nothing to do
1157 // If change tagging was requested, check that the tags are valid.
1158 if ( !is_array( $value ) && !$multi ) {
1159 $value = [ $value ];
1161 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1162 if ( !$tagsStatus->isGood() ) {
1163 $this->dieStatus( $tagsStatus );
1167 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1171 // Throw out duplicates if requested
1172 if ( !$dupes && is_array( $value ) ) {
1173 $value = array_unique( $value );
1176 // Set a warning if a deprecated parameter has been passed
1177 if ( $deprecated && $value !== false ) {
1178 $this->setWarning( "The $encParamName parameter has been deprecated." );
1180 $feature = $encParamName;
1182 while ( !$m->isMain() ) {
1183 $p = $m->getParent();
1184 $name = $m->getModuleName();
1185 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1186 $feature = "{$param}={$name}&{$feature}";
1189 $this->logFeatureUsage( $feature );
1191 } elseif ( $required ) {
1192 $this->dieUsageMsg( [ 'missingparam', $paramName ] );
1199 * Handle when a parameter was Unicode-normalized
1201 * @param string $paramName Unprefixed parameter name
1202 * @param string $value Input that will be used.
1203 * @param string $rawValue Input before normalization.
1205 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1206 $encParamName = $this->encodeParamName( $paramName );
1208 "The value passed for '$encParamName' contains invalid or non-normalized data. "
1209 . 'Textual data should be valid, NFC-normalized Unicode without '
1210 . 'C0 control characters other than HT (\\t), LF (\\n), and CR (\\r).'
1215 * Split a multi-valued parameter string, like explode()
1217 * @param string $value
1221 protected function explodeMultiValue( $value, $limit ) {
1222 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1224 $value = substr( $value, 1 );
1229 return explode( $sep, $value, $limit );
1233 * Return an array of values that were given in a 'a|b|c' notation,
1234 * after it optionally validates them against the list allowed values.
1236 * @param string $valueName The name of the parameter (for error
1238 * @param mixed $value The value being parsed
1239 * @param bool $allowMultiple Can $value contain more than one value
1241 * @param string[]|null $allowedValues An array of values to check against. If
1242 * null, all values are accepted.
1243 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1244 * if this behavior should not be allowed
1245 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1247 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1248 $allSpecifier = null
1250 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1254 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1255 // because it unstubs $wgUser
1256 $valuesList = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1257 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1261 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1262 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1264 return $allowedValues;
1267 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1268 $this->logFeatureUsage( "too-many-$valueName-for-{$this->getModulePath()}" );
1269 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1270 "the limit is $sizeLimit" );
1273 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1274 // Bug 33482 - Allow entries with | in them for non-multiple values
1275 if ( in_array( $value, $allowedValues, true ) ) {
1279 $possibleValues = is_array( $allowedValues )
1280 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1283 "Only one $possibleValues is allowed for parameter '$valueName'",
1284 "multival_$valueName"
1288 if ( is_array( $allowedValues ) ) {
1289 // Check for unknown values
1290 $unknown = array_diff( $valuesList, $allowedValues );
1291 if ( count( $unknown ) ) {
1292 if ( $allowMultiple ) {
1293 $s = count( $unknown ) > 1 ?
's' : '';
1294 $vals = implode( ', ', $unknown );
1295 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1298 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1299 "unknown_$valueName"
1303 // Now throw them out
1304 $valuesList = array_intersect( $valuesList, $allowedValues );
1307 return $allowMultiple ?
$valuesList : $valuesList[0];
1311 * Validate the value against the minimum and user/bot maximum limits.
1312 * Prints usage info on failure.
1313 * @param string $paramName Parameter name
1314 * @param int $value Parameter value
1315 * @param int|null $min Minimum value
1316 * @param int|null $max Maximum value for users
1317 * @param int $botMax Maximum value for sysops/bots
1318 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1320 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1321 $enforceLimits = false
1323 if ( !is_null( $min ) && $value < $min ) {
1324 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1325 $this->warnOrDie( $msg, $enforceLimits );
1329 // Minimum is always validated, whereas maximum is checked only if not
1330 // running in internal call mode
1331 if ( $this->getMain()->isInternalMode() ) {
1335 // Optimization: do not check user's bot status unless really needed -- skips db query
1336 // assumes $botMax >= $max
1337 if ( !is_null( $max ) && $value > $max ) {
1338 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1339 if ( $value > $botMax ) {
1340 $msg = $this->encodeParamName( $paramName ) .
1341 " may not be over $botMax (set to $value) for bots or sysops";
1342 $this->warnOrDie( $msg, $enforceLimits );
1346 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1347 $this->warnOrDie( $msg, $enforceLimits );
1354 * Validate and normalize of parameters of type 'timestamp'
1355 * @param string $value Parameter value
1356 * @param string $encParamName Parameter name
1357 * @return string Validated and normalized parameter
1359 protected function validateTimestamp( $value, $encParamName ) {
1360 // Confusing synonyms for the current time accepted by wfTimestamp()
1361 // (wfTimestamp() also accepts various non-strings and the string of 14
1362 // ASCII NUL bytes, but those can't get here)
1364 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1366 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1367 ' If for some reason you need to explicitly specify the current time without' .
1368 ' calculating it client-side, use "now".'
1370 return wfTimestamp( TS_MW
);
1373 // Explicit synonym for the current time
1374 if ( $value === 'now' ) {
1375 return wfTimestamp( TS_MW
);
1378 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1379 if ( $unixTimestamp === false ) {
1381 "Invalid value '$value' for timestamp parameter $encParamName",
1382 "badtimestamp_{$encParamName}"
1386 return wfTimestamp( TS_MW
, $unixTimestamp );
1390 * Validate the supplied token.
1393 * @param string $token Supplied token
1394 * @param array $params All supplied parameters for the module
1396 * @throws MWException
1398 final public function validateToken( $token, array $params ) {
1399 $tokenType = $this->needsToken();
1400 $salts = ApiQueryTokens
::getTokenTypeSalts();
1401 if ( !isset( $salts[$tokenType] ) ) {
1402 throw new MWException(
1403 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1404 'without registering it'
1408 $tokenObj = ApiQueryTokens
::getToken(
1409 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1411 if ( $tokenObj->match( $token ) ) {
1415 $webUiSalt = $this->getWebUITokenSalt( $params );
1416 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1428 * Validate and normalize of parameters of type 'user'
1429 * @param string $value Parameter value
1430 * @param string $encParamName Parameter name
1431 * @return string Validated and normalized parameter
1433 private function validateUser( $value, $encParamName ) {
1434 $title = Title
::makeTitleSafe( NS_USER
, $value );
1435 if ( $title === null ||
$title->hasFragment() ) {
1437 "Invalid value '$value' for user parameter $encParamName",
1438 "baduser_{$encParamName}"
1442 return $title->getText();
1447 /************************************************************************//**
1448 * @name Utility methods
1453 * Set a watch (or unwatch) based the based on a watchlist parameter.
1454 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1455 * @param Title $titleObj The article's title to change
1456 * @param string $userOption The user option to consider when $watch=preferences
1458 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1459 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1460 if ( $value === null ) {
1464 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1468 * Truncate an array to a certain length.
1469 * @param array $arr Array to truncate
1470 * @param int $limit Maximum length
1471 * @return bool True if the array was truncated, false otherwise
1473 public static function truncateArray( &$arr, $limit ) {
1475 while ( count( $arr ) > $limit ) {
1484 * Gets the user for whom to get the watchlist
1486 * @param array $params
1489 public function getWatchlistUser( $params ) {
1490 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1491 $user = User
::newFromName( $params['owner'], false );
1492 if ( !( $user && $user->getId() ) ) {
1493 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1495 $token = $user->getOption( 'watchlisttoken' );
1496 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1498 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1503 if ( !$this->getUser()->isLoggedIn() ) {
1504 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1506 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1507 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1509 $user = $this->getUser();
1516 * A subset of wfEscapeWikiText for BC texts
1519 * @param string|array $v
1520 * @return string|array
1522 private static function escapeWikiText( $v ) {
1523 if ( is_array( $v ) ) {
1524 return array_map( 'self::escapeWikiText', $v );
1527 '__' => '__', '{' => '{', '}' => '}',
1528 '[[Category:' => '[[:Category:',
1529 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1535 * Create a Message from a string or array
1537 * A string is used as a message key. An array has the message key as the
1538 * first value and message parameters as subsequent values.
1541 * @param string|array|Message $msg
1542 * @param IContextSource $context
1543 * @param array $params
1544 * @return Message|null
1546 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1547 if ( is_string( $msg ) ) {
1548 $msg = wfMessage( $msg );
1549 } elseif ( is_array( $msg ) ) {
1550 $msg = call_user_func_array( 'wfMessage', $msg );
1552 if ( !$msg instanceof Message
) {
1556 $msg->setContext( $context );
1558 $msg->params( $params );
1566 /************************************************************************//**
1567 * @name Warning and error reporting
1572 * Set warning section for this module. Users should monitor this
1573 * section to notice any changes in API. Multiple calls to this
1574 * function will result in the warning messages being separated by
1576 * @param string $warning Warning message
1578 public function setWarning( $warning ) {
1579 $msg = new ApiRawMessage( $warning, 'warning' );
1580 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1584 * Adds a warning to the output, else dies
1586 * @param string $msg Message to show as a warning, or error message if dying
1587 * @param bool $enforceLimits Whether this is an enforce (die)
1589 private function warnOrDie( $msg, $enforceLimits = false ) {
1590 if ( $enforceLimits ) {
1591 $this->dieUsage( $msg, 'integeroutofrange' );
1594 $this->setWarning( $msg );
1598 * Throw a UsageException, which will (if uncaught) call the main module's
1599 * error handler and die with an error message.
1601 * @param string $description One-line human-readable description of the
1602 * error condition, e.g., "The API requires a valid action parameter"
1603 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1604 * automated identification of the error, e.g., 'unknown_action'
1605 * @param int $httpRespCode HTTP response code
1606 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
1607 * @throws UsageException always
1609 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1610 throw new UsageException(
1612 $this->encodeParamName( $errorCode ),
1619 * Throw a UsageException, which will (if uncaught) call the main module's
1620 * error handler and die with an error message including block info.
1623 * @param Block $block The block used to generate the UsageException
1624 * @throws UsageException always
1626 public function dieBlocked( Block
$block ) {
1627 // Die using the appropriate message depending on block type
1628 if ( $block->getType() == Block
::TYPE_AUTO
) {
1630 'Your IP address has been blocked automatically, because it was used by a blocked user',
1633 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1637 'You have been blocked from editing',
1640 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1646 * Get error (as code, string) from a Status object.
1649 * @param Status $status
1650 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
1651 * @return array Array of code and error string
1652 * @throws MWException
1654 public function getErrorFromStatus( $status, &$extraData = null ) {
1655 if ( $status->isGood() ) {
1656 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1659 $errors = $status->getErrorsByType( 'error' );
1661 // No errors? Assume the warnings should be treated as errors
1662 $errors = $status->getErrorsByType( 'warning' );
1665 // Still no errors? Punt
1666 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
1669 // Cannot use dieUsageMsg() because extensions might return custom
1671 if ( $errors[0]['message'] instanceof Message
) {
1672 $msg = $errors[0]['message'];
1673 if ( $msg instanceof IApiMessage
) {
1674 $extraData = $msg->getApiData();
1675 $code = $msg->getApiCode();
1677 $code = $msg->getKey();
1680 $code = $errors[0]['message'];
1681 $msg = wfMessage( $code, $errors[0]['params'] );
1683 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1684 // Translate message to code, for backwards compatibility
1685 $code = ApiBase
::$messageMap[$code]['code'];
1688 return [ $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() ];
1692 * Throw a UsageException based on the errors in the Status object.
1695 * @param Status $status
1696 * @throws UsageException always
1698 public function dieStatus( $status ) {
1700 list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1701 $this->dieUsage( $msg, $code, 0, $extraData );
1704 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1706 * Array that maps message keys to error messages. $1 and friends are replaced.
1708 public static $messageMap = [
1709 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1710 'unknownerror' => [ 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ],
1711 'unknownerror-nocode' => [ 'code' => 'unknownerror', 'info' => 'Unknown error' ],
1713 // Messages from Title::getUserPermissionsErrors()
1714 'ns-specialprotected' => [
1715 'code' => 'unsupportednamespace',
1716 'info' => "Pages in the Special namespace can't be edited"
1718 'protectedinterface' => [
1719 'code' => 'protectednamespace-interface',
1720 'info' => "You're not allowed to edit interface messages"
1722 'namespaceprotected' => [
1723 'code' => 'protectednamespace',
1724 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1726 'customcssprotected' => [
1727 'code' => 'customcssprotected',
1728 'info' => "You're not allowed to edit custom CSS pages"
1730 'customjsprotected' => [
1731 'code' => 'customjsprotected',
1732 'info' => "You're not allowed to edit custom JavaScript pages"
1734 'cascadeprotected' => [
1735 'code' => 'cascadeprotected',
1736 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1738 'protectedpagetext' => [
1739 'code' => 'protectedpage',
1740 'info' => "The \"\$1\" right is required to edit this page"
1742 'protect-cantedit' => [
1743 'code' => 'cantedit',
1744 'info' => "You can't protect this page because you can't edit it"
1746 'deleteprotected' => [
1747 'code' => 'cantedit',
1748 'info' => "You can't delete this page because it has been protected"
1750 'badaccess-group0' => [
1751 'code' => 'permissiondenied',
1752 'info' => 'Permission denied'
1753 ], // Generic permission denied message
1754 'badaccess-groups' => [
1755 'code' => 'permissiondenied',
1756 'info' => 'Permission denied'
1758 'titleprotected' => [
1759 'code' => 'protectedtitle',
1760 'info' => 'This title has been protected from creation'
1762 'nocreate-loggedin' => [
1763 'code' => 'cantcreate',
1764 'info' => "You don't have permission to create new pages"
1767 'code' => 'cantcreate-anon',
1768 'info' => "Anonymous users can't create new pages"
1770 'movenologintext' => [
1771 'code' => 'cantmove-anon',
1772 'info' => "Anonymous users can't move pages"
1774 'movenotallowed' => [
1775 'code' => 'cantmove',
1776 'info' => "You don't have permission to move pages"
1778 'confirmedittext' => [
1779 'code' => 'confirmemail',
1780 'info' => 'You must confirm your email address before you can edit'
1783 'code' => 'blocked',
1784 'info' => 'You have been blocked from editing'
1786 'autoblockedtext' => [
1787 'code' => 'autoblocked',
1788 'info' => 'Your IP address has been blocked automatically, because it was used by a blocked user'
1791 // Miscellaneous interface messages
1792 'actionthrottledtext' => [
1793 'code' => 'ratelimited',
1794 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1796 'alreadyrolled' => [
1797 'code' => 'alreadyrolled',
1798 'info' => 'The page you tried to rollback was already rolled back'
1801 'code' => 'onlyauthor',
1802 'info' => 'The page you tried to rollback only has one author'
1805 'code' => 'readonly',
1806 'info' => 'The wiki is currently in read-only mode'
1808 'sessionfailure' => [
1809 'code' => 'badtoken',
1810 'info' => 'Invalid token' ],
1812 'code' => 'cantdelete',
1813 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1816 'code' => 'missingtitle',
1817 'info' => "The page you requested doesn't exist"
1819 'selfmove' => [ 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1821 'immobile_namespace' => [
1822 'code' => 'immobilenamespace',
1823 'info' => 'You tried to move pages from or to a namespace that is protected from moving'
1825 'articleexists' => [
1826 'code' => 'articleexists',
1827 'info' => 'The destination article already exists and is not a redirect to the source article'
1829 'protectedpage' => [
1830 'code' => 'protectedpage',
1831 'info' => "You don't have permission to perform this move"
1834 'code' => 'hookaborted',
1835 'info' => 'The modification you tried to make was aborted by an extension hook'
1837 'cantmove-titleprotected' => [
1838 'code' => 'protectedtitle',
1839 'info' => 'The destination article has been protected from creation'
1841 'imagenocrossnamespace' => [
1842 'code' => 'nonfilenamespace',
1843 'info' => "Can't move a file to a non-file namespace"
1845 'imagetypemismatch' => [
1846 'code' => 'filetypemismatch',
1847 'info' => "The new file extension doesn't match its type"
1849 // 'badarticleerror' => shouldn't happen
1850 // 'badtitletext' => shouldn't happen
1851 'ip_range_invalid' => [ 'code' => 'invalidrange', 'info' => 'Invalid IP range' ],
1852 'range_block_disabled' => [
1853 'code' => 'rangedisabled',
1854 'info' => 'Blocking IP ranges has been disabled'
1856 'nosuchusershort' => [
1857 'code' => 'nosuchuser',
1858 'info' => "The user you specified doesn't exist"
1860 'badipaddress' => [ 'code' => 'invalidip', 'info' => 'Invalid IP address specified' ],
1861 'ipb_expiry_invalid' => [ 'code' => 'invalidexpiry', 'info' => 'Invalid expiry time' ],
1862 'ipb_already_blocked' => [
1863 'code' => 'alreadyblocked',
1864 'info' => 'The user you tried to block was already blocked'
1866 'ipb_blocked_as_range' => [
1867 'code' => 'blockedasrange',
1868 '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."
1870 'ipb_cant_unblock' => [
1871 'code' => 'cantunblock',
1872 'info' => 'The block you specified was not found. It may have been unblocked already'
1875 'code' => 'cantsend',
1876 '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'
1879 'code' => 'ipbblocked',
1880 'info' => 'You cannot block or unblock users while you are yourself blocked'
1882 'ipbnounblockself' => [
1883 'code' => 'ipbnounblockself',
1884 'info' => 'You are not allowed to unblock yourself'
1886 'usermaildisabled' => [
1887 'code' => 'usermaildisabled',
1888 'info' => 'User email has been disabled'
1890 'blockedemailuser' => [
1891 'code' => 'blockedfrommail',
1892 'info' => 'You have been blocked from sending email'
1895 'code' => 'notarget',
1896 'info' => 'You have not specified a valid target for this action'
1899 'code' => 'noemail',
1900 'info' => 'The user has not specified a valid email address, or has chosen not to receive email from other users'
1902 'rcpatroldisabled' => [
1903 'code' => 'patroldisabled',
1904 'info' => 'Patrolling is disabled on this wiki'
1906 'markedaspatrollederror-noautopatrol' => [
1907 'code' => 'noautopatrol',
1908 'info' => "You don't have permission to patrol your own changes"
1910 'delete-toobig' => [
1911 'code' => 'bigdelete',
1912 'info' => "You can't delete this page because it has more than \$1 revisions"
1914 'movenotallowedfile' => [
1915 'code' => 'cantmovefile',
1916 'info' => "You don't have permission to move files"
1918 'userrights-no-interwiki' => [
1919 'code' => 'nointerwikiuserrights',
1920 'info' => "You don't have permission to change user rights on other wikis"
1922 'userrights-nodatabase' => [
1923 'code' => 'nosuchdatabase',
1924 'info' => "Database \"\$1\" does not exist or is not local"
1926 'nouserspecified' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1927 'noname' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1928 'summaryrequired' => [ 'code' => 'summaryrequired', 'info' => 'Summary required' ],
1929 'import-rootpage-invalid' => [
1930 'code' => 'import-rootpage-invalid',
1931 'info' => 'Root page is an invalid title'
1933 'import-rootpage-nosubpage' => [
1934 'code' => 'import-rootpage-nosubpage',
1935 'info' => 'Namespace "$1" of the root page does not allow subpages'
1938 // API-specific messages
1940 'code' => 'readapidenied',
1941 'info' => 'You need read permission to use this module'
1943 'writedisabled' => [
1944 'code' => 'noapiwrite',
1945 '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"
1947 'writerequired' => [
1948 'code' => 'writeapidenied',
1949 'info' => "You're not allowed to edit this wiki through the API"
1951 'missingparam' => [ 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ],
1952 'invalidtitle' => [ 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ],
1953 'nosuchpageid' => [ 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ],
1954 'nosuchrevid' => [ 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ],
1955 'nosuchuser' => [ 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ],
1956 'invaliduser' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1957 'invalidexpiry' => [ 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ],
1958 'pastexpiry' => [ 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ],
1959 'create-titleexists' => [
1960 'code' => 'create-titleexists',
1961 'info' => "Existing titles can't be protected with 'create'"
1963 'missingtitle-createonly' => [
1964 'code' => 'missingtitle-createonly',
1965 'info' => "Missing titles can only be protected with 'create'"
1967 'cantblock' => [ 'code' => 'cantblock',
1968 'info' => "You don't have permission to block users"
1971 'code' => 'canthide',
1972 'info' => "You don't have permission to hide user names from the block log"
1974 'cantblock-email' => [
1975 'code' => 'cantblock-email',
1976 'info' => "You don't have permission to block users from sending email through the wiki"
1978 'unblock-notarget' => [
1979 'code' => 'notarget',
1980 'info' => 'Either the id or the user parameter must be set'
1982 'unblock-idanduser' => [
1983 'code' => 'idanduser',
1984 'info' => "The id and user parameters can't be used together"
1987 'code' => 'permissiondenied',
1988 'info' => "You don't have permission to unblock users"
1990 'cannotundelete' => [
1991 'code' => 'cantundelete',
1992 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1994 'permdenied-undelete' => [
1995 'code' => 'permissiondenied',
1996 'info' => "You don't have permission to restore deleted revisions"
1998 'createonly-exists' => [
1999 'code' => 'articleexists',
2000 'info' => 'The article you tried to create has been created already'
2002 'nocreate-missing' => [
2003 'code' => 'missingtitle',
2004 'info' => "The article you tried to edit doesn't exist"
2006 'cantchangecontentmodel' => [
2007 'code' => 'cantchangecontentmodel',
2008 'info' => "You don't have permission to change the content model of a page"
2011 'code' => 'nosuchrcid',
2012 'info' => "There is no change with rcid \"\$1\""
2015 'code' => 'nosuchlogid',
2016 'info' => "There is no log entry with ID \"\$1\""
2018 'protect-invalidaction' => [
2019 'code' => 'protect-invalidaction',
2020 'info' => "Invalid protection type \"\$1\""
2022 'protect-invalidlevel' => [
2023 'code' => 'protect-invalidlevel',
2024 'info' => "Invalid protection level \"\$1\""
2026 'toofewexpiries' => [
2027 'code' => 'toofewexpiries',
2028 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
2031 'code' => 'cantimport',
2032 'info' => "You don't have permission to import pages"
2034 'cantimport-upload' => [
2035 'code' => 'cantimport-upload',
2036 'info' => "You don't have permission to import uploaded pages"
2038 'importnofile' => [ 'code' => 'nofile', 'info' => "You didn't upload a file" ],
2039 'importuploaderrorsize' => [
2040 'code' => 'filetoobig',
2041 'info' => 'The file you uploaded is bigger than the maximum upload size'
2043 'importuploaderrorpartial' => [
2044 'code' => 'partialupload',
2045 'info' => 'The file was only partially uploaded'
2047 'importuploaderrortemp' => [
2048 'code' => 'notempdir',
2049 'info' => 'The temporary upload directory is missing'
2051 'importcantopen' => [
2052 'code' => 'cantopenfile',
2053 'info' => "Couldn't open the uploaded file"
2055 'import-noarticle' => [
2056 'code' => 'badinterwiki',
2057 'info' => 'Invalid interwiki title specified'
2059 'importbadinterwiki' => [
2060 'code' => 'badinterwiki',
2061 'info' => 'Invalid interwiki title specified'
2063 'import-unknownerror' => [
2064 'code' => 'import-unknownerror',
2065 'info' => "Unknown error on import: \"\$1\""
2067 'cantoverwrite-sharedfile' => [
2068 'code' => 'cantoverwrite-sharedfile',
2069 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
2071 'sharedfile-exists' => [
2072 'code' => 'fileexists-sharedrepo-perm',
2073 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
2076 'code' => 'mustbeposted',
2077 'info' => "The \$1 module requires a POST request"
2081 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
2083 'specialpage-cantexecute' => [
2084 'code' => 'specialpage-cantexecute',
2085 'info' => "You don't have permission to view the results of this special page"
2087 'invalidoldimage' => [
2088 'code' => 'invalidoldimage',
2089 'info' => 'The oldimage parameter has invalid format'
2091 'nodeleteablefile' => [
2092 'code' => 'nodeleteablefile',
2093 'info' => 'No such old version of the file'
2095 'fileexists-forbidden' => [
2096 'code' => 'fileexists-forbidden',
2097 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
2099 'fileexists-shared-forbidden' => [
2100 'code' => 'fileexists-shared-forbidden',
2101 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
2103 'filerevert-badversion' => [
2104 'code' => 'filerevert-badversion',
2105 'info' => 'There is no previous local version of this file with the provided timestamp.'
2108 // ApiEditPage messages
2109 'noimageredirect-anon' => [
2110 'code' => 'noimageredirect-anon',
2111 'info' => "Anonymous users can't create image redirects"
2113 'noimageredirect-logged' => [
2114 'code' => 'noimageredirect',
2115 'info' => "You don't have permission to create image redirects"
2118 'code' => 'spamdetected',
2119 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
2121 'contenttoobig' => [
2122 'code' => 'contenttoobig',
2123 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
2125 'noedit-anon' => [ 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ],
2126 'noedit' => [ 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ],
2128 'code' => 'pagedeleted',
2129 'info' => 'The page has been deleted since you fetched its timestamp'
2132 'code' => 'emptypage',
2133 'info' => 'Creating new, empty pages is not allowed'
2135 'editconflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2136 'hashcheckfailed' => [ 'code' => 'badmd5', 'info' => 'The supplied MD5 hash was incorrect' ],
2139 'info' => 'One of the text, appendtext, prependtext and undo parameters must be set'
2141 'emptynewsection' => [
2142 'code' => 'emptynewsection',
2143 'info' => 'Creating empty new sections is not possible.'
2146 'code' => 'revwrongpage',
2147 'info' => "r\$1 is not a revision of \"\$2\""
2150 'code' => 'undofailure',
2151 'info' => 'Undo failed due to conflicting intermediate edits'
2153 'content-not-allowed-here' => [
2154 'code' => 'contentnotallowedhere',
2155 'info' => 'Content model "$1" is not allowed at title "$2"'
2158 // Messages from WikiPage::doEit(]
2159 'edit-hook-aborted' => [
2160 'code' => 'edit-hook-aborted',
2161 'info' => 'Your edit was aborted by an ArticleSave hook'
2163 'edit-gone-missing' => [
2164 'code' => 'edit-gone-missing',
2165 'info' => "The page you tried to edit doesn't seem to exist anymore"
2167 'edit-conflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2168 'edit-already-exists' => [
2169 'code' => 'edit-already-exists',
2170 'info' => 'It seems the page you tried to create already exist'
2174 'invalid-file-key' => [ 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ],
2175 'nouploadmodule' => [ 'code' => 'nouploadmodule', 'info' => 'No upload module set' ],
2176 'uploaddisabled' => [
2177 'code' => 'uploaddisabled',
2178 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2180 'copyuploaddisabled' => [
2181 'code' => 'copyuploaddisabled',
2182 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2184 'copyuploadbaddomain' => [
2185 'code' => 'copyuploadbaddomain',
2186 'info' => 'Uploads by URL are not allowed from this domain.'
2188 'copyuploadbadurl' => [
2189 'code' => 'copyuploadbadurl',
2190 'info' => 'Upload not allowed from this URL.'
2193 'filename-tooshort' => [
2194 'code' => 'filename-tooshort',
2195 'info' => 'The filename is too short'
2197 'filename-toolong' => [ 'code' => 'filename-toolong', 'info' => 'The filename is too long' ],
2198 'illegal-filename' => [
2199 'code' => 'illegal-filename',
2200 'info' => 'The filename is not allowed'
2202 'filetype-missing' => [
2203 'code' => 'filetype-missing',
2204 'info' => 'The file is missing an extension'
2207 'mustbeloggedin' => [ 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' ]
2209 // @codingStandardsIgnoreEnd
2212 * Helper function for readonly errors
2214 * @throws UsageException always
2216 public function dieReadOnly() {
2217 $parsed = $this->parseMsg( [ 'readonlytext' ] );
2218 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2219 [ 'readonlyreason' => wfReadOnlyReason() ] );
2223 * Output the error message related to a certain array
2224 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2225 * @throws UsageException always
2227 public function dieUsageMsg( $error ) {
2228 # most of the time we send a 1 element, so we might as well send it as
2229 # a string and make this an array here.
2230 if ( is_string( $error ) ) {
2231 $error = [ $error ];
2233 $parsed = $this->parseMsg( $error );
2234 $extraData = isset( $parsed['data'] ) ?
$parsed['data'] : null;
2235 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2239 * Will only set a warning instead of failing if the global $wgDebugAPI
2240 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2241 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2242 * @throws UsageException
2245 public function dieUsageMsgOrDebug( $error ) {
2246 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2247 $this->dieUsageMsg( $error );
2250 if ( is_string( $error ) ) {
2251 $error = [ $error ];
2253 $parsed = $this->parseMsg( $error );
2254 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2258 * Die with the $prefix.'badcontinue' error. This call is common enough to
2259 * make it into the base method.
2260 * @param bool $condition Will only die if this value is true
2261 * @throws UsageException
2264 protected function dieContinueUsageIf( $condition ) {
2267 'Invalid continue param. You should pass the original value returned by the previous query',
2273 * Return the error message related to a certain array
2274 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2275 * @return [ 'code' => code, 'info' => info ]
2277 public function parseMsg( $error ) {
2278 // Check whether someone passed the whole array, instead of one element as
2279 // documented. This breaks if it's actually an array of fallback keys, but
2280 // that's long-standing misbehavior introduced in r87627 to incorrectly
2282 if ( is_array( $error ) ) {
2283 $first = reset( $error );
2284 if ( is_array( $first ) ) {
2285 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2290 $msg = Message
::newFromSpecifier( $error );
2292 if ( $msg instanceof IApiMessage
) {
2294 'code' => $msg->getApiCode(),
2295 'info' => $msg->inLanguage( 'en' )->useDatabase( false )->text(),
2296 'data' => $msg->getApiData()
2300 $key = $msg->getKey();
2301 if ( isset( self
::$messageMap[$key] ) ) {
2302 $params = $msg->getParams();
2304 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $params ),
2305 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $params )
2309 // If the key isn't present, throw an "unknown error"
2310 return $this->parseMsg( [ 'unknownerror', $key ] );
2314 * Internal code errors should be reported with this method
2315 * @param string $method Method or function name
2316 * @param string $message Error message
2317 * @throws MWException always
2319 protected static function dieDebug( $method, $message ) {
2320 throw new MWException( "Internal error in $method: $message" );
2324 * Write logging information for API features to a debug log, for usage
2326 * @param string $feature Feature being used.
2328 public function logFeatureUsage( $feature ) {
2329 $request = $this->getRequest();
2330 $s = '"' . addslashes( $feature ) . '"' .
2331 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2332 ' "' . $request->getIP() . '"' .
2333 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2334 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2335 wfDebugLog( 'api-feature-usage', $s, 'private' );
2340 /************************************************************************//**
2341 * @name Help message generation
2346 * Return the description message.
2348 * @return string|array|Message
2350 protected function getDescriptionMessage() {
2351 return "apihelp-{$this->getModulePath()}-description";
2355 * Get final module description, after hooks have had a chance to tweak it as
2358 * @since 1.25, returns Message[] rather than string[]
2361 public function getFinalDescription() {
2362 $desc = $this->getDescription();
2363 Hooks
::run( 'APIGetDescription', [ &$this, &$desc ] );
2364 $desc = self
::escapeWikiText( $desc );
2365 if ( is_array( $desc ) ) {
2366 $desc = implode( "\n", $desc );
2368 $desc = (string)$desc;
2371 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2372 $this->getModulePrefix(),
2373 $this->getModuleName(),
2374 $this->getModulePath(),
2376 if ( !$msg->exists() ) {
2377 $msg = $this->msg( 'api-help-fallback-description', $desc );
2381 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2387 * Get final list of parameters, after hooks have had a chance to
2388 * tweak it as needed.
2390 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2391 * @return array|bool False on no parameters
2392 * @since 1.21 $flags param added
2394 public function getFinalParams( $flags = 0 ) {
2395 $params = $this->getAllowedParams( $flags );
2400 if ( $this->needsToken() ) {
2401 $params['token'] = [
2402 ApiBase
::PARAM_TYPE
=> 'string',
2403 ApiBase
::PARAM_REQUIRED
=> true,
2404 ApiBase
::PARAM_HELP_MSG
=> [
2405 'api-help-param-token',
2406 $this->needsToken(),
2408 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2411 Hooks
::run( 'APIGetAllowedParams', [ &$this, &$params, $flags ] );
2417 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2420 * @since 1.25, returns array of Message[] rather than array of string[]
2421 * @return array Keys are parameter names, values are arrays of Message objects
2423 public function getFinalParamDescription() {
2424 $prefix = $this->getModulePrefix();
2425 $name = $this->getModuleName();
2426 $path = $this->getModulePath();
2428 $desc = $this->getParamDescription();
2429 Hooks
::run( 'APIGetParamDescription', [ &$this, &$desc ] );
2434 $desc = self
::escapeWikiText( $desc );
2436 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2438 foreach ( $params as $param => $settings ) {
2439 if ( !is_array( $settings ) ) {
2443 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2444 if ( is_array( $d ) ) {
2445 // Special handling for prop parameters
2446 $d = array_map( function ( $line ) {
2447 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2448 $line = "\n;{$m[1]}:{$m[2]}";
2452 $d = implode( ' ', $d );
2455 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2456 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2458 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2459 if ( !$msg->exists() ) {
2460 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2463 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2464 [ $prefix, $param, $name, $path ] );
2466 self
::dieDebug( __METHOD__
,
2467 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2469 $msgs[$param] = [ $msg ];
2471 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2472 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2473 self
::dieDebug( __METHOD__
,
2474 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2476 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2477 self
::dieDebug( __METHOD__
,
2478 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2479 'ApiBase::PARAM_TYPE is an array' );
2482 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2483 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2484 if ( isset( $valueMsgs[$value] ) ) {
2485 $msg = $valueMsgs[$value];
2487 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2489 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2490 [ $prefix, $param, $name, $path, $value ] );
2492 $m = new ApiHelpParamValueMessage(
2494 [ $m->getKey(), 'api-help-param-no-description' ],
2497 $msgs[$param][] = $m->setContext( $this->getContext() );
2499 self
::dieDebug( __METHOD__
,
2500 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2505 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2506 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2507 self
::dieDebug( __METHOD__
,
2508 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2510 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2511 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2512 [ $prefix, $param, $name, $path ] );
2514 $msgs[$param][] = $m;
2516 self
::dieDebug( __METHOD__
,
2517 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2523 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2529 * Generates the list of flags for the help screen and for action=paraminfo
2531 * Corresponding messages: api-help-flag-deprecated,
2532 * api-help-flag-internal, api-help-flag-readrights,
2533 * api-help-flag-writerights, api-help-flag-mustbeposted
2537 protected function getHelpFlags() {
2540 if ( $this->isDeprecated() ) {
2541 $flags[] = 'deprecated';
2543 if ( $this->isInternal() ) {
2544 $flags[] = 'internal';
2546 if ( $this->isReadMode() ) {
2547 $flags[] = 'readrights';
2549 if ( $this->isWriteMode() ) {
2550 $flags[] = 'writerights';
2552 if ( $this->mustBePosted() ) {
2553 $flags[] = 'mustbeposted';
2560 * Returns information about the source of this module, if known
2562 * Returned array is an array with the following keys:
2563 * - path: Install path
2564 * - name: Extension name, or "MediaWiki" for core
2565 * - namemsg: (optional) i18n message key for a display name
2566 * - license-name: (optional) Name of license
2568 * @return array|null
2570 protected function getModuleSourceInfo() {
2573 if ( $this->mModuleSource
!== false ) {
2574 return $this->mModuleSource
;
2577 // First, try to find where the module comes from...
2578 $rClass = new ReflectionClass( $this );
2579 $path = $rClass->getFileName();
2582 $this->mModuleSource
= null;
2585 $path = realpath( $path ) ?
: $path;
2587 // Build map of extension directories to extension info
2588 if ( self
::$extensionInfo === null ) {
2589 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2590 self
::$extensionInfo = [
2591 realpath( __DIR__
) ?
: __DIR__
=> [
2593 'name' => 'MediaWiki',
2594 'license-name' => 'GPL-2.0+',
2596 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2597 realpath( $extDir ) ?
: $extDir => null,
2603 'license-name' => null,
2605 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2606 foreach ( $group as $ext ) {
2607 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2608 // This shouldn't happen, but does anyway.
2612 $extpath = $ext['path'];
2613 if ( !is_dir( $extpath ) ) {
2614 $extpath = dirname( $extpath );
2616 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2617 array_intersect_key( $ext, $keep );
2620 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2621 $extpath = $ext['path'];
2622 if ( !is_dir( $extpath ) ) {
2623 $extpath = dirname( $extpath );
2625 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2626 array_intersect_key( $ext, $keep );
2630 // Now traverse parent directories until we find a match or run out of
2633 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2635 $this->mModuleSource
= self
::$extensionInfo[$path];
2636 return $this->mModuleSource
;
2640 $path = dirname( $path );
2641 } while ( $path !== $oldpath );
2643 // No idea what extension this might be.
2644 $this->mModuleSource
= null;
2649 * Called from ApiHelp before the pieces are joined together and returned.
2651 * This exists mainly for ApiMain to add the Permissions and Credits
2652 * sections. Other modules probably don't need it.
2654 * @param string[] &$help Array of help data
2655 * @param array $options Options passed to ApiHelp::getHelp
2656 * @param array &$tocData If a TOC is being generated, this array has keys
2657 * as anchors in the page and values as for Linker::generateTOC().
2659 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2664 /************************************************************************//**
2670 * Returns the description string for this module
2672 * Ignored if an i18n message exists for
2673 * "apihelp-{$this->getModulePath()}-description".
2675 * @deprecated since 1.25
2676 * @return Message|string|array
2678 protected function getDescription() {
2683 * Returns an array of parameter descriptions.
2685 * For each parameter, ignored if an i18n message exists for the parameter.
2686 * By default that message is
2687 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2688 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2689 * self::getFinalParams().
2691 * @deprecated since 1.25
2692 * @return array|bool False on no parameter descriptions
2694 protected function getParamDescription() {
2699 * Returns usage examples for this module.
2701 * Return value as an array is either:
2702 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2704 * - sequential numeric keys with even-numbered keys being display-text
2705 * and odd-numbered keys being partial urls
2706 * - partial URLs as keys with display-text (string or array-to-be-joined)
2708 * Return value as a string is the same as an array with a numeric key and
2709 * that value, and boolean false means "no examples".
2711 * @deprecated since 1.25, use getExamplesMessages() instead
2712 * @return bool|string|array
2714 protected function getExamples() {
2719 * @deprecated since 1.25, always returns empty string
2720 * @param IDatabase|bool $db
2723 public function getModuleProfileName( $db = false ) {
2724 wfDeprecated( __METHOD__
, '1.25' );
2729 * @deprecated since 1.25
2731 public function profileIn() {
2732 // No wfDeprecated() yet because extensions call this and might need to
2733 // keep doing so for BC.
2737 * @deprecated since 1.25
2739 public function profileOut() {
2740 // No wfDeprecated() yet because extensions call this and might need to
2741 // keep doing so for BC.
2745 * @deprecated since 1.25
2747 public function safeProfileOut() {
2748 wfDeprecated( __METHOD__
, '1.25' );
2752 * @deprecated since 1.25, always returns 0
2755 public function getProfileTime() {
2756 wfDeprecated( __METHOD__
, '1.25' );
2761 * @deprecated since 1.25
2763 public function profileDBIn() {
2764 wfDeprecated( __METHOD__
, '1.25' );
2768 * @deprecated since 1.25
2770 public function profileDBOut() {
2771 wfDeprecated( __METHOD__
, '1.25' );
2775 * @deprecated since 1.25, always returns 0
2778 public function getProfileDBTime() {
2779 wfDeprecated( __METHOD__
, '1.25' );
2784 * Call wfTransactionalTimeLimit() if this request was POSTed
2787 protected function useTransactionalTimeLimit() {
2788 if ( $this->getRequest()->wasPosted() ) {
2789 wfTransactionalTimeLimit();
2797 * For really cool vim folding this needs to be at the end:
2798 * vim: foldmarker=@{,@} foldmethod=marker