5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
27 use Wikimedia\Rdbms\IDatabase
;
30 * This abstract class implements many basic API functions, and is the base of
32 * The class functions are divided into several areas of functionality:
34 * Module parameters: Derived classes can define getAllowedParams() to specify
35 * which parameters to expect, how to parse and validate them.
37 * Self-documentation: code to allow the API to document its own state
41 abstract class ApiBase
extends ContextSource
{
44 * @name Constants for ::getAllowedParams() arrays
45 * These constants are keys in the arrays returned by ::getAllowedParams()
46 * and accepted by ::getParameterFromSettings() that define how the
47 * parameters coming in from the request are to be interpreted.
51 /** (null|boolean|integer|string) Default value of the parameter. */
54 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
55 const PARAM_ISMULTI
= 1;
58 * (string|string[]) Either an array of allowed value strings, or a string
59 * type as described below. If not specified, will be determined from the
62 * Supported string types are:
63 * - boolean: A boolean parameter, returned as false if the parameter is
64 * omitted and true if present (even with a falsey value, i.e. it works
65 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
66 * Cannot be used with PARAM_ISMULTI.
67 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
68 * PARAM_RANGE_ENFORCE.
69 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
70 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
71 * specified. Cannot be used with PARAM_ISMULTI.
72 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
73 * support easily specifying all namespaces.
75 * - password: Any non-empty string. Input value is private or sensitive.
76 * <input type="password"> would be an appropriate HTML form field.
77 * - string: Any non-empty string, not expected to be very long or contain newlines.
78 * <input type="text"> would be an appropriate HTML form field.
79 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
80 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
81 * used with PARAM_ISMULTI.
82 * - text: Any non-empty string, expected to be very long or contain newlines.
83 * <textarea> would be an appropriate HTML form field.
84 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
85 * string 'now' representing the current timestamp. Will be returned in
87 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
88 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
89 * Cannot be used with PARAM_ISMULTI.
93 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
97 * (integer) Max value allowed for the parameter for users with the
98 * apihighlimits right, for PARAM_TYPE 'limit'.
100 const PARAM_MAX2
= 4;
102 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
105 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
106 const PARAM_ALLOW_DUPLICATES
= 6;
108 /** (boolean) Is the parameter deprecated (will show a warning)? */
109 const PARAM_DEPRECATED
= 7;
112 * (boolean) Is the parameter required?
115 const PARAM_REQUIRED
= 8;
118 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
121 const PARAM_RANGE_ENFORCE
= 9;
124 * (string|array|Message) Specify an alternative i18n documentation message
125 * for this parameter. Default is apihelp-{$path}-param-{$param}.
128 const PARAM_HELP_MSG
= 10;
131 * ((string|array|Message)[]) Specify additional i18n messages to append to
132 * the normal message for this parameter.
135 const PARAM_HELP_MSG_APPEND
= 11;
138 * (array) Specify additional information tags for the parameter. Value is
139 * an array of arrays, with the first member being the 'tag' for the info
140 * and the remaining members being the values. In the help, this is
141 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
142 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
145 const PARAM_HELP_MSG_INFO
= 12;
148 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
149 * those values to page titles which will be linked in the help.
152 const PARAM_VALUE_LINKS
= 13;
155 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
156 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
157 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
160 const PARAM_HELP_MSG_PER_VALUE
= 14;
163 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
164 * submodule paths. Default is to use all modules in
165 * $this->getModuleManager() in the group matching the parameter name.
168 const PARAM_SUBMODULE_MAP
= 15;
171 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
172 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
175 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
178 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
179 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
180 * every possible value. If a string is set, it will be used in place of the asterisk.
183 const PARAM_ALL
= 17;
186 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
189 const PARAM_EXTRA_NAMESPACES
= 18;
193 const ALL_DEFAULT_STRING
= '*';
195 /** Fast query, standard limit. */
196 const LIMIT_BIG1
= 500;
197 /** Fast query, apihighlimits limit. */
198 const LIMIT_BIG2
= 5000;
199 /** Slow query, standard limit. */
200 const LIMIT_SML1
= 50;
201 /** Slow query, apihighlimits limit. */
202 const LIMIT_SML2
= 500;
205 * getAllowedParams() flag: When set, the result could take longer to generate,
206 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
209 const GET_VALUES_FOR_HELP
= 1;
211 /** @var array Maps extension paths to info arrays */
212 private static $extensionInfo = null;
215 private $mMainModule;
217 private $mModuleName, $mModulePrefix;
218 private $mSlaveDB = null;
219 private $mParamCache = [];
220 /** @var array|null|bool */
221 private $mModuleSource = false;
224 * @param ApiMain $mainModule
225 * @param string $moduleName Name of this module
226 * @param string $modulePrefix Prefix to use for parameter names
228 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
229 $this->mMainModule
= $mainModule;
230 $this->mModuleName
= $moduleName;
231 $this->mModulePrefix
= $modulePrefix;
233 if ( !$this->isMain() ) {
234 $this->setContext( $mainModule->getContext() );
238 /************************************************************************//**
239 * @name Methods to implement
244 * Evaluates the parameters, performs the requested query, and sets up
245 * the result. Concrete implementations of ApiBase must override this
246 * method to provide whatever functionality their module offers.
247 * Implementations must not produce any output on their own and are not
248 * expected to handle any errors.
250 * The execute() method will be invoked directly by ApiMain immediately
251 * before the result of the module is output. Aside from the
252 * constructor, implementations should assume that no other methods
253 * will be called externally on the module before the result is
256 * The result data should be stored in the ApiResult object available
257 * through getResult().
259 abstract public function execute();
262 * Get the module manager, or null if this module has no sub-modules
264 * @return ApiModuleManager
266 public function getModuleManager() {
271 * If the module may only be used with a certain format module,
272 * it should override this method to return an instance of that formatter.
273 * A value of null means the default format will be used.
274 * @note Do not use this just because you don't want to support non-json
275 * formats. This should be used only when there is a fundamental
276 * requirement for a specific format.
277 * @return mixed Instance of a derived class of ApiFormatBase, or null
279 public function getCustomPrinter() {
284 * Returns usage examples for this module.
286 * Return value has query strings as keys, with values being either strings
287 * (message key), arrays (message key + parameter), or Message objects.
289 * Do not call this base class implementation when overriding this method.
294 protected function getExamplesMessages() {
295 // Fall back to old non-localised method
298 $examples = $this->getExamples();
300 if ( !is_array( $examples ) ) {
301 $examples = [ $examples ];
302 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
303 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
304 !preg_match( '/^\s*api\.php\?/', $examples[0] )
306 // Fix up the ugly "even numbered elements are description, odd
307 // numbered elemts are the link" format (see doc for self::getExamples)
309 $examplesCount = count( $examples );
310 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
311 $tmp[$examples[$i +
1]] = $examples[$i];
316 foreach ( $examples as $k => $v ) {
317 if ( is_numeric( $k ) ) {
322 $msg = self
::escapeWikiText( $v );
323 if ( is_array( $msg ) ) {
324 $msg = implode( ' ', $msg );
328 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
329 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
337 * Return links to more detailed help pages about the module.
338 * @since 1.25, returning boolean false is deprecated
339 * @return string|array
341 public function getHelpUrls() {
346 * Returns an array of allowed parameters (parameter name) => (default
347 * value) or (parameter name) => (array with PARAM_* constants as keys)
348 * Don't call this function directly: use getFinalParams() to allow
349 * hooks to modify parameters as needed.
351 * Some derived classes may choose to handle an integer $flags parameter
352 * in the overriding methods. Callers of this method can pass zero or
353 * more OR-ed flags like GET_VALUES_FOR_HELP.
357 protected function getAllowedParams( /* $flags = 0 */ ) {
358 // int $flags is not declared because it causes "Strict standards"
359 // warning. Most derived classes do not implement it.
364 * Indicates if this module needs maxlag to be checked
367 public function shouldCheckMaxlag() {
372 * Indicates whether this module requires read rights
375 public function isReadMode() {
380 * Indicates whether this module requires write mode
383 public function isWriteMode() {
388 * Indicates whether this module must be called with a POST request
391 public function mustBePosted() {
392 return $this->needsToken() !== false;
396 * Indicates whether this module is deprecated
400 public function isDeprecated() {
405 * Indicates whether this module is "internal"
406 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
410 public function isInternal() {
415 * Returns the token type this module requires in order to execute.
417 * Modules are strongly encouraged to use the core 'csrf' type unless they
418 * have specialized security needs. If the token type is not one of the
419 * core types, you must use the ApiQueryTokensRegisterTypes hook to
422 * Returning a non-falsey value here will force the addition of an
423 * appropriate 'token' parameter in self::getFinalParams(). Also,
424 * self::mustBePosted() must return true when tokens are used.
426 * In previous versions of MediaWiki, true was a valid return value.
427 * Returning true will generate errors indicating that the API module needs
430 * @return string|false
432 public function needsToken() {
437 * Fetch the salt used in the Web UI corresponding to this module.
439 * Only override this if the Web UI uses a token with a non-constant salt.
442 * @param array $params All supplied parameters for the module
443 * @return string|array|null
445 protected function getWebUITokenSalt( array $params ) {
450 * Returns data for HTTP conditional request mechanisms.
453 * @param string $condition Condition being queried:
454 * - last-modified: Return a timestamp representing the maximum of the
455 * last-modified dates for all resources involved in the request. See
456 * RFC 7232 § 2.2 for semantics.
457 * - etag: Return an entity-tag representing the state of all resources involved
458 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
459 * @return string|bool|null As described above, or null if no value is available.
461 public function getConditionalRequestData( $condition ) {
467 /************************************************************************//**
468 * @name Data access methods
473 * Get the name of the module being executed by this instance
476 public function getModuleName() {
477 return $this->mModuleName
;
481 * Get parameter prefix (usually two letters or an empty string).
484 public function getModulePrefix() {
485 return $this->mModulePrefix
;
489 * Get the main module
492 public function getMain() {
493 return $this->mMainModule
;
497 * Returns true if this module is the main module ($this === $this->mMainModule),
501 public function isMain() {
502 return $this === $this->mMainModule
;
506 * Get the parent of this module
508 * @return ApiBase|null
510 public function getParent() {
511 return $this->isMain() ?
null : $this->getMain();
515 * Returns true if the current request breaks the same-origin policy.
517 * For example, json with callbacks.
519 * https://en.wikipedia.org/wiki/Same-origin_policy
524 public function lacksSameOriginSecurity() {
525 // Main module has this method overridden
526 // Safety - avoid infinite loop:
527 if ( $this->isMain() ) {
528 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
531 return $this->getMain()->lacksSameOriginSecurity();
535 * Get the path to this module
540 public function getModulePath() {
541 if ( $this->isMain() ) {
543 } elseif ( $this->getParent()->isMain() ) {
544 return $this->getModuleName();
546 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
551 * Get a module from its module path
554 * @param string $path
555 * @return ApiBase|null
556 * @throws ApiUsageException
558 public function getModuleFromPath( $path ) {
559 $module = $this->getMain();
560 if ( $path === 'main' ) {
564 $parts = explode( '+', $path );
565 if ( count( $parts ) === 1 ) {
566 // In case the '+' was typed into URL, it resolves as a space
567 $parts = explode( ' ', $path );
570 $count = count( $parts );
571 for ( $i = 0; $i < $count; $i++
) {
573 $manager = $parent->getModuleManager();
574 if ( $manager === null ) {
575 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
576 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
578 $module = $manager->getModule( $parts[$i] );
580 if ( $module === null ) {
581 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
583 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
593 * Get the result object
596 public function getResult() {
597 // Main module has getResult() method overridden
598 // Safety - avoid infinite loop:
599 if ( $this->isMain() ) {
600 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
603 return $this->getMain()->getResult();
607 * Get the error formatter
608 * @return ApiErrorFormatter
610 public function getErrorFormatter() {
611 // Main module has getErrorFormatter() method overridden
612 // Safety - avoid infinite loop:
613 if ( $this->isMain() ) {
614 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
617 return $this->getMain()->getErrorFormatter();
621 * Gets a default replica DB connection object
624 protected function getDB() {
625 if ( !isset( $this->mSlaveDB
) ) {
626 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
629 return $this->mSlaveDB
;
633 * Get the continuation manager
634 * @return ApiContinuationManager|null
636 public function getContinuationManager() {
637 // Main module has getContinuationManager() method overridden
638 // Safety - avoid infinite loop:
639 if ( $this->isMain() ) {
640 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
643 return $this->getMain()->getContinuationManager();
647 * Set the continuation manager
648 * @param ApiContinuationManager|null
650 public function setContinuationManager( $manager ) {
651 // Main module has setContinuationManager() method overridden
652 // Safety - avoid infinite loop:
653 if ( $this->isMain() ) {
654 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
657 $this->getMain()->setContinuationManager( $manager );
662 /************************************************************************//**
663 * @name Parameter handling
668 * Indicate if the module supports dynamically-determined parameters that
669 * cannot be included in self::getAllowedParams().
670 * @return string|array|Message|null Return null if the module does not
671 * support additional dynamic parameters, otherwise return a message
674 public function dynamicParameterDocumentation() {
679 * This method mangles parameter name based on the prefix supplied to the constructor.
680 * Override this method to change parameter name during runtime
681 * @param string|string[] $paramName Parameter name
682 * @return string|string[] Prefixed parameter name
683 * @since 1.29 accepts an array of strings
685 public function encodeParamName( $paramName ) {
686 if ( is_array( $paramName ) ) {
687 return array_map( function ( $name ) {
688 return $this->mModulePrefix
. $name;
691 return $this->mModulePrefix
. $paramName;
696 * Using getAllowedParams(), this function makes an array of the values
697 * provided by the user, with key being the name of the variable, and
698 * value - validated value from user or default. limits will not be
699 * parsed if $parseLimit is set to false; use this when the max
700 * limit is not definitive yet, e.g. when getting revisions.
701 * @param bool $parseLimit True by default
704 public function extractRequestParams( $parseLimit = true ) {
705 // Cache parameters, for performance and to avoid T26564.
706 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
707 $params = $this->getFinalParams();
710 if ( $params ) { // getFinalParams() can return false
711 foreach ( $params as $paramName => $paramSettings ) {
712 $results[$paramName] = $this->getParameterFromSettings(
713 $paramName, $paramSettings, $parseLimit );
716 $this->mParamCache
[$parseLimit] = $results;
719 return $this->mParamCache
[$parseLimit];
723 * Get a value for the given parameter
724 * @param string $paramName Parameter name
725 * @param bool $parseLimit See extractRequestParams()
726 * @return mixed Parameter value
728 protected function getParameter( $paramName, $parseLimit = true ) {
729 $paramSettings = $this->getFinalParams()[$paramName];
731 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
735 * Die if none or more than one of a certain set of parameters is set and not false.
737 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
738 * @param string $required,... Names of parameters of which exactly one must be set
740 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
741 $required = func_get_args();
742 array_shift( $required );
744 $intersection = array_intersect( array_keys( array_filter( $params,
745 [ $this, 'parameterNotEmpty' ] ) ), $required );
747 if ( count( $intersection ) > 1 ) {
748 $this->dieWithError( [
749 'apierror-invalidparammix',
750 Message
::listParam( array_map(
752 return '<var>' . $this->encodeParamName( $p ) . '</var>';
754 array_values( $intersection )
756 count( $intersection ),
758 } elseif ( count( $intersection ) == 0 ) {
759 $this->dieWithError( [
760 'apierror-missingparam-one-of',
761 Message
::listParam( array_map(
763 return '<var>' . $this->encodeParamName( $p ) . '</var>';
765 array_values( $required )
773 * Die if more than one of a certain set of parameters is set and not false.
775 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
776 * @param string $required,... Names of parameters of which at most one must be set
778 public function requireMaxOneParameter( $params, $required /*...*/ ) {
779 $required = func_get_args();
780 array_shift( $required );
782 $intersection = array_intersect( array_keys( array_filter( $params,
783 [ $this, 'parameterNotEmpty' ] ) ), $required );
785 if ( count( $intersection ) > 1 ) {
786 $this->dieWithError( [
787 'apierror-invalidparammix',
788 Message
::listParam( array_map(
790 return '<var>' . $this->encodeParamName( $p ) . '</var>';
792 array_values( $intersection )
794 count( $intersection ),
800 * Die if none of a certain set of parameters is set and not false.
803 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
804 * @param string $required,... Names of parameters of which at least one must be set
806 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
807 $required = func_get_args();
808 array_shift( $required );
810 $intersection = array_intersect(
811 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
815 if ( count( $intersection ) == 0 ) {
816 $this->dieWithError( [
817 'apierror-missingparam-at-least-one-of',
818 Message
::listParam( array_map(
820 return '<var>' . $this->encodeParamName( $p ) . '</var>';
822 array_values( $required )
830 * Die if any of the specified parameters were found in the query part of
831 * the URL rather than the post body.
833 * @param string[] $params Parameters to check
834 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
836 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
837 // Skip if $wgDebugAPI is set or we're in internal mode
838 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
842 $queryValues = $this->getRequest()->getQueryValues();
844 foreach ( $params as $param ) {
845 if ( $prefix !== 'noprefix' ) {
846 $param = $this->encodeParamName( $param );
848 if ( array_key_exists( $param, $queryValues ) ) {
849 $badParams[] = $param;
855 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
861 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
863 * @param object $x Parameter to check is not null/false
866 private function parameterNotEmpty( $x ) {
867 return !is_null( $x ) && $x !== false;
871 * Get a WikiPage object from a title or pageid param, if possible.
872 * Can die, if no param is set or if the title or page id is not valid.
874 * @param array $params
875 * @param bool|string $load Whether load the object's state from the database:
876 * - false: don't load (if the pageid is given, it will still be loaded)
877 * - 'fromdb': load from a replica DB
878 * - 'fromdbmaster': load from the master database
881 public function getTitleOrPageId( $params, $load = false ) {
882 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
885 if ( isset( $params['title'] ) ) {
886 $titleObj = Title
::newFromText( $params['title'] );
887 if ( !$titleObj ||
$titleObj->isExternal() ) {
888 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
890 if ( !$titleObj->canExist() ) {
891 $this->dieWithError( 'apierror-pagecannotexist' );
893 $pageObj = WikiPage
::factory( $titleObj );
894 if ( $load !== false ) {
895 $pageObj->loadPageData( $load );
897 } elseif ( isset( $params['pageid'] ) ) {
898 if ( $load === false ) {
901 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
903 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
911 * Get a Title object from a title or pageid param, if possible.
912 * Can die, if no param is set or if the title or page id is not valid.
915 * @param array $params
918 public function getTitleFromTitleOrPageId( $params ) {
919 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
922 if ( isset( $params['title'] ) ) {
923 $titleObj = Title
::newFromText( $params['title'] );
924 if ( !$titleObj ||
$titleObj->isExternal() ) {
925 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
928 } elseif ( isset( $params['pageid'] ) ) {
929 $titleObj = Title
::newFromID( $params['pageid'] );
931 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
939 * Return true if we're to watch the page, false if not, null if no change.
940 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
941 * @param Title $titleObj The page under consideration
942 * @param string $userOption The user option to consider when $watchlist=preferences.
943 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
946 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
948 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
950 switch ( $watchlist ) {
958 # If the user is already watching, don't bother checking
959 if ( $userWatching ) {
962 # If no user option was passed, use watchdefault and watchcreations
963 if ( is_null( $userOption ) ) {
964 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
965 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
968 # Watch the article based on the user preference
969 return $this->getUser()->getBoolOption( $userOption );
972 return $userWatching;
975 return $userWatching;
980 * Using the settings determine the value for the given parameter
982 * @param string $paramName Parameter name
983 * @param array|mixed $paramSettings Default value or an array of settings
984 * using PARAM_* constants.
985 * @param bool $parseLimit Parse limit?
986 * @return mixed Parameter value
988 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
989 // Some classes may decide to change parameter names
990 $encParamName = $this->encodeParamName( $paramName );
993 if ( !is_array( $paramSettings ) ) {
995 self
::PARAM_DFLT
=> $paramSettings,
999 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1000 ?
$paramSettings[self
::PARAM_DFLT
]
1002 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1003 ?
$paramSettings[self
::PARAM_ISMULTI
]
1005 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1006 ?
$paramSettings[self
::PARAM_TYPE
]
1008 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1009 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1011 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1012 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1014 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1015 ?
$paramSettings[self
::PARAM_REQUIRED
]
1017 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1018 ?
$paramSettings[self
::PARAM_ALL
]
1021 // When type is not given, and no choices, the type is the same as $default
1022 if ( !isset( $type ) ) {
1023 if ( isset( $default ) ) {
1024 $type = gettype( $default );
1026 $type = 'NULL'; // allow everything
1030 if ( $type == 'boolean' ) {
1031 if ( isset( $default ) && $default !== false ) {
1032 // Having a default value of anything other than 'false' is not allowed
1035 "Boolean param $encParamName's default is set to '$default'. " .
1036 'Boolean parameters must default to false.'
1040 $value = $this->getMain()->getCheck( $encParamName );
1041 } elseif ( $type == 'upload' ) {
1042 if ( isset( $default ) ) {
1043 // Having a default value is not allowed
1046 "File upload param $encParamName's default is set to " .
1047 "'$default'. File upload parameters may not have a default." );
1050 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1052 $value = $this->getMain()->getUpload( $encParamName );
1053 if ( !$value->exists() ) {
1054 // This will get the value without trying to normalize it
1055 // (because trying to normalize a large binary file
1056 // accidentally uploaded as a field fails spectacularly)
1057 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1058 if ( $value !== null ) {
1059 $this->dieWithError(
1060 [ 'apierror-badupload', $encParamName ],
1061 "badupload_{$encParamName}"
1066 $value = $this->getMain()->getVal( $encParamName, $default );
1068 if ( isset( $value ) && $type == 'namespace' ) {
1069 $type = MWNamespace
::getValidNamespaces();
1070 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1071 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1073 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1075 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1079 if ( isset( $value ) && $type == 'submodule' ) {
1080 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1081 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1083 $type = $this->getModuleManager()->getNames( $paramName );
1087 $request = $this->getMain()->getRequest();
1088 $rawValue = $request->getRawVal( $encParamName );
1089 if ( $rawValue === null ) {
1090 $rawValue = $default;
1093 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1094 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1096 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1097 // done by WebRequest for $_GET. Let's call that a feature.
1098 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1100 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1104 // Check for NFC normalization, and warn
1105 if ( $rawValue !== $value ) {
1106 $this->handleParamNormalization( $paramName, $value, $rawValue );
1110 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1111 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1114 "For param $encParamName, PARAM_ALL collides with a possible value" );
1116 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1117 $value = $this->parseMultiValue(
1121 is_array( $type ) ?
$type : null,
1122 $allowAll ?
$allSpecifier : null
1126 // More validation only when choices were not given
1127 // choices were validated in parseMultiValue()
1128 if ( isset( $value ) ) {
1129 if ( !is_array( $type ) ) {
1131 case 'NULL': // nothing to do
1136 if ( $required && $value === '' ) {
1137 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1140 case 'integer': // Force everything using intval() and optionally validate limits
1141 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1142 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1143 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1144 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1146 if ( is_array( $value ) ) {
1147 $value = array_map( 'intval', $value );
1148 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1149 foreach ( $value as &$v ) {
1150 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1154 $value = intval( $value );
1155 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1156 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1161 if ( !$parseLimit ) {
1162 // Don't do any validation whatsoever
1165 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1166 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1170 "MAX1 or MAX2 are not defined for the limit $encParamName"
1174 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1176 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1177 if ( $value == 'max' ) {
1178 $value = $this->getMain()->canApiHighLimits()
1179 ?
$paramSettings[self
::PARAM_MAX2
]
1180 : $paramSettings[self
::PARAM_MAX
];
1181 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1183 $value = intval( $value );
1184 $this->validateLimit(
1188 $paramSettings[self
::PARAM_MAX
],
1189 $paramSettings[self
::PARAM_MAX2
]
1195 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1199 if ( is_array( $value ) ) {
1200 foreach ( $value as $key => $val ) {
1201 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1204 $value = $this->validateTimestamp( $value, $encParamName );
1208 if ( is_array( $value ) ) {
1209 foreach ( $value as $key => $val ) {
1210 $value[$key] = $this->validateUser( $val, $encParamName );
1213 $value = $this->validateUser( $value, $encParamName );
1216 case 'upload': // nothing to do
1219 // If change tagging was requested, check that the tags are valid.
1220 if ( !is_array( $value ) && !$multi ) {
1221 $value = [ $value ];
1223 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1224 if ( !$tagsStatus->isGood() ) {
1225 $this->dieStatus( $tagsStatus );
1229 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1233 // Throw out duplicates if requested
1234 if ( !$dupes && is_array( $value ) ) {
1235 $value = array_unique( $value );
1238 // Set a warning if a deprecated parameter has been passed
1239 if ( $deprecated && $value !== false ) {
1240 $feature = $encParamName;
1242 while ( !$m->isMain() ) {
1243 $p = $m->getParent();
1244 $name = $m->getModuleName();
1245 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1246 $feature = "{$param}={$name}&{$feature}";
1249 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1251 } elseif ( $required ) {
1252 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1259 * Handle when a parameter was Unicode-normalized
1261 * @param string $paramName Unprefixed parameter name
1262 * @param string $value Input that will be used.
1263 * @param string $rawValue Input before normalization.
1265 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1266 $encParamName = $this->encodeParamName( $paramName );
1267 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1271 * Split a multi-valued parameter string, like explode()
1273 * @param string $value
1277 protected function explodeMultiValue( $value, $limit ) {
1278 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1280 $value = substr( $value, 1 );
1285 return explode( $sep, $value, $limit );
1289 * Return an array of values that were given in a 'a|b|c' notation,
1290 * after it optionally validates them against the list allowed values.
1292 * @param string $valueName The name of the parameter (for error
1294 * @param mixed $value The value being parsed
1295 * @param bool $allowMultiple Can $value contain more than one value
1297 * @param string[]|null $allowedValues An array of values to check against. If
1298 * null, all values are accepted.
1299 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1300 * if this behavior should not be allowed
1301 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1303 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1304 $allSpecifier = null
1306 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1310 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1311 // because it unstubs $wgUser
1312 $valuesList = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1313 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1317 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1318 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1320 return $allowedValues;
1323 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1324 $this->addDeprecation(
1325 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1326 "too-many-$valueName-for-{$this->getModulePath()}"
1330 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1331 // T35482 - Allow entries with | in them for non-multiple values
1332 if ( in_array( $value, $allowedValues, true ) ) {
1336 if ( is_array( $allowedValues ) ) {
1337 $values = array_map( function ( $v ) {
1338 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1339 }, $allowedValues );
1340 $this->dieWithError( [
1341 'apierror-multival-only-one-of',
1343 Message
::listParam( $values ),
1345 ], "multival_$valueName" );
1347 $this->dieWithError( [
1348 'apierror-multival-only-one',
1350 ], "multival_$valueName" );
1354 if ( is_array( $allowedValues ) ) {
1355 // Check for unknown values
1356 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1357 if ( count( $unknown ) ) {
1358 if ( $allowMultiple ) {
1359 $this->addWarning( [
1360 'apiwarn-unrecognizedvalues',
1362 Message
::listParam( $unknown, 'comma' ),
1366 $this->dieWithError(
1367 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1368 "unknown_$valueName"
1372 // Now throw them out
1373 $valuesList = array_intersect( $valuesList, $allowedValues );
1376 return $allowMultiple ?
$valuesList : $valuesList[0];
1380 * Validate the value against the minimum and user/bot maximum limits.
1381 * Prints usage info on failure.
1382 * @param string $paramName Parameter name
1383 * @param int $value Parameter value
1384 * @param int|null $min Minimum value
1385 * @param int|null $max Maximum value for users
1386 * @param int $botMax Maximum value for sysops/bots
1387 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1389 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1390 $enforceLimits = false
1392 if ( !is_null( $min ) && $value < $min ) {
1393 $msg = ApiMessage
::create(
1394 [ 'apierror-integeroutofrange-belowminimum',
1395 $this->encodeParamName( $paramName ), $min, $value ],
1396 'integeroutofrange',
1397 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1399 $this->warnOrDie( $msg, $enforceLimits );
1403 // Minimum is always validated, whereas maximum is checked only if not
1404 // running in internal call mode
1405 if ( $this->getMain()->isInternalMode() ) {
1409 // Optimization: do not check user's bot status unless really needed -- skips db query
1410 // assumes $botMax >= $max
1411 if ( !is_null( $max ) && $value > $max ) {
1412 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1413 if ( $value > $botMax ) {
1414 $msg = ApiMessage
::create(
1415 [ 'apierror-integeroutofrange-abovebotmax',
1416 $this->encodeParamName( $paramName ), $botMax, $value ],
1417 'integeroutofrange',
1418 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1420 $this->warnOrDie( $msg, $enforceLimits );
1424 $msg = ApiMessage
::create(
1425 [ 'apierror-integeroutofrange-abovemax',
1426 $this->encodeParamName( $paramName ), $max, $value ],
1427 'integeroutofrange',
1428 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1430 $this->warnOrDie( $msg, $enforceLimits );
1437 * Validate and normalize of parameters of type 'timestamp'
1438 * @param string $value Parameter value
1439 * @param string $encParamName Parameter name
1440 * @return string Validated and normalized parameter
1442 protected function validateTimestamp( $value, $encParamName ) {
1443 // Confusing synonyms for the current time accepted by wfTimestamp()
1444 // (wfTimestamp() also accepts various non-strings and the string of 14
1445 // ASCII NUL bytes, but those can't get here)
1447 $this->addDeprecation(
1448 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1449 'unclear-"now"-timestamp'
1451 return wfTimestamp( TS_MW
);
1454 // Explicit synonym for the current time
1455 if ( $value === 'now' ) {
1456 return wfTimestamp( TS_MW
);
1459 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1460 if ( $unixTimestamp === false ) {
1461 $this->dieWithError(
1462 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1463 "badtimestamp_{$encParamName}"
1467 return wfTimestamp( TS_MW
, $unixTimestamp );
1471 * Validate the supplied token.
1474 * @param string $token Supplied token
1475 * @param array $params All supplied parameters for the module
1477 * @throws MWException
1479 final public function validateToken( $token, array $params ) {
1480 $tokenType = $this->needsToken();
1481 $salts = ApiQueryTokens
::getTokenTypeSalts();
1482 if ( !isset( $salts[$tokenType] ) ) {
1483 throw new MWException(
1484 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1485 'without registering it'
1489 $tokenObj = ApiQueryTokens
::getToken(
1490 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1492 if ( $tokenObj->match( $token ) ) {
1496 $webUiSalt = $this->getWebUITokenSalt( $params );
1497 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1509 * Validate and normalize of parameters of type 'user'
1510 * @param string $value Parameter value
1511 * @param string $encParamName Parameter name
1512 * @return string Validated and normalized parameter
1514 private function validateUser( $value, $encParamName ) {
1515 $title = Title
::makeTitleSafe( NS_USER
, $value );
1516 if ( $title === null ||
$title->hasFragment() ) {
1517 $this->dieWithError(
1518 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1519 "baduser_{$encParamName}"
1523 return $title->getText();
1528 /************************************************************************//**
1529 * @name Utility methods
1534 * Set a watch (or unwatch) based the based on a watchlist parameter.
1535 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1536 * @param Title $titleObj The article's title to change
1537 * @param string $userOption The user option to consider when $watch=preferences
1539 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1540 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1541 if ( $value === null ) {
1545 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1549 * Truncate an array to a certain length.
1550 * @param array $arr Array to truncate
1551 * @param int $limit Maximum length
1552 * @return bool True if the array was truncated, false otherwise
1554 public static function truncateArray( &$arr, $limit ) {
1556 while ( count( $arr ) > $limit ) {
1565 * Gets the user for whom to get the watchlist
1567 * @param array $params
1570 public function getWatchlistUser( $params ) {
1571 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1572 $user = User
::newFromName( $params['owner'], false );
1573 if ( !( $user && $user->getId() ) ) {
1574 $this->dieWithError(
1575 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1578 $token = $user->getOption( 'watchlisttoken' );
1579 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1580 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1583 if ( !$this->getUser()->isLoggedIn() ) {
1584 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1586 $this->checkUserRightsAny( 'viewmywatchlist' );
1587 $user = $this->getUser();
1594 * A subset of wfEscapeWikiText for BC texts
1597 * @param string|array $v
1598 * @return string|array
1600 private static function escapeWikiText( $v ) {
1601 if ( is_array( $v ) ) {
1602 return array_map( 'self::escapeWikiText', $v );
1605 '__' => '__', '{' => '{', '}' => '}',
1606 '[[Category:' => '[[:Category:',
1607 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1613 * Create a Message from a string or array
1615 * A string is used as a message key. An array has the message key as the
1616 * first value and message parameters as subsequent values.
1619 * @param string|array|Message $msg
1620 * @param IContextSource $context
1621 * @param array $params
1622 * @return Message|null
1624 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1625 if ( is_string( $msg ) ) {
1626 $msg = wfMessage( $msg );
1627 } elseif ( is_array( $msg ) ) {
1628 $msg = call_user_func_array( 'wfMessage', $msg );
1630 if ( !$msg instanceof Message
) {
1634 $msg->setContext( $context );
1636 $msg->params( $params );
1643 * Turn an array of message keys or key+param arrays into a Status
1645 * @param array $errors
1646 * @param User|null $user
1649 public function errorArrayToStatus( array $errors, User
$user = null ) {
1650 if ( $user === null ) {
1651 $user = $this->getUser();
1654 $status = Status
::newGood();
1655 foreach ( $errors as $error ) {
1656 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1657 $status->fatal( ApiMessage
::create(
1660 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1662 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1663 $status->fatal( ApiMessage
::create(
1664 'apierror-autoblocked',
1666 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1668 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1669 $status->fatal( ApiMessage
::create(
1670 'apierror-systemblocked',
1672 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1675 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1683 /************************************************************************//**
1684 * @name Warning and error reporting
1689 * Add a warning for this module.
1691 * Users should monitor this section to notice any changes in API. Multiple
1692 * calls to this function will result in multiple warning messages.
1694 * If $msg is not an ApiMessage, the message code will be derived from the
1695 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1698 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1699 * @param string|null $code See ApiErrorFormatter::addWarning()
1700 * @param array|null $data See ApiErrorFormatter::addWarning()
1702 public function addWarning( $msg, $code = null, $data = null ) {
1703 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1707 * Add a deprecation warning for this module.
1709 * A combination of $this->addWarning() and $this->logFeatureUsage()
1712 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1713 * @param string|null $feature See ApiBase::logFeatureUsage()
1714 * @param array|null $data See ApiErrorFormatter::addWarning()
1716 public function addDeprecation( $msg, $feature, $data = [] ) {
1717 $data = (array)$data;
1718 if ( $feature !== null ) {
1719 $data['feature'] = $feature;
1720 $this->logFeatureUsage( $feature );
1722 $this->addWarning( $msg, 'deprecation', $data );
1724 // No real need to deduplicate here, ApiErrorFormatter does that for
1725 // us (assuming the hook is deterministic).
1726 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1727 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1728 if ( count( $msgs ) > 1 ) {
1729 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1730 $msg = ( new RawMessage( $key ) )->params( $msgs );
1732 $msg = reset( $msgs );
1734 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1738 * Add an error for this module without aborting
1740 * If $msg is not an ApiMessage, the message code will be derived from the
1741 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1743 * @note If you want to abort processing, use self::dieWithError() instead.
1745 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1746 * @param string|null $code See ApiErrorFormatter::addError()
1747 * @param array|null $data See ApiErrorFormatter::addError()
1749 public function addError( $msg, $code = null, $data = null ) {
1750 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1754 * Add warnings and/or errors from a Status
1756 * @note If you want to abort processing, use self::dieStatus() instead.
1758 * @param StatusValue $status
1759 * @param string[] $types 'warning' and/or 'error'
1761 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1762 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1766 * Abort execution with an error
1768 * If $msg is not an ApiMessage, the message code will be derived from the
1769 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1772 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1773 * @param string|null $code See ApiErrorFormatter::addError()
1774 * @param array|null $data See ApiErrorFormatter::addError()
1775 * @param int|null $httpCode HTTP error code to use
1776 * @throws ApiUsageException always
1778 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1779 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1783 * Abort execution with an error derived from an exception
1786 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1787 * @param array $options See ApiErrorFormatter::getMessageFromException()
1788 * @throws ApiUsageException always
1790 public function dieWithException( $exception, array $options = [] ) {
1791 $this->dieWithError(
1792 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1797 * Adds a warning to the output, else dies
1799 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1800 * @param bool $enforceLimits Whether this is an enforce (die)
1802 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1803 if ( $enforceLimits ) {
1804 $this->dieWithError( $msg );
1806 $this->addWarning( $msg );
1811 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1812 * error handler and die with an error message including block info.
1815 * @param Block $block The block used to generate the ApiUsageException
1816 * @throws ApiUsageException always
1818 public function dieBlocked( Block
$block ) {
1819 // Die using the appropriate message depending on block type
1820 if ( $block->getType() == Block
::TYPE_AUTO
) {
1821 $this->dieWithError(
1822 'apierror-autoblocked',
1824 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1827 $this->dieWithError(
1830 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1836 * Throw an ApiUsageException based on the Status object.
1839 * @since 1.29 Accepts a StatusValue
1840 * @param StatusValue $status
1841 * @throws ApiUsageException always
1843 public function dieStatus( StatusValue
$status ) {
1844 if ( $status->isGood() ) {
1845 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1848 throw new ApiUsageException( $this, $status );
1852 * Helper function for readonly errors
1854 * @throws ApiUsageException always
1856 public function dieReadOnly() {
1857 $this->dieWithError(
1858 'apierror-readonly',
1860 [ 'readonlyreason' => wfReadOnlyReason() ]
1865 * Helper function for permission-denied errors
1867 * @param string|string[] $rights
1868 * @param User|null $user
1869 * @throws ApiUsageException if the user doesn't have any of the rights.
1870 * The error message is based on $rights[0].
1872 public function checkUserRightsAny( $rights, $user = null ) {
1874 $user = $this->getUser();
1876 $rights = (array)$rights;
1877 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1878 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1883 * Helper function for permission-denied errors
1885 * @param Title $title
1886 * @param string|string[] $actions
1887 * @param User|null $user
1888 * @throws ApiUsageException if the user doesn't have all of the rights.
1890 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
1892 $user = $this->getUser();
1896 foreach ( (array)$actions as $action ) {
1897 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1900 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1905 * Will only set a warning instead of failing if the global $wgDebugAPI
1906 * is set to true. Otherwise behaves exactly as self::dieWithError().
1909 * @param string|array|Message $msg
1910 * @param string|null $code
1911 * @param array|null $data
1912 * @param int|null $httpCode
1913 * @throws ApiUsageException
1915 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1916 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1917 $this->dieWithError( $msg, $code, $data, $httpCode );
1919 $this->addWarning( $msg, $code, $data );
1924 * Die with the 'badcontinue' error.
1926 * This call is common enough to make it into the base method.
1928 * @param bool $condition Will only die if this value is true
1929 * @throws ApiUsageException
1932 protected function dieContinueUsageIf( $condition ) {
1934 $this->dieWithError( 'apierror-badcontinue' );
1939 * Internal code errors should be reported with this method
1940 * @param string $method Method or function name
1941 * @param string $message Error message
1942 * @throws MWException always
1944 protected static function dieDebug( $method, $message ) {
1945 throw new MWException( "Internal error in $method: $message" );
1949 * Write logging information for API features to a debug log, for usage
1951 * @note Consider using $this->addDeprecation() instead to both warn and log.
1952 * @param string $feature Feature being used.
1954 public function logFeatureUsage( $feature ) {
1955 $request = $this->getRequest();
1956 $s = '"' . addslashes( $feature ) . '"' .
1957 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1958 ' "' . $request->getIP() . '"' .
1959 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1960 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1961 wfDebugLog( 'api-feature-usage', $s, 'private' );
1966 /************************************************************************//**
1967 * @name Help message generation
1972 * Return the description message.
1974 * @return string|array|Message
1976 protected function getDescriptionMessage() {
1977 return "apihelp-{$this->getModulePath()}-description";
1981 * Get final module description, after hooks have had a chance to tweak it as
1984 * @since 1.25, returns Message[] rather than string[]
1987 public function getFinalDescription() {
1988 $desc = $this->getDescription();
1990 // Avoid PHP 7.1 warning of passing $this by reference
1992 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
1993 $desc = self
::escapeWikiText( $desc );
1994 if ( is_array( $desc ) ) {
1995 $desc = implode( "\n", $desc );
1997 $desc = (string)$desc;
2000 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2001 $this->getModulePrefix(),
2002 $this->getModuleName(),
2003 $this->getModulePath(),
2005 if ( !$msg->exists() ) {
2006 $msg = $this->msg( 'api-help-fallback-description', $desc );
2010 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2016 * Get final list of parameters, after hooks have had a chance to
2017 * tweak it as needed.
2019 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2020 * @return array|bool False on no parameters
2021 * @since 1.21 $flags param added
2023 public function getFinalParams( $flags = 0 ) {
2024 $params = $this->getAllowedParams( $flags );
2029 if ( $this->needsToken() ) {
2030 $params['token'] = [
2031 ApiBase
::PARAM_TYPE
=> 'string',
2032 ApiBase
::PARAM_REQUIRED
=> true,
2033 ApiBase
::PARAM_HELP_MSG
=> [
2034 'api-help-param-token',
2035 $this->needsToken(),
2037 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2040 // Avoid PHP 7.1 warning of passing $this by reference
2042 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2048 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2051 * @since 1.25, returns array of Message[] rather than array of string[]
2052 * @return array Keys are parameter names, values are arrays of Message objects
2054 public function getFinalParamDescription() {
2055 $prefix = $this->getModulePrefix();
2056 $name = $this->getModuleName();
2057 $path = $this->getModulePath();
2059 $desc = $this->getParamDescription();
2061 // Avoid PHP 7.1 warning of passing $this by reference
2063 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2068 $desc = self
::escapeWikiText( $desc );
2070 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2072 foreach ( $params as $param => $settings ) {
2073 if ( !is_array( $settings ) ) {
2077 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2078 if ( is_array( $d ) ) {
2079 // Special handling for prop parameters
2080 $d = array_map( function ( $line ) {
2081 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2082 $line = "\n;{$m[1]}:{$m[2]}";
2086 $d = implode( ' ', $d );
2089 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2090 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2092 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2093 if ( !$msg->exists() ) {
2094 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2097 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2098 [ $prefix, $param, $name, $path ] );
2100 self
::dieDebug( __METHOD__
,
2101 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2103 $msgs[$param] = [ $msg ];
2105 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2106 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2107 self
::dieDebug( __METHOD__
,
2108 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2110 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2111 self
::dieDebug( __METHOD__
,
2112 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2113 'ApiBase::PARAM_TYPE is an array' );
2116 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2117 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2118 if ( isset( $valueMsgs[$value] ) ) {
2119 $msg = $valueMsgs[$value];
2121 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2123 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2124 [ $prefix, $param, $name, $path, $value ] );
2126 $m = new ApiHelpParamValueMessage(
2128 [ $m->getKey(), 'api-help-param-no-description' ],
2131 $msgs[$param][] = $m->setContext( $this->getContext() );
2133 self
::dieDebug( __METHOD__
,
2134 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2139 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2140 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2141 self
::dieDebug( __METHOD__
,
2142 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2144 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2145 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2146 [ $prefix, $param, $name, $path ] );
2148 $msgs[$param][] = $m;
2150 self
::dieDebug( __METHOD__
,
2151 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2157 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2163 * Generates the list of flags for the help screen and for action=paraminfo
2165 * Corresponding messages: api-help-flag-deprecated,
2166 * api-help-flag-internal, api-help-flag-readrights,
2167 * api-help-flag-writerights, api-help-flag-mustbeposted
2171 protected function getHelpFlags() {
2174 if ( $this->isDeprecated() ) {
2175 $flags[] = 'deprecated';
2177 if ( $this->isInternal() ) {
2178 $flags[] = 'internal';
2180 if ( $this->isReadMode() ) {
2181 $flags[] = 'readrights';
2183 if ( $this->isWriteMode() ) {
2184 $flags[] = 'writerights';
2186 if ( $this->mustBePosted() ) {
2187 $flags[] = 'mustbeposted';
2194 * Returns information about the source of this module, if known
2196 * Returned array is an array with the following keys:
2197 * - path: Install path
2198 * - name: Extension name, or "MediaWiki" for core
2199 * - namemsg: (optional) i18n message key for a display name
2200 * - license-name: (optional) Name of license
2202 * @return array|null
2204 protected function getModuleSourceInfo() {
2207 if ( $this->mModuleSource
!== false ) {
2208 return $this->mModuleSource
;
2211 // First, try to find where the module comes from...
2212 $rClass = new ReflectionClass( $this );
2213 $path = $rClass->getFileName();
2216 $this->mModuleSource
= null;
2219 $path = realpath( $path ) ?
: $path;
2221 // Build map of extension directories to extension info
2222 if ( self
::$extensionInfo === null ) {
2223 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2224 self
::$extensionInfo = [
2225 realpath( __DIR__
) ?
: __DIR__
=> [
2227 'name' => 'MediaWiki',
2228 'license-name' => 'GPL-2.0+',
2230 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2231 realpath( $extDir ) ?
: $extDir => null,
2237 'license-name' => null,
2239 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2240 foreach ( $group as $ext ) {
2241 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2242 // This shouldn't happen, but does anyway.
2246 $extpath = $ext['path'];
2247 if ( !is_dir( $extpath ) ) {
2248 $extpath = dirname( $extpath );
2250 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2251 array_intersect_key( $ext, $keep );
2254 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2255 $extpath = $ext['path'];
2256 if ( !is_dir( $extpath ) ) {
2257 $extpath = dirname( $extpath );
2259 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2260 array_intersect_key( $ext, $keep );
2264 // Now traverse parent directories until we find a match or run out of
2267 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2269 $this->mModuleSource
= self
::$extensionInfo[$path];
2270 return $this->mModuleSource
;
2274 $path = dirname( $path );
2275 } while ( $path !== $oldpath );
2277 // No idea what extension this might be.
2278 $this->mModuleSource
= null;
2283 * Called from ApiHelp before the pieces are joined together and returned.
2285 * This exists mainly for ApiMain to add the Permissions and Credits
2286 * sections. Other modules probably don't need it.
2288 * @param string[] &$help Array of help data
2289 * @param array $options Options passed to ApiHelp::getHelp
2290 * @param array &$tocData If a TOC is being generated, this array has keys
2291 * as anchors in the page and values as for Linker::generateTOC().
2293 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2298 /************************************************************************//**
2304 * Returns the description string for this module
2306 * Ignored if an i18n message exists for
2307 * "apihelp-{$this->getModulePath()}-description".
2309 * @deprecated since 1.25
2310 * @return Message|string|array|false
2312 protected function getDescription() {
2317 * Returns an array of parameter descriptions.
2319 * For each parameter, ignored if an i18n message exists for the parameter.
2320 * By default that message is
2321 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2322 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2323 * self::getFinalParams().
2325 * @deprecated since 1.25
2326 * @return array|bool False on no parameter descriptions
2328 protected function getParamDescription() {
2333 * Returns usage examples for this module.
2335 * Return value as an array is either:
2336 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2338 * - sequential numeric keys with even-numbered keys being display-text
2339 * and odd-numbered keys being partial urls
2340 * - partial URLs as keys with display-text (string or array-to-be-joined)
2342 * Return value as a string is the same as an array with a numeric key and
2343 * that value, and boolean false means "no examples".
2345 * @deprecated since 1.25, use getExamplesMessages() instead
2346 * @return bool|string|array
2348 protected function getExamples() {
2353 * @deprecated since 1.25, always returns empty string
2354 * @param IDatabase|bool $db
2357 public function getModuleProfileName( $db = false ) {
2358 wfDeprecated( __METHOD__
, '1.25' );
2363 * @deprecated since 1.25
2365 public function profileIn() {
2366 // No wfDeprecated() yet because extensions call this and might need to
2367 // keep doing so for BC.
2371 * @deprecated since 1.25
2373 public function profileOut() {
2374 // No wfDeprecated() yet because extensions call this and might need to
2375 // keep doing so for BC.
2379 * @deprecated since 1.25
2381 public function safeProfileOut() {
2382 wfDeprecated( __METHOD__
, '1.25' );
2386 * @deprecated since 1.25, always returns 0
2389 public function getProfileTime() {
2390 wfDeprecated( __METHOD__
, '1.25' );
2395 * @deprecated since 1.25
2397 public function profileDBIn() {
2398 wfDeprecated( __METHOD__
, '1.25' );
2402 * @deprecated since 1.25
2404 public function profileDBOut() {
2405 wfDeprecated( __METHOD__
, '1.25' );
2409 * @deprecated since 1.25, always returns 0
2412 public function getProfileDBTime() {
2413 wfDeprecated( __METHOD__
, '1.25' );
2418 * Call wfTransactionalTimeLimit() if this request was POSTed
2421 protected function useTransactionalTimeLimit() {
2422 if ( $this->getRequest()->wasPosted() ) {
2423 wfTransactionalTimeLimit();
2428 * @deprecated since 1.29, use ApiBase::addWarning() instead
2429 * @param string $warning Warning message
2431 public function setWarning( $warning ) {
2432 $msg = new ApiRawMessage( $warning, 'warning' );
2433 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2437 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2438 * error handler and die with an error message.
2440 * @deprecated since 1.29, use self::dieWithError() instead
2441 * @param string $description One-line human-readable description of the
2442 * error condition, e.g., "The API requires a valid action parameter"
2443 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2444 * automated identification of the error, e.g., 'unknown_action'
2445 * @param int $httpRespCode HTTP response code
2446 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2447 * @throws ApiUsageException always
2449 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2450 $this->dieWithError(
2451 new RawMessage( '$1', [ $description ] ),
2459 * Get error (as code, string) from a Status object.
2462 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2463 * @param Status $status
2464 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2465 * @return array Array of code and error string
2466 * @throws MWException
2468 public function getErrorFromStatus( $status, &$extraData = null ) {
2469 if ( $status->isGood() ) {
2470 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2473 $errors = $status->getErrorsByType( 'error' );
2475 // No errors? Assume the warnings should be treated as errors
2476 $errors = $status->getErrorsByType( 'warning' );
2479 // Still no errors? Punt
2480 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2483 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2484 $msg = $errors[0]['message'];
2486 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2488 if ( !$msg instanceof IApiMessage
) {
2489 $key = $msg->getKey();
2490 $params = $msg->getParams();
2491 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2492 $msg = ApiMessage
::create( $params );
2497 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2502 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2503 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2504 * API codes and message texts, and a few interfaces required poking
2505 * something in here. Now we're repurposing it to map those same strings
2506 * to i18n messages, and declaring that any interface that requires poking
2507 * at this is broken and needs replacing ASAP.
2509 private static $messageMap = [
2510 'unknownerror' => 'apierror-unknownerror',
2511 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2512 'ns-specialprotected' => 'ns-specialprotected',
2513 'protectedinterface' => 'protectedinterface',
2514 'namespaceprotected' => 'namespaceprotected',
2515 'customcssprotected' => 'customcssprotected',
2516 'customjsprotected' => 'customjsprotected',
2517 'cascadeprotected' => 'cascadeprotected',
2518 'protectedpagetext' => 'protectedpagetext',
2519 'protect-cantedit' => 'protect-cantedit',
2520 'deleteprotected' => 'deleteprotected',
2521 'badaccess-group0' => 'badaccess-group0',
2522 'badaccess-groups' => 'badaccess-groups',
2523 'titleprotected' => 'titleprotected',
2524 'nocreate-loggedin' => 'nocreate-loggedin',
2525 'nocreatetext' => 'nocreatetext',
2526 'movenologintext' => 'movenologintext',
2527 'movenotallowed' => 'movenotallowed',
2528 'confirmedittext' => 'confirmedittext',
2529 'blockedtext' => 'apierror-blocked',
2530 'autoblockedtext' => 'apierror-autoblocked',
2531 'systemblockedtext' => 'apierror-systemblocked',
2532 'actionthrottledtext' => 'apierror-ratelimited',
2533 'alreadyrolled' => 'alreadyrolled',
2534 'cantrollback' => 'cantrollback',
2535 'readonlytext' => 'readonlytext',
2536 'sessionfailure' => 'sessionfailure',
2537 'cannotdelete' => 'cannotdelete',
2538 'notanarticle' => 'apierror-missingtitle',
2539 'selfmove' => 'selfmove',
2540 'immobile_namespace' => 'apierror-immobilenamespace',
2541 'articleexists' => 'articleexists',
2542 'hookaborted' => 'hookaborted',
2543 'cantmove-titleprotected' => 'cantmove-titleprotected',
2544 'imagenocrossnamespace' => 'imagenocrossnamespace',
2545 'imagetypemismatch' => 'imagetypemismatch',
2546 'ip_range_invalid' => 'ip_range_invalid',
2547 'range_block_disabled' => 'range_block_disabled',
2548 'nosuchusershort' => 'nosuchusershort',
2549 'badipaddress' => 'badipaddress',
2550 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2551 'ipb_already_blocked' => 'ipb_already_blocked',
2552 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2553 'ipb_cant_unblock' => 'ipb_cant_unblock',
2554 'mailnologin' => 'apierror-cantsend',
2555 'ipbblocked' => 'ipbblocked',
2556 'ipbnounblockself' => 'ipbnounblockself',
2557 'usermaildisabled' => 'usermaildisabled',
2558 'blockedemailuser' => 'apierror-blockedfrommail',
2559 'notarget' => 'apierror-notarget',
2560 'noemail' => 'noemail',
2561 'rcpatroldisabled' => 'rcpatroldisabled',
2562 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2563 'delete-toobig' => 'delete-toobig',
2564 'movenotallowedfile' => 'movenotallowedfile',
2565 'userrights-no-interwiki' => 'userrights-no-interwiki',
2566 'userrights-nodatabase' => 'userrights-nodatabase',
2567 'nouserspecified' => 'nouserspecified',
2568 'noname' => 'noname',
2569 'summaryrequired' => 'apierror-summaryrequired',
2570 'import-rootpage-invalid' => 'import-rootpage-invalid',
2571 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2572 'readrequired' => 'apierror-readapidenied',
2573 'writedisabled' => 'apierror-noapiwrite',
2574 'writerequired' => 'apierror-writeapidenied',
2575 'missingparam' => 'apierror-missingparam',
2576 'invalidtitle' => 'apierror-invalidtitle',
2577 'nosuchpageid' => 'apierror-nosuchpageid',
2578 'nosuchrevid' => 'apierror-nosuchrevid',
2579 'nosuchuser' => 'nosuchusershort',
2580 'invaliduser' => 'apierror-invaliduser',
2581 'invalidexpiry' => 'apierror-invalidexpiry',
2582 'pastexpiry' => 'apierror-pastexpiry',
2583 'create-titleexists' => 'apierror-create-titleexists',
2584 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2585 'cantblock' => 'apierror-cantblock',
2586 'canthide' => 'apierror-canthide',
2587 'cantblock-email' => 'apierror-cantblock-email',
2588 'cantunblock' => 'apierror-permissiondenied-generic',
2589 'cannotundelete' => 'cannotundelete',
2590 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2591 'createonly-exists' => 'apierror-articleexists',
2592 'nocreate-missing' => 'apierror-missingtitle',
2593 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2594 'nosuchrcid' => 'apierror-nosuchrcid',
2595 'nosuchlogid' => 'apierror-nosuchlogid',
2596 'protect-invalidaction' => 'apierror-protect-invalidaction',
2597 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2598 'toofewexpiries' => 'apierror-toofewexpiries',
2599 'cantimport' => 'apierror-cantimport',
2600 'cantimport-upload' => 'apierror-cantimport-upload',
2601 'importnofile' => 'importnofile',
2602 'importuploaderrorsize' => 'importuploaderrorsize',
2603 'importuploaderrorpartial' => 'importuploaderrorpartial',
2604 'importuploaderrortemp' => 'importuploaderrortemp',
2605 'importcantopen' => 'importcantopen',
2606 'import-noarticle' => 'import-noarticle',
2607 'importbadinterwiki' => 'importbadinterwiki',
2608 'import-unknownerror' => 'apierror-import-unknownerror',
2609 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2610 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2611 'mustbeposted' => 'apierror-mustbeposted',
2612 'show' => 'apierror-show',
2613 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2614 'invalidoldimage' => 'apierror-invalidoldimage',
2615 'nodeleteablefile' => 'apierror-nodeleteablefile',
2616 'fileexists-forbidden' => 'fileexists-forbidden',
2617 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2618 'filerevert-badversion' => 'filerevert-badversion',
2619 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2620 'noimageredirect-logged' => 'apierror-noimageredirect',
2621 'spamdetected' => 'apierror-spamdetected',
2622 'contenttoobig' => 'apierror-contenttoobig',
2623 'noedit-anon' => 'apierror-noedit-anon',
2624 'noedit' => 'apierror-noedit',
2625 'wasdeleted' => 'apierror-pagedeleted',
2626 'blankpage' => 'apierror-emptypage',
2627 'editconflict' => 'editconflict',
2628 'hashcheckfailed' => 'apierror-badmd5',
2629 'missingtext' => 'apierror-notext',
2630 'emptynewsection' => 'apierror-emptynewsection',
2631 'revwrongpage' => 'apierror-revwrongpage',
2632 'undo-failure' => 'undo-failure',
2633 'content-not-allowed-here' => 'content-not-allowed-here',
2634 'edit-hook-aborted' => 'edit-hook-aborted',
2635 'edit-gone-missing' => 'edit-gone-missing',
2636 'edit-conflict' => 'edit-conflict',
2637 'edit-already-exists' => 'edit-already-exists',
2638 'invalid-file-key' => 'apierror-invalid-file-key',
2639 'nouploadmodule' => 'apierror-nouploadmodule',
2640 'uploaddisabled' => 'uploaddisabled',
2641 'copyuploaddisabled' => 'copyuploaddisabled',
2642 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2643 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2644 'filename-tooshort' => 'filename-tooshort',
2645 'filename-toolong' => 'filename-toolong',
2646 'illegal-filename' => 'illegal-filename',
2647 'filetype-missing' => 'filetype-missing',
2648 'mustbeloggedin' => 'apierror-mustbeloggedin',
2652 * @deprecated do not use
2653 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2654 * @return ApiMessage
2656 private function parseMsgInternal( $error ) {
2657 $msg = Message
::newFromSpecifier( $error );
2658 if ( !$msg instanceof IApiMessage
) {
2659 $key = $msg->getKey();
2660 if ( isset( self
::$messageMap[$key] ) ) {
2661 $params = $msg->getParams();
2662 array_unshift( $params, self
::$messageMap[$key] );
2664 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2666 $msg = ApiMessage
::create( $params );
2672 * Return the error message related to a certain array
2673 * @deprecated since 1.29
2674 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2675 * @return [ 'code' => code, 'info' => info ]
2677 public function parseMsg( $error ) {
2678 // Check whether someone passed the whole array, instead of one element as
2679 // documented. This breaks if it's actually an array of fallback keys, but
2680 // that's long-standing misbehavior introduced in r87627 to incorrectly
2682 if ( is_array( $error ) ) {
2683 $first = reset( $error );
2684 if ( is_array( $first ) ) {
2685 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2690 $msg = $this->parseMsgInternal( $error );
2692 'code' => $msg->getApiCode(),
2693 'info' => ApiErrorFormatter
::stripMarkup(
2694 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2696 'data' => $msg->getApiData()
2701 * Output the error message related to a certain array
2702 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2703 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2704 * @throws ApiUsageException always
2706 public function dieUsageMsg( $error ) {
2707 $this->dieWithError( $this->parseMsgInternal( $error ) );
2711 * Will only set a warning instead of failing if the global $wgDebugAPI
2712 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2713 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2714 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2715 * @throws ApiUsageException
2718 public function dieUsageMsgOrDebug( $error ) {
2719 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2726 * For really cool vim folding this needs to be at the end:
2727 * vim: foldmarker=@{,@} foldmethod=marker