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 = array();
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 = array( $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 = join( " ", $msg );
309 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
310 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $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|boolean|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 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
510 * Get the path to this module
515 public function getModulePath() {
516 if ( $this->isMain() ) {
518 } elseif ( $this->getParent()->isMain() ) {
519 return $this->getModuleName();
521 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
526 * Get a module from its module path
529 * @param string $path
530 * @return ApiBase|null
531 * @throws UsageException
533 public function getModuleFromPath( $path ) {
534 $module = $this->getMain();
535 if ( $path === 'main' ) {
539 $parts = explode( '+', $path );
540 if ( count( $parts ) === 1 ) {
541 // In case the '+' was typed into URL, it resolves as a space
542 $parts = explode( ' ', $path );
545 $count = count( $parts );
546 for ( $i = 0; $i < $count; $i++
) {
548 $manager = $parent->getModuleManager();
549 if ( $manager === null ) {
550 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
551 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
553 $module = $manager->getModule( $parts[$i] );
555 if ( $module === null ) {
556 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
558 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
568 * Get the result object
571 public function getResult() {
572 // Main module has getResult() method overridden
573 // Safety - avoid infinite loop:
574 if ( $this->isMain() ) {
575 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
578 return $this->getMain()->getResult();
582 * Get the error formatter
583 * @return ApiErrorFormatter
585 public function getErrorFormatter() {
586 // Main module has getErrorFormatter() method overridden
587 // Safety - avoid infinite loop:
588 if ( $this->isMain() ) {
589 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
592 return $this->getMain()->getErrorFormatter();
596 * Gets a default slave database connection object
597 * @return DatabaseBase
599 protected function getDB() {
600 if ( !isset( $this->mSlaveDB
) ) {
601 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
604 return $this->mSlaveDB
;
608 * Get the continuation manager
609 * @return ApiContinuationManager|null
611 public function getContinuationManager() {
612 // Main module has getContinuationManager() method overridden
613 // Safety - avoid infinite loop:
614 if ( $this->isMain() ) {
615 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
618 return $this->getMain()->getContinuationManager();
622 * Set the continuation manager
623 * @param ApiContinuationManager|null
625 public function setContinuationManager( $manager ) {
626 // Main module has setContinuationManager() method overridden
627 // Safety - avoid infinite loop:
628 if ( $this->isMain() ) {
629 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
632 $this->getMain()->setContinuationManager( $manager );
637 /************************************************************************//**
638 * @name Parameter handling
643 * Indicate if the module supports dynamically-determined parameters that
644 * cannot be included in self::getAllowedParams().
645 * @return string|array|Message|null Return null if the module does not
646 * support additional dynamic parameters, otherwise return a message
649 public function dynamicParameterDocumentation() {
654 * This method mangles parameter name based on the prefix supplied to the constructor.
655 * Override this method to change parameter name during runtime
656 * @param string $paramName Parameter name
657 * @return string Prefixed parameter name
659 public function encodeParamName( $paramName ) {
660 return $this->mModulePrefix
. $paramName;
664 * Using getAllowedParams(), this function makes an array of the values
665 * provided by the user, with key being the name of the variable, and
666 * value - validated value from user or default. limits will not be
667 * parsed if $parseLimit is set to false; use this when the max
668 * limit is not definitive yet, e.g. when getting revisions.
669 * @param bool $parseLimit True by default
672 public function extractRequestParams( $parseLimit = true ) {
673 // Cache parameters, for performance and to avoid bug 24564.
674 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
675 $params = $this->getFinalParams();
678 if ( $params ) { // getFinalParams() can return false
679 foreach ( $params as $paramName => $paramSettings ) {
680 $results[$paramName] = $this->getParameterFromSettings(
681 $paramName, $paramSettings, $parseLimit );
684 $this->mParamCache
[$parseLimit] = $results;
687 return $this->mParamCache
[$parseLimit];
691 * Get a value for the given parameter
692 * @param string $paramName Parameter name
693 * @param bool $parseLimit See extractRequestParams()
694 * @return mixed Parameter value
696 protected function getParameter( $paramName, $parseLimit = true ) {
697 $params = $this->getFinalParams();
698 $paramSettings = $params[$paramName];
700 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
704 * Die if none or more than one of a certain set of parameters is set and not false.
706 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
707 * @param string $required,... Names of parameters of which exactly one must be set
709 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
710 $required = func_get_args();
711 array_shift( $required );
712 $p = $this->getModulePrefix();
714 $intersection = array_intersect( array_keys( array_filter( $params,
715 array( $this, "parameterNotEmpty" ) ) ), $required );
717 if ( count( $intersection ) > 1 ) {
719 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
721 } elseif ( count( $intersection ) == 0 ) {
723 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
730 * Die if more than one of a certain set of parameters is set and not false.
732 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
733 * @param string $required,... Names of parameters of which at most one must be set
735 public function requireMaxOneParameter( $params, $required /*...*/ ) {
736 $required = func_get_args();
737 array_shift( $required );
738 $p = $this->getModulePrefix();
740 $intersection = array_intersect( array_keys( array_filter( $params,
741 array( $this, "parameterNotEmpty" ) ) ), $required );
743 if ( count( $intersection ) > 1 ) {
745 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
752 * Die if none of a certain set of parameters is set and not false.
755 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
756 * @param string $required,... Names of parameters of which at least one must be set
758 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
759 $required = func_get_args();
760 array_shift( $required );
761 $p = $this->getModulePrefix();
763 $intersection = array_intersect(
764 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
768 if ( count( $intersection ) == 0 ) {
769 $this->dieUsage( "At least one of the parameters {$p}" .
770 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
775 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
777 * @param object $x Parameter to check is not null/false
780 private function parameterNotEmpty( $x ) {
781 return !is_null( $x ) && $x !== false;
785 * Get a WikiPage object from a title or pageid param, if possible.
786 * Can die, if no param is set or if the title or page id is not valid.
788 * @param array $params
789 * @param bool|string $load Whether load the object's state from the database:
790 * - false: don't load (if the pageid is given, it will still be loaded)
791 * - 'fromdb': load from a slave database
792 * - 'fromdbmaster': load from the master database
795 public function getTitleOrPageId( $params, $load = false ) {
796 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
799 if ( isset( $params['title'] ) ) {
800 $titleObj = Title
::newFromText( $params['title'] );
801 if ( !$titleObj ||
$titleObj->isExternal() ) {
802 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
804 if ( !$titleObj->canExist() ) {
805 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
807 $pageObj = WikiPage
::factory( $titleObj );
808 if ( $load !== false ) {
809 $pageObj->loadPageData( $load );
811 } elseif ( isset( $params['pageid'] ) ) {
812 if ( $load === false ) {
815 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
817 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
825 * Return true if we're to watch the page, false if not, null if no change.
826 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
827 * @param Title $titleObj The page under consideration
828 * @param string $userOption The user option to consider when $watchlist=preferences.
829 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
832 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
834 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
836 switch ( $watchlist ) {
844 # If the user is already watching, don't bother checking
845 if ( $userWatching ) {
848 # If no user option was passed, use watchdefault and watchcreations
849 if ( is_null( $userOption ) ) {
850 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
851 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
854 # Watch the article based on the user preference
855 return $this->getUser()->getBoolOption( $userOption );
858 return $userWatching;
861 return $userWatching;
866 * Using the settings determine the value for the given parameter
868 * @param string $paramName Parameter name
869 * @param array|mixed $paramSettings Default value or an array of settings
870 * using PARAM_* constants.
871 * @param bool $parseLimit Parse limit?
872 * @return mixed Parameter value
874 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
875 // Some classes may decide to change parameter names
876 $encParamName = $this->encodeParamName( $paramName );
878 if ( !is_array( $paramSettings ) ) {
879 $default = $paramSettings;
881 $type = gettype( $paramSettings );
886 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
887 ?
$paramSettings[self
::PARAM_DFLT
]
889 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
890 ?
$paramSettings[self
::PARAM_ISMULTI
]
892 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
893 ?
$paramSettings[self
::PARAM_TYPE
]
895 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
896 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
898 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
899 ?
$paramSettings[self
::PARAM_DEPRECATED
]
901 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
902 ?
$paramSettings[self
::PARAM_REQUIRED
]
905 // When type is not given, and no choices, the type is the same as $default
906 if ( !isset( $type ) ) {
907 if ( isset( $default ) ) {
908 $type = gettype( $default );
910 $type = 'NULL'; // allow everything
915 if ( $type == 'boolean' ) {
916 if ( isset( $default ) && $default !== false ) {
917 // Having a default value of anything other than 'false' is not allowed
920 "Boolean param $encParamName's default is set to '$default'. " .
921 "Boolean parameters must default to false."
925 $value = $this->getMain()->getCheck( $encParamName );
926 } elseif ( $type == 'upload' ) {
927 if ( isset( $default ) ) {
928 // Having a default value is not allowed
931 "File upload param $encParamName's default is set to " .
932 "'$default'. File upload parameters may not have a default." );
935 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
937 $value = $this->getMain()->getUpload( $encParamName );
938 if ( !$value->exists() ) {
939 // This will get the value without trying to normalize it
940 // (because trying to normalize a large binary file
941 // accidentally uploaded as a field fails spectacularly)
942 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
943 if ( $value !== null ) {
945 "File upload param $encParamName is not a file upload; " .
946 "be sure to use multipart/form-data for your POST and include " .
947 "a filename in the Content-Disposition header.",
948 "badupload_{$encParamName}"
953 $value = $this->getMain()->getVal( $encParamName, $default );
955 if ( isset( $value ) && $type == 'namespace' ) {
956 $type = MWNamespace
::getValidNamespaces();
958 if ( isset( $value ) && $type == 'submodule' ) {
959 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
960 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
962 $type = $this->getModuleManager()->getNames( $paramName );
967 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
968 $value = $this->parseMultiValue(
972 is_array( $type ) ?
$type : null
976 // More validation only when choices were not given
977 // choices were validated in parseMultiValue()
978 if ( isset( $value ) ) {
979 if ( !is_array( $type ) ) {
981 case 'NULL': // nothing to do
986 if ( $required && $value === '' ) {
987 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
990 case 'integer': // Force everything using intval() and optionally validate limits
991 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
992 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
993 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
994 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
996 if ( is_array( $value ) ) {
997 $value = array_map( 'intval', $value );
998 if ( !is_null( $min ) ||
!is_null( $max ) ) {
999 foreach ( $value as &$v ) {
1000 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1004 $value = intval( $value );
1005 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1006 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1011 if ( !$parseLimit ) {
1012 // Don't do any validation whatsoever
1015 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1016 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1020 "MAX1 or MAX2 are not defined for the limit $encParamName"
1024 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1026 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1027 if ( $value == 'max' ) {
1028 $value = $this->getMain()->canApiHighLimits()
1029 ?
$paramSettings[self
::PARAM_MAX2
]
1030 : $paramSettings[self
::PARAM_MAX
];
1031 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1033 $value = intval( $value );
1034 $this->validateLimit(
1038 $paramSettings[self
::PARAM_MAX
],
1039 $paramSettings[self
::PARAM_MAX2
]
1045 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1049 if ( is_array( $value ) ) {
1050 foreach ( $value as $key => $val ) {
1051 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1054 $value = $this->validateTimestamp( $value, $encParamName );
1058 if ( is_array( $value ) ) {
1059 foreach ( $value as $key => $val ) {
1060 $value[$key] = $this->validateUser( $val, $encParamName );
1063 $value = $this->validateUser( $value, $encParamName );
1066 case 'upload': // nothing to do
1069 // If change tagging was requested, check that the tags are valid.
1070 if ( !is_array( $value ) && !$multi ) {
1071 $value = array( $value );
1073 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1074 if ( !$tagsStatus->isGood() ) {
1075 $this->dieStatus( $tagsStatus );
1079 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1083 // Throw out duplicates if requested
1084 if ( !$dupes && is_array( $value ) ) {
1085 $value = array_unique( $value );
1088 // Set a warning if a deprecated parameter has been passed
1089 if ( $deprecated && $value !== false ) {
1090 $this->setWarning( "The $encParamName parameter has been deprecated." );
1092 $feature = $encParamName;
1094 while ( !$m->isMain() ) {
1095 $p = $m->getParent();
1096 $name = $m->getModuleName();
1097 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1098 $feature = "{$param}={$name}&{$feature}";
1101 $this->logFeatureUsage( $feature );
1103 } elseif ( $required ) {
1104 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1111 * Return an array of values that were given in a 'a|b|c' notation,
1112 * after it optionally validates them against the list allowed values.
1114 * @param string $valueName The name of the parameter (for error
1116 * @param mixed $value The value being parsed
1117 * @param bool $allowMultiple Can $value contain more than one value
1119 * @param string[]|null $allowedValues An array of values to check against. If
1120 * null, all values are accepted.
1121 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1123 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1124 if ( trim( $value ) === '' && $allowMultiple ) {
1128 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1129 // because it unstubs $wgUser
1130 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1131 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1135 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1136 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1137 "the limit is $sizeLimit" );
1140 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1141 // Bug 33482 - Allow entries with | in them for non-multiple values
1142 if ( in_array( $value, $allowedValues, true ) ) {
1146 $possibleValues = is_array( $allowedValues )
1147 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1150 "Only one $possibleValues is allowed for parameter '$valueName'",
1151 "multival_$valueName"
1155 if ( is_array( $allowedValues ) ) {
1156 // Check for unknown values
1157 $unknown = array_diff( $valuesList, $allowedValues );
1158 if ( count( $unknown ) ) {
1159 if ( $allowMultiple ) {
1160 $s = count( $unknown ) > 1 ?
's' : '';
1161 $vals = implode( ", ", $unknown );
1162 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1165 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1166 "unknown_$valueName"
1170 // Now throw them out
1171 $valuesList = array_intersect( $valuesList, $allowedValues );
1174 return $allowMultiple ?
$valuesList : $valuesList[0];
1178 * Validate the value against the minimum and user/bot maximum limits.
1179 * Prints usage info on failure.
1180 * @param string $paramName Parameter name
1181 * @param int $value Parameter value
1182 * @param int|null $min Minimum value
1183 * @param int|null $max Maximum value for users
1184 * @param int $botMax Maximum value for sysops/bots
1185 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1187 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1188 $enforceLimits = false
1190 if ( !is_null( $min ) && $value < $min ) {
1191 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1192 $this->warnOrDie( $msg, $enforceLimits );
1196 // Minimum is always validated, whereas maximum is checked only if not
1197 // running in internal call mode
1198 if ( $this->getMain()->isInternalMode() ) {
1202 // Optimization: do not check user's bot status unless really needed -- skips db query
1203 // assumes $botMax >= $max
1204 if ( !is_null( $max ) && $value > $max ) {
1205 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1206 if ( $value > $botMax ) {
1207 $msg = $this->encodeParamName( $paramName ) .
1208 " may not be over $botMax (set to $value) for bots or sysops";
1209 $this->warnOrDie( $msg, $enforceLimits );
1213 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1214 $this->warnOrDie( $msg, $enforceLimits );
1221 * Validate and normalize of parameters of type 'timestamp'
1222 * @param string $value Parameter value
1223 * @param string $encParamName Parameter name
1224 * @return string Validated and normalized parameter
1226 protected function validateTimestamp( $value, $encParamName ) {
1227 // Confusing synonyms for the current time accepted by wfTimestamp()
1228 // (wfTimestamp() also accepts various non-strings and the string of 14
1229 // ASCII NUL bytes, but those can't get here)
1231 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1233 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1234 ' If for some reason you need to explicitly specify the current time without' .
1235 ' calculating it client-side, use "now".'
1237 return wfTimestamp( TS_MW
);
1240 // Explicit synonym for the current time
1241 if ( $value === 'now' ) {
1242 return wfTimestamp( TS_MW
);
1245 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1246 if ( $unixTimestamp === false ) {
1248 "Invalid value '$value' for timestamp parameter $encParamName",
1249 "badtimestamp_{$encParamName}"
1253 return wfTimestamp( TS_MW
, $unixTimestamp );
1257 * Validate the supplied token.
1260 * @param string $token Supplied token
1261 * @param array $params All supplied parameters for the module
1263 * @throws MWException
1265 final public function validateToken( $token, array $params ) {
1266 $tokenType = $this->needsToken();
1267 $salts = ApiQueryTokens
::getTokenTypeSalts();
1268 if ( !isset( $salts[$tokenType] ) ) {
1269 throw new MWException(
1270 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1271 'without registering it'
1275 $tokenObj = ApiQueryTokens
::getToken(
1276 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1278 if ( $tokenObj->match( $token ) ) {
1282 $webUiSalt = $this->getWebUITokenSalt( $params );
1283 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1295 * Validate and normalize of parameters of type 'user'
1296 * @param string $value Parameter value
1297 * @param string $encParamName Parameter name
1298 * @return string Validated and normalized parameter
1300 private function validateUser( $value, $encParamName ) {
1301 $title = Title
::makeTitleSafe( NS_USER
, $value );
1302 if ( $title === null ) {
1304 "Invalid value '$value' for user parameter $encParamName",
1305 "baduser_{$encParamName}"
1309 return $title->getText();
1314 /************************************************************************//**
1315 * @name Utility methods
1320 * Set a watch (or unwatch) based the based on a watchlist parameter.
1321 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1322 * @param Title $titleObj The article's title to change
1323 * @param string $userOption The user option to consider when $watch=preferences
1325 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1326 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1327 if ( $value === null ) {
1331 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1335 * Truncate an array to a certain length.
1336 * @param array $arr Array to truncate
1337 * @param int $limit Maximum length
1338 * @return bool True if the array was truncated, false otherwise
1340 public static function truncateArray( &$arr, $limit ) {
1342 while ( count( $arr ) > $limit ) {
1351 * Gets the user for whom to get the watchlist
1353 * @param array $params
1356 public function getWatchlistUser( $params ) {
1357 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1358 $user = User
::newFromName( $params['owner'], false );
1359 if ( !( $user && $user->getId() ) ) {
1360 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1362 $token = $user->getOption( 'watchlisttoken' );
1363 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1365 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1370 if ( !$this->getUser()->isLoggedIn() ) {
1371 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1373 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1374 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1376 $user = $this->getUser();
1383 * A subset of wfEscapeWikiText for BC texts
1386 * @param string|array $v
1387 * @return string|array
1389 private static function escapeWikiText( $v ) {
1390 if ( is_array( $v ) ) {
1391 return array_map( 'self::escapeWikiText', $v );
1393 return strtr( $v, array(
1394 '__' => '__', '{' => '{', '}' => '}',
1395 '[[Category:' => '[[:Category:',
1396 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1402 * Create a Message from a string or array
1404 * A string is used as a message key. An array has the message key as the
1405 * first value and message parameters as subsequent values.
1408 * @param string|array|Message $msg
1409 * @param IContextSource $context
1410 * @param array $params
1411 * @return Message|null
1413 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1414 if ( is_string( $msg ) ) {
1415 $msg = wfMessage( $msg );
1416 } elseif ( is_array( $msg ) ) {
1417 $msg = call_user_func_array( 'wfMessage', $msg );
1419 if ( !$msg instanceof Message
) {
1423 $msg->setContext( $context );
1425 $msg->params( $params );
1433 /************************************************************************//**
1434 * @name Warning and error reporting
1439 * Set warning section for this module. Users should monitor this
1440 * section to notice any changes in API. Multiple calls to this
1441 * function will result in the warning messages being separated by
1443 * @param string $warning Warning message
1445 public function setWarning( $warning ) {
1446 $msg = new ApiRawMessage( $warning, 'warning' );
1447 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1451 * Adds a warning to the output, else dies
1453 * @param string $msg Message to show as a warning, or error message if dying
1454 * @param bool $enforceLimits Whether this is an enforce (die)
1456 private function warnOrDie( $msg, $enforceLimits = false ) {
1457 if ( $enforceLimits ) {
1458 $this->dieUsage( $msg, 'integeroutofrange' );
1461 $this->setWarning( $msg );
1465 * Throw a UsageException, which will (if uncaught) call the main module's
1466 * error handler and die with an error message.
1468 * @param string $description One-line human-readable description of the
1469 * error condition, e.g., "The API requires a valid action parameter"
1470 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1471 * automated identification of the error, e.g., 'unknown_action'
1472 * @param int $httpRespCode HTTP response code
1473 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
1474 * @throws UsageException always
1476 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1477 throw new UsageException(
1479 $this->encodeParamName( $errorCode ),
1486 * Throw a UsageException, which will (if uncaught) call the main module's
1487 * error handler and die with an error message including block info.
1490 * @param Block $block The block used to generate the UsageException
1491 * @throws UsageException always
1493 public function dieBlocked( Block
$block ) {
1494 // Die using the appropriate message depending on block type
1495 if ( $block->getType() == Block
::TYPE_AUTO
) {
1497 'Your IP address has been blocked automatically, because it was used by a blocked user',
1500 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) )
1504 'You have been blocked from editing',
1507 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) )
1513 * Get error (as code, string) from a Status object.
1516 * @param Status $status
1517 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
1518 * @return array Array of code and error string
1519 * @throws MWException
1521 public function getErrorFromStatus( $status, &$extraData = null ) {
1522 if ( $status->isGood() ) {
1523 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1526 $errors = $status->getErrorsArray();
1528 // No errors? Assume the warnings should be treated as errors
1529 $errors = $status->getWarningsArray();
1532 // Still no errors? Punt
1533 $errors = array( array( 'unknownerror-nocode' ) );
1536 // Cannot use dieUsageMsg() because extensions might return custom
1538 if ( $errors[0] instanceof Message
) {
1540 if ( $msg instanceof IApiMessage
) {
1541 $extraData = $msg->getApiData();
1542 $code = $msg->getApiCode();
1544 $code = $msg->getKey();
1547 $code = array_shift( $errors[0] );
1548 $msg = wfMessage( $code, $errors[0] );
1550 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1551 // Translate message to code, for backwards compatibility
1552 $code = ApiBase
::$messageMap[$code]['code'];
1555 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1559 * Throw a UsageException based on the errors in the Status object.
1562 * @param Status $status
1563 * @throws UsageException always
1565 public function dieStatus( $status ) {
1567 list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1568 $this->dieUsage( $msg, $code, 0, $extraData );
1571 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1573 * Array that maps message keys to error messages. $1 and friends are replaced.
1575 public static $messageMap = array(
1576 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1577 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1578 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1580 // Messages from Title::getUserPermissionsErrors()
1581 'ns-specialprotected' => array(
1582 'code' => 'unsupportednamespace',
1583 'info' => "Pages in the Special namespace can't be edited"
1585 'protectedinterface' => array(
1586 'code' => 'protectednamespace-interface',
1587 'info' => "You're not allowed to edit interface messages"
1589 'namespaceprotected' => array(
1590 'code' => 'protectednamespace',
1591 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1593 'customcssprotected' => array(
1594 'code' => 'customcssprotected',
1595 'info' => "You're not allowed to edit custom CSS pages"
1597 'customjsprotected' => array(
1598 'code' => 'customjsprotected',
1599 'info' => "You're not allowed to edit custom JavaScript pages"
1601 'cascadeprotected' => array(
1602 'code' => 'cascadeprotected',
1603 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1605 'protectedpagetext' => array(
1606 'code' => 'protectedpage',
1607 'info' => "The \"\$1\" right is required to edit this page"
1609 'protect-cantedit' => array(
1610 'code' => 'cantedit',
1611 'info' => "You can't protect this page because you can't edit it"
1613 'deleteprotected' => array(
1614 'code' => 'cantedit',
1615 'info' => "You can't delete this page because it has been protected"
1617 'badaccess-group0' => array(
1618 'code' => 'permissiondenied',
1619 'info' => "Permission denied"
1620 ), // Generic permission denied message
1621 'badaccess-groups' => array(
1622 'code' => 'permissiondenied',
1623 'info' => "Permission denied"
1625 'titleprotected' => array(
1626 'code' => 'protectedtitle',
1627 'info' => "This title has been protected from creation"
1629 'nocreate-loggedin' => array(
1630 'code' => 'cantcreate',
1631 'info' => "You don't have permission to create new pages"
1633 'nocreatetext' => array(
1634 'code' => 'cantcreate-anon',
1635 'info' => "Anonymous users can't create new pages"
1637 'movenologintext' => array(
1638 'code' => 'cantmove-anon',
1639 'info' => "Anonymous users can't move pages"
1641 'movenotallowed' => array(
1642 'code' => 'cantmove',
1643 'info' => "You don't have permission to move pages"
1645 'confirmedittext' => array(
1646 'code' => 'confirmemail',
1647 'info' => "You must confirm your email address before you can edit"
1649 'blockedtext' => array(
1650 'code' => 'blocked',
1651 'info' => "You have been blocked from editing"
1653 'autoblockedtext' => array(
1654 'code' => 'autoblocked',
1655 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1658 // Miscellaneous interface messages
1659 'actionthrottledtext' => array(
1660 'code' => 'ratelimited',
1661 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1663 'alreadyrolled' => array(
1664 'code' => 'alreadyrolled',
1665 'info' => "The page you tried to rollback was already rolled back"
1667 'cantrollback' => array(
1668 'code' => 'onlyauthor',
1669 'info' => "The page you tried to rollback only has one author"
1671 'readonlytext' => array(
1672 'code' => 'readonly',
1673 'info' => "The wiki is currently in read-only mode"
1675 'sessionfailure' => array(
1676 'code' => 'badtoken',
1677 'info' => "Invalid token" ),
1678 'cannotdelete' => array(
1679 'code' => 'cantdelete',
1680 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1682 'notanarticle' => array(
1683 'code' => 'missingtitle',
1684 'info' => "The page you requested doesn't exist"
1686 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1688 'immobile_namespace' => array(
1689 'code' => 'immobilenamespace',
1690 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1692 'articleexists' => array(
1693 'code' => 'articleexists',
1694 'info' => "The destination article already exists and is not a redirect to the source article"
1696 'protectedpage' => array(
1697 'code' => 'protectedpage',
1698 'info' => "You don't have permission to perform this move"
1700 'hookaborted' => array(
1701 'code' => 'hookaborted',
1702 'info' => "The modification you tried to make was aborted by an extension hook"
1704 'cantmove-titleprotected' => array(
1705 'code' => 'protectedtitle',
1706 'info' => "The destination article has been protected from creation"
1708 'imagenocrossnamespace' => array(
1709 'code' => 'nonfilenamespace',
1710 'info' => "Can't move a file to a non-file namespace"
1712 'imagetypemismatch' => array(
1713 'code' => 'filetypemismatch',
1714 'info' => "The new file extension doesn't match its type"
1716 // 'badarticleerror' => shouldn't happen
1717 // 'badtitletext' => shouldn't happen
1718 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1719 'range_block_disabled' => array(
1720 'code' => 'rangedisabled',
1721 'info' => "Blocking IP ranges has been disabled"
1723 'nosuchusershort' => array(
1724 'code' => 'nosuchuser',
1725 'info' => "The user you specified doesn't exist"
1727 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1728 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1729 'ipb_already_blocked' => array(
1730 'code' => 'alreadyblocked',
1731 'info' => "The user you tried to block was already blocked"
1733 'ipb_blocked_as_range' => array(
1734 'code' => 'blockedasrange',
1735 '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."
1737 'ipb_cant_unblock' => array(
1738 'code' => 'cantunblock',
1739 'info' => "The block you specified was not found. It may have been unblocked already"
1741 'mailnologin' => array(
1742 'code' => 'cantsend',
1743 '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"
1745 'ipbblocked' => array(
1746 'code' => 'ipbblocked',
1747 'info' => 'You cannot block or unblock users while you are yourself blocked'
1749 'ipbnounblockself' => array(
1750 'code' => 'ipbnounblockself',
1751 'info' => 'You are not allowed to unblock yourself'
1753 'usermaildisabled' => array(
1754 'code' => 'usermaildisabled',
1755 'info' => "User email has been disabled"
1757 'blockedemailuser' => array(
1758 'code' => 'blockedfrommail',
1759 'info' => "You have been blocked from sending email"
1761 'notarget' => array(
1762 'code' => 'notarget',
1763 'info' => "You have not specified a valid target for this action"
1766 'code' => 'noemail',
1767 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1769 'rcpatroldisabled' => array(
1770 'code' => 'patroldisabled',
1771 'info' => "Patrolling is disabled on this wiki"
1773 'markedaspatrollederror-noautopatrol' => array(
1774 'code' => 'noautopatrol',
1775 'info' => "You don't have permission to patrol your own changes"
1777 'delete-toobig' => array(
1778 'code' => 'bigdelete',
1779 'info' => "You can't delete this page because it has more than \$1 revisions"
1781 'movenotallowedfile' => array(
1782 'code' => 'cantmovefile',
1783 'info' => "You don't have permission to move files"
1785 'userrights-no-interwiki' => array(
1786 'code' => 'nointerwikiuserrights',
1787 'info' => "You don't have permission to change user rights on other wikis"
1789 'userrights-nodatabase' => array(
1790 'code' => 'nosuchdatabase',
1791 'info' => "Database \"\$1\" does not exist or is not local"
1793 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1794 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1795 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1796 'import-rootpage-invalid' => array(
1797 'code' => 'import-rootpage-invalid',
1798 'info' => 'Root page is an invalid title'
1800 'import-rootpage-nosubpage' => array(
1801 'code' => 'import-rootpage-nosubpage',
1802 'info' => 'Namespace "$1" of the root page does not allow subpages'
1805 // API-specific messages
1806 'readrequired' => array(
1807 'code' => 'readapidenied',
1808 'info' => "You need read permission to use this module"
1810 'writedisabled' => array(
1811 'code' => 'noapiwrite',
1812 '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"
1814 'writerequired' => array(
1815 'code' => 'writeapidenied',
1816 'info' => "You're not allowed to edit this wiki through the API"
1818 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1819 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1820 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1821 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1822 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1823 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1824 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1825 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1826 'create-titleexists' => array(
1827 'code' => 'create-titleexists',
1828 'info' => "Existing titles can't be protected with 'create'"
1830 'missingtitle-createonly' => array(
1831 'code' => 'missingtitle-createonly',
1832 'info' => "Missing titles can only be protected with 'create'"
1834 'cantblock' => array( 'code' => 'cantblock',
1835 'info' => "You don't have permission to block users"
1837 'canthide' => array(
1838 'code' => 'canthide',
1839 'info' => "You don't have permission to hide user names from the block log"
1841 'cantblock-email' => array(
1842 'code' => 'cantblock-email',
1843 'info' => "You don't have permission to block users from sending email through the wiki"
1845 'unblock-notarget' => array(
1846 'code' => 'notarget',
1847 'info' => "Either the id or the user parameter must be set"
1849 'unblock-idanduser' => array(
1850 'code' => 'idanduser',
1851 'info' => "The id and user parameters can't be used together"
1853 'cantunblock' => array(
1854 'code' => 'permissiondenied',
1855 'info' => "You don't have permission to unblock users"
1857 'cannotundelete' => array(
1858 'code' => 'cantundelete',
1859 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1861 'permdenied-undelete' => array(
1862 'code' => 'permissiondenied',
1863 'info' => "You don't have permission to restore deleted revisions"
1865 'createonly-exists' => array(
1866 'code' => 'articleexists',
1867 'info' => "The article you tried to create has been created already"
1869 'nocreate-missing' => array(
1870 'code' => 'missingtitle',
1871 'info' => "The article you tried to edit doesn't exist"
1873 'cantchangecontentmodel' => array(
1874 'code' => 'cantchangecontentmodel',
1875 'info' => "You don't have permission to change the content model of a page"
1877 'nosuchrcid' => array(
1878 'code' => 'nosuchrcid',
1879 'info' => "There is no change with rcid \"\$1\""
1881 'nosuchlogid' => array(
1882 'code' => 'nosuchlogid',
1883 'info' => "There is no log entry with ID \"\$1\""
1885 'protect-invalidaction' => array(
1886 'code' => 'protect-invalidaction',
1887 'info' => "Invalid protection type \"\$1\""
1889 'protect-invalidlevel' => array(
1890 'code' => 'protect-invalidlevel',
1891 'info' => "Invalid protection level \"\$1\""
1893 'toofewexpiries' => array(
1894 'code' => 'toofewexpiries',
1895 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1897 'cantimport' => array(
1898 'code' => 'cantimport',
1899 'info' => "You don't have permission to import pages"
1901 'cantimport-upload' => array(
1902 'code' => 'cantimport-upload',
1903 'info' => "You don't have permission to import uploaded pages"
1905 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1906 'importuploaderrorsize' => array(
1907 'code' => 'filetoobig',
1908 'info' => 'The file you uploaded is bigger than the maximum upload size'
1910 'importuploaderrorpartial' => array(
1911 'code' => 'partialupload',
1912 'info' => 'The file was only partially uploaded'
1914 'importuploaderrortemp' => array(
1915 'code' => 'notempdir',
1916 'info' => 'The temporary upload directory is missing'
1918 'importcantopen' => array(
1919 'code' => 'cantopenfile',
1920 'info' => "Couldn't open the uploaded file"
1922 'import-noarticle' => array(
1923 'code' => 'badinterwiki',
1924 'info' => 'Invalid interwiki title specified'
1926 'importbadinterwiki' => array(
1927 'code' => 'badinterwiki',
1928 'info' => 'Invalid interwiki title specified'
1930 'import-unknownerror' => array(
1931 'code' => 'import-unknownerror',
1932 'info' => "Unknown error on import: \"\$1\""
1934 'cantoverwrite-sharedfile' => array(
1935 'code' => 'cantoverwrite-sharedfile',
1936 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1938 'sharedfile-exists' => array(
1939 'code' => 'fileexists-sharedrepo-perm',
1940 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1942 'mustbeposted' => array(
1943 'code' => 'mustbeposted',
1944 'info' => "The \$1 module requires a POST request"
1948 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1950 'specialpage-cantexecute' => array(
1951 'code' => 'specialpage-cantexecute',
1952 'info' => "You don't have permission to view the results of this special page"
1954 'invalidoldimage' => array(
1955 'code' => 'invalidoldimage',
1956 'info' => 'The oldimage parameter has invalid format'
1958 'nodeleteablefile' => array(
1959 'code' => 'nodeleteablefile',
1960 'info' => 'No such old version of the file'
1962 'fileexists-forbidden' => array(
1963 'code' => 'fileexists-forbidden',
1964 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1966 'fileexists-shared-forbidden' => array(
1967 'code' => 'fileexists-shared-forbidden',
1968 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1970 'filerevert-badversion' => array(
1971 'code' => 'filerevert-badversion',
1972 'info' => 'There is no previous local version of this file with the provided timestamp.'
1975 // ApiEditPage messages
1976 'noimageredirect-anon' => array(
1977 'code' => 'noimageredirect-anon',
1978 'info' => "Anonymous users can't create image redirects"
1980 'noimageredirect-logged' => array(
1981 'code' => 'noimageredirect',
1982 'info' => "You don't have permission to create image redirects"
1984 'spamdetected' => array(
1985 'code' => 'spamdetected',
1986 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1988 'contenttoobig' => array(
1989 'code' => 'contenttoobig',
1990 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1992 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1993 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1994 'wasdeleted' => array(
1995 'code' => 'pagedeleted',
1996 'info' => "The page has been deleted since you fetched its timestamp"
1998 'blankpage' => array(
1999 'code' => 'emptypage',
2000 'info' => "Creating new, empty pages is not allowed"
2002 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
2003 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
2004 'missingtext' => array(
2006 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
2008 'emptynewsection' => array(
2009 'code' => 'emptynewsection',
2010 'info' => 'Creating empty new sections is not possible.'
2012 'revwrongpage' => array(
2013 'code' => 'revwrongpage',
2014 'info' => "r\$1 is not a revision of \"\$2\""
2016 'undo-failure' => array(
2017 'code' => 'undofailure',
2018 'info' => 'Undo failed due to conflicting intermediate edits'
2020 'content-not-allowed-here' => array(
2021 'code' => 'contentnotallowedhere',
2022 'info' => 'Content model "$1" is not allowed at title "$2"'
2025 // Messages from WikiPage::doEit()
2026 'edit-hook-aborted' => array(
2027 'code' => 'edit-hook-aborted',
2028 'info' => "Your edit was aborted by an ArticleSave hook"
2030 'edit-gone-missing' => array(
2031 'code' => 'edit-gone-missing',
2032 'info' => "The page you tried to edit doesn't seem to exist anymore"
2034 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
2035 'edit-already-exists' => array(
2036 'code' => 'edit-already-exists',
2037 'info' => 'It seems the page you tried to create already exist'
2041 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
2042 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
2043 'uploaddisabled' => array(
2044 'code' => 'uploaddisabled',
2045 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2047 'copyuploaddisabled' => array(
2048 'code' => 'copyuploaddisabled',
2049 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2051 'copyuploadbaddomain' => array(
2052 'code' => 'copyuploadbaddomain',
2053 'info' => 'Uploads by URL are not allowed from this domain.'
2055 'copyuploadbadurl' => array(
2056 'code' => 'copyuploadbadurl',
2057 'info' => 'Upload not allowed from this URL.'
2060 'filename-tooshort' => array(
2061 'code' => 'filename-tooshort',
2062 'info' => 'The filename is too short'
2064 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
2065 'illegal-filename' => array(
2066 'code' => 'illegal-filename',
2067 'info' => 'The filename is not allowed'
2069 'filetype-missing' => array(
2070 'code' => 'filetype-missing',
2071 'info' => 'The file is missing an extension'
2074 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
2076 // @codingStandardsIgnoreEnd
2079 * Helper function for readonly errors
2081 * @throws UsageException always
2083 public function dieReadOnly() {
2084 $parsed = $this->parseMsg( array( 'readonlytext' ) );
2085 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2086 array( 'readonlyreason' => wfReadOnlyReason() ) );
2090 * Output the error message related to a certain array
2091 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2092 * @throws UsageException always
2094 public function dieUsageMsg( $error ) {
2095 # most of the time we send a 1 element, so we might as well send it as
2096 # a string and make this an array here.
2097 if ( is_string( $error ) ) {
2098 $error = array( $error );
2100 $parsed = $this->parseMsg( $error );
2101 $extraData = isset( $parsed['data'] ) ?
$parsed['data'] : null;
2102 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2106 * Will only set a warning instead of failing if the global $wgDebugAPI
2107 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2108 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2109 * @throws UsageException
2112 public function dieUsageMsgOrDebug( $error ) {
2113 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2114 $this->dieUsageMsg( $error );
2117 if ( is_string( $error ) ) {
2118 $error = array( $error );
2120 $parsed = $this->parseMsg( $error );
2121 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2125 * Die with the $prefix.'badcontinue' error. This call is common enough to
2126 * make it into the base method.
2127 * @param bool $condition Will only die if this value is true
2128 * @throws UsageException
2131 protected function dieContinueUsageIf( $condition ) {
2134 'Invalid continue param. You should pass the original value returned by the previous query',
2140 * Return the error message related to a certain array
2141 * @param array $error Element of a getUserPermissionsErrors()-style array
2142 * @return array('code' => code, 'info' => info)
2144 public function parseMsg( $error ) {
2145 $error = (array)$error; // It seems strings sometimes make their way in here
2146 $key = array_shift( $error );
2148 // Check whether the error array was nested
2149 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2150 if ( is_array( $key ) ) {
2152 $key = array_shift( $error );
2155 if ( $key instanceof IApiMessage
) {
2157 'code' => $key->getApiCode(),
2158 'info' => $key->inLanguage( 'en' )->useDatabase( false )->text(),
2159 'data' => $key->getApiData()
2163 if ( isset( self
::$messageMap[$key] ) ) {
2165 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
2166 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
2170 // If the key isn't present, throw an "unknown error"
2171 return $this->parseMsg( array( 'unknownerror', $key ) );
2175 * Internal code errors should be reported with this method
2176 * @param string $method Method or function name
2177 * @param string $message Error message
2178 * @throws MWException always
2180 protected static function dieDebug( $method, $message ) {
2181 throw new MWException( "Internal error in $method: $message" );
2185 * Write logging information for API features to a debug log, for usage
2187 * @param string $feature Feature being used.
2189 protected function logFeatureUsage( $feature ) {
2190 $request = $this->getRequest();
2191 $s = '"' . addslashes( $feature ) . '"' .
2192 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2193 ' "' . $request->getIP() . '"' .
2194 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2195 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2196 wfDebugLog( 'api-feature-usage', $s, 'private' );
2201 /************************************************************************//**
2202 * @name Help message generation
2207 * Return the description message.
2209 * @return string|array|Message
2211 protected function getDescriptionMessage() {
2212 return "apihelp-{$this->getModulePath()}-description";
2216 * Get final module description, after hooks have had a chance to tweak it as
2219 * @since 1.25, returns Message[] rather than string[]
2222 public function getFinalDescription() {
2223 $desc = $this->getDescription();
2224 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2225 $desc = self
::escapeWikiText( $desc );
2226 if ( is_array( $desc ) ) {
2227 $desc = join( "\n", $desc );
2229 $desc = (string)$desc;
2232 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2233 $this->getModulePrefix(),
2234 $this->getModuleName(),
2235 $this->getModulePath(),
2237 if ( !$msg->exists() ) {
2238 $msg = $this->msg( 'api-help-fallback-description', $desc );
2240 $msgs = array( $msg );
2242 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2248 * Get final list of parameters, after hooks have had a chance to
2249 * tweak it as needed.
2251 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2252 * @return array|bool False on no parameters
2253 * @since 1.21 $flags param added
2255 public function getFinalParams( $flags = 0 ) {
2256 $params = $this->getAllowedParams( $flags );
2261 if ( $this->needsToken() ) {
2262 $params['token'] = array(
2263 ApiBase
::PARAM_TYPE
=> 'string',
2264 ApiBase
::PARAM_REQUIRED
=> true,
2265 ApiBase
::PARAM_HELP_MSG
=> array(
2266 'api-help-param-token',
2267 $this->needsToken(),
2269 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2272 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2278 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2281 * @since 1.25, returns array of Message[] rather than array of string[]
2282 * @return array Keys are parameter names, values are arrays of Message objects
2284 public function getFinalParamDescription() {
2285 $prefix = $this->getModulePrefix();
2286 $name = $this->getModuleName();
2287 $path = $this->getModulePath();
2289 $desc = $this->getParamDescription();
2290 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2295 $desc = self
::escapeWikiText( $desc );
2297 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2299 foreach ( $params as $param => $settings ) {
2300 if ( !is_array( $settings ) ) {
2301 $settings = array();
2304 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2305 if ( is_array( $d ) ) {
2306 // Special handling for prop parameters
2307 $d = array_map( function ( $line ) {
2308 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2309 $line = "\n;{$m[1]}:{$m[2]}";
2313 $d = join( ' ', $d );
2316 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2317 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2319 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2320 if ( !$msg->exists() ) {
2321 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2324 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2325 array( $prefix, $param, $name, $path ) );
2327 $this->dieDebug( __METHOD__
,
2328 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2330 $msgs[$param] = array( $msg );
2332 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2333 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2334 $this->dieDebug( __METHOD__
,
2335 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2337 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2338 $this->dieDebug( __METHOD__
,
2339 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2340 'ApiBase::PARAM_TYPE is an array' );
2343 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2344 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2345 if ( isset( $valueMsgs[$value] ) ) {
2346 $msg = $valueMsgs[$value];
2348 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2350 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2351 array( $prefix, $param, $name, $path, $value ) );
2353 $m = new ApiHelpParamValueMessage(
2355 array( $m->getKey(), 'api-help-param-no-description' ),
2358 $msgs[$param][] = $m->setContext( $this->getContext() );
2360 $this->dieDebug( __METHOD__
,
2361 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2366 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2367 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2368 $this->dieDebug( __METHOD__
,
2369 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2371 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2372 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2373 array( $prefix, $param, $name, $path ) );
2375 $msgs[$param][] = $m;
2377 $this->dieDebug( __METHOD__
,
2378 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2384 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2390 * Generates the list of flags for the help screen and for action=paraminfo
2392 * Corresponding messages: api-help-flag-deprecated,
2393 * api-help-flag-internal, api-help-flag-readrights,
2394 * api-help-flag-writerights, api-help-flag-mustbeposted
2398 protected function getHelpFlags() {
2401 if ( $this->isDeprecated() ) {
2402 $flags[] = 'deprecated';
2404 if ( $this->isInternal() ) {
2405 $flags[] = 'internal';
2407 if ( $this->isReadMode() ) {
2408 $flags[] = 'readrights';
2410 if ( $this->isWriteMode() ) {
2411 $flags[] = 'writerights';
2413 if ( $this->mustBePosted() ) {
2414 $flags[] = 'mustbeposted';
2421 * Returns information about the source of this module, if known
2423 * Returned array is an array with the following keys:
2424 * - path: Install path
2425 * - name: Extension name, or "MediaWiki" for core
2426 * - namemsg: (optional) i18n message key for a display name
2427 * - license-name: (optional) Name of license
2429 * @return array|null
2431 protected function getModuleSourceInfo() {
2434 if ( $this->mModuleSource
!== false ) {
2435 return $this->mModuleSource
;
2438 // First, try to find where the module comes from...
2439 $rClass = new ReflectionClass( $this );
2440 $path = $rClass->getFileName();
2443 $this->mModuleSource
= null;
2446 $path = realpath( $path ) ?
: $path;
2448 // Build map of extension directories to extension info
2449 if ( self
::$extensionInfo === null ) {
2450 self
::$extensionInfo = array(
2451 realpath( __DIR__
) ?
: __DIR__
=> array(
2453 'name' => 'MediaWiki',
2454 'license-name' => 'GPL-2.0+',
2456 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2462 'license-name' => null,
2464 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2465 foreach ( $group as $ext ) {
2466 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2467 // This shouldn't happen, but does anyway.
2471 $extpath = $ext['path'];
2472 if ( !is_dir( $extpath ) ) {
2473 $extpath = dirname( $extpath );
2475 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2476 array_intersect_key( $ext, $keep );
2479 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2480 $extpath = $ext['path'];
2481 if ( !is_dir( $extpath ) ) {
2482 $extpath = dirname( $extpath );
2484 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2485 array_intersect_key( $ext, $keep );
2489 // Now traverse parent directories until we find a match or run out of
2492 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2494 $this->mModuleSource
= self
::$extensionInfo[$path];
2495 return $this->mModuleSource
;
2499 $path = dirname( $path );
2500 } while ( $path !== $oldpath );
2502 // No idea what extension this might be.
2503 $this->mModuleSource
= null;
2508 * Called from ApiHelp before the pieces are joined together and returned.
2510 * This exists mainly for ApiMain to add the Permissions and Credits
2511 * sections. Other modules probably don't need it.
2513 * @param string[] &$help Array of help data
2514 * @param array $options Options passed to ApiHelp::getHelp
2515 * @param array &$tocData If a TOC is being generated, this array has keys
2516 * as anchors in the page and values as for Linker::generateTOC().
2518 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2523 /************************************************************************//**
2528 /// @deprecated since 1.24
2529 const PROP_ROOT
= 'ROOT';
2530 /// @deprecated since 1.24
2531 const PROP_LIST
= 'LIST';
2532 /// @deprecated since 1.24
2533 const PROP_TYPE
= 0;
2534 /// @deprecated since 1.24
2535 const PROP_NULLABLE
= 1;
2538 * Formerly used to fetch a list of possible properites in the result,
2539 * somehow organized with respect to the prop parameter that causes them to
2540 * be returned. The specific semantics of the return value was never
2541 * specified. Since this was never possible to be accurately updated, it
2544 * @deprecated since 1.24
2545 * @return array|bool
2547 protected function getResultProperties() {
2548 wfDeprecated( __METHOD__
, '1.24' );
2553 * @see self::getResultProperties()
2554 * @deprecated since 1.24
2555 * @return array|bool
2557 public function getFinalResultProperties() {
2558 wfDeprecated( __METHOD__
, '1.24' );
2563 * @see self::getResultProperties()
2564 * @deprecated since 1.24
2566 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2567 wfDeprecated( __METHOD__
, '1.24' );
2571 * @see self::getPossibleErrors()
2572 * @deprecated since 1.24
2575 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2576 wfDeprecated( __METHOD__
, '1.24' );
2581 * @see self::getPossibleErrors()
2582 * @deprecated since 1.24
2585 public function getRequireMaxOneParameterErrorMessages( $params ) {
2586 wfDeprecated( __METHOD__
, '1.24' );
2591 * @see self::getPossibleErrors()
2592 * @deprecated since 1.24
2595 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2596 wfDeprecated( __METHOD__
, '1.24' );
2601 * @see self::getPossibleErrors()
2602 * @deprecated since 1.24
2605 public function getTitleOrPageIdErrorMessage() {
2606 wfDeprecated( __METHOD__
, '1.24' );
2611 * This formerly attempted to return a list of all possible errors returned
2612 * by the module. However, this was impossible to maintain in many cases
2613 * since errors could come from other areas of MediaWiki and in some cases
2614 * from arbitrary extension hooks. Since a partial list claiming to be
2615 * comprehensive is unlikely to be useful, it was removed.
2617 * @deprecated since 1.24
2620 public function getPossibleErrors() {
2621 wfDeprecated( __METHOD__
, '1.24' );
2626 * @see self::getPossibleErrors()
2627 * @deprecated since 1.24
2630 public function getFinalPossibleErrors() {
2631 wfDeprecated( __METHOD__
, '1.24' );
2636 * @see self::getPossibleErrors()
2637 * @deprecated since 1.24
2640 public function parseErrors( $errors ) {
2641 wfDeprecated( __METHOD__
, '1.24' );
2646 * Returns the description string for this module
2648 * Ignored if an i18n message exists for
2649 * "apihelp-{$this->getModulePath()}-description".
2651 * @deprecated since 1.25
2652 * @return Message|string|array
2654 protected function getDescription() {
2659 * Returns an array of parameter descriptions.
2661 * For each parameter, ignored if an i18n message exists for the parameter.
2662 * By default that message is
2663 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2664 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2665 * self::getFinalParams().
2667 * @deprecated since 1.25
2668 * @return array|bool False on no parameter descriptions
2670 protected function getParamDescription() {
2675 * Returns usage examples for this module.
2677 * Return value as an array is either:
2678 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2680 * - sequential numeric keys with even-numbered keys being display-text
2681 * and odd-numbered keys being partial urls
2682 * - partial URLs as keys with display-text (string or array-to-be-joined)
2684 * Return value as a string is the same as an array with a numeric key and
2685 * that value, and boolean false means "no examples".
2687 * @deprecated since 1.25, use getExamplesMessages() instead
2688 * @return bool|string|array
2690 protected function getExamples() {
2695 * Generates help message for this module, or false if there is no description
2696 * @deprecated since 1.25
2697 * @return string|bool
2699 public function makeHelpMsg() {
2700 wfDeprecated( __METHOD__
, '1.25' );
2701 static $lnPrfx = "\n ";
2703 $msg = $this->getFinalDescription();
2705 if ( $msg !== false ) {
2707 if ( !is_array( $msg ) ) {
2712 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2714 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2716 if ( $this->isReadMode() ) {
2717 $msg .= "\nThis module requires read rights";
2719 if ( $this->isWriteMode() ) {
2720 $msg .= "\nThis module requires write rights";
2722 if ( $this->mustBePosted() ) {
2723 $msg .= "\nThis module only accepts POST requests";
2725 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2726 $this->mustBePosted()
2732 $paramsMsg = $this->makeHelpMsgParameters();
2733 if ( $paramsMsg !== false ) {
2734 $msg .= "Parameters:\n$paramsMsg";
2737 $examples = $this->getExamples();
2739 if ( !is_array( $examples ) ) {
2744 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2745 foreach ( $examples as $k => $v ) {
2746 if ( is_numeric( $k ) ) {
2749 if ( is_array( $v ) ) {
2750 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2752 $msgExample = " $v";
2755 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2765 * @deprecated since 1.25
2766 * @param string $item
2769 private function indentExampleText( $item ) {
2774 * @deprecated since 1.25
2775 * @param string $prefix Text to split output items
2776 * @param string $title What is being output
2777 * @param string|array $input
2780 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2781 wfDeprecated( __METHOD__
, '1.25' );
2782 if ( $input === false ) {
2785 if ( !is_array( $input ) ) {
2786 $input = array( $input );
2789 if ( count( $input ) > 0 ) {
2791 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2795 $msg .= implode( $prefix, $input ) . "\n";
2804 * Generates the parameter descriptions for this module, to be displayed in the
2806 * @deprecated since 1.25
2807 * @return string|bool
2809 public function makeHelpMsgParameters() {
2810 wfDeprecated( __METHOD__
, '1.25' );
2811 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2813 $paramsDescription = $this->getFinalParamDescription();
2815 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2816 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2817 foreach ( $params as $paramName => $paramSettings ) {
2818 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2819 if ( is_array( $desc ) ) {
2820 $desc = implode( $paramPrefix, $desc );
2824 if ( !is_array( $paramSettings ) ) {
2825 $paramSettings = array(
2826 self
::PARAM_DFLT
=> $paramSettings,
2830 // handle missing type
2831 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2832 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2833 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2835 if ( is_bool( $dflt ) ) {
2836 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2837 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2838 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2839 } elseif ( is_int( $dflt ) ) {
2840 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2844 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2845 && $paramSettings[self
::PARAM_DEPRECATED
]
2847 $desc = "DEPRECATED! $desc";
2850 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2851 && $paramSettings[self
::PARAM_REQUIRED
]
2853 $desc .= $paramPrefix . "This parameter is required";
2856 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2857 ?
$paramSettings[self
::PARAM_TYPE
]
2859 if ( isset( $type ) ) {
2860 $hintPipeSeparated = true;
2861 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2862 ?
$paramSettings[self
::PARAM_ISMULTI
]
2865 $prompt = 'Values (separate with \'|\'): ';
2867 $prompt = 'One value: ';
2870 if ( $type === 'submodule' ) {
2871 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2872 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
2874 $type = $this->getModuleManager()->getNames( $paramName );
2878 if ( is_array( $type ) ) {
2880 $nothingPrompt = '';
2881 foreach ( $type as $t ) {
2883 $nothingPrompt = 'Can be empty, or ';
2888 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2889 $choicesstring = implode( ', ', $choices );
2890 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2891 $hintPipeSeparated = false;
2895 // Special handling because namespaces are
2896 // type-limited, yet they are not given
2897 $desc .= $paramPrefix . $prompt;
2898 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2899 100, $descWordwrap );
2900 $hintPipeSeparated = false;
2903 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2904 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2905 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2907 $desc .= ' allowed';
2910 $s = $multi ?
's' : '';
2911 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2912 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2913 if ( $hasMin ||
$hasMax ) {
2915 $intRangeStr = "The value$s must be no less than " .
2916 "{$paramSettings[self::PARAM_MIN]}";
2917 } elseif ( !$hasMin ) {
2918 $intRangeStr = "The value$s must be no more than " .
2919 "{$paramSettings[self::PARAM_MAX]}";
2921 $intRangeStr = "The value$s must be between " .
2922 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2925 $desc .= $paramPrefix . $intRangeStr;
2929 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2935 if ( $hintPipeSeparated ) {
2936 $desc .= $paramPrefix . "Separate values with '|'";
2939 $isArray = is_array( $type );
2941 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2943 $desc .= $paramPrefix . "Maximum number of values " .
2944 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2949 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2950 if ( !is_null( $default ) && $default !== false ) {
2951 $desc .= $paramPrefix . "Default: $default";
2954 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2964 * @deprecated since 1.25, always returns empty string
2965 * @param IDatabase|bool $db
2968 public function getModuleProfileName( $db = false ) {
2969 wfDeprecated( __METHOD__
, '1.25' );
2974 * @deprecated since 1.25
2976 public function profileIn() {
2977 // No wfDeprecated() yet because extensions call this and might need to
2978 // keep doing so for BC.
2982 * @deprecated since 1.25
2984 public function profileOut() {
2985 // No wfDeprecated() yet because extensions call this and might need to
2986 // keep doing so for BC.
2990 * @deprecated since 1.25
2992 public function safeProfileOut() {
2993 wfDeprecated( __METHOD__
, '1.25' );
2997 * @deprecated since 1.25, always returns 0
3000 public function getProfileTime() {
3001 wfDeprecated( __METHOD__
, '1.25' );
3006 * @deprecated since 1.25
3008 public function profileDBIn() {
3009 wfDeprecated( __METHOD__
, '1.25' );
3013 * @deprecated since 1.25
3015 public function profileDBOut() {
3016 wfDeprecated( __METHOD__
, '1.25' );
3020 * @deprecated since 1.25, always returns 0
3023 public function getProfileDBTime() {
3024 wfDeprecated( __METHOD__
, '1.25' );
3029 * Get the result data array (read-only)
3030 * @deprecated since 1.25, use $this->getResult() methods instead
3033 public function getResultData() {
3034 wfDeprecated( __METHOD__
, '1.25' );
3035 return $this->getResult()->getData();
3039 * Call wfTransactionalTimeLimit() if this request was POSTed
3042 protected function useTransactionalTimeLimit() {
3043 if ( $this->getRequest()->wasPosted() ) {
3044 wfTransactionalTimeLimit();
3052 * For really cool vim folding this needs to be at the end:
3053 * vim: foldmarker=@{,@} foldmethod=marker