5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Self-documentation: code to allow the API to document its own state
39 abstract class ApiBase
extends ContextSource
{
42 * @name Constants for ::getAllowedParams() arrays
43 * These constants are keys in the arrays returned by ::getAllowedParams()
44 * and accepted by ::getParameterFromSettings() that define how the
45 * parameters coming in from the request are to be interpreted.
49 /** (null|boolean|integer|string) Default value of the parameter. */
52 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
53 const PARAM_ISMULTI
= 1;
56 * (string|string[]) Either an array of allowed value strings, or a string
57 * type as described below. If not specified, will be determined from the
60 * Supported string types are:
61 * - boolean: A boolean parameter, returned as false if the parameter is
62 * omitted and true if present (even with a falsey value, i.e. it works
63 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
64 * Cannot be used with PARAM_ISMULTI.
65 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
66 * PARAM_RANGE_ENFORCE.
67 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
68 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
69 * specified. Cannot be used with PARAM_ISMULTI.
70 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
71 * support easily specifying all namespaces.
73 * - password: Any non-empty string. Input value is private or sensitive.
74 * <input type="password"> would be an appropriate HTML form field.
75 * - string: Any non-empty string, not expected to be very long or contain newlines.
76 * <input type="text"> would be an appropriate HTML form field.
77 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
78 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
79 * used with PARAM_ISMULTI.
80 * - text: Any non-empty string, expected to be very long or contain newlines.
81 * <textarea> would be an appropriate HTML form field.
82 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
83 * string 'now' representing the current timestamp. Will be returned in
85 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
86 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
87 * Cannot be used with PARAM_ISMULTI.
91 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
95 * (integer) Max value allowed for the parameter for users with the
96 * apihighlimits right, for PARAM_TYPE 'limit'.
100 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
103 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
104 const PARAM_ALLOW_DUPLICATES
= 6;
106 /** (boolean) Is the parameter deprecated (will show a warning)? */
107 const PARAM_DEPRECATED
= 7;
110 * (boolean) Is the parameter required?
113 const PARAM_REQUIRED
= 8;
116 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
119 const PARAM_RANGE_ENFORCE
= 9;
122 * (string|array|Message) Specify an alternative i18n documentation message
123 * for this parameter. Default is apihelp-{$path}-param-{$param}.
126 const PARAM_HELP_MSG
= 10;
129 * ((string|array|Message)[]) Specify additional i18n messages to append to
130 * the normal message for this parameter.
133 const PARAM_HELP_MSG_APPEND
= 11;
136 * (array) Specify additional information tags for the parameter. Value is
137 * an array of arrays, with the first member being the 'tag' for the info
138 * and the remaining members being the values. In the help, this is
139 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
140 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
143 const PARAM_HELP_MSG_INFO
= 12;
146 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
147 * those values to page titles which will be linked in the help.
150 const PARAM_VALUE_LINKS
= 13;
153 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
154 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
155 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
158 const PARAM_HELP_MSG_PER_VALUE
= 14;
161 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
162 * submodule paths. Default is to use all modules in
163 * $this->getModuleManager() in the group matching the parameter name.
166 const PARAM_SUBMODULE_MAP
= 15;
169 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
170 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
173 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
176 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
177 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
178 * every possible value. If a string is set, it will be used in place of the asterisk.
181 const PARAM_ALL
= 17;
185 const ALL_DEFAULT_STRING
= '*';
187 /** Fast query, standard limit. */
188 const LIMIT_BIG1
= 500;
189 /** Fast query, apihighlimits limit. */
190 const LIMIT_BIG2
= 5000;
191 /** Slow query, standard limit. */
192 const LIMIT_SML1
= 50;
193 /** Slow query, apihighlimits limit. */
194 const LIMIT_SML2
= 500;
197 * getAllowedParams() flag: When set, the result could take longer to generate,
198 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
201 const GET_VALUES_FOR_HELP
= 1;
203 /** @var array Maps extension paths to info arrays */
204 private static $extensionInfo = null;
207 private $mMainModule;
209 private $mModuleName, $mModulePrefix;
210 private $mSlaveDB = null;
211 private $mParamCache = [];
212 /** @var array|null|bool */
213 private $mModuleSource = false;
216 * @param ApiMain $mainModule
217 * @param string $moduleName Name of this module
218 * @param string $modulePrefix Prefix to use for parameter names
220 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
221 $this->mMainModule
= $mainModule;
222 $this->mModuleName
= $moduleName;
223 $this->mModulePrefix
= $modulePrefix;
225 if ( !$this->isMain() ) {
226 $this->setContext( $mainModule->getContext() );
230 /************************************************************************//**
231 * @name Methods to implement
236 * Evaluates the parameters, performs the requested query, and sets up
237 * the result. Concrete implementations of ApiBase must override this
238 * method to provide whatever functionality their module offers.
239 * Implementations must not produce any output on their own and are not
240 * expected to handle any errors.
242 * The execute() method will be invoked directly by ApiMain immediately
243 * before the result of the module is output. Aside from the
244 * constructor, implementations should assume that no other methods
245 * will be called externally on the module before the result is
248 * The result data should be stored in the ApiResult object available
249 * through getResult().
251 abstract public function execute();
254 * Get the module manager, or null if this module has no sub-modules
256 * @return ApiModuleManager
258 public function getModuleManager() {
263 * If the module may only be used with a certain format module,
264 * it should override this method to return an instance of that formatter.
265 * A value of null means the default format will be used.
266 * @note Do not use this just because you don't want to support non-json
267 * formats. This should be used only when there is a fundamental
268 * requirement for a specific format.
269 * @return mixed Instance of a derived class of ApiFormatBase, or null
271 public function getCustomPrinter() {
276 * Returns usage examples for this module.
278 * Return value has query strings as keys, with values being either strings
279 * (message key), arrays (message key + parameter), or Message objects.
281 * Do not call this base class implementation when overriding this method.
286 protected function getExamplesMessages() {
287 // Fall back to old non-localised method
290 $examples = $this->getExamples();
292 if ( !is_array( $examples ) ) {
293 $examples = [ $examples ];
294 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
295 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
296 !preg_match( '/^\s*api\.php\?/', $examples[0] )
298 // Fix up the ugly "even numbered elements are description, odd
299 // numbered elemts are the link" format (see doc for self::getExamples)
301 $examplesCount = count( $examples );
302 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
303 $tmp[$examples[$i +
1]] = $examples[$i];
308 foreach ( $examples as $k => $v ) {
309 if ( is_numeric( $k ) ) {
314 $msg = self
::escapeWikiText( $v );
315 if ( is_array( $msg ) ) {
316 $msg = implode( ' ', $msg );
320 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
321 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
329 * Return links to more detailed help pages about the module.
330 * @since 1.25, returning boolean false is deprecated
331 * @return string|array
333 public function getHelpUrls() {
338 * Returns an array of allowed parameters (parameter name) => (default
339 * value) or (parameter name) => (array with PARAM_* constants as keys)
340 * Don't call this function directly: use getFinalParams() to allow
341 * hooks to modify parameters as needed.
343 * Some derived classes may choose to handle an integer $flags parameter
344 * in the overriding methods. Callers of this method can pass zero or
345 * more OR-ed flags like GET_VALUES_FOR_HELP.
349 protected function getAllowedParams( /* $flags = 0 */ ) {
350 // int $flags is not declared because it causes "Strict standards"
351 // warning. Most derived classes do not implement it.
356 * Indicates if this module needs maxlag to be checked
359 public function shouldCheckMaxlag() {
364 * Indicates whether this module requires read rights
367 public function isReadMode() {
372 * Indicates whether this module requires write mode
375 public function isWriteMode() {
380 * Indicates whether this module must be called with a POST request
383 public function mustBePosted() {
384 return $this->needsToken() !== false;
388 * Indicates whether this module is deprecated
392 public function isDeprecated() {
397 * Indicates whether this module is "internal"
398 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
402 public function isInternal() {
407 * Returns the token type this module requires in order to execute.
409 * Modules are strongly encouraged to use the core 'csrf' type unless they
410 * have specialized security needs. If the token type is not one of the
411 * core types, you must use the ApiQueryTokensRegisterTypes hook to
414 * Returning a non-falsey value here will force the addition of an
415 * appropriate 'token' parameter in self::getFinalParams(). Also,
416 * self::mustBePosted() must return true when tokens are used.
418 * In previous versions of MediaWiki, true was a valid return value.
419 * Returning true will generate errors indicating that the API module needs
422 * @return string|false
424 public function needsToken() {
429 * Fetch the salt used in the Web UI corresponding to this module.
431 * Only override this if the Web UI uses a token with a non-constant salt.
434 * @param array $params All supplied parameters for the module
435 * @return string|array|null
437 protected function getWebUITokenSalt( array $params ) {
442 * Returns data for HTTP conditional request mechanisms.
445 * @param string $condition Condition being queried:
446 * - last-modified: Return a timestamp representing the maximum of the
447 * last-modified dates for all resources involved in the request. See
448 * RFC 7232 § 2.2 for semantics.
449 * - etag: Return an entity-tag representing the state of all resources involved
450 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
451 * @return string|bool|null As described above, or null if no value is available.
453 public function getConditionalRequestData( $condition ) {
459 /************************************************************************//**
460 * @name Data access methods
465 * Get the name of the module being executed by this instance
468 public function getModuleName() {
469 return $this->mModuleName
;
473 * Get parameter prefix (usually two letters or an empty string).
476 public function getModulePrefix() {
477 return $this->mModulePrefix
;
481 * Get the main module
484 public function getMain() {
485 return $this->mMainModule
;
489 * Returns true if this module is the main module ($this === $this->mMainModule),
493 public function isMain() {
494 return $this === $this->mMainModule
;
498 * Get the parent of this module
500 * @return ApiBase|null
502 public function getParent() {
503 return $this->isMain() ?
null : $this->getMain();
507 * Returns true if the current request breaks the same-origin policy.
509 * For example, json with callbacks.
511 * https://en.wikipedia.org/wiki/Same-origin_policy
516 public function lacksSameOriginSecurity() {
517 // Main module has this method overridden
518 // Safety - avoid infinite loop:
519 if ( $this->isMain() ) {
520 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
523 return $this->getMain()->lacksSameOriginSecurity();
527 * Get the path to this module
532 public function getModulePath() {
533 if ( $this->isMain() ) {
535 } elseif ( $this->getParent()->isMain() ) {
536 return $this->getModuleName();
538 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
543 * Get a module from its module path
546 * @param string $path
547 * @return ApiBase|null
548 * @throws ApiUsageException
550 public function getModuleFromPath( $path ) {
551 $module = $this->getMain();
552 if ( $path === 'main' ) {
556 $parts = explode( '+', $path );
557 if ( count( $parts ) === 1 ) {
558 // In case the '+' was typed into URL, it resolves as a space
559 $parts = explode( ' ', $path );
562 $count = count( $parts );
563 for ( $i = 0; $i < $count; $i++
) {
565 $manager = $parent->getModuleManager();
566 if ( $manager === null ) {
567 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
568 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
570 $module = $manager->getModule( $parts[$i] );
572 if ( $module === null ) {
573 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
575 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
585 * Get the result object
588 public function getResult() {
589 // Main module has getResult() method overridden
590 // Safety - avoid infinite loop:
591 if ( $this->isMain() ) {
592 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
595 return $this->getMain()->getResult();
599 * Get the error formatter
600 * @return ApiErrorFormatter
602 public function getErrorFormatter() {
603 // Main module has getErrorFormatter() method overridden
604 // Safety - avoid infinite loop:
605 if ( $this->isMain() ) {
606 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
609 return $this->getMain()->getErrorFormatter();
613 * Gets a default replica DB connection object
616 protected function getDB() {
617 if ( !isset( $this->mSlaveDB
) ) {
618 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
621 return $this->mSlaveDB
;
625 * Get the continuation manager
626 * @return ApiContinuationManager|null
628 public function getContinuationManager() {
629 // Main module has getContinuationManager() method overridden
630 // Safety - avoid infinite loop:
631 if ( $this->isMain() ) {
632 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
635 return $this->getMain()->getContinuationManager();
639 * Set the continuation manager
640 * @param ApiContinuationManager|null
642 public function setContinuationManager( $manager ) {
643 // Main module has setContinuationManager() method overridden
644 // Safety - avoid infinite loop:
645 if ( $this->isMain() ) {
646 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
649 $this->getMain()->setContinuationManager( $manager );
654 /************************************************************************//**
655 * @name Parameter handling
660 * Indicate if the module supports dynamically-determined parameters that
661 * cannot be included in self::getAllowedParams().
662 * @return string|array|Message|null Return null if the module does not
663 * support additional dynamic parameters, otherwise return a message
666 public function dynamicParameterDocumentation() {
671 * This method mangles parameter name based on the prefix supplied to the constructor.
672 * Override this method to change parameter name during runtime
673 * @param string|string[] $paramName Parameter name
674 * @return string|string[] Prefixed parameter name
675 * @since 1.29 accepts an array of strings
677 public function encodeParamName( $paramName ) {
678 if ( is_array( $paramName ) ) {
679 return array_map( function ( $name ) {
680 return $this->mModulePrefix
. $name;
683 return $this->mModulePrefix
. $paramName;
688 * Using getAllowedParams(), this function makes an array of the values
689 * provided by the user, with key being the name of the variable, and
690 * value - validated value from user or default. limits will not be
691 * parsed if $parseLimit is set to false; use this when the max
692 * limit is not definitive yet, e.g. when getting revisions.
693 * @param bool $parseLimit True by default
696 public function extractRequestParams( $parseLimit = true ) {
697 // Cache parameters, for performance and to avoid bug 24564.
698 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
699 $params = $this->getFinalParams();
702 if ( $params ) { // getFinalParams() can return false
703 foreach ( $params as $paramName => $paramSettings ) {
704 $results[$paramName] = $this->getParameterFromSettings(
705 $paramName, $paramSettings, $parseLimit );
708 $this->mParamCache
[$parseLimit] = $results;
711 return $this->mParamCache
[$parseLimit];
715 * Get a value for the given parameter
716 * @param string $paramName Parameter name
717 * @param bool $parseLimit See extractRequestParams()
718 * @return mixed Parameter value
720 protected function getParameter( $paramName, $parseLimit = true ) {
721 $paramSettings = $this->getFinalParams()[$paramName];
723 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
727 * Die if none or more than one of a certain set of parameters is set and not false.
729 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
730 * @param string $required,... Names of parameters of which exactly one must be set
732 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
733 $required = func_get_args();
734 array_shift( $required );
736 $intersection = array_intersect( array_keys( array_filter( $params,
737 [ $this, 'parameterNotEmpty' ] ) ), $required );
739 if ( count( $intersection ) > 1 ) {
740 $this->dieWithError( [
741 'apierror-invalidparammix',
742 Message
::listParam( array_map(
744 return '<var>' . $this->encodeParamName( $p ) . '</var>';
746 array_values( $intersection )
748 count( $intersection ),
750 } elseif ( count( $intersection ) == 0 ) {
751 $this->dieWithError( [
752 'apierror-missingparam-one-of',
753 Message
::listParam( array_map(
755 return '<var>' . $this->encodeParamName( $p ) . '</var>';
757 array_values( $required )
765 * Die if more than one of a certain set of parameters is set and not false.
767 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
768 * @param string $required,... Names of parameters of which at most one must be set
770 public function requireMaxOneParameter( $params, $required /*...*/ ) {
771 $required = func_get_args();
772 array_shift( $required );
774 $intersection = array_intersect( array_keys( array_filter( $params,
775 [ $this, 'parameterNotEmpty' ] ) ), $required );
777 if ( count( $intersection ) > 1 ) {
778 $this->dieWithError( [
779 'apierror-invalidparammix',
780 Message
::listParam( array_map(
782 return '<var>' . $this->encodeParamName( $p ) . '</var>';
784 array_values( $intersection )
786 count( $intersection ),
792 * Die if none of a certain set of parameters is set and not false.
795 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
796 * @param string $required,... Names of parameters of which at least one must be set
798 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
799 $required = func_get_args();
800 array_shift( $required );
802 $intersection = array_intersect(
803 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
807 if ( count( $intersection ) == 0 ) {
808 $this->dieWithError( [
809 'apierror-missingparam-at-least-one-of',
810 Message
::listParam( array_map(
812 return '<var>' . $this->encodeParamName( $p ) . '</var>';
814 array_values( $required )
822 * Die if any of the specified parameters were found in the query part of
823 * the URL rather than the post body.
825 * @param string[] $params Parameters to check
826 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
828 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
829 // Skip if $wgDebugAPI is set or we're in internal mode
830 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
834 $queryValues = $this->getRequest()->getQueryValues();
836 foreach ( $params as $param ) {
837 if ( $prefix !== 'noprefix' ) {
838 $param = $this->encodeParamName( $param );
840 if ( array_key_exists( $param, $queryValues ) ) {
841 $badParams[] = $param;
847 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
853 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
855 * @param object $x Parameter to check is not null/false
858 private function parameterNotEmpty( $x ) {
859 return !is_null( $x ) && $x !== false;
863 * Get a WikiPage object from a title or pageid param, if possible.
864 * Can die, if no param is set or if the title or page id is not valid.
866 * @param array $params
867 * @param bool|string $load Whether load the object's state from the database:
868 * - false: don't load (if the pageid is given, it will still be loaded)
869 * - 'fromdb': load from a replica DB
870 * - 'fromdbmaster': load from the master database
873 public function getTitleOrPageId( $params, $load = false ) {
874 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
877 if ( isset( $params['title'] ) ) {
878 $titleObj = Title
::newFromText( $params['title'] );
879 if ( !$titleObj ||
$titleObj->isExternal() ) {
880 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
882 if ( !$titleObj->canExist() ) {
883 $this->dieWithError( 'apierror-pagecannotexist' );
885 $pageObj = WikiPage
::factory( $titleObj );
886 if ( $load !== false ) {
887 $pageObj->loadPageData( $load );
889 } elseif ( isset( $params['pageid'] ) ) {
890 if ( $load === false ) {
893 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
895 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
903 * Return true if we're to watch the page, false if not, null if no change.
904 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
905 * @param Title $titleObj The page under consideration
906 * @param string $userOption The user option to consider when $watchlist=preferences.
907 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
910 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
912 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
914 switch ( $watchlist ) {
922 # If the user is already watching, don't bother checking
923 if ( $userWatching ) {
926 # If no user option was passed, use watchdefault and watchcreations
927 if ( is_null( $userOption ) ) {
928 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
929 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
932 # Watch the article based on the user preference
933 return $this->getUser()->getBoolOption( $userOption );
936 return $userWatching;
939 return $userWatching;
944 * Using the settings determine the value for the given parameter
946 * @param string $paramName Parameter name
947 * @param array|mixed $paramSettings Default value or an array of settings
948 * using PARAM_* constants.
949 * @param bool $parseLimit Parse limit?
950 * @return mixed Parameter value
952 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
953 // Some classes may decide to change parameter names
954 $encParamName = $this->encodeParamName( $paramName );
956 if ( !is_array( $paramSettings ) ) {
957 $default = $paramSettings;
959 $type = gettype( $paramSettings );
965 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
966 ?
$paramSettings[self
::PARAM_DFLT
]
968 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
969 ?
$paramSettings[self
::PARAM_ISMULTI
]
971 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
972 ?
$paramSettings[self
::PARAM_TYPE
]
974 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
975 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
977 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
978 ?
$paramSettings[self
::PARAM_DEPRECATED
]
980 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
981 ?
$paramSettings[self
::PARAM_REQUIRED
]
983 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
984 ?
$paramSettings[self
::PARAM_ALL
]
987 // When type is not given, and no choices, the type is the same as $default
988 if ( !isset( $type ) ) {
989 if ( isset( $default ) ) {
990 $type = gettype( $default );
992 $type = 'NULL'; // allow everything
997 if ( $type == 'boolean' ) {
998 if ( isset( $default ) && $default !== false ) {
999 // Having a default value of anything other than 'false' is not allowed
1002 "Boolean param $encParamName's default is set to '$default'. " .
1003 'Boolean parameters must default to false.'
1007 $value = $this->getMain()->getCheck( $encParamName );
1008 } elseif ( $type == 'upload' ) {
1009 if ( isset( $default ) ) {
1010 // Having a default value is not allowed
1013 "File upload param $encParamName's default is set to " .
1014 "'$default'. File upload parameters may not have a default." );
1017 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1019 $value = $this->getMain()->getUpload( $encParamName );
1020 if ( !$value->exists() ) {
1021 // This will get the value without trying to normalize it
1022 // (because trying to normalize a large binary file
1023 // accidentally uploaded as a field fails spectacularly)
1024 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1025 if ( $value !== null ) {
1026 $this->dieWithError(
1027 [ 'apierror-badupload', $encParamName ],
1028 "badupload_{$encParamName}"
1033 $value = $this->getMain()->getVal( $encParamName, $default );
1035 if ( isset( $value ) && $type == 'namespace' ) {
1036 $type = MWNamespace
::getValidNamespaces();
1037 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1041 if ( isset( $value ) && $type == 'submodule' ) {
1042 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1043 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1045 $type = $this->getModuleManager()->getNames( $paramName );
1049 $request = $this->getMain()->getRequest();
1050 $rawValue = $request->getRawVal( $encParamName );
1051 if ( $rawValue === null ) {
1052 $rawValue = $default;
1055 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1056 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1058 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1059 // done by WebRequest for $_GET. Let's call that a feature.
1060 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1062 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1066 // Check for NFC normalization, and warn
1067 if ( $rawValue !== $value ) {
1068 $this->handleParamNormalization( $paramName, $value, $rawValue );
1072 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1073 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1076 "For param $encParamName, PARAM_ALL collides with a possible value" );
1078 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1079 $value = $this->parseMultiValue(
1083 is_array( $type ) ?
$type : null,
1084 $allowAll ?
$allSpecifier : null
1088 // More validation only when choices were not given
1089 // choices were validated in parseMultiValue()
1090 if ( isset( $value ) ) {
1091 if ( !is_array( $type ) ) {
1093 case 'NULL': // nothing to do
1098 if ( $required && $value === '' ) {
1099 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1102 case 'integer': // Force everything using intval() and optionally validate limits
1103 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1104 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1105 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1106 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1108 if ( is_array( $value ) ) {
1109 $value = array_map( 'intval', $value );
1110 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1111 foreach ( $value as &$v ) {
1112 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1116 $value = intval( $value );
1117 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1118 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1123 if ( !$parseLimit ) {
1124 // Don't do any validation whatsoever
1127 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1128 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1132 "MAX1 or MAX2 are not defined for the limit $encParamName"
1136 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1138 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1139 if ( $value == 'max' ) {
1140 $value = $this->getMain()->canApiHighLimits()
1141 ?
$paramSettings[self
::PARAM_MAX2
]
1142 : $paramSettings[self
::PARAM_MAX
];
1143 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1145 $value = intval( $value );
1146 $this->validateLimit(
1150 $paramSettings[self
::PARAM_MAX
],
1151 $paramSettings[self
::PARAM_MAX2
]
1157 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1161 if ( is_array( $value ) ) {
1162 foreach ( $value as $key => $val ) {
1163 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1166 $value = $this->validateTimestamp( $value, $encParamName );
1170 if ( is_array( $value ) ) {
1171 foreach ( $value as $key => $val ) {
1172 $value[$key] = $this->validateUser( $val, $encParamName );
1175 $value = $this->validateUser( $value, $encParamName );
1178 case 'upload': // nothing to do
1181 // If change tagging was requested, check that the tags are valid.
1182 if ( !is_array( $value ) && !$multi ) {
1183 $value = [ $value ];
1185 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1186 if ( !$tagsStatus->isGood() ) {
1187 $this->dieStatus( $tagsStatus );
1191 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1195 // Throw out duplicates if requested
1196 if ( !$dupes && is_array( $value ) ) {
1197 $value = array_unique( $value );
1200 // Set a warning if a deprecated parameter has been passed
1201 if ( $deprecated && $value !== false ) {
1202 $feature = $encParamName;
1204 while ( !$m->isMain() ) {
1205 $p = $m->getParent();
1206 $name = $m->getModuleName();
1207 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1208 $feature = "{$param}={$name}&{$feature}";
1211 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1213 } elseif ( $required ) {
1214 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1221 * Handle when a parameter was Unicode-normalized
1223 * @param string $paramName Unprefixed parameter name
1224 * @param string $value Input that will be used.
1225 * @param string $rawValue Input before normalization.
1227 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1228 $encParamName = $this->encodeParamName( $paramName );
1229 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1233 * Split a multi-valued parameter string, like explode()
1235 * @param string $value
1239 protected function explodeMultiValue( $value, $limit ) {
1240 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1242 $value = substr( $value, 1 );
1247 return explode( $sep, $value, $limit );
1251 * Return an array of values that were given in a 'a|b|c' notation,
1252 * after it optionally validates them against the list allowed values.
1254 * @param string $valueName The name of the parameter (for error
1256 * @param mixed $value The value being parsed
1257 * @param bool $allowMultiple Can $value contain more than one value
1259 * @param string[]|null $allowedValues An array of values to check against. If
1260 * null, all values are accepted.
1261 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1262 * if this behavior should not be allowed
1263 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1265 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1266 $allSpecifier = null
1268 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1272 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1273 // because it unstubs $wgUser
1274 $valuesList = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1275 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1279 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1280 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1282 return $allowedValues;
1285 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1286 $this->addDeprecation(
1287 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1288 "too-many-$valueName-for-{$this->getModulePath()}"
1292 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1293 // Bug 33482 - Allow entries with | in them for non-multiple values
1294 if ( in_array( $value, $allowedValues, true ) ) {
1298 if ( is_array( $allowedValues ) ) {
1299 $values = array_map( function ( $v ) {
1300 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1301 }, $allowedValues );
1302 $this->dieWithError( [
1303 'apierror-multival-only-one-of',
1305 Message
::listParam( $values ),
1307 ], "multival_$valueName" );
1309 $this->dieWithError( [
1310 'apierror-multival-only-one',
1312 ], "multival_$valueName" );
1316 if ( is_array( $allowedValues ) ) {
1317 // Check for unknown values
1318 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1319 if ( count( $unknown ) ) {
1320 if ( $allowMultiple ) {
1321 $this->addWarning( [
1322 'apiwarn-unrecognizedvalues',
1324 Message
::listParam( $unknown, 'comma' ),
1328 $this->dieWithError(
1329 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1330 "unknown_$valueName"
1334 // Now throw them out
1335 $valuesList = array_intersect( $valuesList, $allowedValues );
1338 return $allowMultiple ?
$valuesList : $valuesList[0];
1342 * Validate the value against the minimum and user/bot maximum limits.
1343 * Prints usage info on failure.
1344 * @param string $paramName Parameter name
1345 * @param int $value Parameter value
1346 * @param int|null $min Minimum value
1347 * @param int|null $max Maximum value for users
1348 * @param int $botMax Maximum value for sysops/bots
1349 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1351 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1352 $enforceLimits = false
1354 if ( !is_null( $min ) && $value < $min ) {
1355 $msg = ApiMessage
::create(
1356 [ 'apierror-integeroutofrange-belowminimum',
1357 $this->encodeParamName( $paramName ), $min, $value ],
1358 'integeroutofrange',
1359 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1361 $this->warnOrDie( $msg, $enforceLimits );
1365 // Minimum is always validated, whereas maximum is checked only if not
1366 // running in internal call mode
1367 if ( $this->getMain()->isInternalMode() ) {
1371 // Optimization: do not check user's bot status unless really needed -- skips db query
1372 // assumes $botMax >= $max
1373 if ( !is_null( $max ) && $value > $max ) {
1374 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1375 if ( $value > $botMax ) {
1376 $msg = ApiMessage
::create(
1377 [ 'apierror-integeroutofrange-abovebotmax',
1378 $this->encodeParamName( $paramName ), $botMax, $value ],
1379 'integeroutofrange',
1380 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1382 $this->warnOrDie( $msg, $enforceLimits );
1386 $msg = ApiMessage
::create(
1387 [ 'apierror-integeroutofrange-abovemax',
1388 $this->encodeParamName( $paramName ), $max, $value ],
1389 'integeroutofrange',
1390 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1392 $this->warnOrDie( $msg, $enforceLimits );
1399 * Validate and normalize of parameters of type 'timestamp'
1400 * @param string $value Parameter value
1401 * @param string $encParamName Parameter name
1402 * @return string Validated and normalized parameter
1404 protected function validateTimestamp( $value, $encParamName ) {
1405 // Confusing synonyms for the current time accepted by wfTimestamp()
1406 // (wfTimestamp() also accepts various non-strings and the string of 14
1407 // ASCII NUL bytes, but those can't get here)
1409 $this->addDeprecation(
1410 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1411 'unclear-"now"-timestamp'
1413 return wfTimestamp( TS_MW
);
1416 // Explicit synonym for the current time
1417 if ( $value === 'now' ) {
1418 return wfTimestamp( TS_MW
);
1421 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1422 if ( $unixTimestamp === false ) {
1423 $this->dieWithError(
1424 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1425 "badtimestamp_{$encParamName}"
1429 return wfTimestamp( TS_MW
, $unixTimestamp );
1433 * Validate the supplied token.
1436 * @param string $token Supplied token
1437 * @param array $params All supplied parameters for the module
1439 * @throws MWException
1441 final public function validateToken( $token, array $params ) {
1442 $tokenType = $this->needsToken();
1443 $salts = ApiQueryTokens
::getTokenTypeSalts();
1444 if ( !isset( $salts[$tokenType] ) ) {
1445 throw new MWException(
1446 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1447 'without registering it'
1451 $tokenObj = ApiQueryTokens
::getToken(
1452 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1454 if ( $tokenObj->match( $token ) ) {
1458 $webUiSalt = $this->getWebUITokenSalt( $params );
1459 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1471 * Validate and normalize of parameters of type 'user'
1472 * @param string $value Parameter value
1473 * @param string $encParamName Parameter name
1474 * @return string Validated and normalized parameter
1476 private function validateUser( $value, $encParamName ) {
1477 $title = Title
::makeTitleSafe( NS_USER
, $value );
1478 if ( $title === null ||
$title->hasFragment() ) {
1479 $this->dieWithError(
1480 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1481 "baduser_{$encParamName}"
1485 return $title->getText();
1490 /************************************************************************//**
1491 * @name Utility methods
1496 * Set a watch (or unwatch) based the based on a watchlist parameter.
1497 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1498 * @param Title $titleObj The article's title to change
1499 * @param string $userOption The user option to consider when $watch=preferences
1501 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1502 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1503 if ( $value === null ) {
1507 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1511 * Truncate an array to a certain length.
1512 * @param array $arr Array to truncate
1513 * @param int $limit Maximum length
1514 * @return bool True if the array was truncated, false otherwise
1516 public static function truncateArray( &$arr, $limit ) {
1518 while ( count( $arr ) > $limit ) {
1527 * Gets the user for whom to get the watchlist
1529 * @param array $params
1532 public function getWatchlistUser( $params ) {
1533 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1534 $user = User
::newFromName( $params['owner'], false );
1535 if ( !( $user && $user->getId() ) ) {
1536 $this->dieWithError(
1537 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1540 $token = $user->getOption( 'watchlisttoken' );
1541 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1542 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1545 if ( !$this->getUser()->isLoggedIn() ) {
1546 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1548 $this->checkUserRightsAny( 'viewmywatchlist' );
1549 $user = $this->getUser();
1556 * A subset of wfEscapeWikiText for BC texts
1559 * @param string|array $v
1560 * @return string|array
1562 private static function escapeWikiText( $v ) {
1563 if ( is_array( $v ) ) {
1564 return array_map( 'self::escapeWikiText', $v );
1567 '__' => '__', '{' => '{', '}' => '}',
1568 '[[Category:' => '[[:Category:',
1569 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1575 * Create a Message from a string or array
1577 * A string is used as a message key. An array has the message key as the
1578 * first value and message parameters as subsequent values.
1581 * @param string|array|Message $msg
1582 * @param IContextSource $context
1583 * @param array $params
1584 * @return Message|null
1586 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1587 if ( is_string( $msg ) ) {
1588 $msg = wfMessage( $msg );
1589 } elseif ( is_array( $msg ) ) {
1590 $msg = call_user_func_array( 'wfMessage', $msg );
1592 if ( !$msg instanceof Message
) {
1596 $msg->setContext( $context );
1598 $msg->params( $params );
1605 * Turn an array of message keys or key+param arrays into a Status
1607 * @param array $errors
1608 * @param User|null $user
1611 public function errorArrayToStatus( array $errors, User
$user = null ) {
1612 if ( $user === null ) {
1613 $user = $this->getUser();
1616 $status = Status
::newGood();
1617 foreach ( $errors as $error ) {
1618 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1619 $status->fatal( ApiMessage
::create(
1622 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1624 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1625 $status->fatal( ApiMessage
::create(
1626 'apierror-autoblocked',
1628 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1631 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1639 /************************************************************************//**
1640 * @name Warning and error reporting
1645 * Add a warning for this module.
1647 * Users should monitor this section to notice any changes in API. Multiple
1648 * calls to this function will result in multiple warning messages.
1650 * If $msg is not an ApiMessage, the message code will be derived from the
1651 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1654 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1655 * @param string|null $code See ApiErrorFormatter::addWarning()
1656 * @param array|null $data See ApiErrorFormatter::addWarning()
1658 public function addWarning( $msg, $code = null, $data = null ) {
1659 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1663 * Add a deprecation warning for this module.
1665 * A combination of $this->addWarning() and $this->logFeatureUsage()
1668 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1669 * @param string|null $feature See ApiBase::logFeatureUsage()
1670 * @param array|null $data See ApiErrorFormatter::addWarning()
1672 public function addDeprecation( $msg, $feature, $data = [] ) {
1673 $data = (array)$data;
1674 if ( $feature !== null ) {
1675 $data['feature'] = $feature;
1676 $this->logFeatureUsage( $feature );
1678 $this->addWarning( $msg, 'deprecation', $data );
1682 * Add an error for this module without aborting
1684 * If $msg is not an ApiMessage, the message code will be derived from the
1685 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1687 * @note If you want to abort processing, use self::dieWithError() instead.
1689 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1690 * @param string|null $code See ApiErrorFormatter::addError()
1691 * @param array|null $data See ApiErrorFormatter::addError()
1693 public function addError( $msg, $code = null, $data = null ) {
1694 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1698 * Add warnings and/or errors from a Status
1700 * @note If you want to abort processing, use self::dieStatus() instead.
1702 * @param StatusValue $status
1703 * @param string[] $types 'warning' and/or 'error'
1705 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1706 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1710 * Abort execution with an error
1712 * If $msg is not an ApiMessage, the message code will be derived from the
1713 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1716 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1717 * @param string|null $code See ApiErrorFormatter::addError()
1718 * @param array|null $data See ApiErrorFormatter::addError()
1719 * @param int|null $httpCode HTTP error code to use
1720 * @throws ApiUsageException always
1722 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1723 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1727 * Adds a warning to the output, else dies
1729 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1730 * @param bool $enforceLimits Whether this is an enforce (die)
1732 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1733 if ( $enforceLimits ) {
1734 $this->dieWithError( $msg );
1736 $this->addWarning( $msg );
1741 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1742 * error handler and die with an error message including block info.
1745 * @param Block $block The block used to generate the ApiUsageException
1746 * @throws ApiUsageException always
1748 public function dieBlocked( Block
$block ) {
1749 // Die using the appropriate message depending on block type
1750 if ( $block->getType() == Block
::TYPE_AUTO
) {
1751 $this->dieWithError(
1752 'apierror-autoblocked',
1754 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1757 $this->dieWithError(
1760 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1766 * Throw an ApiUsageException based on the Status object.
1769 * @since 1.29 Accepts a StatusValue
1770 * @param StatusValue $status
1771 * @throws ApiUsageException always
1773 public function dieStatus( StatusValue
$status ) {
1774 if ( $status->isGood() ) {
1775 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1778 throw new ApiUsageException( $this, $status );
1782 * Helper function for readonly errors
1784 * @throws ApiUsageException always
1786 public function dieReadOnly() {
1787 $this->dieWithError(
1788 'apierror-readonly',
1790 [ 'readonlyreason' => wfReadOnlyReason() ]
1795 * Helper function for permission-denied errors
1797 * @param string|string[] $rights
1798 * @param User|null $user
1799 * @throws ApiUsageException if the user doesn't have any of the rights.
1800 * The error message is based on $rights[0].
1802 public function checkUserRightsAny( $rights, $user = null ) {
1804 $user = $this->getUser();
1806 $rights = (array)$rights;
1807 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1808 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1813 * Helper function for permission-denied errors
1815 * @param Title $title
1816 * @param string|string[] $actions
1817 * @param User|null $user
1818 * @throws ApiUsageException if the user doesn't have all of the rights.
1820 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
1822 $user = $this->getUser();
1826 foreach ( (array)$actions as $action ) {
1827 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1830 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1835 * Will only set a warning instead of failing if the global $wgDebugAPI
1836 * is set to true. Otherwise behaves exactly as self::dieWithError().
1839 * @param string|array|Message $msg
1840 * @param string|null $code
1841 * @param array|null $data
1842 * @param int|null $httpCode
1843 * @throws ApiUsageException
1845 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1846 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1847 $this->dieWithError( $msg, $code, $data, $httpCode );
1849 $this->addWarning( $msg, $code, $data );
1854 * Die with the 'badcontinue' error.
1856 * This call is common enough to make it into the base method.
1858 * @param bool $condition Will only die if this value is true
1859 * @throws ApiUsageException
1862 protected function dieContinueUsageIf( $condition ) {
1864 $this->dieWithError( 'apierror-badcontinue' );
1869 * Internal code errors should be reported with this method
1870 * @param string $method Method or function name
1871 * @param string $message Error message
1872 * @throws MWException always
1874 protected static function dieDebug( $method, $message ) {
1875 throw new MWException( "Internal error in $method: $message" );
1879 * Write logging information for API features to a debug log, for usage
1881 * @note Consider using $this->addDeprecation() instead to both warn and log.
1882 * @param string $feature Feature being used.
1884 public function logFeatureUsage( $feature ) {
1885 $request = $this->getRequest();
1886 $s = '"' . addslashes( $feature ) . '"' .
1887 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1888 ' "' . $request->getIP() . '"' .
1889 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1890 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1891 wfDebugLog( 'api-feature-usage', $s, 'private' );
1896 /************************************************************************//**
1897 * @name Help message generation
1902 * Return the description message.
1904 * @return string|array|Message
1906 protected function getDescriptionMessage() {
1907 return "apihelp-{$this->getModulePath()}-description";
1911 * Get final module description, after hooks have had a chance to tweak it as
1914 * @since 1.25, returns Message[] rather than string[]
1917 public function getFinalDescription() {
1918 $desc = $this->getDescription();
1919 Hooks
::run( 'APIGetDescription', [ &$this, &$desc ] );
1920 $desc = self
::escapeWikiText( $desc );
1921 if ( is_array( $desc ) ) {
1922 $desc = implode( "\n", $desc );
1924 $desc = (string)$desc;
1927 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
1928 $this->getModulePrefix(),
1929 $this->getModuleName(),
1930 $this->getModulePath(),
1932 if ( !$msg->exists() ) {
1933 $msg = $this->msg( 'api-help-fallback-description', $desc );
1937 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
1943 * Get final list of parameters, after hooks have had a chance to
1944 * tweak it as needed.
1946 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1947 * @return array|bool False on no parameters
1948 * @since 1.21 $flags param added
1950 public function getFinalParams( $flags = 0 ) {
1951 $params = $this->getAllowedParams( $flags );
1956 if ( $this->needsToken() ) {
1957 $params['token'] = [
1958 ApiBase
::PARAM_TYPE
=> 'string',
1959 ApiBase
::PARAM_REQUIRED
=> true,
1960 ApiBase
::PARAM_HELP_MSG
=> [
1961 'api-help-param-token',
1962 $this->needsToken(),
1964 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
1967 Hooks
::run( 'APIGetAllowedParams', [ &$this, &$params, $flags ] );
1973 * Get final parameter descriptions, after hooks have had a chance to tweak it as
1976 * @since 1.25, returns array of Message[] rather than array of string[]
1977 * @return array Keys are parameter names, values are arrays of Message objects
1979 public function getFinalParamDescription() {
1980 $prefix = $this->getModulePrefix();
1981 $name = $this->getModuleName();
1982 $path = $this->getModulePath();
1984 $desc = $this->getParamDescription();
1985 Hooks
::run( 'APIGetParamDescription', [ &$this, &$desc ] );
1990 $desc = self
::escapeWikiText( $desc );
1992 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
1994 foreach ( $params as $param => $settings ) {
1995 if ( !is_array( $settings ) ) {
1999 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2000 if ( is_array( $d ) ) {
2001 // Special handling for prop parameters
2002 $d = array_map( function ( $line ) {
2003 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2004 $line = "\n;{$m[1]}:{$m[2]}";
2008 $d = implode( ' ', $d );
2011 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2012 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2014 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2015 if ( !$msg->exists() ) {
2016 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2019 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2020 [ $prefix, $param, $name, $path ] );
2022 self
::dieDebug( __METHOD__
,
2023 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2025 $msgs[$param] = [ $msg ];
2027 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2028 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2029 self
::dieDebug( __METHOD__
,
2030 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2032 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2033 self
::dieDebug( __METHOD__
,
2034 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2035 'ApiBase::PARAM_TYPE is an array' );
2038 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2039 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2040 if ( isset( $valueMsgs[$value] ) ) {
2041 $msg = $valueMsgs[$value];
2043 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2045 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2046 [ $prefix, $param, $name, $path, $value ] );
2048 $m = new ApiHelpParamValueMessage(
2050 [ $m->getKey(), 'api-help-param-no-description' ],
2053 $msgs[$param][] = $m->setContext( $this->getContext() );
2055 self
::dieDebug( __METHOD__
,
2056 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2061 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2062 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2063 self
::dieDebug( __METHOD__
,
2064 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2066 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2067 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2068 [ $prefix, $param, $name, $path ] );
2070 $msgs[$param][] = $m;
2072 self
::dieDebug( __METHOD__
,
2073 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2079 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2085 * Generates the list of flags for the help screen and for action=paraminfo
2087 * Corresponding messages: api-help-flag-deprecated,
2088 * api-help-flag-internal, api-help-flag-readrights,
2089 * api-help-flag-writerights, api-help-flag-mustbeposted
2093 protected function getHelpFlags() {
2096 if ( $this->isDeprecated() ) {
2097 $flags[] = 'deprecated';
2099 if ( $this->isInternal() ) {
2100 $flags[] = 'internal';
2102 if ( $this->isReadMode() ) {
2103 $flags[] = 'readrights';
2105 if ( $this->isWriteMode() ) {
2106 $flags[] = 'writerights';
2108 if ( $this->mustBePosted() ) {
2109 $flags[] = 'mustbeposted';
2116 * Returns information about the source of this module, if known
2118 * Returned array is an array with the following keys:
2119 * - path: Install path
2120 * - name: Extension name, or "MediaWiki" for core
2121 * - namemsg: (optional) i18n message key for a display name
2122 * - license-name: (optional) Name of license
2124 * @return array|null
2126 protected function getModuleSourceInfo() {
2129 if ( $this->mModuleSource
!== false ) {
2130 return $this->mModuleSource
;
2133 // First, try to find where the module comes from...
2134 $rClass = new ReflectionClass( $this );
2135 $path = $rClass->getFileName();
2138 $this->mModuleSource
= null;
2141 $path = realpath( $path ) ?
: $path;
2143 // Build map of extension directories to extension info
2144 if ( self
::$extensionInfo === null ) {
2145 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2146 self
::$extensionInfo = [
2147 realpath( __DIR__
) ?
: __DIR__
=> [
2149 'name' => 'MediaWiki',
2150 'license-name' => 'GPL-2.0+',
2152 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2153 realpath( $extDir ) ?
: $extDir => null,
2159 'license-name' => null,
2161 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2162 foreach ( $group as $ext ) {
2163 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2164 // This shouldn't happen, but does anyway.
2168 $extpath = $ext['path'];
2169 if ( !is_dir( $extpath ) ) {
2170 $extpath = dirname( $extpath );
2172 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2173 array_intersect_key( $ext, $keep );
2176 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2177 $extpath = $ext['path'];
2178 if ( !is_dir( $extpath ) ) {
2179 $extpath = dirname( $extpath );
2181 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2182 array_intersect_key( $ext, $keep );
2186 // Now traverse parent directories until we find a match or run out of
2189 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2191 $this->mModuleSource
= self
::$extensionInfo[$path];
2192 return $this->mModuleSource
;
2196 $path = dirname( $path );
2197 } while ( $path !== $oldpath );
2199 // No idea what extension this might be.
2200 $this->mModuleSource
= null;
2205 * Called from ApiHelp before the pieces are joined together and returned.
2207 * This exists mainly for ApiMain to add the Permissions and Credits
2208 * sections. Other modules probably don't need it.
2210 * @param string[] &$help Array of help data
2211 * @param array $options Options passed to ApiHelp::getHelp
2212 * @param array &$tocData If a TOC is being generated, this array has keys
2213 * as anchors in the page and values as for Linker::generateTOC().
2215 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2220 /************************************************************************//**
2226 * Returns the description string for this module
2228 * Ignored if an i18n message exists for
2229 * "apihelp-{$this->getModulePath()}-description".
2231 * @deprecated since 1.25
2232 * @return Message|string|array
2234 protected function getDescription() {
2239 * Returns an array of parameter descriptions.
2241 * For each parameter, ignored if an i18n message exists for the parameter.
2242 * By default that message is
2243 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2244 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2245 * self::getFinalParams().
2247 * @deprecated since 1.25
2248 * @return array|bool False on no parameter descriptions
2250 protected function getParamDescription() {
2255 * Returns usage examples for this module.
2257 * Return value as an array is either:
2258 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2260 * - sequential numeric keys with even-numbered keys being display-text
2261 * and odd-numbered keys being partial urls
2262 * - partial URLs as keys with display-text (string or array-to-be-joined)
2264 * Return value as a string is the same as an array with a numeric key and
2265 * that value, and boolean false means "no examples".
2267 * @deprecated since 1.25, use getExamplesMessages() instead
2268 * @return bool|string|array
2270 protected function getExamples() {
2275 * @deprecated since 1.25, always returns empty string
2276 * @param IDatabase|bool $db
2279 public function getModuleProfileName( $db = false ) {
2280 wfDeprecated( __METHOD__
, '1.25' );
2285 * @deprecated since 1.25
2287 public function profileIn() {
2288 // No wfDeprecated() yet because extensions call this and might need to
2289 // keep doing so for BC.
2293 * @deprecated since 1.25
2295 public function profileOut() {
2296 // No wfDeprecated() yet because extensions call this and might need to
2297 // keep doing so for BC.
2301 * @deprecated since 1.25
2303 public function safeProfileOut() {
2304 wfDeprecated( __METHOD__
, '1.25' );
2308 * @deprecated since 1.25, always returns 0
2311 public function getProfileTime() {
2312 wfDeprecated( __METHOD__
, '1.25' );
2317 * @deprecated since 1.25
2319 public function profileDBIn() {
2320 wfDeprecated( __METHOD__
, '1.25' );
2324 * @deprecated since 1.25
2326 public function profileDBOut() {
2327 wfDeprecated( __METHOD__
, '1.25' );
2331 * @deprecated since 1.25, always returns 0
2334 public function getProfileDBTime() {
2335 wfDeprecated( __METHOD__
, '1.25' );
2340 * Call wfTransactionalTimeLimit() if this request was POSTed
2343 protected function useTransactionalTimeLimit() {
2344 if ( $this->getRequest()->wasPosted() ) {
2345 wfTransactionalTimeLimit();
2350 * @deprecated since 1.29, use ApiBase::addWarning() instead
2351 * @param string $warning Warning message
2353 public function setWarning( $warning ) {
2354 $msg = new ApiRawMessage( $warning, 'warning' );
2355 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2359 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2360 * error handler and die with an error message.
2362 * @deprecated since 1.29, use self::dieWithError() instead
2363 * @param string $description One-line human-readable description of the
2364 * error condition, e.g., "The API requires a valid action parameter"
2365 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2366 * automated identification of the error, e.g., 'unknown_action'
2367 * @param int $httpRespCode HTTP response code
2368 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2369 * @throws ApiUsageException always
2371 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2372 $this->dieWithError(
2373 new RawMessage( '$1', [ $description ] ),
2381 * Get error (as code, string) from a Status object.
2384 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2385 * @param Status $status
2386 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2387 * @return array Array of code and error string
2388 * @throws MWException
2390 public function getErrorFromStatus( $status, &$extraData = null ) {
2391 if ( $status->isGood() ) {
2392 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2395 $errors = $status->getErrorsByType( 'error' );
2397 // No errors? Assume the warnings should be treated as errors
2398 $errors = $status->getErrorsByType( 'warning' );
2401 // Still no errors? Punt
2402 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2405 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2406 $msg = $errors[0]['message'];
2408 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2410 if ( !$msg instanceof IApiMessage
) {
2411 $key = $msg->getKey();
2412 $params = $msg->getParams();
2413 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2414 $msg = ApiMessage
::create( $params );
2419 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2424 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2425 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2426 * API codes and message texts, and a few interfaces required poking
2427 * something in here. Now we're repurposing it to map those same strings
2428 * to i18n messages, and declaring that any interface that requires poking
2429 * at this is broken and needs replacing ASAP.
2431 private static $messageMap = [
2432 'unknownerror' => 'apierror-unknownerror',
2433 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2434 'ns-specialprotected' => 'ns-specialprotected',
2435 'protectedinterface' => 'protectedinterface',
2436 'namespaceprotected' => 'namespaceprotected',
2437 'customcssprotected' => 'customcssprotected',
2438 'customjsprotected' => 'customjsprotected',
2439 'cascadeprotected' => 'cascadeprotected',
2440 'protectedpagetext' => 'protectedpagetext',
2441 'protect-cantedit' => 'protect-cantedit',
2442 'deleteprotected' => 'deleteprotected',
2443 'badaccess-group0' => 'badaccess-group0',
2444 'badaccess-groups' => 'badaccess-groups',
2445 'titleprotected' => 'titleprotected',
2446 'nocreate-loggedin' => 'nocreate-loggedin',
2447 'nocreatetext' => 'nocreatetext',
2448 'movenologintext' => 'movenologintext',
2449 'movenotallowed' => 'movenotallowed',
2450 'confirmedittext' => 'confirmedittext',
2451 'blockedtext' => 'apierror-blocked',
2452 'autoblockedtext' => 'apierror-autoblocked',
2453 'actionthrottledtext' => 'apierror-ratelimited',
2454 'alreadyrolled' => 'alreadyrolled',
2455 'cantrollback' => 'cantrollback',
2456 'readonlytext' => 'readonlytext',
2457 'sessionfailure' => 'sessionfailure',
2458 'cannotdelete' => 'cannotdelete',
2459 'notanarticle' => 'apierror-missingtitle',
2460 'selfmove' => 'selfmove',
2461 'immobile_namespace' => 'apierror-immobilenamespace',
2462 'articleexists' => 'articleexists',
2463 'hookaborted' => 'hookaborted',
2464 'cantmove-titleprotected' => 'cantmove-titleprotected',
2465 'imagenocrossnamespace' => 'imagenocrossnamespace',
2466 'imagetypemismatch' => 'imagetypemismatch',
2467 'ip_range_invalid' => 'ip_range_invalid',
2468 'range_block_disabled' => 'range_block_disabled',
2469 'nosuchusershort' => 'nosuchusershort',
2470 'badipaddress' => 'badipaddress',
2471 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2472 'ipb_already_blocked' => 'ipb_already_blocked',
2473 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2474 'ipb_cant_unblock' => 'ipb_cant_unblock',
2475 'mailnologin' => 'apierror-cantsend',
2476 'ipbblocked' => 'ipbblocked',
2477 'ipbnounblockself' => 'ipbnounblockself',
2478 'usermaildisabled' => 'usermaildisabled',
2479 'blockedemailuser' => 'apierror-blockedfrommail',
2480 'notarget' => 'apierror-notarget',
2481 'noemail' => 'noemail',
2482 'rcpatroldisabled' => 'rcpatroldisabled',
2483 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2484 'delete-toobig' => 'delete-toobig',
2485 'movenotallowedfile' => 'movenotallowedfile',
2486 'userrights-no-interwiki' => 'userrights-no-interwiki',
2487 'userrights-nodatabase' => 'userrights-nodatabase',
2488 'nouserspecified' => 'nouserspecified',
2489 'noname' => 'noname',
2490 'summaryrequired' => 'apierror-summaryrequired',
2491 'import-rootpage-invalid' => 'import-rootpage-invalid',
2492 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2493 'readrequired' => 'apierror-readapidenied',
2494 'writedisabled' => 'apierror-noapiwrite',
2495 'writerequired' => 'apierror-writeapidenied',
2496 'missingparam' => 'apierror-missingparam',
2497 'invalidtitle' => 'apierror-invalidtitle',
2498 'nosuchpageid' => 'apierror-nosuchpageid',
2499 'nosuchrevid' => 'apierror-nosuchrevid',
2500 'nosuchuser' => 'nosuchusershort',
2501 'invaliduser' => 'apierror-invaliduser',
2502 'invalidexpiry' => 'apierror-invalidexpiry',
2503 'pastexpiry' => 'apierror-pastexpiry',
2504 'create-titleexists' => 'apierror-create-titleexists',
2505 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2506 'cantblock' => 'apierror-cantblock',
2507 'canthide' => 'apierror-canthide',
2508 'cantblock-email' => 'apierror-cantblock-email',
2509 'cantunblock' => 'apierror-permissiondenied-generic',
2510 'cannotundelete' => 'cannotundelete',
2511 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2512 'createonly-exists' => 'apierror-articleexists',
2513 'nocreate-missing' => 'apierror-missingtitle',
2514 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2515 'nosuchrcid' => 'apierror-nosuchrcid',
2516 'nosuchlogid' => 'apierror-nosuchlogid',
2517 'protect-invalidaction' => 'apierror-protect-invalidaction',
2518 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2519 'toofewexpiries' => 'apierror-toofewexpiries',
2520 'cantimport' => 'apierror-cantimport',
2521 'cantimport-upload' => 'apierror-cantimport-upload',
2522 'importnofile' => 'importnofile',
2523 'importuploaderrorsize' => 'importuploaderrorsize',
2524 'importuploaderrorpartial' => 'importuploaderrorpartial',
2525 'importuploaderrortemp' => 'importuploaderrortemp',
2526 'importcantopen' => 'importcantopen',
2527 'import-noarticle' => 'import-noarticle',
2528 'importbadinterwiki' => 'importbadinterwiki',
2529 'import-unknownerror' => 'apierror-import-unknownerror',
2530 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2531 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2532 'mustbeposted' => 'apierror-mustbeposted',
2533 'show' => 'apierror-show',
2534 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2535 'invalidoldimage' => 'apierror-invalidoldimage',
2536 'nodeleteablefile' => 'apierror-nodeleteablefile',
2537 'fileexists-forbidden' => 'fileexists-forbidden',
2538 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2539 'filerevert-badversion' => 'filerevert-badversion',
2540 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2541 'noimageredirect-logged' => 'apierror-noimageredirect',
2542 'spamdetected' => 'apierror-spamdetected',
2543 'contenttoobig' => 'apierror-contenttoobig',
2544 'noedit-anon' => 'apierror-noedit-anon',
2545 'noedit' => 'apierror-noedit',
2546 'wasdeleted' => 'apierror-pagedeleted',
2547 'blankpage' => 'apierror-emptypage',
2548 'editconflict' => 'editconflict',
2549 'hashcheckfailed' => 'apierror-badmd5',
2550 'missingtext' => 'apierror-notext',
2551 'emptynewsection' => 'apierror-emptynewsection',
2552 'revwrongpage' => 'apierror-revwrongpage',
2553 'undo-failure' => 'undo-failure',
2554 'content-not-allowed-here' => 'content-not-allowed-here',
2555 'edit-hook-aborted' => 'edit-hook-aborted',
2556 'edit-gone-missing' => 'edit-gone-missing',
2557 'edit-conflict' => 'edit-conflict',
2558 'edit-already-exists' => 'edit-already-exists',
2559 'invalid-file-key' => 'apierror-invalid-file-key',
2560 'nouploadmodule' => 'apierror-nouploadmodule',
2561 'uploaddisabled' => 'uploaddisabled',
2562 'copyuploaddisabled' => 'copyuploaddisabled',
2563 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2564 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2565 'filename-tooshort' => 'filename-tooshort',
2566 'filename-toolong' => 'filename-toolong',
2567 'illegal-filename' => 'illegal-filename',
2568 'filetype-missing' => 'filetype-missing',
2569 'mustbeloggedin' => 'apierror-mustbeloggedin',
2573 * @deprecated do not use
2574 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2575 * @return ApiMessage
2577 private function parseMsgInternal( $error ) {
2578 $msg = Message
::newFromSpecifier( $error );
2579 if ( !$msg instanceof IApiMessage
) {
2580 $key = $msg->getKey();
2581 if ( isset( self
::$messageMap[$key] ) ) {
2582 $params = $msg->getParams();
2583 array_unshift( $params, self
::$messageMap[$key] );
2585 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2587 $msg = ApiMessage
::create( $params );
2593 * Return the error message related to a certain array
2594 * @deprecated since 1.29
2595 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2596 * @return [ 'code' => code, 'info' => info ]
2598 public function parseMsg( $error ) {
2599 // Check whether someone passed the whole array, instead of one element as
2600 // documented. This breaks if it's actually an array of fallback keys, but
2601 // that's long-standing misbehavior introduced in r87627 to incorrectly
2603 if ( is_array( $error ) ) {
2604 $first = reset( $error );
2605 if ( is_array( $first ) ) {
2606 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2611 $msg = $this->parseMsgInternal( $error );
2613 'code' => $msg->getApiCode(),
2614 'info' => ApiErrorFormatter
::stripMarkup(
2615 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2617 'data' => $msg->getApiData()
2622 * Output the error message related to a certain array
2623 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2624 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2625 * @throws ApiUsageException always
2627 public function dieUsageMsg( $error ) {
2628 $this->dieWithError( $this->parseMsgInternal( $error ) );
2632 * Will only set a warning instead of failing if the global $wgDebugAPI
2633 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2634 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2635 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2636 * @throws ApiUsageException
2639 public function dieUsageMsgOrDebug( $error ) {
2640 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2647 * For really cool vim folding this needs to be at the end:
2648 * vim: foldmarker=@{,@} foldmethod=marker