5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Self-documentation: code to allow the API to document its own state
39 abstract class ApiBase
extends ContextSource
{
42 * @name Constants for ::getAllowedParams() arrays
43 * These constants are keys in the arrays returned by ::getAllowedParams()
44 * and accepted by ::getParameterFromSettings() that define how the
45 * parameters coming in from the request are to be interpreted.
49 /** (null|boolean|integer|string) Default value of the parameter. */
52 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
53 const PARAM_ISMULTI
= 1;
56 * (string|string[]) Either an array of allowed value strings, or a string
57 * type as described below. If not specified, will be determined from the
60 * Supported string types are:
61 * - boolean: A boolean parameter, returned as false if the parameter is
62 * omitted and true if present (even with a falsey value, i.e. it works
63 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
64 * Cannot be used with PARAM_ISMULTI.
65 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
66 * PARAM_RANGE_ENFORCE.
67 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
68 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
69 * specified. Cannot be used with PARAM_ISMULTI.
70 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
71 * support easily specifying all namespaces.
73 * - password: Any non-empty string. Input value is private or sensitive.
74 * <input type="password"> would be an appropriate HTML form field.
75 * - string: Any non-empty string, not expected to be very long or contain newlines.
76 * <input type="text"> would be an appropriate HTML form field.
77 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
78 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
79 * used with PARAM_ISMULTI.
80 * - text: Any non-empty string, expected to be very long or contain newlines.
81 * <textarea> would be an appropriate HTML form field.
82 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
83 * string 'now' representing the current timestamp. Will be returned in
85 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
86 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
87 * Cannot be used with PARAM_ISMULTI.
91 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
95 * (integer) Max value allowed for the parameter for users with the
96 * apihighlimits right, for PARAM_TYPE 'limit'.
100 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
103 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
104 const PARAM_ALLOW_DUPLICATES
= 6;
106 /** (boolean) Is the parameter deprecated (will show a warning)? */
107 const PARAM_DEPRECATED
= 7;
110 * (boolean) Is the parameter required?
113 const PARAM_REQUIRED
= 8;
116 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
119 const PARAM_RANGE_ENFORCE
= 9;
122 * (string|array|Message) Specify an alternative i18n documentation message
123 * for this parameter. Default is apihelp-{$path}-param-{$param}.
126 const PARAM_HELP_MSG
= 10;
129 * ((string|array|Message)[]) Specify additional i18n messages to append to
130 * the normal message for this parameter.
133 const PARAM_HELP_MSG_APPEND
= 11;
136 * (array) Specify additional information tags for the parameter. Value is
137 * an array of arrays, with the first member being the 'tag' for the info
138 * and the remaining members being the values. In the help, this is
139 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
140 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
143 const PARAM_HELP_MSG_INFO
= 12;
146 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
147 * those values to page titles which will be linked in the help.
150 const PARAM_VALUE_LINKS
= 13;
153 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
154 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
155 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
158 const PARAM_HELP_MSG_PER_VALUE
= 14;
161 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
162 * submodule paths. Default is to use all modules in
163 * $this->getModuleManager() in the group matching the parameter name.
166 const PARAM_SUBMODULE_MAP
= 15;
169 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
170 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
173 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
176 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
177 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
178 * every possible value. If a string is set, it will be used in place of the asterisk.
181 const PARAM_ALL
= 17;
184 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
187 const PARAM_EXTRA_NAMESPACES
= 18;
191 const ALL_DEFAULT_STRING
= '*';
193 /** Fast query, standard limit. */
194 const LIMIT_BIG1
= 500;
195 /** Fast query, apihighlimits limit. */
196 const LIMIT_BIG2
= 5000;
197 /** Slow query, standard limit. */
198 const LIMIT_SML1
= 50;
199 /** Slow query, apihighlimits limit. */
200 const LIMIT_SML2
= 500;
203 * getAllowedParams() flag: When set, the result could take longer to generate,
204 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
207 const GET_VALUES_FOR_HELP
= 1;
209 /** @var array Maps extension paths to info arrays */
210 private static $extensionInfo = null;
213 private $mMainModule;
215 private $mModuleName, $mModulePrefix;
216 private $mSlaveDB = null;
217 private $mParamCache = [];
218 /** @var array|null|bool */
219 private $mModuleSource = false;
222 * @param ApiMain $mainModule
223 * @param string $moduleName Name of this module
224 * @param string $modulePrefix Prefix to use for parameter names
226 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
227 $this->mMainModule
= $mainModule;
228 $this->mModuleName
= $moduleName;
229 $this->mModulePrefix
= $modulePrefix;
231 if ( !$this->isMain() ) {
232 $this->setContext( $mainModule->getContext() );
236 /************************************************************************//**
237 * @name Methods to implement
242 * Evaluates the parameters, performs the requested query, and sets up
243 * the result. Concrete implementations of ApiBase must override this
244 * method to provide whatever functionality their module offers.
245 * Implementations must not produce any output on their own and are not
246 * expected to handle any errors.
248 * The execute() method will be invoked directly by ApiMain immediately
249 * before the result of the module is output. Aside from the
250 * constructor, implementations should assume that no other methods
251 * will be called externally on the module before the result is
254 * The result data should be stored in the ApiResult object available
255 * through getResult().
257 abstract public function execute();
260 * Get the module manager, or null if this module has no sub-modules
262 * @return ApiModuleManager
264 public function getModuleManager() {
269 * If the module may only be used with a certain format module,
270 * it should override this method to return an instance of that formatter.
271 * A value of null means the default format will be used.
272 * @note Do not use this just because you don't want to support non-json
273 * formats. This should be used only when there is a fundamental
274 * requirement for a specific format.
275 * @return mixed Instance of a derived class of ApiFormatBase, or null
277 public function getCustomPrinter() {
282 * Returns usage examples for this module.
284 * Return value has query strings as keys, with values being either strings
285 * (message key), arrays (message key + parameter), or Message objects.
287 * Do not call this base class implementation when overriding this method.
292 protected function getExamplesMessages() {
293 // Fall back to old non-localised method
296 $examples = $this->getExamples();
298 if ( !is_array( $examples ) ) {
299 $examples = [ $examples ];
300 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
301 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
302 !preg_match( '/^\s*api\.php\?/', $examples[0] )
304 // Fix up the ugly "even numbered elements are description, odd
305 // numbered elemts are the link" format (see doc for self::getExamples)
307 $examplesCount = count( $examples );
308 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
309 $tmp[$examples[$i +
1]] = $examples[$i];
314 foreach ( $examples as $k => $v ) {
315 if ( is_numeric( $k ) ) {
320 $msg = self
::escapeWikiText( $v );
321 if ( is_array( $msg ) ) {
322 $msg = implode( ' ', $msg );
326 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
327 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
335 * Return links to more detailed help pages about the module.
336 * @since 1.25, returning boolean false is deprecated
337 * @return string|array
339 public function getHelpUrls() {
344 * Returns an array of allowed parameters (parameter name) => (default
345 * value) or (parameter name) => (array with PARAM_* constants as keys)
346 * Don't call this function directly: use getFinalParams() to allow
347 * hooks to modify parameters as needed.
349 * Some derived classes may choose to handle an integer $flags parameter
350 * in the overriding methods. Callers of this method can pass zero or
351 * more OR-ed flags like GET_VALUES_FOR_HELP.
355 protected function getAllowedParams( /* $flags = 0 */ ) {
356 // int $flags is not declared because it causes "Strict standards"
357 // warning. Most derived classes do not implement it.
362 * Indicates if this module needs maxlag to be checked
365 public function shouldCheckMaxlag() {
370 * Indicates whether this module requires read rights
373 public function isReadMode() {
378 * Indicates whether this module requires write mode
381 public function isWriteMode() {
386 * Indicates whether this module must be called with a POST request
389 public function mustBePosted() {
390 return $this->needsToken() !== false;
394 * Indicates whether this module is deprecated
398 public function isDeprecated() {
403 * Indicates whether this module is "internal"
404 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
408 public function isInternal() {
413 * Returns the token type this module requires in order to execute.
415 * Modules are strongly encouraged to use the core 'csrf' type unless they
416 * have specialized security needs. If the token type is not one of the
417 * core types, you must use the ApiQueryTokensRegisterTypes hook to
420 * Returning a non-falsey value here will force the addition of an
421 * appropriate 'token' parameter in self::getFinalParams(). Also,
422 * self::mustBePosted() must return true when tokens are used.
424 * In previous versions of MediaWiki, true was a valid return value.
425 * Returning true will generate errors indicating that the API module needs
428 * @return string|false
430 public function needsToken() {
435 * Fetch the salt used in the Web UI corresponding to this module.
437 * Only override this if the Web UI uses a token with a non-constant salt.
440 * @param array $params All supplied parameters for the module
441 * @return string|array|null
443 protected function getWebUITokenSalt( array $params ) {
448 * Returns data for HTTP conditional request mechanisms.
451 * @param string $condition Condition being queried:
452 * - last-modified: Return a timestamp representing the maximum of the
453 * last-modified dates for all resources involved in the request. See
454 * RFC 7232 § 2.2 for semantics.
455 * - etag: Return an entity-tag representing the state of all resources involved
456 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
457 * @return string|bool|null As described above, or null if no value is available.
459 public function getConditionalRequestData( $condition ) {
465 /************************************************************************//**
466 * @name Data access methods
471 * Get the name of the module being executed by this instance
474 public function getModuleName() {
475 return $this->mModuleName
;
479 * Get parameter prefix (usually two letters or an empty string).
482 public function getModulePrefix() {
483 return $this->mModulePrefix
;
487 * Get the main module
490 public function getMain() {
491 return $this->mMainModule
;
495 * Returns true if this module is the main module ($this === $this->mMainModule),
499 public function isMain() {
500 return $this === $this->mMainModule
;
504 * Get the parent of this module
506 * @return ApiBase|null
508 public function getParent() {
509 return $this->isMain() ?
null : $this->getMain();
513 * Returns true if the current request breaks the same-origin policy.
515 * For example, json with callbacks.
517 * https://en.wikipedia.org/wiki/Same-origin_policy
522 public function lacksSameOriginSecurity() {
523 // Main module has this method overridden
524 // Safety - avoid infinite loop:
525 if ( $this->isMain() ) {
526 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
529 return $this->getMain()->lacksSameOriginSecurity();
533 * Get the path to this module
538 public function getModulePath() {
539 if ( $this->isMain() ) {
541 } elseif ( $this->getParent()->isMain() ) {
542 return $this->getModuleName();
544 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
549 * Get a module from its module path
552 * @param string $path
553 * @return ApiBase|null
554 * @throws ApiUsageException
556 public function getModuleFromPath( $path ) {
557 $module = $this->getMain();
558 if ( $path === 'main' ) {
562 $parts = explode( '+', $path );
563 if ( count( $parts ) === 1 ) {
564 // In case the '+' was typed into URL, it resolves as a space
565 $parts = explode( ' ', $path );
568 $count = count( $parts );
569 for ( $i = 0; $i < $count; $i++
) {
571 $manager = $parent->getModuleManager();
572 if ( $manager === null ) {
573 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
574 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
576 $module = $manager->getModule( $parts[$i] );
578 if ( $module === null ) {
579 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
581 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
591 * Get the result object
594 public function getResult() {
595 // Main module has getResult() method overridden
596 // Safety - avoid infinite loop:
597 if ( $this->isMain() ) {
598 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
601 return $this->getMain()->getResult();
605 * Get the error formatter
606 * @return ApiErrorFormatter
608 public function getErrorFormatter() {
609 // Main module has getErrorFormatter() method overridden
610 // Safety - avoid infinite loop:
611 if ( $this->isMain() ) {
612 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
615 return $this->getMain()->getErrorFormatter();
619 * Gets a default replica DB connection object
622 protected function getDB() {
623 if ( !isset( $this->mSlaveDB
) ) {
624 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
627 return $this->mSlaveDB
;
631 * Get the continuation manager
632 * @return ApiContinuationManager|null
634 public function getContinuationManager() {
635 // Main module has getContinuationManager() method overridden
636 // Safety - avoid infinite loop:
637 if ( $this->isMain() ) {
638 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
641 return $this->getMain()->getContinuationManager();
645 * Set the continuation manager
646 * @param ApiContinuationManager|null
648 public function setContinuationManager( $manager ) {
649 // Main module has setContinuationManager() method overridden
650 // Safety - avoid infinite loop:
651 if ( $this->isMain() ) {
652 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
655 $this->getMain()->setContinuationManager( $manager );
660 /************************************************************************//**
661 * @name Parameter handling
666 * Indicate if the module supports dynamically-determined parameters that
667 * cannot be included in self::getAllowedParams().
668 * @return string|array|Message|null Return null if the module does not
669 * support additional dynamic parameters, otherwise return a message
672 public function dynamicParameterDocumentation() {
677 * This method mangles parameter name based on the prefix supplied to the constructor.
678 * Override this method to change parameter name during runtime
679 * @param string|string[] $paramName Parameter name
680 * @return string|string[] Prefixed parameter name
681 * @since 1.29 accepts an array of strings
683 public function encodeParamName( $paramName ) {
684 if ( is_array( $paramName ) ) {
685 return array_map( function ( $name ) {
686 return $this->mModulePrefix
. $name;
689 return $this->mModulePrefix
. $paramName;
694 * Using getAllowedParams(), this function makes an array of the values
695 * provided by the user, with key being the name of the variable, and
696 * value - validated value from user or default. limits will not be
697 * parsed if $parseLimit is set to false; use this when the max
698 * limit is not definitive yet, e.g. when getting revisions.
699 * @param bool $parseLimit True by default
702 public function extractRequestParams( $parseLimit = true ) {
703 // Cache parameters, for performance and to avoid bug 24564.
704 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
705 $params = $this->getFinalParams();
708 if ( $params ) { // getFinalParams() can return false
709 foreach ( $params as $paramName => $paramSettings ) {
710 $results[$paramName] = $this->getParameterFromSettings(
711 $paramName, $paramSettings, $parseLimit );
714 $this->mParamCache
[$parseLimit] = $results;
717 return $this->mParamCache
[$parseLimit];
721 * Get a value for the given parameter
722 * @param string $paramName Parameter name
723 * @param bool $parseLimit See extractRequestParams()
724 * @return mixed Parameter value
726 protected function getParameter( $paramName, $parseLimit = true ) {
727 $paramSettings = $this->getFinalParams()[$paramName];
729 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
733 * Die if none or more than one of a certain set of parameters is set and not false.
735 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
736 * @param string $required,... Names of parameters of which exactly one must be set
738 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
739 $required = func_get_args();
740 array_shift( $required );
742 $intersection = array_intersect( array_keys( array_filter( $params,
743 [ $this, 'parameterNotEmpty' ] ) ), $required );
745 if ( count( $intersection ) > 1 ) {
746 $this->dieWithError( [
747 'apierror-invalidparammix',
748 Message
::listParam( array_map(
750 return '<var>' . $this->encodeParamName( $p ) . '</var>';
752 array_values( $intersection )
754 count( $intersection ),
756 } elseif ( count( $intersection ) == 0 ) {
757 $this->dieWithError( [
758 'apierror-missingparam-one-of',
759 Message
::listParam( array_map(
761 return '<var>' . $this->encodeParamName( $p ) . '</var>';
763 array_values( $required )
771 * Die if more than one of a certain set of parameters is set and not false.
773 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
774 * @param string $required,... Names of parameters of which at most one must be set
776 public function requireMaxOneParameter( $params, $required /*...*/ ) {
777 $required = func_get_args();
778 array_shift( $required );
780 $intersection = array_intersect( array_keys( array_filter( $params,
781 [ $this, 'parameterNotEmpty' ] ) ), $required );
783 if ( count( $intersection ) > 1 ) {
784 $this->dieWithError( [
785 'apierror-invalidparammix',
786 Message
::listParam( array_map(
788 return '<var>' . $this->encodeParamName( $p ) . '</var>';
790 array_values( $intersection )
792 count( $intersection ),
798 * Die if none of a certain set of parameters is set and not false.
801 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
802 * @param string $required,... Names of parameters of which at least one must be set
804 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
805 $required = func_get_args();
806 array_shift( $required );
808 $intersection = array_intersect(
809 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
813 if ( count( $intersection ) == 0 ) {
814 $this->dieWithError( [
815 'apierror-missingparam-at-least-one-of',
816 Message
::listParam( array_map(
818 return '<var>' . $this->encodeParamName( $p ) . '</var>';
820 array_values( $required )
828 * Die if any of the specified parameters were found in the query part of
829 * the URL rather than the post body.
831 * @param string[] $params Parameters to check
832 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
834 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
835 // Skip if $wgDebugAPI is set or we're in internal mode
836 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
840 $queryValues = $this->getRequest()->getQueryValues();
842 foreach ( $params as $param ) {
843 if ( $prefix !== 'noprefix' ) {
844 $param = $this->encodeParamName( $param );
846 if ( array_key_exists( $param, $queryValues ) ) {
847 $badParams[] = $param;
853 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
859 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
861 * @param object $x Parameter to check is not null/false
864 private function parameterNotEmpty( $x ) {
865 return !is_null( $x ) && $x !== false;
869 * Get a WikiPage object from a title or pageid param, if possible.
870 * Can die, if no param is set or if the title or page id is not valid.
872 * @param array $params
873 * @param bool|string $load Whether load the object's state from the database:
874 * - false: don't load (if the pageid is given, it will still be loaded)
875 * - 'fromdb': load from a replica DB
876 * - 'fromdbmaster': load from the master database
879 public function getTitleOrPageId( $params, $load = false ) {
880 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
883 if ( isset( $params['title'] ) ) {
884 $titleObj = Title
::newFromText( $params['title'] );
885 if ( !$titleObj ||
$titleObj->isExternal() ) {
886 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
888 if ( !$titleObj->canExist() ) {
889 $this->dieWithError( 'apierror-pagecannotexist' );
891 $pageObj = WikiPage
::factory( $titleObj );
892 if ( $load !== false ) {
893 $pageObj->loadPageData( $load );
895 } elseif ( isset( $params['pageid'] ) ) {
896 if ( $load === false ) {
899 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
901 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
909 * Get a Title object from a title or pageid param, if possible.
910 * Can die, if no param is set or if the title or page id is not valid.
913 * @param array $params
916 public function getTitleFromTitleOrPageId( $params ) {
917 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
920 if ( isset( $params['title'] ) ) {
921 $titleObj = Title
::newFromText( $params['title'] );
922 if ( !$titleObj ||
$titleObj->isExternal() ) {
923 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
926 } elseif ( isset( $params['pageid'] ) ) {
927 $titleObj = Title
::newFromID( $params['pageid'] );
929 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
937 * Return true if we're to watch the page, false if not, null if no change.
938 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
939 * @param Title $titleObj The page under consideration
940 * @param string $userOption The user option to consider when $watchlist=preferences.
941 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
944 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
946 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
948 switch ( $watchlist ) {
956 # If the user is already watching, don't bother checking
957 if ( $userWatching ) {
960 # If no user option was passed, use watchdefault and watchcreations
961 if ( is_null( $userOption ) ) {
962 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
963 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
966 # Watch the article based on the user preference
967 return $this->getUser()->getBoolOption( $userOption );
970 return $userWatching;
973 return $userWatching;
978 * Using the settings determine the value for the given parameter
980 * @param string $paramName Parameter name
981 * @param array|mixed $paramSettings Default value or an array of settings
982 * using PARAM_* constants.
983 * @param bool $parseLimit Parse limit?
984 * @return mixed Parameter value
986 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
987 // Some classes may decide to change parameter names
988 $encParamName = $this->encodeParamName( $paramName );
991 if ( !is_array( $paramSettings ) ) {
993 self
::PARAM_DFLT
=> $paramSettings,
997 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
998 ?
$paramSettings[self
::PARAM_DFLT
]
1000 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1001 ?
$paramSettings[self
::PARAM_ISMULTI
]
1003 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1004 ?
$paramSettings[self
::PARAM_TYPE
]
1006 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1007 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1009 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1010 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1012 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1013 ?
$paramSettings[self
::PARAM_REQUIRED
]
1015 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1016 ?
$paramSettings[self
::PARAM_ALL
]
1019 // When type is not given, and no choices, the type is the same as $default
1020 if ( !isset( $type ) ) {
1021 if ( isset( $default ) ) {
1022 $type = gettype( $default );
1024 $type = 'NULL'; // allow everything
1028 if ( $type == 'boolean' ) {
1029 if ( isset( $default ) && $default !== false ) {
1030 // Having a default value of anything other than 'false' is not allowed
1033 "Boolean param $encParamName's default is set to '$default'. " .
1034 'Boolean parameters must default to false.'
1038 $value = $this->getMain()->getCheck( $encParamName );
1039 } elseif ( $type == 'upload' ) {
1040 if ( isset( $default ) ) {
1041 // Having a default value is not allowed
1044 "File upload param $encParamName's default is set to " .
1045 "'$default'. File upload parameters may not have a default." );
1048 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1050 $value = $this->getMain()->getUpload( $encParamName );
1051 if ( !$value->exists() ) {
1052 // This will get the value without trying to normalize it
1053 // (because trying to normalize a large binary file
1054 // accidentally uploaded as a field fails spectacularly)
1055 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1056 if ( $value !== null ) {
1057 $this->dieWithError(
1058 [ 'apierror-badupload', $encParamName ],
1059 "badupload_{$encParamName}"
1064 $value = $this->getMain()->getVal( $encParamName, $default );
1066 if ( isset( $value ) && $type == 'namespace' ) {
1067 $type = MWNamespace
::getValidNamespaces();
1068 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1069 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1071 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1073 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1077 if ( isset( $value ) && $type == 'submodule' ) {
1078 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1079 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1081 $type = $this->getModuleManager()->getNames( $paramName );
1085 $request = $this->getMain()->getRequest();
1086 $rawValue = $request->getRawVal( $encParamName );
1087 if ( $rawValue === null ) {
1088 $rawValue = $default;
1091 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1092 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1094 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1095 // done by WebRequest for $_GET. Let's call that a feature.
1096 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1098 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1102 // Check for NFC normalization, and warn
1103 if ( $rawValue !== $value ) {
1104 $this->handleParamNormalization( $paramName, $value, $rawValue );
1108 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1109 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1112 "For param $encParamName, PARAM_ALL collides with a possible value" );
1114 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1115 $value = $this->parseMultiValue(
1119 is_array( $type ) ?
$type : null,
1120 $allowAll ?
$allSpecifier : null
1124 // More validation only when choices were not given
1125 // choices were validated in parseMultiValue()
1126 if ( isset( $value ) ) {
1127 if ( !is_array( $type ) ) {
1129 case 'NULL': // nothing to do
1134 if ( $required && $value === '' ) {
1135 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1138 case 'integer': // Force everything using intval() and optionally validate limits
1139 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1140 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1141 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1142 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1144 if ( is_array( $value ) ) {
1145 $value = array_map( 'intval', $value );
1146 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1147 foreach ( $value as &$v ) {
1148 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1152 $value = intval( $value );
1153 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1154 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1159 if ( !$parseLimit ) {
1160 // Don't do any validation whatsoever
1163 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1164 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1168 "MAX1 or MAX2 are not defined for the limit $encParamName"
1172 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1174 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1175 if ( $value == 'max' ) {
1176 $value = $this->getMain()->canApiHighLimits()
1177 ?
$paramSettings[self
::PARAM_MAX2
]
1178 : $paramSettings[self
::PARAM_MAX
];
1179 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1181 $value = intval( $value );
1182 $this->validateLimit(
1186 $paramSettings[self
::PARAM_MAX
],
1187 $paramSettings[self
::PARAM_MAX2
]
1193 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1197 if ( is_array( $value ) ) {
1198 foreach ( $value as $key => $val ) {
1199 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1202 $value = $this->validateTimestamp( $value, $encParamName );
1206 if ( is_array( $value ) ) {
1207 foreach ( $value as $key => $val ) {
1208 $value[$key] = $this->validateUser( $val, $encParamName );
1211 $value = $this->validateUser( $value, $encParamName );
1214 case 'upload': // nothing to do
1217 // If change tagging was requested, check that the tags are valid.
1218 if ( !is_array( $value ) && !$multi ) {
1219 $value = [ $value ];
1221 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1222 if ( !$tagsStatus->isGood() ) {
1223 $this->dieStatus( $tagsStatus );
1227 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1231 // Throw out duplicates if requested
1232 if ( !$dupes && is_array( $value ) ) {
1233 $value = array_unique( $value );
1236 // Set a warning if a deprecated parameter has been passed
1237 if ( $deprecated && $value !== false ) {
1238 $feature = $encParamName;
1240 while ( !$m->isMain() ) {
1241 $p = $m->getParent();
1242 $name = $m->getModuleName();
1243 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1244 $feature = "{$param}={$name}&{$feature}";
1247 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1249 } elseif ( $required ) {
1250 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1257 * Handle when a parameter was Unicode-normalized
1259 * @param string $paramName Unprefixed parameter name
1260 * @param string $value Input that will be used.
1261 * @param string $rawValue Input before normalization.
1263 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1264 $encParamName = $this->encodeParamName( $paramName );
1265 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1269 * Split a multi-valued parameter string, like explode()
1271 * @param string $value
1275 protected function explodeMultiValue( $value, $limit ) {
1276 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1278 $value = substr( $value, 1 );
1283 return explode( $sep, $value, $limit );
1287 * Return an array of values that were given in a 'a|b|c' notation,
1288 * after it optionally validates them against the list allowed values.
1290 * @param string $valueName The name of the parameter (for error
1292 * @param mixed $value The value being parsed
1293 * @param bool $allowMultiple Can $value contain more than one value
1295 * @param string[]|null $allowedValues An array of values to check against. If
1296 * null, all values are accepted.
1297 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1298 * if this behavior should not be allowed
1299 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1301 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1302 $allSpecifier = null
1304 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1308 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1309 // because it unstubs $wgUser
1310 $valuesList = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1311 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1315 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1316 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1318 return $allowedValues;
1321 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1322 $this->addDeprecation(
1323 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1324 "too-many-$valueName-for-{$this->getModulePath()}"
1328 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1329 // Bug 33482 - Allow entries with | in them for non-multiple values
1330 if ( in_array( $value, $allowedValues, true ) ) {
1334 if ( is_array( $allowedValues ) ) {
1335 $values = array_map( function ( $v ) {
1336 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1337 }, $allowedValues );
1338 $this->dieWithError( [
1339 'apierror-multival-only-one-of',
1341 Message
::listParam( $values ),
1343 ], "multival_$valueName" );
1345 $this->dieWithError( [
1346 'apierror-multival-only-one',
1348 ], "multival_$valueName" );
1352 if ( is_array( $allowedValues ) ) {
1353 // Check for unknown values
1354 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1355 if ( count( $unknown ) ) {
1356 if ( $allowMultiple ) {
1357 $this->addWarning( [
1358 'apiwarn-unrecognizedvalues',
1360 Message
::listParam( $unknown, 'comma' ),
1364 $this->dieWithError(
1365 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1366 "unknown_$valueName"
1370 // Now throw them out
1371 $valuesList = array_intersect( $valuesList, $allowedValues );
1374 return $allowMultiple ?
$valuesList : $valuesList[0];
1378 * Validate the value against the minimum and user/bot maximum limits.
1379 * Prints usage info on failure.
1380 * @param string $paramName Parameter name
1381 * @param int $value Parameter value
1382 * @param int|null $min Minimum value
1383 * @param int|null $max Maximum value for users
1384 * @param int $botMax Maximum value for sysops/bots
1385 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1387 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1388 $enforceLimits = false
1390 if ( !is_null( $min ) && $value < $min ) {
1391 $msg = ApiMessage
::create(
1392 [ 'apierror-integeroutofrange-belowminimum',
1393 $this->encodeParamName( $paramName ), $min, $value ],
1394 'integeroutofrange',
1395 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1397 $this->warnOrDie( $msg, $enforceLimits );
1401 // Minimum is always validated, whereas maximum is checked only if not
1402 // running in internal call mode
1403 if ( $this->getMain()->isInternalMode() ) {
1407 // Optimization: do not check user's bot status unless really needed -- skips db query
1408 // assumes $botMax >= $max
1409 if ( !is_null( $max ) && $value > $max ) {
1410 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1411 if ( $value > $botMax ) {
1412 $msg = ApiMessage
::create(
1413 [ 'apierror-integeroutofrange-abovebotmax',
1414 $this->encodeParamName( $paramName ), $botMax, $value ],
1415 'integeroutofrange',
1416 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1418 $this->warnOrDie( $msg, $enforceLimits );
1422 $msg = ApiMessage
::create(
1423 [ 'apierror-integeroutofrange-abovemax',
1424 $this->encodeParamName( $paramName ), $max, $value ],
1425 'integeroutofrange',
1426 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1428 $this->warnOrDie( $msg, $enforceLimits );
1435 * Validate and normalize of parameters of type 'timestamp'
1436 * @param string $value Parameter value
1437 * @param string $encParamName Parameter name
1438 * @return string Validated and normalized parameter
1440 protected function validateTimestamp( $value, $encParamName ) {
1441 // Confusing synonyms for the current time accepted by wfTimestamp()
1442 // (wfTimestamp() also accepts various non-strings and the string of 14
1443 // ASCII NUL bytes, but those can't get here)
1445 $this->addDeprecation(
1446 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1447 'unclear-"now"-timestamp'
1449 return wfTimestamp( TS_MW
);
1452 // Explicit synonym for the current time
1453 if ( $value === 'now' ) {
1454 return wfTimestamp( TS_MW
);
1457 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1458 if ( $unixTimestamp === false ) {
1459 $this->dieWithError(
1460 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1461 "badtimestamp_{$encParamName}"
1465 return wfTimestamp( TS_MW
, $unixTimestamp );
1469 * Validate the supplied token.
1472 * @param string $token Supplied token
1473 * @param array $params All supplied parameters for the module
1475 * @throws MWException
1477 final public function validateToken( $token, array $params ) {
1478 $tokenType = $this->needsToken();
1479 $salts = ApiQueryTokens
::getTokenTypeSalts();
1480 if ( !isset( $salts[$tokenType] ) ) {
1481 throw new MWException(
1482 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1483 'without registering it'
1487 $tokenObj = ApiQueryTokens
::getToken(
1488 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1490 if ( $tokenObj->match( $token ) ) {
1494 $webUiSalt = $this->getWebUITokenSalt( $params );
1495 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1507 * Validate and normalize of parameters of type 'user'
1508 * @param string $value Parameter value
1509 * @param string $encParamName Parameter name
1510 * @return string Validated and normalized parameter
1512 private function validateUser( $value, $encParamName ) {
1513 $title = Title
::makeTitleSafe( NS_USER
, $value );
1514 if ( $title === null ||
$title->hasFragment() ) {
1515 $this->dieWithError(
1516 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1517 "baduser_{$encParamName}"
1521 return $title->getText();
1526 /************************************************************************//**
1527 * @name Utility methods
1532 * Set a watch (or unwatch) based the based on a watchlist parameter.
1533 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1534 * @param Title $titleObj The article's title to change
1535 * @param string $userOption The user option to consider when $watch=preferences
1537 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1538 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1539 if ( $value === null ) {
1543 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1547 * Truncate an array to a certain length.
1548 * @param array $arr Array to truncate
1549 * @param int $limit Maximum length
1550 * @return bool True if the array was truncated, false otherwise
1552 public static function truncateArray( &$arr, $limit ) {
1554 while ( count( $arr ) > $limit ) {
1563 * Gets the user for whom to get the watchlist
1565 * @param array $params
1568 public function getWatchlistUser( $params ) {
1569 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1570 $user = User
::newFromName( $params['owner'], false );
1571 if ( !( $user && $user->getId() ) ) {
1572 $this->dieWithError(
1573 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1576 $token = $user->getOption( 'watchlisttoken' );
1577 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1578 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1581 if ( !$this->getUser()->isLoggedIn() ) {
1582 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1584 $this->checkUserRightsAny( 'viewmywatchlist' );
1585 $user = $this->getUser();
1592 * A subset of wfEscapeWikiText for BC texts
1595 * @param string|array $v
1596 * @return string|array
1598 private static function escapeWikiText( $v ) {
1599 if ( is_array( $v ) ) {
1600 return array_map( 'self::escapeWikiText', $v );
1603 '__' => '__', '{' => '{', '}' => '}',
1604 '[[Category:' => '[[:Category:',
1605 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1611 * Create a Message from a string or array
1613 * A string is used as a message key. An array has the message key as the
1614 * first value and message parameters as subsequent values.
1617 * @param string|array|Message $msg
1618 * @param IContextSource $context
1619 * @param array $params
1620 * @return Message|null
1622 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1623 if ( is_string( $msg ) ) {
1624 $msg = wfMessage( $msg );
1625 } elseif ( is_array( $msg ) ) {
1626 $msg = call_user_func_array( 'wfMessage', $msg );
1628 if ( !$msg instanceof Message
) {
1632 $msg->setContext( $context );
1634 $msg->params( $params );
1641 * Turn an array of message keys or key+param arrays into a Status
1643 * @param array $errors
1644 * @param User|null $user
1647 public function errorArrayToStatus( array $errors, User
$user = null ) {
1648 if ( $user === null ) {
1649 $user = $this->getUser();
1652 $status = Status
::newGood();
1653 foreach ( $errors as $error ) {
1654 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1655 $status->fatal( ApiMessage
::create(
1658 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1660 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1661 $status->fatal( ApiMessage
::create(
1662 'apierror-autoblocked',
1664 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1666 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1667 $status->fatal( ApiMessage
::create(
1668 'apierror-systemblocked',
1670 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1673 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1681 /************************************************************************//**
1682 * @name Warning and error reporting
1687 * Add a warning for this module.
1689 * Users should monitor this section to notice any changes in API. Multiple
1690 * calls to this function will result in multiple warning messages.
1692 * If $msg is not an ApiMessage, the message code will be derived from the
1693 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1696 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1697 * @param string|null $code See ApiErrorFormatter::addWarning()
1698 * @param array|null $data See ApiErrorFormatter::addWarning()
1700 public function addWarning( $msg, $code = null, $data = null ) {
1701 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1705 * Add a deprecation warning for this module.
1707 * A combination of $this->addWarning() and $this->logFeatureUsage()
1710 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1711 * @param string|null $feature See ApiBase::logFeatureUsage()
1712 * @param array|null $data See ApiErrorFormatter::addWarning()
1714 public function addDeprecation( $msg, $feature, $data = [] ) {
1715 $data = (array)$data;
1716 if ( $feature !== null ) {
1717 $data['feature'] = $feature;
1718 $this->logFeatureUsage( $feature );
1720 $this->addWarning( $msg, 'deprecation', $data );
1724 * Add an error for this module without aborting
1726 * If $msg is not an ApiMessage, the message code will be derived from the
1727 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1729 * @note If you want to abort processing, use self::dieWithError() instead.
1731 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1732 * @param string|null $code See ApiErrorFormatter::addError()
1733 * @param array|null $data See ApiErrorFormatter::addError()
1735 public function addError( $msg, $code = null, $data = null ) {
1736 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1740 * Add warnings and/or errors from a Status
1742 * @note If you want to abort processing, use self::dieStatus() instead.
1744 * @param StatusValue $status
1745 * @param string[] $types 'warning' and/or 'error'
1747 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1748 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1752 * Abort execution with an error
1754 * If $msg is not an ApiMessage, the message code will be derived from the
1755 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1758 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1759 * @param string|null $code See ApiErrorFormatter::addError()
1760 * @param array|null $data See ApiErrorFormatter::addError()
1761 * @param int|null $httpCode HTTP error code to use
1762 * @throws ApiUsageException always
1764 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1765 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1769 * Abort execution with an error derived from an exception
1772 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1773 * @param array $options See ApiErrorFormatter::getMessageFromException()
1774 * @throws ApiUsageException always
1776 public function dieWithException( $exception, array $options = [] ) {
1777 $this->dieWithError(
1778 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1783 * Adds a warning to the output, else dies
1785 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1786 * @param bool $enforceLimits Whether this is an enforce (die)
1788 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1789 if ( $enforceLimits ) {
1790 $this->dieWithError( $msg );
1792 $this->addWarning( $msg );
1797 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1798 * error handler and die with an error message including block info.
1801 * @param Block $block The block used to generate the ApiUsageException
1802 * @throws ApiUsageException always
1804 public function dieBlocked( Block
$block ) {
1805 // Die using the appropriate message depending on block type
1806 if ( $block->getType() == Block
::TYPE_AUTO
) {
1807 $this->dieWithError(
1808 'apierror-autoblocked',
1810 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1813 $this->dieWithError(
1816 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1822 * Throw an ApiUsageException based on the Status object.
1825 * @since 1.29 Accepts a StatusValue
1826 * @param StatusValue $status
1827 * @throws ApiUsageException always
1829 public function dieStatus( StatusValue
$status ) {
1830 if ( $status->isGood() ) {
1831 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1834 throw new ApiUsageException( $this, $status );
1838 * Helper function for readonly errors
1840 * @throws ApiUsageException always
1842 public function dieReadOnly() {
1843 $this->dieWithError(
1844 'apierror-readonly',
1846 [ 'readonlyreason' => wfReadOnlyReason() ]
1851 * Helper function for permission-denied errors
1853 * @param string|string[] $rights
1854 * @param User|null $user
1855 * @throws ApiUsageException if the user doesn't have any of the rights.
1856 * The error message is based on $rights[0].
1858 public function checkUserRightsAny( $rights, $user = null ) {
1860 $user = $this->getUser();
1862 $rights = (array)$rights;
1863 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1864 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1869 * Helper function for permission-denied errors
1871 * @param Title $title
1872 * @param string|string[] $actions
1873 * @param User|null $user
1874 * @throws ApiUsageException if the user doesn't have all of the rights.
1876 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
1878 $user = $this->getUser();
1882 foreach ( (array)$actions as $action ) {
1883 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1886 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1891 * Will only set a warning instead of failing if the global $wgDebugAPI
1892 * is set to true. Otherwise behaves exactly as self::dieWithError().
1895 * @param string|array|Message $msg
1896 * @param string|null $code
1897 * @param array|null $data
1898 * @param int|null $httpCode
1899 * @throws ApiUsageException
1901 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1902 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1903 $this->dieWithError( $msg, $code, $data, $httpCode );
1905 $this->addWarning( $msg, $code, $data );
1910 * Die with the 'badcontinue' error.
1912 * This call is common enough to make it into the base method.
1914 * @param bool $condition Will only die if this value is true
1915 * @throws ApiUsageException
1918 protected function dieContinueUsageIf( $condition ) {
1920 $this->dieWithError( 'apierror-badcontinue' );
1925 * Internal code errors should be reported with this method
1926 * @param string $method Method or function name
1927 * @param string $message Error message
1928 * @throws MWException always
1930 protected static function dieDebug( $method, $message ) {
1931 throw new MWException( "Internal error in $method: $message" );
1935 * Write logging information for API features to a debug log, for usage
1937 * @note Consider using $this->addDeprecation() instead to both warn and log.
1938 * @param string $feature Feature being used.
1940 public function logFeatureUsage( $feature ) {
1941 $request = $this->getRequest();
1942 $s = '"' . addslashes( $feature ) . '"' .
1943 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1944 ' "' . $request->getIP() . '"' .
1945 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1946 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1947 wfDebugLog( 'api-feature-usage', $s, 'private' );
1952 /************************************************************************//**
1953 * @name Help message generation
1958 * Return the description message.
1960 * @return string|array|Message
1962 protected function getDescriptionMessage() {
1963 return "apihelp-{$this->getModulePath()}-description";
1967 * Get final module description, after hooks have had a chance to tweak it as
1970 * @since 1.25, returns Message[] rather than string[]
1973 public function getFinalDescription() {
1974 $desc = $this->getDescription();
1976 // Avoid PHP 7.1 warning of passing $this by reference
1978 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
1979 $desc = self
::escapeWikiText( $desc );
1980 if ( is_array( $desc ) ) {
1981 $desc = implode( "\n", $desc );
1983 $desc = (string)$desc;
1986 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
1987 $this->getModulePrefix(),
1988 $this->getModuleName(),
1989 $this->getModulePath(),
1991 if ( !$msg->exists() ) {
1992 $msg = $this->msg( 'api-help-fallback-description', $desc );
1996 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2002 * Get final list of parameters, after hooks have had a chance to
2003 * tweak it as needed.
2005 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2006 * @return array|bool False on no parameters
2007 * @since 1.21 $flags param added
2009 public function getFinalParams( $flags = 0 ) {
2010 $params = $this->getAllowedParams( $flags );
2015 if ( $this->needsToken() ) {
2016 $params['token'] = [
2017 ApiBase
::PARAM_TYPE
=> 'string',
2018 ApiBase
::PARAM_REQUIRED
=> true,
2019 ApiBase
::PARAM_HELP_MSG
=> [
2020 'api-help-param-token',
2021 $this->needsToken(),
2023 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2026 // Avoid PHP 7.1 warning of passing $this by reference
2028 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2034 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2037 * @since 1.25, returns array of Message[] rather than array of string[]
2038 * @return array Keys are parameter names, values are arrays of Message objects
2040 public function getFinalParamDescription() {
2041 $prefix = $this->getModulePrefix();
2042 $name = $this->getModuleName();
2043 $path = $this->getModulePath();
2045 $desc = $this->getParamDescription();
2047 // Avoid PHP 7.1 warning of passing $this by reference
2049 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2054 $desc = self
::escapeWikiText( $desc );
2056 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2058 foreach ( $params as $param => $settings ) {
2059 if ( !is_array( $settings ) ) {
2063 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2064 if ( is_array( $d ) ) {
2065 // Special handling for prop parameters
2066 $d = array_map( function ( $line ) {
2067 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2068 $line = "\n;{$m[1]}:{$m[2]}";
2072 $d = implode( ' ', $d );
2075 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2076 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2078 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2079 if ( !$msg->exists() ) {
2080 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2083 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2084 [ $prefix, $param, $name, $path ] );
2086 self
::dieDebug( __METHOD__
,
2087 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2089 $msgs[$param] = [ $msg ];
2091 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2092 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2093 self
::dieDebug( __METHOD__
,
2094 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2096 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2097 self
::dieDebug( __METHOD__
,
2098 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2099 'ApiBase::PARAM_TYPE is an array' );
2102 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2103 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2104 if ( isset( $valueMsgs[$value] ) ) {
2105 $msg = $valueMsgs[$value];
2107 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2109 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2110 [ $prefix, $param, $name, $path, $value ] );
2112 $m = new ApiHelpParamValueMessage(
2114 [ $m->getKey(), 'api-help-param-no-description' ],
2117 $msgs[$param][] = $m->setContext( $this->getContext() );
2119 self
::dieDebug( __METHOD__
,
2120 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2125 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2126 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2127 self
::dieDebug( __METHOD__
,
2128 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2130 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2131 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2132 [ $prefix, $param, $name, $path ] );
2134 $msgs[$param][] = $m;
2136 self
::dieDebug( __METHOD__
,
2137 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2143 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2149 * Generates the list of flags for the help screen and for action=paraminfo
2151 * Corresponding messages: api-help-flag-deprecated,
2152 * api-help-flag-internal, api-help-flag-readrights,
2153 * api-help-flag-writerights, api-help-flag-mustbeposted
2157 protected function getHelpFlags() {
2160 if ( $this->isDeprecated() ) {
2161 $flags[] = 'deprecated';
2163 if ( $this->isInternal() ) {
2164 $flags[] = 'internal';
2166 if ( $this->isReadMode() ) {
2167 $flags[] = 'readrights';
2169 if ( $this->isWriteMode() ) {
2170 $flags[] = 'writerights';
2172 if ( $this->mustBePosted() ) {
2173 $flags[] = 'mustbeposted';
2180 * Returns information about the source of this module, if known
2182 * Returned array is an array with the following keys:
2183 * - path: Install path
2184 * - name: Extension name, or "MediaWiki" for core
2185 * - namemsg: (optional) i18n message key for a display name
2186 * - license-name: (optional) Name of license
2188 * @return array|null
2190 protected function getModuleSourceInfo() {
2193 if ( $this->mModuleSource
!== false ) {
2194 return $this->mModuleSource
;
2197 // First, try to find where the module comes from...
2198 $rClass = new ReflectionClass( $this );
2199 $path = $rClass->getFileName();
2202 $this->mModuleSource
= null;
2205 $path = realpath( $path ) ?
: $path;
2207 // Build map of extension directories to extension info
2208 if ( self
::$extensionInfo === null ) {
2209 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2210 self
::$extensionInfo = [
2211 realpath( __DIR__
) ?
: __DIR__
=> [
2213 'name' => 'MediaWiki',
2214 'license-name' => 'GPL-2.0+',
2216 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2217 realpath( $extDir ) ?
: $extDir => null,
2223 'license-name' => null,
2225 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2226 foreach ( $group as $ext ) {
2227 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2228 // This shouldn't happen, but does anyway.
2232 $extpath = $ext['path'];
2233 if ( !is_dir( $extpath ) ) {
2234 $extpath = dirname( $extpath );
2236 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2237 array_intersect_key( $ext, $keep );
2240 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2241 $extpath = $ext['path'];
2242 if ( !is_dir( $extpath ) ) {
2243 $extpath = dirname( $extpath );
2245 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2246 array_intersect_key( $ext, $keep );
2250 // Now traverse parent directories until we find a match or run out of
2253 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2255 $this->mModuleSource
= self
::$extensionInfo[$path];
2256 return $this->mModuleSource
;
2260 $path = dirname( $path );
2261 } while ( $path !== $oldpath );
2263 // No idea what extension this might be.
2264 $this->mModuleSource
= null;
2269 * Called from ApiHelp before the pieces are joined together and returned.
2271 * This exists mainly for ApiMain to add the Permissions and Credits
2272 * sections. Other modules probably don't need it.
2274 * @param string[] &$help Array of help data
2275 * @param array $options Options passed to ApiHelp::getHelp
2276 * @param array &$tocData If a TOC is being generated, this array has keys
2277 * as anchors in the page and values as for Linker::generateTOC().
2279 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2284 /************************************************************************//**
2290 * Returns the description string for this module
2292 * Ignored if an i18n message exists for
2293 * "apihelp-{$this->getModulePath()}-description".
2295 * @deprecated since 1.25
2296 * @return Message|string|array|false
2298 protected function getDescription() {
2303 * Returns an array of parameter descriptions.
2305 * For each parameter, ignored if an i18n message exists for the parameter.
2306 * By default that message is
2307 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2308 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2309 * self::getFinalParams().
2311 * @deprecated since 1.25
2312 * @return array|bool False on no parameter descriptions
2314 protected function getParamDescription() {
2319 * Returns usage examples for this module.
2321 * Return value as an array is either:
2322 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2324 * - sequential numeric keys with even-numbered keys being display-text
2325 * and odd-numbered keys being partial urls
2326 * - partial URLs as keys with display-text (string or array-to-be-joined)
2328 * Return value as a string is the same as an array with a numeric key and
2329 * that value, and boolean false means "no examples".
2331 * @deprecated since 1.25, use getExamplesMessages() instead
2332 * @return bool|string|array
2334 protected function getExamples() {
2339 * @deprecated since 1.25, always returns empty string
2340 * @param IDatabase|bool $db
2343 public function getModuleProfileName( $db = false ) {
2344 wfDeprecated( __METHOD__
, '1.25' );
2349 * @deprecated since 1.25
2351 public function profileIn() {
2352 // No wfDeprecated() yet because extensions call this and might need to
2353 // keep doing so for BC.
2357 * @deprecated since 1.25
2359 public function profileOut() {
2360 // No wfDeprecated() yet because extensions call this and might need to
2361 // keep doing so for BC.
2365 * @deprecated since 1.25
2367 public function safeProfileOut() {
2368 wfDeprecated( __METHOD__
, '1.25' );
2372 * @deprecated since 1.25, always returns 0
2375 public function getProfileTime() {
2376 wfDeprecated( __METHOD__
, '1.25' );
2381 * @deprecated since 1.25
2383 public function profileDBIn() {
2384 wfDeprecated( __METHOD__
, '1.25' );
2388 * @deprecated since 1.25
2390 public function profileDBOut() {
2391 wfDeprecated( __METHOD__
, '1.25' );
2395 * @deprecated since 1.25, always returns 0
2398 public function getProfileDBTime() {
2399 wfDeprecated( __METHOD__
, '1.25' );
2404 * Call wfTransactionalTimeLimit() if this request was POSTed
2407 protected function useTransactionalTimeLimit() {
2408 if ( $this->getRequest()->wasPosted() ) {
2409 wfTransactionalTimeLimit();
2414 * @deprecated since 1.29, use ApiBase::addWarning() instead
2415 * @param string $warning Warning message
2417 public function setWarning( $warning ) {
2418 $msg = new ApiRawMessage( $warning, 'warning' );
2419 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2423 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2424 * error handler and die with an error message.
2426 * @deprecated since 1.29, use self::dieWithError() instead
2427 * @param string $description One-line human-readable description of the
2428 * error condition, e.g., "The API requires a valid action parameter"
2429 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2430 * automated identification of the error, e.g., 'unknown_action'
2431 * @param int $httpRespCode HTTP response code
2432 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2433 * @throws ApiUsageException always
2435 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2436 $this->dieWithError(
2437 new RawMessage( '$1', [ $description ] ),
2445 * Get error (as code, string) from a Status object.
2448 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2449 * @param Status $status
2450 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2451 * @return array Array of code and error string
2452 * @throws MWException
2454 public function getErrorFromStatus( $status, &$extraData = null ) {
2455 if ( $status->isGood() ) {
2456 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2459 $errors = $status->getErrorsByType( 'error' );
2461 // No errors? Assume the warnings should be treated as errors
2462 $errors = $status->getErrorsByType( 'warning' );
2465 // Still no errors? Punt
2466 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2469 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2470 $msg = $errors[0]['message'];
2472 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2474 if ( !$msg instanceof IApiMessage
) {
2475 $key = $msg->getKey();
2476 $params = $msg->getParams();
2477 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2478 $msg = ApiMessage
::create( $params );
2483 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2488 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2489 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2490 * API codes and message texts, and a few interfaces required poking
2491 * something in here. Now we're repurposing it to map those same strings
2492 * to i18n messages, and declaring that any interface that requires poking
2493 * at this is broken and needs replacing ASAP.
2495 private static $messageMap = [
2496 'unknownerror' => 'apierror-unknownerror',
2497 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2498 'ns-specialprotected' => 'ns-specialprotected',
2499 'protectedinterface' => 'protectedinterface',
2500 'namespaceprotected' => 'namespaceprotected',
2501 'customcssprotected' => 'customcssprotected',
2502 'customjsprotected' => 'customjsprotected',
2503 'cascadeprotected' => 'cascadeprotected',
2504 'protectedpagetext' => 'protectedpagetext',
2505 'protect-cantedit' => 'protect-cantedit',
2506 'deleteprotected' => 'deleteprotected',
2507 'badaccess-group0' => 'badaccess-group0',
2508 'badaccess-groups' => 'badaccess-groups',
2509 'titleprotected' => 'titleprotected',
2510 'nocreate-loggedin' => 'nocreate-loggedin',
2511 'nocreatetext' => 'nocreatetext',
2512 'movenologintext' => 'movenologintext',
2513 'movenotallowed' => 'movenotallowed',
2514 'confirmedittext' => 'confirmedittext',
2515 'blockedtext' => 'apierror-blocked',
2516 'autoblockedtext' => 'apierror-autoblocked',
2517 'systemblockedtext' => 'apierror-systemblocked',
2518 'actionthrottledtext' => 'apierror-ratelimited',
2519 'alreadyrolled' => 'alreadyrolled',
2520 'cantrollback' => 'cantrollback',
2521 'readonlytext' => 'readonlytext',
2522 'sessionfailure' => 'sessionfailure',
2523 'cannotdelete' => 'cannotdelete',
2524 'notanarticle' => 'apierror-missingtitle',
2525 'selfmove' => 'selfmove',
2526 'immobile_namespace' => 'apierror-immobilenamespace',
2527 'articleexists' => 'articleexists',
2528 'hookaborted' => 'hookaborted',
2529 'cantmove-titleprotected' => 'cantmove-titleprotected',
2530 'imagenocrossnamespace' => 'imagenocrossnamespace',
2531 'imagetypemismatch' => 'imagetypemismatch',
2532 'ip_range_invalid' => 'ip_range_invalid',
2533 'range_block_disabled' => 'range_block_disabled',
2534 'nosuchusershort' => 'nosuchusershort',
2535 'badipaddress' => 'badipaddress',
2536 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2537 'ipb_already_blocked' => 'ipb_already_blocked',
2538 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2539 'ipb_cant_unblock' => 'ipb_cant_unblock',
2540 'mailnologin' => 'apierror-cantsend',
2541 'ipbblocked' => 'ipbblocked',
2542 'ipbnounblockself' => 'ipbnounblockself',
2543 'usermaildisabled' => 'usermaildisabled',
2544 'blockedemailuser' => 'apierror-blockedfrommail',
2545 'notarget' => 'apierror-notarget',
2546 'noemail' => 'noemail',
2547 'rcpatroldisabled' => 'rcpatroldisabled',
2548 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2549 'delete-toobig' => 'delete-toobig',
2550 'movenotallowedfile' => 'movenotallowedfile',
2551 'userrights-no-interwiki' => 'userrights-no-interwiki',
2552 'userrights-nodatabase' => 'userrights-nodatabase',
2553 'nouserspecified' => 'nouserspecified',
2554 'noname' => 'noname',
2555 'summaryrequired' => 'apierror-summaryrequired',
2556 'import-rootpage-invalid' => 'import-rootpage-invalid',
2557 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2558 'readrequired' => 'apierror-readapidenied',
2559 'writedisabled' => 'apierror-noapiwrite',
2560 'writerequired' => 'apierror-writeapidenied',
2561 'missingparam' => 'apierror-missingparam',
2562 'invalidtitle' => 'apierror-invalidtitle',
2563 'nosuchpageid' => 'apierror-nosuchpageid',
2564 'nosuchrevid' => 'apierror-nosuchrevid',
2565 'nosuchuser' => 'nosuchusershort',
2566 'invaliduser' => 'apierror-invaliduser',
2567 'invalidexpiry' => 'apierror-invalidexpiry',
2568 'pastexpiry' => 'apierror-pastexpiry',
2569 'create-titleexists' => 'apierror-create-titleexists',
2570 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2571 'cantblock' => 'apierror-cantblock',
2572 'canthide' => 'apierror-canthide',
2573 'cantblock-email' => 'apierror-cantblock-email',
2574 'cantunblock' => 'apierror-permissiondenied-generic',
2575 'cannotundelete' => 'cannotundelete',
2576 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2577 'createonly-exists' => 'apierror-articleexists',
2578 'nocreate-missing' => 'apierror-missingtitle',
2579 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2580 'nosuchrcid' => 'apierror-nosuchrcid',
2581 'nosuchlogid' => 'apierror-nosuchlogid',
2582 'protect-invalidaction' => 'apierror-protect-invalidaction',
2583 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2584 'toofewexpiries' => 'apierror-toofewexpiries',
2585 'cantimport' => 'apierror-cantimport',
2586 'cantimport-upload' => 'apierror-cantimport-upload',
2587 'importnofile' => 'importnofile',
2588 'importuploaderrorsize' => 'importuploaderrorsize',
2589 'importuploaderrorpartial' => 'importuploaderrorpartial',
2590 'importuploaderrortemp' => 'importuploaderrortemp',
2591 'importcantopen' => 'importcantopen',
2592 'import-noarticle' => 'import-noarticle',
2593 'importbadinterwiki' => 'importbadinterwiki',
2594 'import-unknownerror' => 'apierror-import-unknownerror',
2595 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2596 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2597 'mustbeposted' => 'apierror-mustbeposted',
2598 'show' => 'apierror-show',
2599 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2600 'invalidoldimage' => 'apierror-invalidoldimage',
2601 'nodeleteablefile' => 'apierror-nodeleteablefile',
2602 'fileexists-forbidden' => 'fileexists-forbidden',
2603 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2604 'filerevert-badversion' => 'filerevert-badversion',
2605 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2606 'noimageredirect-logged' => 'apierror-noimageredirect',
2607 'spamdetected' => 'apierror-spamdetected',
2608 'contenttoobig' => 'apierror-contenttoobig',
2609 'noedit-anon' => 'apierror-noedit-anon',
2610 'noedit' => 'apierror-noedit',
2611 'wasdeleted' => 'apierror-pagedeleted',
2612 'blankpage' => 'apierror-emptypage',
2613 'editconflict' => 'editconflict',
2614 'hashcheckfailed' => 'apierror-badmd5',
2615 'missingtext' => 'apierror-notext',
2616 'emptynewsection' => 'apierror-emptynewsection',
2617 'revwrongpage' => 'apierror-revwrongpage',
2618 'undo-failure' => 'undo-failure',
2619 'content-not-allowed-here' => 'content-not-allowed-here',
2620 'edit-hook-aborted' => 'edit-hook-aborted',
2621 'edit-gone-missing' => 'edit-gone-missing',
2622 'edit-conflict' => 'edit-conflict',
2623 'edit-already-exists' => 'edit-already-exists',
2624 'invalid-file-key' => 'apierror-invalid-file-key',
2625 'nouploadmodule' => 'apierror-nouploadmodule',
2626 'uploaddisabled' => 'uploaddisabled',
2627 'copyuploaddisabled' => 'copyuploaddisabled',
2628 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2629 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2630 'filename-tooshort' => 'filename-tooshort',
2631 'filename-toolong' => 'filename-toolong',
2632 'illegal-filename' => 'illegal-filename',
2633 'filetype-missing' => 'filetype-missing',
2634 'mustbeloggedin' => 'apierror-mustbeloggedin',
2638 * @deprecated do not use
2639 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2640 * @return ApiMessage
2642 private function parseMsgInternal( $error ) {
2643 $msg = Message
::newFromSpecifier( $error );
2644 if ( !$msg instanceof IApiMessage
) {
2645 $key = $msg->getKey();
2646 if ( isset( self
::$messageMap[$key] ) ) {
2647 $params = $msg->getParams();
2648 array_unshift( $params, self
::$messageMap[$key] );
2650 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2652 $msg = ApiMessage
::create( $params );
2658 * Return the error message related to a certain array
2659 * @deprecated since 1.29
2660 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2661 * @return [ 'code' => code, 'info' => info ]
2663 public function parseMsg( $error ) {
2664 // Check whether someone passed the whole array, instead of one element as
2665 // documented. This breaks if it's actually an array of fallback keys, but
2666 // that's long-standing misbehavior introduced in r87627 to incorrectly
2668 if ( is_array( $error ) ) {
2669 $first = reset( $error );
2670 if ( is_array( $first ) ) {
2671 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2676 $msg = $this->parseMsgInternal( $error );
2678 'code' => $msg->getApiCode(),
2679 'info' => ApiErrorFormatter
::stripMarkup(
2680 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2682 'data' => $msg->getApiData()
2687 * Output the error message related to a certain array
2688 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2689 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2690 * @throws ApiUsageException always
2692 public function dieUsageMsg( $error ) {
2693 $this->dieWithError( $this->parseMsgInternal( $error ) );
2697 * Will only set a warning instead of failing if the global $wgDebugAPI
2698 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2699 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2700 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2701 * @throws ApiUsageException
2704 public function dieUsageMsgOrDebug( $error ) {
2705 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2712 * For really cool vim folding this needs to be at the end:
2713 * vim: foldmarker=@{,@} foldmethod=marker