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
27 use Wikimedia\Rdbms\IDatabase
;
30 * This abstract class implements many basic API functions, and is the base of
32 * The class functions are divided into several areas of functionality:
34 * Module parameters: Derived classes can define getAllowedParams() to specify
35 * which parameters to expect, how to parse and validate them.
37 * Self-documentation: code to allow the API to document its own state
41 abstract class ApiBase
extends ContextSource
{
44 * @name Constants for ::getAllowedParams() arrays
45 * These constants are keys in the arrays returned by ::getAllowedParams()
46 * and accepted by ::getParameterFromSettings() that define how the
47 * parameters coming in from the request are to be interpreted.
51 /** (null|boolean|integer|string) Default value of the parameter. */
54 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
55 const PARAM_ISMULTI
= 1;
58 * (string|string[]) Either an array of allowed value strings, or a string
59 * type as described below. If not specified, will be determined from the
62 * Supported string types are:
63 * - boolean: A boolean parameter, returned as false if the parameter is
64 * omitted and true if present (even with a falsey value, i.e. it works
65 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
66 * Cannot be used with PARAM_ISMULTI.
67 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
68 * PARAM_RANGE_ENFORCE.
69 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
70 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
71 * specified. Cannot be used with PARAM_ISMULTI.
72 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
73 * support easily specifying all namespaces.
75 * - password: Any non-empty string. Input value is private or sensitive.
76 * <input type="password"> would be an appropriate HTML form field.
77 * - string: Any non-empty string, not expected to be very long or contain newlines.
78 * <input type="text"> would be an appropriate HTML form field.
79 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
80 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
81 * used with PARAM_ISMULTI.
82 * - text: Any non-empty string, expected to be very long or contain newlines.
83 * <textarea> would be an appropriate HTML form field.
84 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
85 * string 'now' representing the current timestamp. Will be returned in
87 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
88 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
89 * Cannot be used with PARAM_ISMULTI.
93 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
97 * (integer) Max value allowed for the parameter for users with the
98 * apihighlimits right, for PARAM_TYPE 'limit'.
100 const PARAM_MAX2
= 4;
102 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
105 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
106 const PARAM_ALLOW_DUPLICATES
= 6;
108 /** (boolean) Is the parameter deprecated (will show a warning)? */
109 const PARAM_DEPRECATED
= 7;
112 * (boolean) Is the parameter required?
115 const PARAM_REQUIRED
= 8;
118 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
121 const PARAM_RANGE_ENFORCE
= 9;
124 * (string|array|Message) Specify an alternative i18n documentation message
125 * for this parameter. Default is apihelp-{$path}-param-{$param}.
128 const PARAM_HELP_MSG
= 10;
131 * ((string|array|Message)[]) Specify additional i18n messages to append to
132 * the normal message for this parameter.
135 const PARAM_HELP_MSG_APPEND
= 11;
138 * (array) Specify additional information tags for the parameter. Value is
139 * an array of arrays, with the first member being the 'tag' for the info
140 * and the remaining members being the values. In the help, this is
141 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
142 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
145 const PARAM_HELP_MSG_INFO
= 12;
148 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
149 * those values to page titles which will be linked in the help.
152 const PARAM_VALUE_LINKS
= 13;
155 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
156 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
157 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
160 const PARAM_HELP_MSG_PER_VALUE
= 14;
163 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
164 * submodule paths. Default is to use all modules in
165 * $this->getModuleManager() in the group matching the parameter name.
168 const PARAM_SUBMODULE_MAP
= 15;
171 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
172 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
175 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
178 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
179 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
180 * every possible value. If a string is set, it will be used in place of the asterisk.
183 const PARAM_ALL
= 17;
186 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
189 const PARAM_EXTRA_NAMESPACES
= 18;
192 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
193 * always sensitive regardless of the value of this field.
196 const PARAM_SENSITIVE
= 19;
200 const ALL_DEFAULT_STRING
= '*';
202 /** Fast query, standard limit. */
203 const LIMIT_BIG1
= 500;
204 /** Fast query, apihighlimits limit. */
205 const LIMIT_BIG2
= 5000;
206 /** Slow query, standard limit. */
207 const LIMIT_SML1
= 50;
208 /** Slow query, apihighlimits limit. */
209 const LIMIT_SML2
= 500;
212 * getAllowedParams() flag: When set, the result could take longer to generate,
213 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
216 const GET_VALUES_FOR_HELP
= 1;
218 /** @var array Maps extension paths to info arrays */
219 private static $extensionInfo = null;
222 private $mMainModule;
224 private $mModuleName, $mModulePrefix;
225 private $mSlaveDB = null;
226 private $mParamCache = [];
227 /** @var array|null|bool */
228 private $mModuleSource = false;
231 * @param ApiMain $mainModule
232 * @param string $moduleName Name of this module
233 * @param string $modulePrefix Prefix to use for parameter names
235 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
236 $this->mMainModule
= $mainModule;
237 $this->mModuleName
= $moduleName;
238 $this->mModulePrefix
= $modulePrefix;
240 if ( !$this->isMain() ) {
241 $this->setContext( $mainModule->getContext() );
245 /************************************************************************//**
246 * @name Methods to implement
251 * Evaluates the parameters, performs the requested query, and sets up
252 * the result. Concrete implementations of ApiBase must override this
253 * method to provide whatever functionality their module offers.
254 * Implementations must not produce any output on their own and are not
255 * expected to handle any errors.
257 * The execute() method will be invoked directly by ApiMain immediately
258 * before the result of the module is output. Aside from the
259 * constructor, implementations should assume that no other methods
260 * will be called externally on the module before the result is
263 * The result data should be stored in the ApiResult object available
264 * through getResult().
266 abstract public function execute();
269 * Get the module manager, or null if this module has no sub-modules
271 * @return ApiModuleManager
273 public function getModuleManager() {
278 * If the module may only be used with a certain format module,
279 * it should override this method to return an instance of that formatter.
280 * A value of null means the default format will be used.
281 * @note Do not use this just because you don't want to support non-json
282 * formats. This should be used only when there is a fundamental
283 * requirement for a specific format.
284 * @return mixed Instance of a derived class of ApiFormatBase, or null
286 public function getCustomPrinter() {
291 * Returns usage examples for this module.
293 * Return value has query strings as keys, with values being either strings
294 * (message key), arrays (message key + parameter), or Message objects.
296 * Do not call this base class implementation when overriding this method.
301 protected function getExamplesMessages() {
302 // Fall back to old non-localised method
305 $examples = $this->getExamples();
307 if ( !is_array( $examples ) ) {
308 $examples = [ $examples ];
309 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
310 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
311 !preg_match( '/^\s*api\.php\?/', $examples[0] )
313 // Fix up the ugly "even numbered elements are description, odd
314 // numbered elemts are the link" format (see doc for self::getExamples)
316 $examplesCount = count( $examples );
317 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
318 $tmp[$examples[$i +
1]] = $examples[$i];
323 foreach ( $examples as $k => $v ) {
324 if ( is_numeric( $k ) ) {
329 $msg = self
::escapeWikiText( $v );
330 if ( is_array( $msg ) ) {
331 $msg = implode( ' ', $msg );
335 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
336 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
344 * Return links to more detailed help pages about the module.
345 * @since 1.25, returning boolean false is deprecated
346 * @return string|array
348 public function getHelpUrls() {
353 * Returns an array of allowed parameters (parameter name) => (default
354 * value) or (parameter name) => (array with PARAM_* constants as keys)
355 * Don't call this function directly: use getFinalParams() to allow
356 * hooks to modify parameters as needed.
358 * Some derived classes may choose to handle an integer $flags parameter
359 * in the overriding methods. Callers of this method can pass zero or
360 * more OR-ed flags like GET_VALUES_FOR_HELP.
364 protected function getAllowedParams( /* $flags = 0 */ ) {
365 // int $flags is not declared because it causes "Strict standards"
366 // warning. Most derived classes do not implement it.
371 * Indicates if this module needs maxlag to be checked
374 public function shouldCheckMaxlag() {
379 * Indicates whether this module requires read rights
382 public function isReadMode() {
387 * Indicates whether this module requires write mode
390 public function isWriteMode() {
395 * Indicates whether this module must be called with a POST request
398 public function mustBePosted() {
399 return $this->needsToken() !== false;
403 * Indicates whether this module is deprecated
407 public function isDeprecated() {
412 * Indicates whether this module is "internal"
413 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
417 public function isInternal() {
422 * Returns the token type this module requires in order to execute.
424 * Modules are strongly encouraged to use the core 'csrf' type unless they
425 * have specialized security needs. If the token type is not one of the
426 * core types, you must use the ApiQueryTokensRegisterTypes hook to
429 * Returning a non-falsey value here will force the addition of an
430 * appropriate 'token' parameter in self::getFinalParams(). Also,
431 * self::mustBePosted() must return true when tokens are used.
433 * In previous versions of MediaWiki, true was a valid return value.
434 * Returning true will generate errors indicating that the API module needs
437 * @return string|false
439 public function needsToken() {
444 * Fetch the salt used in the Web UI corresponding to this module.
446 * Only override this if the Web UI uses a token with a non-constant salt.
449 * @param array $params All supplied parameters for the module
450 * @return string|array|null
452 protected function getWebUITokenSalt( array $params ) {
457 * Returns data for HTTP conditional request mechanisms.
460 * @param string $condition Condition being queried:
461 * - last-modified: Return a timestamp representing the maximum of the
462 * last-modified dates for all resources involved in the request. See
463 * RFC 7232 § 2.2 for semantics.
464 * - etag: Return an entity-tag representing the state of all resources involved
465 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
466 * @return string|bool|null As described above, or null if no value is available.
468 public function getConditionalRequestData( $condition ) {
474 /************************************************************************//**
475 * @name Data access methods
480 * Get the name of the module being executed by this instance
483 public function getModuleName() {
484 return $this->mModuleName
;
488 * Get parameter prefix (usually two letters or an empty string).
491 public function getModulePrefix() {
492 return $this->mModulePrefix
;
496 * Get the main module
499 public function getMain() {
500 return $this->mMainModule
;
504 * Returns true if this module is the main module ($this === $this->mMainModule),
508 public function isMain() {
509 return $this === $this->mMainModule
;
513 * Get the parent of this module
515 * @return ApiBase|null
517 public function getParent() {
518 return $this->isMain() ?
null : $this->getMain();
522 * Returns true if the current request breaks the same-origin policy.
524 * For example, json with callbacks.
526 * https://en.wikipedia.org/wiki/Same-origin_policy
531 public function lacksSameOriginSecurity() {
532 // Main module has this method overridden
533 // Safety - avoid infinite loop:
534 if ( $this->isMain() ) {
535 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
538 return $this->getMain()->lacksSameOriginSecurity();
542 * Get the path to this module
547 public function getModulePath() {
548 if ( $this->isMain() ) {
550 } elseif ( $this->getParent()->isMain() ) {
551 return $this->getModuleName();
553 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
558 * Get a module from its module path
561 * @param string $path
562 * @return ApiBase|null
563 * @throws ApiUsageException
565 public function getModuleFromPath( $path ) {
566 $module = $this->getMain();
567 if ( $path === 'main' ) {
571 $parts = explode( '+', $path );
572 if ( count( $parts ) === 1 ) {
573 // In case the '+' was typed into URL, it resolves as a space
574 $parts = explode( ' ', $path );
577 $count = count( $parts );
578 for ( $i = 0; $i < $count; $i++
) {
580 $manager = $parent->getModuleManager();
581 if ( $manager === null ) {
582 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
583 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
585 $module = $manager->getModule( $parts[$i] );
587 if ( $module === null ) {
588 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
590 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
600 * Get the result object
603 public function getResult() {
604 // Main module has getResult() method overridden
605 // Safety - avoid infinite loop:
606 if ( $this->isMain() ) {
607 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
610 return $this->getMain()->getResult();
614 * Get the error formatter
615 * @return ApiErrorFormatter
617 public function getErrorFormatter() {
618 // Main module has getErrorFormatter() method overridden
619 // Safety - avoid infinite loop:
620 if ( $this->isMain() ) {
621 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
624 return $this->getMain()->getErrorFormatter();
628 * Gets a default replica DB connection object
631 protected function getDB() {
632 if ( !isset( $this->mSlaveDB
) ) {
633 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
636 return $this->mSlaveDB
;
640 * Get the continuation manager
641 * @return ApiContinuationManager|null
643 public function getContinuationManager() {
644 // Main module has getContinuationManager() method overridden
645 // Safety - avoid infinite loop:
646 if ( $this->isMain() ) {
647 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
650 return $this->getMain()->getContinuationManager();
654 * Set the continuation manager
655 * @param ApiContinuationManager|null
657 public function setContinuationManager( $manager ) {
658 // Main module has setContinuationManager() method overridden
659 // Safety - avoid infinite loop:
660 if ( $this->isMain() ) {
661 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
664 $this->getMain()->setContinuationManager( $manager );
669 /************************************************************************//**
670 * @name Parameter handling
675 * Indicate if the module supports dynamically-determined parameters that
676 * cannot be included in self::getAllowedParams().
677 * @return string|array|Message|null Return null if the module does not
678 * support additional dynamic parameters, otherwise return a message
681 public function dynamicParameterDocumentation() {
686 * This method mangles parameter name based on the prefix supplied to the constructor.
687 * Override this method to change parameter name during runtime
688 * @param string|string[] $paramName Parameter name
689 * @return string|string[] Prefixed parameter name
690 * @since 1.29 accepts an array of strings
692 public function encodeParamName( $paramName ) {
693 if ( is_array( $paramName ) ) {
694 return array_map( function ( $name ) {
695 return $this->mModulePrefix
. $name;
698 return $this->mModulePrefix
. $paramName;
703 * Using getAllowedParams(), this function makes an array of the values
704 * provided by the user, with key being the name of the variable, and
705 * value - validated value from user or default. limits will not be
706 * parsed if $parseLimit is set to false; use this when the max
707 * limit is not definitive yet, e.g. when getting revisions.
708 * @param bool $parseLimit True by default
711 public function extractRequestParams( $parseLimit = true ) {
712 // Cache parameters, for performance and to avoid T26564.
713 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
714 $params = $this->getFinalParams();
717 if ( $params ) { // getFinalParams() can return false
718 foreach ( $params as $paramName => $paramSettings ) {
719 $results[$paramName] = $this->getParameterFromSettings(
720 $paramName, $paramSettings, $parseLimit );
723 $this->mParamCache
[$parseLimit] = $results;
726 return $this->mParamCache
[$parseLimit];
730 * Get a value for the given parameter
731 * @param string $paramName Parameter name
732 * @param bool $parseLimit See extractRequestParams()
733 * @return mixed Parameter value
735 protected function getParameter( $paramName, $parseLimit = true ) {
736 $paramSettings = $this->getFinalParams()[$paramName];
738 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
742 * Die if none or more than one of a certain set of parameters is set and not false.
744 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
745 * @param string $required,... Names of parameters of which exactly one must be set
747 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
748 $required = func_get_args();
749 array_shift( $required );
751 $intersection = array_intersect( array_keys( array_filter( $params,
752 [ $this, 'parameterNotEmpty' ] ) ), $required );
754 if ( count( $intersection ) > 1 ) {
755 $this->dieWithError( [
756 'apierror-invalidparammix',
757 Message
::listParam( array_map(
759 return '<var>' . $this->encodeParamName( $p ) . '</var>';
761 array_values( $intersection )
763 count( $intersection ),
765 } elseif ( count( $intersection ) == 0 ) {
766 $this->dieWithError( [
767 'apierror-missingparam-one-of',
768 Message
::listParam( array_map(
770 return '<var>' . $this->encodeParamName( $p ) . '</var>';
772 array_values( $required )
780 * Die if more than one of a certain set of parameters is set and not false.
782 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
783 * @param string $required,... Names of parameters of which at most one must be set
785 public function requireMaxOneParameter( $params, $required /*...*/ ) {
786 $required = func_get_args();
787 array_shift( $required );
789 $intersection = array_intersect( array_keys( array_filter( $params,
790 [ $this, 'parameterNotEmpty' ] ) ), $required );
792 if ( count( $intersection ) > 1 ) {
793 $this->dieWithError( [
794 'apierror-invalidparammix',
795 Message
::listParam( array_map(
797 return '<var>' . $this->encodeParamName( $p ) . '</var>';
799 array_values( $intersection )
801 count( $intersection ),
807 * Die if none of a certain set of parameters is set and not false.
810 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
811 * @param string $required,... Names of parameters of which at least one must be set
813 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
814 $required = func_get_args();
815 array_shift( $required );
817 $intersection = array_intersect(
818 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
822 if ( count( $intersection ) == 0 ) {
823 $this->dieWithError( [
824 'apierror-missingparam-at-least-one-of',
825 Message
::listParam( array_map(
827 return '<var>' . $this->encodeParamName( $p ) . '</var>';
829 array_values( $required )
837 * Die if any of the specified parameters were found in the query part of
838 * the URL rather than the post body.
840 * @param string[] $params Parameters to check
841 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
843 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
844 // Skip if $wgDebugAPI is set or we're in internal mode
845 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
849 $queryValues = $this->getRequest()->getQueryValues();
851 foreach ( $params as $param ) {
852 if ( $prefix !== 'noprefix' ) {
853 $param = $this->encodeParamName( $param );
855 if ( array_key_exists( $param, $queryValues ) ) {
856 $badParams[] = $param;
862 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
868 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
870 * @param object $x Parameter to check is not null/false
873 private function parameterNotEmpty( $x ) {
874 return !is_null( $x ) && $x !== false;
878 * Get a WikiPage object from a title or pageid param, if possible.
879 * Can die, if no param is set or if the title or page id is not valid.
881 * @param array $params
882 * @param bool|string $load Whether load the object's state from the database:
883 * - false: don't load (if the pageid is given, it will still be loaded)
884 * - 'fromdb': load from a replica DB
885 * - 'fromdbmaster': load from the master database
888 public function getTitleOrPageId( $params, $load = false ) {
889 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
892 if ( isset( $params['title'] ) ) {
893 $titleObj = Title
::newFromText( $params['title'] );
894 if ( !$titleObj ||
$titleObj->isExternal() ) {
895 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
897 if ( !$titleObj->canExist() ) {
898 $this->dieWithError( 'apierror-pagecannotexist' );
900 $pageObj = WikiPage
::factory( $titleObj );
901 if ( $load !== false ) {
902 $pageObj->loadPageData( $load );
904 } elseif ( isset( $params['pageid'] ) ) {
905 if ( $load === false ) {
908 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
910 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
918 * Get a Title object from a title or pageid param, if possible.
919 * Can die, if no param is set or if the title or page id is not valid.
922 * @param array $params
925 public function getTitleFromTitleOrPageId( $params ) {
926 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
929 if ( isset( $params['title'] ) ) {
930 $titleObj = Title
::newFromText( $params['title'] );
931 if ( !$titleObj ||
$titleObj->isExternal() ) {
932 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
935 } elseif ( isset( $params['pageid'] ) ) {
936 $titleObj = Title
::newFromID( $params['pageid'] );
938 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
946 * Return true if we're to watch the page, false if not, null if no change.
947 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
948 * @param Title $titleObj The page under consideration
949 * @param string $userOption The user option to consider when $watchlist=preferences.
950 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
953 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
955 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
957 switch ( $watchlist ) {
965 # If the user is already watching, don't bother checking
966 if ( $userWatching ) {
969 # If no user option was passed, use watchdefault and watchcreations
970 if ( is_null( $userOption ) ) {
971 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
972 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
975 # Watch the article based on the user preference
976 return $this->getUser()->getBoolOption( $userOption );
979 return $userWatching;
982 return $userWatching;
987 * Using the settings determine the value for the given parameter
989 * @param string $paramName Parameter name
990 * @param array|mixed $paramSettings Default value or an array of settings
991 * using PARAM_* constants.
992 * @param bool $parseLimit Parse limit?
993 * @return mixed Parameter value
995 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
996 // Some classes may decide to change parameter names
997 $encParamName = $this->encodeParamName( $paramName );
1000 if ( !is_array( $paramSettings ) ) {
1002 self
::PARAM_DFLT
=> $paramSettings,
1006 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1007 ?
$paramSettings[self
::PARAM_DFLT
]
1009 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1010 ?
$paramSettings[self
::PARAM_ISMULTI
]
1012 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1013 ?
$paramSettings[self
::PARAM_TYPE
]
1015 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1016 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1018 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1019 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1021 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1022 ?
$paramSettings[self
::PARAM_REQUIRED
]
1024 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1025 ?
$paramSettings[self
::PARAM_ALL
]
1028 // When type is not given, and no choices, the type is the same as $default
1029 if ( !isset( $type ) ) {
1030 if ( isset( $default ) ) {
1031 $type = gettype( $default );
1033 $type = 'NULL'; // allow everything
1036 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1037 $this->getMain()->markParamsSensitive( $encParamName );
1041 if ( $type == 'boolean' ) {
1042 if ( isset( $default ) && $default !== false ) {
1043 // Having a default value of anything other than 'false' is not allowed
1046 "Boolean param $encParamName's default is set to '$default'. " .
1047 'Boolean parameters must default to false.'
1051 $value = $this->getMain()->getCheck( $encParamName );
1052 } elseif ( $type == 'upload' ) {
1053 if ( isset( $default ) ) {
1054 // Having a default value is not allowed
1057 "File upload param $encParamName's default is set to " .
1058 "'$default'. File upload parameters may not have a default." );
1061 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1063 $value = $this->getMain()->getUpload( $encParamName );
1064 if ( !$value->exists() ) {
1065 // This will get the value without trying to normalize it
1066 // (because trying to normalize a large binary file
1067 // accidentally uploaded as a field fails spectacularly)
1068 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1069 if ( $value !== null ) {
1070 $this->dieWithError(
1071 [ 'apierror-badupload', $encParamName ],
1072 "badupload_{$encParamName}"
1077 $value = $this->getMain()->getVal( $encParamName, $default );
1079 if ( isset( $value ) && $type == 'namespace' ) {
1080 $type = MWNamespace
::getValidNamespaces();
1081 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1082 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1084 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1086 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1090 if ( isset( $value ) && $type == 'submodule' ) {
1091 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1092 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1094 $type = $this->getModuleManager()->getNames( $paramName );
1098 $request = $this->getMain()->getRequest();
1099 $rawValue = $request->getRawVal( $encParamName );
1100 if ( $rawValue === null ) {
1101 $rawValue = $default;
1104 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1105 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1107 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1108 // done by WebRequest for $_GET. Let's call that a feature.
1109 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1111 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1115 // Check for NFC normalization, and warn
1116 if ( $rawValue !== $value ) {
1117 $this->handleParamNormalization( $paramName, $value, $rawValue );
1121 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1122 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1125 "For param $encParamName, PARAM_ALL collides with a possible value" );
1127 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1128 $value = $this->parseMultiValue(
1132 is_array( $type ) ?
$type : null,
1133 $allowAll ?
$allSpecifier : null
1137 // More validation only when choices were not given
1138 // choices were validated in parseMultiValue()
1139 if ( isset( $value ) ) {
1140 if ( !is_array( $type ) ) {
1142 case 'NULL': // nothing to do
1147 if ( $required && $value === '' ) {
1148 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1151 case 'integer': // Force everything using intval() and optionally validate limits
1152 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1153 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1154 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1155 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1157 if ( is_array( $value ) ) {
1158 $value = array_map( 'intval', $value );
1159 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1160 foreach ( $value as &$v ) {
1161 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1165 $value = intval( $value );
1166 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1167 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1172 if ( !$parseLimit ) {
1173 // Don't do any validation whatsoever
1176 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1177 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1181 "MAX1 or MAX2 are not defined for the limit $encParamName"
1185 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1187 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1188 if ( $value == 'max' ) {
1189 $value = $this->getMain()->canApiHighLimits()
1190 ?
$paramSettings[self
::PARAM_MAX2
]
1191 : $paramSettings[self
::PARAM_MAX
];
1192 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1194 $value = intval( $value );
1195 $this->validateLimit(
1199 $paramSettings[self
::PARAM_MAX
],
1200 $paramSettings[self
::PARAM_MAX2
]
1206 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1210 if ( is_array( $value ) ) {
1211 foreach ( $value as $key => $val ) {
1212 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1215 $value = $this->validateTimestamp( $value, $encParamName );
1219 if ( is_array( $value ) ) {
1220 foreach ( $value as $key => $val ) {
1221 $value[$key] = $this->validateUser( $val, $encParamName );
1224 $value = $this->validateUser( $value, $encParamName );
1227 case 'upload': // nothing to do
1230 // If change tagging was requested, check that the tags are valid.
1231 if ( !is_array( $value ) && !$multi ) {
1232 $value = [ $value ];
1234 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1235 if ( !$tagsStatus->isGood() ) {
1236 $this->dieStatus( $tagsStatus );
1240 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1244 // Throw out duplicates if requested
1245 if ( !$dupes && is_array( $value ) ) {
1246 $value = array_unique( $value );
1249 // Set a warning if a deprecated parameter has been passed
1250 if ( $deprecated && $value !== false ) {
1251 $feature = $encParamName;
1253 while ( !$m->isMain() ) {
1254 $p = $m->getParent();
1255 $name = $m->getModuleName();
1256 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1257 $feature = "{$param}={$name}&{$feature}";
1260 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1262 } elseif ( $required ) {
1263 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1270 * Handle when a parameter was Unicode-normalized
1272 * @param string $paramName Unprefixed parameter name
1273 * @param string $value Input that will be used.
1274 * @param string $rawValue Input before normalization.
1276 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1277 $encParamName = $this->encodeParamName( $paramName );
1278 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1282 * Split a multi-valued parameter string, like explode()
1284 * @param string $value
1288 protected function explodeMultiValue( $value, $limit ) {
1289 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1291 $value = substr( $value, 1 );
1296 return explode( $sep, $value, $limit );
1300 * Return an array of values that were given in a 'a|b|c' notation,
1301 * after it optionally validates them against the list allowed values.
1303 * @param string $valueName The name of the parameter (for error
1305 * @param mixed $value The value being parsed
1306 * @param bool $allowMultiple Can $value contain more than one value
1308 * @param string[]|null $allowedValues An array of values to check against. If
1309 * null, all values are accepted.
1310 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1311 * if this behavior should not be allowed
1312 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1314 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1315 $allSpecifier = null
1317 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1321 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1322 // because it unstubs $wgUser
1323 $valuesList = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1324 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1328 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1329 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1331 return $allowedValues;
1334 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1335 $this->addDeprecation(
1336 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1337 "too-many-$valueName-for-{$this->getModulePath()}"
1341 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1342 // T35482 - Allow entries with | in them for non-multiple values
1343 if ( in_array( $value, $allowedValues, true ) ) {
1347 if ( is_array( $allowedValues ) ) {
1348 $values = array_map( function ( $v ) {
1349 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1350 }, $allowedValues );
1351 $this->dieWithError( [
1352 'apierror-multival-only-one-of',
1354 Message
::listParam( $values ),
1356 ], "multival_$valueName" );
1358 $this->dieWithError( [
1359 'apierror-multival-only-one',
1361 ], "multival_$valueName" );
1365 if ( is_array( $allowedValues ) ) {
1366 // Check for unknown values
1367 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1368 if ( count( $unknown ) ) {
1369 if ( $allowMultiple ) {
1370 $this->addWarning( [
1371 'apiwarn-unrecognizedvalues',
1373 Message
::listParam( $unknown, 'comma' ),
1377 $this->dieWithError(
1378 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1379 "unknown_$valueName"
1383 // Now throw them out
1384 $valuesList = array_intersect( $valuesList, $allowedValues );
1387 return $allowMultiple ?
$valuesList : $valuesList[0];
1391 * Validate the value against the minimum and user/bot maximum limits.
1392 * Prints usage info on failure.
1393 * @param string $paramName Parameter name
1394 * @param int $value Parameter value
1395 * @param int|null $min Minimum value
1396 * @param int|null $max Maximum value for users
1397 * @param int $botMax Maximum value for sysops/bots
1398 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1400 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1401 $enforceLimits = false
1403 if ( !is_null( $min ) && $value < $min ) {
1404 $msg = ApiMessage
::create(
1405 [ 'apierror-integeroutofrange-belowminimum',
1406 $this->encodeParamName( $paramName ), $min, $value ],
1407 'integeroutofrange',
1408 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1410 $this->warnOrDie( $msg, $enforceLimits );
1414 // Minimum is always validated, whereas maximum is checked only if not
1415 // running in internal call mode
1416 if ( $this->getMain()->isInternalMode() ) {
1420 // Optimization: do not check user's bot status unless really needed -- skips db query
1421 // assumes $botMax >= $max
1422 if ( !is_null( $max ) && $value > $max ) {
1423 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1424 if ( $value > $botMax ) {
1425 $msg = ApiMessage
::create(
1426 [ 'apierror-integeroutofrange-abovebotmax',
1427 $this->encodeParamName( $paramName ), $botMax, $value ],
1428 'integeroutofrange',
1429 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1431 $this->warnOrDie( $msg, $enforceLimits );
1435 $msg = ApiMessage
::create(
1436 [ 'apierror-integeroutofrange-abovemax',
1437 $this->encodeParamName( $paramName ), $max, $value ],
1438 'integeroutofrange',
1439 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1441 $this->warnOrDie( $msg, $enforceLimits );
1448 * Validate and normalize of parameters of type 'timestamp'
1449 * @param string $value Parameter value
1450 * @param string $encParamName Parameter name
1451 * @return string Validated and normalized parameter
1453 protected function validateTimestamp( $value, $encParamName ) {
1454 // Confusing synonyms for the current time accepted by wfTimestamp()
1455 // (wfTimestamp() also accepts various non-strings and the string of 14
1456 // ASCII NUL bytes, but those can't get here)
1458 $this->addDeprecation(
1459 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1460 'unclear-"now"-timestamp'
1462 return wfTimestamp( TS_MW
);
1465 // Explicit synonym for the current time
1466 if ( $value === 'now' ) {
1467 return wfTimestamp( TS_MW
);
1470 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1471 if ( $unixTimestamp === false ) {
1472 $this->dieWithError(
1473 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1474 "badtimestamp_{$encParamName}"
1478 return wfTimestamp( TS_MW
, $unixTimestamp );
1482 * Validate the supplied token.
1485 * @param string $token Supplied token
1486 * @param array $params All supplied parameters for the module
1488 * @throws MWException
1490 final public function validateToken( $token, array $params ) {
1491 $tokenType = $this->needsToken();
1492 $salts = ApiQueryTokens
::getTokenTypeSalts();
1493 if ( !isset( $salts[$tokenType] ) ) {
1494 throw new MWException(
1495 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1496 'without registering it'
1500 $tokenObj = ApiQueryTokens
::getToken(
1501 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1503 if ( $tokenObj->match( $token ) ) {
1507 $webUiSalt = $this->getWebUITokenSalt( $params );
1508 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1520 * Validate and normalize of parameters of type 'user'
1521 * @param string $value Parameter value
1522 * @param string $encParamName Parameter name
1523 * @return string Validated and normalized parameter
1525 private function validateUser( $value, $encParamName ) {
1526 $title = Title
::makeTitleSafe( NS_USER
, $value );
1527 if ( $title === null ||
$title->hasFragment() ) {
1528 $this->dieWithError(
1529 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1530 "baduser_{$encParamName}"
1534 return $title->getText();
1539 /************************************************************************//**
1540 * @name Utility methods
1545 * Set a watch (or unwatch) based the based on a watchlist parameter.
1546 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1547 * @param Title $titleObj The article's title to change
1548 * @param string $userOption The user option to consider when $watch=preferences
1550 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1551 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1552 if ( $value === null ) {
1556 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1560 * Truncate an array to a certain length.
1561 * @param array $arr Array to truncate
1562 * @param int $limit Maximum length
1563 * @return bool True if the array was truncated, false otherwise
1565 public static function truncateArray( &$arr, $limit ) {
1567 while ( count( $arr ) > $limit ) {
1576 * Gets the user for whom to get the watchlist
1578 * @param array $params
1581 public function getWatchlistUser( $params ) {
1582 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1583 $user = User
::newFromName( $params['owner'], false );
1584 if ( !( $user && $user->getId() ) ) {
1585 $this->dieWithError(
1586 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1589 $token = $user->getOption( 'watchlisttoken' );
1590 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1591 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1594 if ( !$this->getUser()->isLoggedIn() ) {
1595 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1597 $this->checkUserRightsAny( 'viewmywatchlist' );
1598 $user = $this->getUser();
1605 * A subset of wfEscapeWikiText for BC texts
1608 * @param string|array $v
1609 * @return string|array
1611 private static function escapeWikiText( $v ) {
1612 if ( is_array( $v ) ) {
1613 return array_map( 'self::escapeWikiText', $v );
1616 '__' => '__', '{' => '{', '}' => '}',
1617 '[[Category:' => '[[:Category:',
1618 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1624 * Create a Message from a string or array
1626 * A string is used as a message key. An array has the message key as the
1627 * first value and message parameters as subsequent values.
1630 * @param string|array|Message $msg
1631 * @param IContextSource $context
1632 * @param array $params
1633 * @return Message|null
1635 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1636 if ( is_string( $msg ) ) {
1637 $msg = wfMessage( $msg );
1638 } elseif ( is_array( $msg ) ) {
1639 $msg = call_user_func_array( 'wfMessage', $msg );
1641 if ( !$msg instanceof Message
) {
1645 $msg->setContext( $context );
1647 $msg->params( $params );
1654 * Turn an array of message keys or key+param arrays into a Status
1656 * @param array $errors
1657 * @param User|null $user
1660 public function errorArrayToStatus( array $errors, User
$user = null ) {
1661 if ( $user === null ) {
1662 $user = $this->getUser();
1665 $status = Status
::newGood();
1666 foreach ( $errors as $error ) {
1667 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1668 $status->fatal( ApiMessage
::create(
1671 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1673 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1674 $status->fatal( ApiMessage
::create(
1675 'apierror-autoblocked',
1677 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1679 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1680 $status->fatal( ApiMessage
::create(
1681 'apierror-systemblocked',
1683 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1686 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1694 /************************************************************************//**
1695 * @name Warning and error reporting
1700 * Add a warning for this module.
1702 * Users should monitor this section to notice any changes in API. Multiple
1703 * calls to this function will result in multiple warning messages.
1705 * If $msg is not an ApiMessage, the message code will be derived from the
1706 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1709 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1710 * @param string|null $code See ApiErrorFormatter::addWarning()
1711 * @param array|null $data See ApiErrorFormatter::addWarning()
1713 public function addWarning( $msg, $code = null, $data = null ) {
1714 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1718 * Add a deprecation warning for this module.
1720 * A combination of $this->addWarning() and $this->logFeatureUsage()
1723 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1724 * @param string|null $feature See ApiBase::logFeatureUsage()
1725 * @param array|null $data See ApiErrorFormatter::addWarning()
1727 public function addDeprecation( $msg, $feature, $data = [] ) {
1728 $data = (array)$data;
1729 if ( $feature !== null ) {
1730 $data['feature'] = $feature;
1731 $this->logFeatureUsage( $feature );
1733 $this->addWarning( $msg, 'deprecation', $data );
1735 // No real need to deduplicate here, ApiErrorFormatter does that for
1736 // us (assuming the hook is deterministic).
1737 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1738 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1739 if ( count( $msgs ) > 1 ) {
1740 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1741 $msg = ( new RawMessage( $key ) )->params( $msgs );
1743 $msg = reset( $msgs );
1745 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1749 * Add an error for this module without aborting
1751 * If $msg is not an ApiMessage, the message code will be derived from the
1752 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1754 * @note If you want to abort processing, use self::dieWithError() instead.
1756 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1757 * @param string|null $code See ApiErrorFormatter::addError()
1758 * @param array|null $data See ApiErrorFormatter::addError()
1760 public function addError( $msg, $code = null, $data = null ) {
1761 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1765 * Add warnings and/or errors from a Status
1767 * @note If you want to abort processing, use self::dieStatus() instead.
1769 * @param StatusValue $status
1770 * @param string[] $types 'warning' and/or 'error'
1772 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1773 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1777 * Abort execution with an error
1779 * If $msg is not an ApiMessage, the message code will be derived from the
1780 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1783 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1784 * @param string|null $code See ApiErrorFormatter::addError()
1785 * @param array|null $data See ApiErrorFormatter::addError()
1786 * @param int|null $httpCode HTTP error code to use
1787 * @throws ApiUsageException always
1789 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1790 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1794 * Abort execution with an error derived from an exception
1797 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1798 * @param array $options See ApiErrorFormatter::getMessageFromException()
1799 * @throws ApiUsageException always
1801 public function dieWithException( $exception, array $options = [] ) {
1802 $this->dieWithError(
1803 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1808 * Adds a warning to the output, else dies
1810 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1811 * @param bool $enforceLimits Whether this is an enforce (die)
1813 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1814 if ( $enforceLimits ) {
1815 $this->dieWithError( $msg );
1817 $this->addWarning( $msg );
1822 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1823 * error handler and die with an error message including block info.
1826 * @param Block $block The block used to generate the ApiUsageException
1827 * @throws ApiUsageException always
1829 public function dieBlocked( Block
$block ) {
1830 // Die using the appropriate message depending on block type
1831 if ( $block->getType() == Block
::TYPE_AUTO
) {
1832 $this->dieWithError(
1833 'apierror-autoblocked',
1835 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1838 $this->dieWithError(
1841 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1847 * Throw an ApiUsageException based on the Status object.
1850 * @since 1.29 Accepts a StatusValue
1851 * @param StatusValue $status
1852 * @throws ApiUsageException always
1854 public function dieStatus( StatusValue
$status ) {
1855 if ( $status->isGood() ) {
1856 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1859 throw new ApiUsageException( $this, $status );
1863 * Helper function for readonly errors
1865 * @throws ApiUsageException always
1867 public function dieReadOnly() {
1868 $this->dieWithError(
1869 'apierror-readonly',
1871 [ 'readonlyreason' => wfReadOnlyReason() ]
1876 * Helper function for permission-denied errors
1878 * @param string|string[] $rights
1879 * @param User|null $user
1880 * @throws ApiUsageException if the user doesn't have any of the rights.
1881 * The error message is based on $rights[0].
1883 public function checkUserRightsAny( $rights, $user = null ) {
1885 $user = $this->getUser();
1887 $rights = (array)$rights;
1888 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1889 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1894 * Helper function for permission-denied errors
1896 * @param Title $title
1897 * @param string|string[] $actions
1898 * @param User|null $user
1899 * @throws ApiUsageException if the user doesn't have all of the rights.
1901 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
1903 $user = $this->getUser();
1907 foreach ( (array)$actions as $action ) {
1908 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1911 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1916 * Will only set a warning instead of failing if the global $wgDebugAPI
1917 * is set to true. Otherwise behaves exactly as self::dieWithError().
1920 * @param string|array|Message $msg
1921 * @param string|null $code
1922 * @param array|null $data
1923 * @param int|null $httpCode
1924 * @throws ApiUsageException
1926 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1927 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1928 $this->dieWithError( $msg, $code, $data, $httpCode );
1930 $this->addWarning( $msg, $code, $data );
1935 * Die with the 'badcontinue' error.
1937 * This call is common enough to make it into the base method.
1939 * @param bool $condition Will only die if this value is true
1940 * @throws ApiUsageException
1943 protected function dieContinueUsageIf( $condition ) {
1945 $this->dieWithError( 'apierror-badcontinue' );
1950 * Internal code errors should be reported with this method
1951 * @param string $method Method or function name
1952 * @param string $message Error message
1953 * @throws MWException always
1955 protected static function dieDebug( $method, $message ) {
1956 throw new MWException( "Internal error in $method: $message" );
1960 * Write logging information for API features to a debug log, for usage
1962 * @note Consider using $this->addDeprecation() instead to both warn and log.
1963 * @param string $feature Feature being used.
1965 public function logFeatureUsage( $feature ) {
1966 $request = $this->getRequest();
1967 $s = '"' . addslashes( $feature ) . '"' .
1968 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1969 ' "' . $request->getIP() . '"' .
1970 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1971 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1972 wfDebugLog( 'api-feature-usage', $s, 'private' );
1977 /************************************************************************//**
1978 * @name Help message generation
1983 * Return the description message.
1985 * @return string|array|Message
1987 protected function getDescriptionMessage() {
1988 return "apihelp-{$this->getModulePath()}-description";
1992 * Get final module description, after hooks have had a chance to tweak it as
1995 * @since 1.25, returns Message[] rather than string[]
1998 public function getFinalDescription() {
1999 $desc = $this->getDescription();
2001 // Avoid PHP 7.1 warning of passing $this by reference
2003 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2004 $desc = self
::escapeWikiText( $desc );
2005 if ( is_array( $desc ) ) {
2006 $desc = implode( "\n", $desc );
2008 $desc = (string)$desc;
2011 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2012 $this->getModulePrefix(),
2013 $this->getModuleName(),
2014 $this->getModulePath(),
2016 if ( !$msg->exists() ) {
2017 $msg = $this->msg( 'api-help-fallback-description', $desc );
2021 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2027 * Get final list of parameters, after hooks have had a chance to
2028 * tweak it as needed.
2030 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2031 * @return array|bool False on no parameters
2032 * @since 1.21 $flags param added
2034 public function getFinalParams( $flags = 0 ) {
2035 $params = $this->getAllowedParams( $flags );
2040 if ( $this->needsToken() ) {
2041 $params['token'] = [
2042 ApiBase
::PARAM_TYPE
=> 'string',
2043 ApiBase
::PARAM_REQUIRED
=> true,
2044 ApiBase
::PARAM_SENSITIVE
=> true,
2045 ApiBase
::PARAM_HELP_MSG
=> [
2046 'api-help-param-token',
2047 $this->needsToken(),
2049 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2052 // Avoid PHP 7.1 warning of passing $this by reference
2054 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2060 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2063 * @since 1.25, returns array of Message[] rather than array of string[]
2064 * @return array Keys are parameter names, values are arrays of Message objects
2066 public function getFinalParamDescription() {
2067 $prefix = $this->getModulePrefix();
2068 $name = $this->getModuleName();
2069 $path = $this->getModulePath();
2071 $desc = $this->getParamDescription();
2073 // Avoid PHP 7.1 warning of passing $this by reference
2075 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2080 $desc = self
::escapeWikiText( $desc );
2082 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2084 foreach ( $params as $param => $settings ) {
2085 if ( !is_array( $settings ) ) {
2089 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2090 if ( is_array( $d ) ) {
2091 // Special handling for prop parameters
2092 $d = array_map( function ( $line ) {
2093 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2094 $line = "\n;{$m[1]}:{$m[2]}";
2098 $d = implode( ' ', $d );
2101 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2102 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2104 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2105 if ( !$msg->exists() ) {
2106 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2109 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2110 [ $prefix, $param, $name, $path ] );
2112 self
::dieDebug( __METHOD__
,
2113 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2115 $msgs[$param] = [ $msg ];
2117 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2118 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2119 self
::dieDebug( __METHOD__
,
2120 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2122 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2123 self
::dieDebug( __METHOD__
,
2124 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2125 'ApiBase::PARAM_TYPE is an array' );
2128 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2129 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2130 if ( isset( $valueMsgs[$value] ) ) {
2131 $msg = $valueMsgs[$value];
2133 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2135 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2136 [ $prefix, $param, $name, $path, $value ] );
2138 $m = new ApiHelpParamValueMessage(
2140 [ $m->getKey(), 'api-help-param-no-description' ],
2143 $msgs[$param][] = $m->setContext( $this->getContext() );
2145 self
::dieDebug( __METHOD__
,
2146 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2151 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2152 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2153 self
::dieDebug( __METHOD__
,
2154 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2156 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2157 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2158 [ $prefix, $param, $name, $path ] );
2160 $msgs[$param][] = $m;
2162 self
::dieDebug( __METHOD__
,
2163 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2169 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2175 * Generates the list of flags for the help screen and for action=paraminfo
2177 * Corresponding messages: api-help-flag-deprecated,
2178 * api-help-flag-internal, api-help-flag-readrights,
2179 * api-help-flag-writerights, api-help-flag-mustbeposted
2183 protected function getHelpFlags() {
2186 if ( $this->isDeprecated() ) {
2187 $flags[] = 'deprecated';
2189 if ( $this->isInternal() ) {
2190 $flags[] = 'internal';
2192 if ( $this->isReadMode() ) {
2193 $flags[] = 'readrights';
2195 if ( $this->isWriteMode() ) {
2196 $flags[] = 'writerights';
2198 if ( $this->mustBePosted() ) {
2199 $flags[] = 'mustbeposted';
2206 * Returns information about the source of this module, if known
2208 * Returned array is an array with the following keys:
2209 * - path: Install path
2210 * - name: Extension name, or "MediaWiki" for core
2211 * - namemsg: (optional) i18n message key for a display name
2212 * - license-name: (optional) Name of license
2214 * @return array|null
2216 protected function getModuleSourceInfo() {
2219 if ( $this->mModuleSource
!== false ) {
2220 return $this->mModuleSource
;
2223 // First, try to find where the module comes from...
2224 $rClass = new ReflectionClass( $this );
2225 $path = $rClass->getFileName();
2228 $this->mModuleSource
= null;
2231 $path = realpath( $path ) ?
: $path;
2233 // Build map of extension directories to extension info
2234 if ( self
::$extensionInfo === null ) {
2235 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2236 self
::$extensionInfo = [
2237 realpath( __DIR__
) ?
: __DIR__
=> [
2239 'name' => 'MediaWiki',
2240 'license-name' => 'GPL-2.0+',
2242 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2243 realpath( $extDir ) ?
: $extDir => null,
2249 'license-name' => null,
2251 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2252 foreach ( $group as $ext ) {
2253 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2254 // This shouldn't happen, but does anyway.
2258 $extpath = $ext['path'];
2259 if ( !is_dir( $extpath ) ) {
2260 $extpath = dirname( $extpath );
2262 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2263 array_intersect_key( $ext, $keep );
2266 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2267 $extpath = $ext['path'];
2268 if ( !is_dir( $extpath ) ) {
2269 $extpath = dirname( $extpath );
2271 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2272 array_intersect_key( $ext, $keep );
2276 // Now traverse parent directories until we find a match or run out of
2279 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2281 $this->mModuleSource
= self
::$extensionInfo[$path];
2282 return $this->mModuleSource
;
2286 $path = dirname( $path );
2287 } while ( $path !== $oldpath );
2289 // No idea what extension this might be.
2290 $this->mModuleSource
= null;
2295 * Called from ApiHelp before the pieces are joined together and returned.
2297 * This exists mainly for ApiMain to add the Permissions and Credits
2298 * sections. Other modules probably don't need it.
2300 * @param string[] &$help Array of help data
2301 * @param array $options Options passed to ApiHelp::getHelp
2302 * @param array &$tocData If a TOC is being generated, this array has keys
2303 * as anchors in the page and values as for Linker::generateTOC().
2305 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2310 /************************************************************************//**
2316 * Returns the description string for this module
2318 * Ignored if an i18n message exists for
2319 * "apihelp-{$this->getModulePath()}-description".
2321 * @deprecated since 1.25
2322 * @return Message|string|array|false
2324 protected function getDescription() {
2329 * Returns an array of parameter descriptions.
2331 * For each parameter, ignored if an i18n message exists for the parameter.
2332 * By default that message is
2333 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2334 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2335 * self::getFinalParams().
2337 * @deprecated since 1.25
2338 * @return array|bool False on no parameter descriptions
2340 protected function getParamDescription() {
2345 * Returns usage examples for this module.
2347 * Return value as an array is either:
2348 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2350 * - sequential numeric keys with even-numbered keys being display-text
2351 * and odd-numbered keys being partial urls
2352 * - partial URLs as keys with display-text (string or array-to-be-joined)
2354 * Return value as a string is the same as an array with a numeric key and
2355 * that value, and boolean false means "no examples".
2357 * @deprecated since 1.25, use getExamplesMessages() instead
2358 * @return bool|string|array
2360 protected function getExamples() {
2365 * @deprecated since 1.25, always returns empty string
2366 * @param IDatabase|bool $db
2369 public function getModuleProfileName( $db = false ) {
2370 wfDeprecated( __METHOD__
, '1.25' );
2375 * @deprecated since 1.25
2377 public function profileIn() {
2378 // No wfDeprecated() yet because extensions call this and might need to
2379 // keep doing so for BC.
2383 * @deprecated since 1.25
2385 public function profileOut() {
2386 // No wfDeprecated() yet because extensions call this and might need to
2387 // keep doing so for BC.
2391 * @deprecated since 1.25
2393 public function safeProfileOut() {
2394 wfDeprecated( __METHOD__
, '1.25' );
2398 * @deprecated since 1.25, always returns 0
2401 public function getProfileTime() {
2402 wfDeprecated( __METHOD__
, '1.25' );
2407 * @deprecated since 1.25
2409 public function profileDBIn() {
2410 wfDeprecated( __METHOD__
, '1.25' );
2414 * @deprecated since 1.25
2416 public function profileDBOut() {
2417 wfDeprecated( __METHOD__
, '1.25' );
2421 * @deprecated since 1.25, always returns 0
2424 public function getProfileDBTime() {
2425 wfDeprecated( __METHOD__
, '1.25' );
2430 * Call wfTransactionalTimeLimit() if this request was POSTed
2433 protected function useTransactionalTimeLimit() {
2434 if ( $this->getRequest()->wasPosted() ) {
2435 wfTransactionalTimeLimit();
2440 * @deprecated since 1.29, use ApiBase::addWarning() instead
2441 * @param string $warning Warning message
2443 public function setWarning( $warning ) {
2444 $msg = new ApiRawMessage( $warning, 'warning' );
2445 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2449 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2450 * error handler and die with an error message.
2452 * @deprecated since 1.29, use self::dieWithError() instead
2453 * @param string $description One-line human-readable description of the
2454 * error condition, e.g., "The API requires a valid action parameter"
2455 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2456 * automated identification of the error, e.g., 'unknown_action'
2457 * @param int $httpRespCode HTTP response code
2458 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2459 * @throws ApiUsageException always
2461 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2462 $this->dieWithError(
2463 new RawMessage( '$1', [ $description ] ),
2471 * Get error (as code, string) from a Status object.
2474 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2475 * @param Status $status
2476 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2477 * @return array Array of code and error string
2478 * @throws MWException
2480 public function getErrorFromStatus( $status, &$extraData = null ) {
2481 if ( $status->isGood() ) {
2482 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2485 $errors = $status->getErrorsByType( 'error' );
2487 // No errors? Assume the warnings should be treated as errors
2488 $errors = $status->getErrorsByType( 'warning' );
2491 // Still no errors? Punt
2492 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2495 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2496 $msg = $errors[0]['message'];
2498 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2500 if ( !$msg instanceof IApiMessage
) {
2501 $key = $msg->getKey();
2502 $params = $msg->getParams();
2503 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2504 $msg = ApiMessage
::create( $params );
2509 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2514 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2515 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2516 * API codes and message texts, and a few interfaces required poking
2517 * something in here. Now we're repurposing it to map those same strings
2518 * to i18n messages, and declaring that any interface that requires poking
2519 * at this is broken and needs replacing ASAP.
2521 private static $messageMap = [
2522 'unknownerror' => 'apierror-unknownerror',
2523 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2524 'ns-specialprotected' => 'ns-specialprotected',
2525 'protectedinterface' => 'protectedinterface',
2526 'namespaceprotected' => 'namespaceprotected',
2527 'customcssprotected' => 'customcssprotected',
2528 'customjsprotected' => 'customjsprotected',
2529 'cascadeprotected' => 'cascadeprotected',
2530 'protectedpagetext' => 'protectedpagetext',
2531 'protect-cantedit' => 'protect-cantedit',
2532 'deleteprotected' => 'deleteprotected',
2533 'badaccess-group0' => 'badaccess-group0',
2534 'badaccess-groups' => 'badaccess-groups',
2535 'titleprotected' => 'titleprotected',
2536 'nocreate-loggedin' => 'nocreate-loggedin',
2537 'nocreatetext' => 'nocreatetext',
2538 'movenologintext' => 'movenologintext',
2539 'movenotallowed' => 'movenotallowed',
2540 'confirmedittext' => 'confirmedittext',
2541 'blockedtext' => 'apierror-blocked',
2542 'autoblockedtext' => 'apierror-autoblocked',
2543 'systemblockedtext' => 'apierror-systemblocked',
2544 'actionthrottledtext' => 'apierror-ratelimited',
2545 'alreadyrolled' => 'alreadyrolled',
2546 'cantrollback' => 'cantrollback',
2547 'readonlytext' => 'readonlytext',
2548 'sessionfailure' => 'sessionfailure',
2549 'cannotdelete' => 'cannotdelete',
2550 'notanarticle' => 'apierror-missingtitle',
2551 'selfmove' => 'selfmove',
2552 'immobile_namespace' => 'apierror-immobilenamespace',
2553 'articleexists' => 'articleexists',
2554 'hookaborted' => 'hookaborted',
2555 'cantmove-titleprotected' => 'cantmove-titleprotected',
2556 'imagenocrossnamespace' => 'imagenocrossnamespace',
2557 'imagetypemismatch' => 'imagetypemismatch',
2558 'ip_range_invalid' => 'ip_range_invalid',
2559 'range_block_disabled' => 'range_block_disabled',
2560 'nosuchusershort' => 'nosuchusershort',
2561 'badipaddress' => 'badipaddress',
2562 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2563 'ipb_already_blocked' => 'ipb_already_blocked',
2564 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2565 'ipb_cant_unblock' => 'ipb_cant_unblock',
2566 'mailnologin' => 'apierror-cantsend',
2567 'ipbblocked' => 'ipbblocked',
2568 'ipbnounblockself' => 'ipbnounblockself',
2569 'usermaildisabled' => 'usermaildisabled',
2570 'blockedemailuser' => 'apierror-blockedfrommail',
2571 'notarget' => 'apierror-notarget',
2572 'noemail' => 'noemail',
2573 'rcpatroldisabled' => 'rcpatroldisabled',
2574 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2575 'delete-toobig' => 'delete-toobig',
2576 'movenotallowedfile' => 'movenotallowedfile',
2577 'userrights-no-interwiki' => 'userrights-no-interwiki',
2578 'userrights-nodatabase' => 'userrights-nodatabase',
2579 'nouserspecified' => 'nouserspecified',
2580 'noname' => 'noname',
2581 'summaryrequired' => 'apierror-summaryrequired',
2582 'import-rootpage-invalid' => 'import-rootpage-invalid',
2583 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2584 'readrequired' => 'apierror-readapidenied',
2585 'writedisabled' => 'apierror-noapiwrite',
2586 'writerequired' => 'apierror-writeapidenied',
2587 'missingparam' => 'apierror-missingparam',
2588 'invalidtitle' => 'apierror-invalidtitle',
2589 'nosuchpageid' => 'apierror-nosuchpageid',
2590 'nosuchrevid' => 'apierror-nosuchrevid',
2591 'nosuchuser' => 'nosuchusershort',
2592 'invaliduser' => 'apierror-invaliduser',
2593 'invalidexpiry' => 'apierror-invalidexpiry',
2594 'pastexpiry' => 'apierror-pastexpiry',
2595 'create-titleexists' => 'apierror-create-titleexists',
2596 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2597 'cantblock' => 'apierror-cantblock',
2598 'canthide' => 'apierror-canthide',
2599 'cantblock-email' => 'apierror-cantblock-email',
2600 'cantunblock' => 'apierror-permissiondenied-generic',
2601 'cannotundelete' => 'cannotundelete',
2602 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2603 'createonly-exists' => 'apierror-articleexists',
2604 'nocreate-missing' => 'apierror-missingtitle',
2605 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2606 'nosuchrcid' => 'apierror-nosuchrcid',
2607 'nosuchlogid' => 'apierror-nosuchlogid',
2608 'protect-invalidaction' => 'apierror-protect-invalidaction',
2609 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2610 'toofewexpiries' => 'apierror-toofewexpiries',
2611 'cantimport' => 'apierror-cantimport',
2612 'cantimport-upload' => 'apierror-cantimport-upload',
2613 'importnofile' => 'importnofile',
2614 'importuploaderrorsize' => 'importuploaderrorsize',
2615 'importuploaderrorpartial' => 'importuploaderrorpartial',
2616 'importuploaderrortemp' => 'importuploaderrortemp',
2617 'importcantopen' => 'importcantopen',
2618 'import-noarticle' => 'import-noarticle',
2619 'importbadinterwiki' => 'importbadinterwiki',
2620 'import-unknownerror' => 'apierror-import-unknownerror',
2621 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2622 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2623 'mustbeposted' => 'apierror-mustbeposted',
2624 'show' => 'apierror-show',
2625 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2626 'invalidoldimage' => 'apierror-invalidoldimage',
2627 'nodeleteablefile' => 'apierror-nodeleteablefile',
2628 'fileexists-forbidden' => 'fileexists-forbidden',
2629 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2630 'filerevert-badversion' => 'filerevert-badversion',
2631 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2632 'noimageredirect-logged' => 'apierror-noimageredirect',
2633 'spamdetected' => 'apierror-spamdetected',
2634 'contenttoobig' => 'apierror-contenttoobig',
2635 'noedit-anon' => 'apierror-noedit-anon',
2636 'noedit' => 'apierror-noedit',
2637 'wasdeleted' => 'apierror-pagedeleted',
2638 'blankpage' => 'apierror-emptypage',
2639 'editconflict' => 'editconflict',
2640 'hashcheckfailed' => 'apierror-badmd5',
2641 'missingtext' => 'apierror-notext',
2642 'emptynewsection' => 'apierror-emptynewsection',
2643 'revwrongpage' => 'apierror-revwrongpage',
2644 'undo-failure' => 'undo-failure',
2645 'content-not-allowed-here' => 'content-not-allowed-here',
2646 'edit-hook-aborted' => 'edit-hook-aborted',
2647 'edit-gone-missing' => 'edit-gone-missing',
2648 'edit-conflict' => 'edit-conflict',
2649 'edit-already-exists' => 'edit-already-exists',
2650 'invalid-file-key' => 'apierror-invalid-file-key',
2651 'nouploadmodule' => 'apierror-nouploadmodule',
2652 'uploaddisabled' => 'uploaddisabled',
2653 'copyuploaddisabled' => 'copyuploaddisabled',
2654 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2655 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2656 'filename-tooshort' => 'filename-tooshort',
2657 'filename-toolong' => 'filename-toolong',
2658 'illegal-filename' => 'illegal-filename',
2659 'filetype-missing' => 'filetype-missing',
2660 'mustbeloggedin' => 'apierror-mustbeloggedin',
2664 * @deprecated do not use
2665 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2666 * @return ApiMessage
2668 private function parseMsgInternal( $error ) {
2669 $msg = Message
::newFromSpecifier( $error );
2670 if ( !$msg instanceof IApiMessage
) {
2671 $key = $msg->getKey();
2672 if ( isset( self
::$messageMap[$key] ) ) {
2673 $params = $msg->getParams();
2674 array_unshift( $params, self
::$messageMap[$key] );
2676 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2678 $msg = ApiMessage
::create( $params );
2684 * Return the error message related to a certain array
2685 * @deprecated since 1.29
2686 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2687 * @return [ 'code' => code, 'info' => info ]
2689 public function parseMsg( $error ) {
2690 // Check whether someone passed the whole array, instead of one element as
2691 // documented. This breaks if it's actually an array of fallback keys, but
2692 // that's long-standing misbehavior introduced in r87627 to incorrectly
2694 if ( is_array( $error ) ) {
2695 $first = reset( $error );
2696 if ( is_array( $first ) ) {
2697 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2702 $msg = $this->parseMsgInternal( $error );
2704 'code' => $msg->getApiCode(),
2705 'info' => ApiErrorFormatter
::stripMarkup(
2706 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2708 'data' => $msg->getApiData()
2713 * Output the error message related to a certain array
2714 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2715 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2716 * @throws ApiUsageException always
2718 public function dieUsageMsg( $error ) {
2719 $this->dieWithError( $this->parseMsgInternal( $error ) );
2723 * Will only set a warning instead of failing if the global $wgDebugAPI
2724 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2725 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2726 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2727 * @throws ApiUsageException
2730 public function dieUsageMsgOrDebug( $error ) {
2731 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2738 * For really cool vim folding this needs to be at the end:
2739 * vim: foldmarker=@{,@} foldmethod=marker