5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
27 use Wikimedia\Rdbms\IDatabase
;
30 * This abstract class implements many basic API functions, and is the base of
32 * The class functions are divided into several areas of functionality:
34 * Module parameters: Derived classes can define getAllowedParams() to specify
35 * which parameters to expect, how to parse and validate them.
37 * Self-documentation: code to allow the API to document its own state
41 abstract class ApiBase
extends ContextSource
{
44 * @name Constants for ::getAllowedParams() arrays
45 * These constants are keys in the arrays returned by ::getAllowedParams()
46 * and accepted by ::getParameterFromSettings() that define how the
47 * parameters coming in from the request are to be interpreted.
51 /** (null|boolean|integer|string) Default value of the parameter. */
54 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
55 const PARAM_ISMULTI
= 1;
58 * (string|string[]) Either an array of allowed value strings, or a string
59 * type as described below. If not specified, will be determined from the
62 * Supported string types are:
63 * - boolean: A boolean parameter, returned as false if the parameter is
64 * omitted and true if present (even with a falsey value, i.e. it works
65 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
66 * Cannot be used with PARAM_ISMULTI.
67 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
68 * PARAM_RANGE_ENFORCE.
69 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
70 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
71 * specified. Cannot be used with PARAM_ISMULTI.
72 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
73 * support easily specifying all namespaces.
75 * - password: Any non-empty string. Input value is private or sensitive.
76 * <input type="password"> would be an appropriate HTML form field.
77 * - string: Any non-empty string, not expected to be very long or contain newlines.
78 * <input type="text"> would be an appropriate HTML form field.
79 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
80 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
81 * used with PARAM_ISMULTI.
82 * - text: Any non-empty string, expected to be very long or contain newlines.
83 * <textarea> would be an appropriate HTML form field.
84 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
85 * string 'now' representing the current timestamp. Will be returned in
87 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
88 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
89 * Cannot be used with PARAM_ISMULTI.
93 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
97 * (integer) Max value allowed for the parameter for users with the
98 * apihighlimits right, for PARAM_TYPE 'limit'.
100 const PARAM_MAX2
= 4;
102 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
105 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
106 const PARAM_ALLOW_DUPLICATES
= 6;
108 /** (boolean) Is the parameter deprecated (will show a warning)? */
109 const PARAM_DEPRECATED
= 7;
112 * (boolean) Is the parameter required?
115 const PARAM_REQUIRED
= 8;
118 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
121 const PARAM_RANGE_ENFORCE
= 9;
124 * (string|array|Message) Specify an alternative i18n documentation message
125 * for this parameter. Default is apihelp-{$path}-param-{$param}.
128 const PARAM_HELP_MSG
= 10;
131 * ((string|array|Message)[]) Specify additional i18n messages to append to
132 * the normal message for this parameter.
135 const PARAM_HELP_MSG_APPEND
= 11;
138 * (array) Specify additional information tags for the parameter. Value is
139 * an array of arrays, with the first member being the 'tag' for the info
140 * and the remaining members being the values. In the help, this is
141 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
142 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
145 const PARAM_HELP_MSG_INFO
= 12;
148 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
149 * those values to page titles which will be linked in the help.
152 const PARAM_VALUE_LINKS
= 13;
155 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
156 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
157 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
160 const PARAM_HELP_MSG_PER_VALUE
= 14;
163 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
164 * submodule paths. Default is to use all modules in
165 * $this->getModuleManager() in the group matching the parameter name.
168 const PARAM_SUBMODULE_MAP
= 15;
171 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
172 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
175 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
178 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
179 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
180 * every possible value. If a string is set, it will be used in place of the asterisk.
183 const PARAM_ALL
= 17;
186 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
189 const PARAM_EXTRA_NAMESPACES
= 18;
192 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
193 * always sensitive regardless of the value of this field.
196 const PARAM_SENSITIVE
= 19;
200 const ALL_DEFAULT_STRING
= '*';
202 /** Fast query, standard limit. */
203 const LIMIT_BIG1
= 500;
204 /** Fast query, apihighlimits limit. */
205 const LIMIT_BIG2
= 5000;
206 /** Slow query, standard limit. */
207 const LIMIT_SML1
= 50;
208 /** Slow query, apihighlimits limit. */
209 const LIMIT_SML2
= 500;
212 * getAllowedParams() flag: When set, the result could take longer to generate,
213 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
216 const GET_VALUES_FOR_HELP
= 1;
218 /** @var array Maps extension paths to info arrays */
219 private static $extensionInfo = null;
222 private $mMainModule;
224 private $mModuleName, $mModulePrefix;
225 private $mSlaveDB = null;
226 private $mParamCache = [];
227 /** @var array|null|bool */
228 private $mModuleSource = false;
231 * @param ApiMain $mainModule
232 * @param string $moduleName Name of this module
233 * @param string $modulePrefix Prefix to use for parameter names
235 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
236 $this->mMainModule
= $mainModule;
237 $this->mModuleName
= $moduleName;
238 $this->mModulePrefix
= $modulePrefix;
240 if ( !$this->isMain() ) {
241 $this->setContext( $mainModule->getContext() );
245 /************************************************************************//**
246 * @name Methods to implement
251 * Evaluates the parameters, performs the requested query, and sets up
252 * the result. Concrete implementations of ApiBase must override this
253 * method to provide whatever functionality their module offers.
254 * Implementations must not produce any output on their own and are not
255 * expected to handle any errors.
257 * The execute() method will be invoked directly by ApiMain immediately
258 * before the result of the module is output. Aside from the
259 * constructor, implementations should assume that no other methods
260 * will be called externally on the module before the result is
263 * The result data should be stored in the ApiResult object available
264 * through getResult().
266 abstract public function execute();
269 * Get the module manager, or null if this module has no sub-modules
271 * @return ApiModuleManager
273 public function getModuleManager() {
278 * If the module may only be used with a certain format module,
279 * it should override this method to return an instance of that formatter.
280 * A value of null means the default format will be used.
281 * @note Do not use this just because you don't want to support non-json
282 * formats. This should be used only when there is a fundamental
283 * requirement for a specific format.
284 * @return mixed Instance of a derived class of ApiFormatBase, or null
286 public function getCustomPrinter() {
291 * Returns usage examples for this module.
293 * Return value has query strings as keys, with values being either strings
294 * (message key), arrays (message key + parameter), or Message objects.
296 * Do not call this base class implementation when overriding this method.
301 protected function getExamplesMessages() {
302 // Fall back to old non-localised method
305 $examples = $this->getExamples();
307 if ( !is_array( $examples ) ) {
308 $examples = [ $examples ];
309 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
310 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
311 !preg_match( '/^\s*api\.php\?/', $examples[0] )
313 // Fix up the ugly "even numbered elements are description, odd
314 // numbered elemts are the link" format (see doc for self::getExamples)
316 $examplesCount = count( $examples );
317 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
318 $tmp[$examples[$i +
1]] = $examples[$i];
323 foreach ( $examples as $k => $v ) {
324 if ( is_numeric( $k ) ) {
329 $msg = self
::escapeWikiText( $v );
330 if ( is_array( $msg ) ) {
331 $msg = implode( ' ', $msg );
335 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
336 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
344 * Return links to more detailed help pages about the module.
345 * @since 1.25, returning boolean false is deprecated
346 * @return string|array
348 public function getHelpUrls() {
353 * Returns an array of allowed parameters (parameter name) => (default
354 * value) or (parameter name) => (array with PARAM_* constants as keys)
355 * Don't call this function directly: use getFinalParams() to allow
356 * hooks to modify parameters as needed.
358 * Some derived classes may choose to handle an integer $flags parameter
359 * in the overriding methods. Callers of this method can pass zero or
360 * more OR-ed flags like GET_VALUES_FOR_HELP.
364 protected function getAllowedParams( /* $flags = 0 */ ) {
365 // int $flags is not declared because it causes "Strict standards"
366 // warning. Most derived classes do not implement it.
371 * Indicates if this module needs maxlag to be checked
374 public function shouldCheckMaxlag() {
379 * Indicates whether this module requires read rights
382 public function isReadMode() {
387 * Indicates whether this module requires write mode
389 * This should return true for modules that may require synchronous database writes.
390 * Modules that do not need such writes should also not rely on master database access,
391 * since only read queries are needed and each master DB is a single point of failure.
392 * Additionally, requests that only need replica DBs can be efficiently routed to any
393 * datacenter via the Promise-Non-Write-API-Action header.
397 public function isWriteMode() {
402 * Indicates whether this module must be called with a POST request
405 public function mustBePosted() {
406 return $this->needsToken() !== false;
410 * Indicates whether this module is deprecated
414 public function isDeprecated() {
419 * Indicates whether this module is "internal"
420 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
424 public function isInternal() {
429 * Returns the token type this module requires in order to execute.
431 * Modules are strongly encouraged to use the core 'csrf' type unless they
432 * have specialized security needs. If the token type is not one of the
433 * core types, you must use the ApiQueryTokensRegisterTypes hook to
436 * Returning a non-falsey value here will force the addition of an
437 * appropriate 'token' parameter in self::getFinalParams(). Also,
438 * self::mustBePosted() must return true when tokens are used.
440 * In previous versions of MediaWiki, true was a valid return value.
441 * Returning true will generate errors indicating that the API module needs
444 * @return string|false
446 public function needsToken() {
451 * Fetch the salt used in the Web UI corresponding to this module.
453 * Only override this if the Web UI uses a token with a non-constant salt.
456 * @param array $params All supplied parameters for the module
457 * @return string|array|null
459 protected function getWebUITokenSalt( array $params ) {
464 * Returns data for HTTP conditional request mechanisms.
467 * @param string $condition Condition being queried:
468 * - last-modified: Return a timestamp representing the maximum of the
469 * last-modified dates for all resources involved in the request. See
470 * RFC 7232 § 2.2 for semantics.
471 * - etag: Return an entity-tag representing the state of all resources involved
472 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
473 * @return string|bool|null As described above, or null if no value is available.
475 public function getConditionalRequestData( $condition ) {
481 /************************************************************************//**
482 * @name Data access methods
487 * Get the name of the module being executed by this instance
490 public function getModuleName() {
491 return $this->mModuleName
;
495 * Get parameter prefix (usually two letters or an empty string).
498 public function getModulePrefix() {
499 return $this->mModulePrefix
;
503 * Get the main module
506 public function getMain() {
507 return $this->mMainModule
;
511 * Returns true if this module is the main module ($this === $this->mMainModule),
515 public function isMain() {
516 return $this === $this->mMainModule
;
520 * Get the parent of this module
522 * @return ApiBase|null
524 public function getParent() {
525 return $this->isMain() ?
null : $this->getMain();
529 * Returns true if the current request breaks the same-origin policy.
531 * For example, json with callbacks.
533 * https://en.wikipedia.org/wiki/Same-origin_policy
538 public function lacksSameOriginSecurity() {
539 // Main module has this method overridden
540 // Safety - avoid infinite loop:
541 if ( $this->isMain() ) {
542 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
545 return $this->getMain()->lacksSameOriginSecurity();
549 * Get the path to this module
554 public function getModulePath() {
555 if ( $this->isMain() ) {
557 } elseif ( $this->getParent()->isMain() ) {
558 return $this->getModuleName();
560 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
565 * Get a module from its module path
568 * @param string $path
569 * @return ApiBase|null
570 * @throws ApiUsageException
572 public function getModuleFromPath( $path ) {
573 $module = $this->getMain();
574 if ( $path === 'main' ) {
578 $parts = explode( '+', $path );
579 if ( count( $parts ) === 1 ) {
580 // In case the '+' was typed into URL, it resolves as a space
581 $parts = explode( ' ', $path );
584 $count = count( $parts );
585 for ( $i = 0; $i < $count; $i++
) {
587 $manager = $parent->getModuleManager();
588 if ( $manager === null ) {
589 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
590 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
592 $module = $manager->getModule( $parts[$i] );
594 if ( $module === null ) {
595 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
597 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
607 * Get the result object
610 public function getResult() {
611 // Main module has getResult() 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()->getResult();
621 * Get the error formatter
622 * @return ApiErrorFormatter
624 public function getErrorFormatter() {
625 // Main module has getErrorFormatter() method overridden
626 // Safety - avoid infinite loop:
627 if ( $this->isMain() ) {
628 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
631 return $this->getMain()->getErrorFormatter();
635 * Gets a default replica DB connection object
638 protected function getDB() {
639 if ( !isset( $this->mSlaveDB
) ) {
640 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
643 return $this->mSlaveDB
;
647 * Get the continuation manager
648 * @return ApiContinuationManager|null
650 public function getContinuationManager() {
651 // Main module has getContinuationManager() method overridden
652 // Safety - avoid infinite loop:
653 if ( $this->isMain() ) {
654 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
657 return $this->getMain()->getContinuationManager();
661 * Set the continuation manager
662 * @param ApiContinuationManager|null
664 public function setContinuationManager( $manager ) {
665 // Main module has setContinuationManager() method overridden
666 // Safety - avoid infinite loop:
667 if ( $this->isMain() ) {
668 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
671 $this->getMain()->setContinuationManager( $manager );
676 /************************************************************************//**
677 * @name Parameter handling
682 * Indicate if the module supports dynamically-determined parameters that
683 * cannot be included in self::getAllowedParams().
684 * @return string|array|Message|null Return null if the module does not
685 * support additional dynamic parameters, otherwise return a message
688 public function dynamicParameterDocumentation() {
693 * This method mangles parameter name based on the prefix supplied to the constructor.
694 * Override this method to change parameter name during runtime
695 * @param string|string[] $paramName Parameter name
696 * @return string|string[] Prefixed parameter name
697 * @since 1.29 accepts an array of strings
699 public function encodeParamName( $paramName ) {
700 if ( is_array( $paramName ) ) {
701 return array_map( function ( $name ) {
702 return $this->mModulePrefix
. $name;
705 return $this->mModulePrefix
. $paramName;
710 * Using getAllowedParams(), this function makes an array of the values
711 * provided by the user, with key being the name of the variable, and
712 * value - validated value from user or default. limits will not be
713 * parsed if $parseLimit is set to false; use this when the max
714 * limit is not definitive yet, e.g. when getting revisions.
715 * @param bool $parseLimit True by default
718 public function extractRequestParams( $parseLimit = true ) {
719 // Cache parameters, for performance and to avoid T26564.
720 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
721 $params = $this->getFinalParams();
724 if ( $params ) { // getFinalParams() can return false
725 foreach ( $params as $paramName => $paramSettings ) {
726 $results[$paramName] = $this->getParameterFromSettings(
727 $paramName, $paramSettings, $parseLimit );
730 $this->mParamCache
[$parseLimit] = $results;
733 return $this->mParamCache
[$parseLimit];
737 * Get a value for the given parameter
738 * @param string $paramName Parameter name
739 * @param bool $parseLimit See extractRequestParams()
740 * @return mixed Parameter value
742 protected function getParameter( $paramName, $parseLimit = true ) {
743 $paramSettings = $this->getFinalParams()[$paramName];
745 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
749 * Die if none or more than one of a certain set of parameters is set and not false.
751 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
752 * @param string $required,... Names of parameters of which exactly one must be set
754 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
755 $required = func_get_args();
756 array_shift( $required );
758 $intersection = array_intersect( array_keys( array_filter( $params,
759 [ $this, 'parameterNotEmpty' ] ) ), $required );
761 if ( count( $intersection ) > 1 ) {
762 $this->dieWithError( [
763 'apierror-invalidparammix',
764 Message
::listParam( array_map(
766 return '<var>' . $this->encodeParamName( $p ) . '</var>';
768 array_values( $intersection )
770 count( $intersection ),
772 } elseif ( count( $intersection ) == 0 ) {
773 $this->dieWithError( [
774 'apierror-missingparam-one-of',
775 Message
::listParam( array_map(
777 return '<var>' . $this->encodeParamName( $p ) . '</var>';
779 array_values( $required )
787 * Die if more than one of a certain set of parameters is set and not false.
789 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
790 * @param string $required,... Names of parameters of which at most one must be set
792 public function requireMaxOneParameter( $params, $required /*...*/ ) {
793 $required = func_get_args();
794 array_shift( $required );
796 $intersection = array_intersect( array_keys( array_filter( $params,
797 [ $this, 'parameterNotEmpty' ] ) ), $required );
799 if ( count( $intersection ) > 1 ) {
800 $this->dieWithError( [
801 'apierror-invalidparammix',
802 Message
::listParam( array_map(
804 return '<var>' . $this->encodeParamName( $p ) . '</var>';
806 array_values( $intersection )
808 count( $intersection ),
814 * Die if none of a certain set of parameters is set and not false.
817 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
818 * @param string $required,... Names of parameters of which at least one must be set
820 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
821 $required = func_get_args();
822 array_shift( $required );
824 $intersection = array_intersect(
825 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
829 if ( count( $intersection ) == 0 ) {
830 $this->dieWithError( [
831 'apierror-missingparam-at-least-one-of',
832 Message
::listParam( array_map(
834 return '<var>' . $this->encodeParamName( $p ) . '</var>';
836 array_values( $required )
844 * Die if any of the specified parameters were found in the query part of
845 * the URL rather than the post body.
847 * @param string[] $params Parameters to check
848 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
850 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
851 // Skip if $wgDebugAPI is set or we're in internal mode
852 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
856 $queryValues = $this->getRequest()->getQueryValues();
858 foreach ( $params as $param ) {
859 if ( $prefix !== 'noprefix' ) {
860 $param = $this->encodeParamName( $param );
862 if ( array_key_exists( $param, $queryValues ) ) {
863 $badParams[] = $param;
869 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
875 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
877 * @param object $x Parameter to check is not null/false
880 private function parameterNotEmpty( $x ) {
881 return !is_null( $x ) && $x !== false;
885 * Get a WikiPage object from a title or pageid param, if possible.
886 * Can die, if no param is set or if the title or page id is not valid.
888 * @param array $params
889 * @param bool|string $load Whether load the object's state from the database:
890 * - false: don't load (if the pageid is given, it will still be loaded)
891 * - 'fromdb': load from a replica DB
892 * - 'fromdbmaster': load from the master database
895 public function getTitleOrPageId( $params, $load = false ) {
896 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
899 if ( isset( $params['title'] ) ) {
900 $titleObj = Title
::newFromText( $params['title'] );
901 if ( !$titleObj ||
$titleObj->isExternal() ) {
902 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
904 if ( !$titleObj->canExist() ) {
905 $this->dieWithError( 'apierror-pagecannotexist' );
907 $pageObj = WikiPage
::factory( $titleObj );
908 if ( $load !== false ) {
909 $pageObj->loadPageData( $load );
911 } elseif ( isset( $params['pageid'] ) ) {
912 if ( $load === false ) {
915 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
917 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
925 * Get a Title object from a title or pageid param, if possible.
926 * Can die, if no param is set or if the title or page id is not valid.
929 * @param array $params
932 public function getTitleFromTitleOrPageId( $params ) {
933 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
936 if ( isset( $params['title'] ) ) {
937 $titleObj = Title
::newFromText( $params['title'] );
938 if ( !$titleObj ||
$titleObj->isExternal() ) {
939 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
942 } elseif ( isset( $params['pageid'] ) ) {
943 $titleObj = Title
::newFromID( $params['pageid'] );
945 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
953 * Return true if we're to watch the page, false if not, null if no change.
954 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
955 * @param Title $titleObj The page under consideration
956 * @param string $userOption The user option to consider when $watchlist=preferences.
957 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
960 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
962 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
964 switch ( $watchlist ) {
972 # If the user is already watching, don't bother checking
973 if ( $userWatching ) {
976 # If no user option was passed, use watchdefault and watchcreations
977 if ( is_null( $userOption ) ) {
978 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
979 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
982 # Watch the article based on the user preference
983 return $this->getUser()->getBoolOption( $userOption );
986 return $userWatching;
989 return $userWatching;
994 * Using the settings determine the value for the given parameter
996 * @param string $paramName Parameter name
997 * @param array|mixed $paramSettings Default value or an array of settings
998 * using PARAM_* constants.
999 * @param bool $parseLimit Parse limit?
1000 * @return mixed Parameter value
1002 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1003 // Some classes may decide to change parameter names
1004 $encParamName = $this->encodeParamName( $paramName );
1007 if ( !is_array( $paramSettings ) ) {
1009 self
::PARAM_DFLT
=> $paramSettings,
1013 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1014 ?
$paramSettings[self
::PARAM_DFLT
]
1016 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1017 ?
$paramSettings[self
::PARAM_ISMULTI
]
1019 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1020 ?
$paramSettings[self
::PARAM_TYPE
]
1022 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1023 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1025 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1026 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1028 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1029 ?
$paramSettings[self
::PARAM_REQUIRED
]
1031 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1032 ?
$paramSettings[self
::PARAM_ALL
]
1035 // When type is not given, and no choices, the type is the same as $default
1036 if ( !isset( $type ) ) {
1037 if ( isset( $default ) ) {
1038 $type = gettype( $default );
1040 $type = 'NULL'; // allow everything
1043 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1044 $this->getMain()->markParamsSensitive( $encParamName );
1048 if ( $type == 'boolean' ) {
1049 if ( isset( $default ) && $default !== false ) {
1050 // Having a default value of anything other than 'false' is not allowed
1053 "Boolean param $encParamName's default is set to '$default'. " .
1054 'Boolean parameters must default to false.'
1058 $value = $this->getMain()->getCheck( $encParamName );
1059 } elseif ( $type == 'upload' ) {
1060 if ( isset( $default ) ) {
1061 // Having a default value is not allowed
1064 "File upload param $encParamName's default is set to " .
1065 "'$default'. File upload parameters may not have a default." );
1068 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1070 $value = $this->getMain()->getUpload( $encParamName );
1071 if ( !$value->exists() ) {
1072 // This will get the value without trying to normalize it
1073 // (because trying to normalize a large binary file
1074 // accidentally uploaded as a field fails spectacularly)
1075 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1076 if ( $value !== null ) {
1077 $this->dieWithError(
1078 [ 'apierror-badupload', $encParamName ],
1079 "badupload_{$encParamName}"
1084 $value = $this->getMain()->getVal( $encParamName, $default );
1086 if ( isset( $value ) && $type == 'namespace' ) {
1087 $type = MWNamespace
::getValidNamespaces();
1088 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1089 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1091 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1093 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1097 if ( isset( $value ) && $type == 'submodule' ) {
1098 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1099 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1101 $type = $this->getModuleManager()->getNames( $paramName );
1105 $request = $this->getMain()->getRequest();
1106 $rawValue = $request->getRawVal( $encParamName );
1107 if ( $rawValue === null ) {
1108 $rawValue = $default;
1111 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1112 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1114 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1115 // done by WebRequest for $_GET. Let's call that a feature.
1116 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1118 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1122 // Check for NFC normalization, and warn
1123 if ( $rawValue !== $value ) {
1124 $this->handleParamNormalization( $paramName, $value, $rawValue );
1128 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1129 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1132 "For param $encParamName, PARAM_ALL collides with a possible value" );
1134 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1135 $value = $this->parseMultiValue(
1139 is_array( $type ) ?
$type : null,
1140 $allowAll ?
$allSpecifier : null
1144 // More validation only when choices were not given
1145 // choices were validated in parseMultiValue()
1146 if ( isset( $value ) ) {
1147 if ( !is_array( $type ) ) {
1149 case 'NULL': // nothing to do
1154 if ( $required && $value === '' ) {
1155 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1158 case 'integer': // Force everything using intval() and optionally validate limits
1159 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1160 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1161 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1162 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1164 if ( is_array( $value ) ) {
1165 $value = array_map( 'intval', $value );
1166 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1167 foreach ( $value as &$v ) {
1168 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1172 $value = intval( $value );
1173 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1174 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1179 if ( !$parseLimit ) {
1180 // Don't do any validation whatsoever
1183 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1184 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1188 "MAX1 or MAX2 are not defined for the limit $encParamName"
1192 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1194 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1195 if ( $value == 'max' ) {
1196 $value = $this->getMain()->canApiHighLimits()
1197 ?
$paramSettings[self
::PARAM_MAX2
]
1198 : $paramSettings[self
::PARAM_MAX
];
1199 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1201 $value = intval( $value );
1202 $this->validateLimit(
1206 $paramSettings[self
::PARAM_MAX
],
1207 $paramSettings[self
::PARAM_MAX2
]
1213 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1217 if ( is_array( $value ) ) {
1218 foreach ( $value as $key => $val ) {
1219 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1222 $value = $this->validateTimestamp( $value, $encParamName );
1226 if ( is_array( $value ) ) {
1227 foreach ( $value as $key => $val ) {
1228 $value[$key] = $this->validateUser( $val, $encParamName );
1231 $value = $this->validateUser( $value, $encParamName );
1234 case 'upload': // nothing to do
1237 // If change tagging was requested, check that the tags are valid.
1238 if ( !is_array( $value ) && !$multi ) {
1239 $value = [ $value ];
1241 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1242 if ( !$tagsStatus->isGood() ) {
1243 $this->dieStatus( $tagsStatus );
1247 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1251 // Throw out duplicates if requested
1252 if ( !$dupes && is_array( $value ) ) {
1253 $value = array_unique( $value );
1256 // Set a warning if a deprecated parameter has been passed
1257 if ( $deprecated && $value !== false ) {
1258 $feature = $encParamName;
1260 while ( !$m->isMain() ) {
1261 $p = $m->getParent();
1262 $name = $m->getModuleName();
1263 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1264 $feature = "{$param}={$name}&{$feature}";
1267 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1269 } elseif ( $required ) {
1270 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1277 * Handle when a parameter was Unicode-normalized
1279 * @param string $paramName Unprefixed parameter name
1280 * @param string $value Input that will be used.
1281 * @param string $rawValue Input before normalization.
1283 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1284 $encParamName = $this->encodeParamName( $paramName );
1285 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1289 * Split a multi-valued parameter string, like explode()
1291 * @param string $value
1295 protected function explodeMultiValue( $value, $limit ) {
1296 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1298 $value = substr( $value, 1 );
1303 return explode( $sep, $value, $limit );
1307 * Return an array of values that were given in a 'a|b|c' notation,
1308 * after it optionally validates them against the list allowed values.
1310 * @param string $valueName The name of the parameter (for error
1312 * @param mixed $value The value being parsed
1313 * @param bool $allowMultiple Can $value contain more than one value
1315 * @param string[]|null $allowedValues An array of values to check against. If
1316 * null, all values are accepted.
1317 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1318 * if this behavior should not be allowed
1319 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1321 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1322 $allSpecifier = null
1324 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1328 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1329 // because it unstubs $wgUser
1330 $valuesList = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1331 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1335 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1336 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1338 return $allowedValues;
1341 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1342 $this->addDeprecation(
1343 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1344 "too-many-$valueName-for-{$this->getModulePath()}"
1348 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1349 // T35482 - Allow entries with | in them for non-multiple values
1350 if ( in_array( $value, $allowedValues, true ) ) {
1354 if ( is_array( $allowedValues ) ) {
1355 $values = array_map( function ( $v ) {
1356 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1357 }, $allowedValues );
1358 $this->dieWithError( [
1359 'apierror-multival-only-one-of',
1361 Message
::listParam( $values ),
1363 ], "multival_$valueName" );
1365 $this->dieWithError( [
1366 'apierror-multival-only-one',
1368 ], "multival_$valueName" );
1372 if ( is_array( $allowedValues ) ) {
1373 // Check for unknown values
1374 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1375 if ( count( $unknown ) ) {
1376 if ( $allowMultiple ) {
1377 $this->addWarning( [
1378 'apiwarn-unrecognizedvalues',
1380 Message
::listParam( $unknown, 'comma' ),
1384 $this->dieWithError(
1385 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1386 "unknown_$valueName"
1390 // Now throw them out
1391 $valuesList = array_intersect( $valuesList, $allowedValues );
1394 return $allowMultiple ?
$valuesList : $valuesList[0];
1398 * Validate the value against the minimum and user/bot maximum limits.
1399 * Prints usage info on failure.
1400 * @param string $paramName Parameter name
1401 * @param int $value Parameter value
1402 * @param int|null $min Minimum value
1403 * @param int|null $max Maximum value for users
1404 * @param int $botMax Maximum value for sysops/bots
1405 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1407 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1408 $enforceLimits = false
1410 if ( !is_null( $min ) && $value < $min ) {
1411 $msg = ApiMessage
::create(
1412 [ 'apierror-integeroutofrange-belowminimum',
1413 $this->encodeParamName( $paramName ), $min, $value ],
1414 'integeroutofrange',
1415 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1417 $this->warnOrDie( $msg, $enforceLimits );
1421 // Minimum is always validated, whereas maximum is checked only if not
1422 // running in internal call mode
1423 if ( $this->getMain()->isInternalMode() ) {
1427 // Optimization: do not check user's bot status unless really needed -- skips db query
1428 // assumes $botMax >= $max
1429 if ( !is_null( $max ) && $value > $max ) {
1430 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1431 if ( $value > $botMax ) {
1432 $msg = ApiMessage
::create(
1433 [ 'apierror-integeroutofrange-abovebotmax',
1434 $this->encodeParamName( $paramName ), $botMax, $value ],
1435 'integeroutofrange',
1436 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1438 $this->warnOrDie( $msg, $enforceLimits );
1442 $msg = ApiMessage
::create(
1443 [ 'apierror-integeroutofrange-abovemax',
1444 $this->encodeParamName( $paramName ), $max, $value ],
1445 'integeroutofrange',
1446 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1448 $this->warnOrDie( $msg, $enforceLimits );
1455 * Validate and normalize of parameters of type 'timestamp'
1456 * @param string $value Parameter value
1457 * @param string $encParamName Parameter name
1458 * @return string Validated and normalized parameter
1460 protected function validateTimestamp( $value, $encParamName ) {
1461 // Confusing synonyms for the current time accepted by wfTimestamp()
1462 // (wfTimestamp() also accepts various non-strings and the string of 14
1463 // ASCII NUL bytes, but those can't get here)
1465 $this->addDeprecation(
1466 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1467 'unclear-"now"-timestamp'
1469 return wfTimestamp( TS_MW
);
1472 // Explicit synonym for the current time
1473 if ( $value === 'now' ) {
1474 return wfTimestamp( TS_MW
);
1477 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1478 if ( $unixTimestamp === false ) {
1479 $this->dieWithError(
1480 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1481 "badtimestamp_{$encParamName}"
1485 return wfTimestamp( TS_MW
, $unixTimestamp );
1489 * Validate the supplied token.
1492 * @param string $token Supplied token
1493 * @param array $params All supplied parameters for the module
1495 * @throws MWException
1497 final public function validateToken( $token, array $params ) {
1498 $tokenType = $this->needsToken();
1499 $salts = ApiQueryTokens
::getTokenTypeSalts();
1500 if ( !isset( $salts[$tokenType] ) ) {
1501 throw new MWException(
1502 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1503 'without registering it'
1507 $tokenObj = ApiQueryTokens
::getToken(
1508 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1510 if ( $tokenObj->match( $token ) ) {
1514 $webUiSalt = $this->getWebUITokenSalt( $params );
1515 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1527 * Validate and normalize of parameters of type 'user'
1528 * @param string $value Parameter value
1529 * @param string $encParamName Parameter name
1530 * @return string Validated and normalized parameter
1532 private function validateUser( $value, $encParamName ) {
1533 $title = Title
::makeTitleSafe( NS_USER
, $value );
1534 if ( $title === null ||
$title->hasFragment() ) {
1535 $this->dieWithError(
1536 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1537 "baduser_{$encParamName}"
1541 return $title->getText();
1546 /************************************************************************//**
1547 * @name Utility methods
1552 * Set a watch (or unwatch) based the based on a watchlist parameter.
1553 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1554 * @param Title $titleObj The article's title to change
1555 * @param string $userOption The user option to consider when $watch=preferences
1557 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1558 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1559 if ( $value === null ) {
1563 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1567 * Truncate an array to a certain length.
1568 * @param array $arr Array to truncate
1569 * @param int $limit Maximum length
1570 * @return bool True if the array was truncated, false otherwise
1572 public static function truncateArray( &$arr, $limit ) {
1574 while ( count( $arr ) > $limit ) {
1583 * Gets the user for whom to get the watchlist
1585 * @param array $params
1588 public function getWatchlistUser( $params ) {
1589 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1590 $user = User
::newFromName( $params['owner'], false );
1591 if ( !( $user && $user->getId() ) ) {
1592 $this->dieWithError(
1593 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1596 $token = $user->getOption( 'watchlisttoken' );
1597 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1598 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1601 if ( !$this->getUser()->isLoggedIn() ) {
1602 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1604 $this->checkUserRightsAny( 'viewmywatchlist' );
1605 $user = $this->getUser();
1612 * A subset of wfEscapeWikiText for BC texts
1615 * @param string|array $v
1616 * @return string|array
1618 private static function escapeWikiText( $v ) {
1619 if ( is_array( $v ) ) {
1620 return array_map( 'self::escapeWikiText', $v );
1623 '__' => '__', '{' => '{', '}' => '}',
1624 '[[Category:' => '[[:Category:',
1625 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1631 * Create a Message from a string or array
1633 * A string is used as a message key. An array has the message key as the
1634 * first value and message parameters as subsequent values.
1637 * @param string|array|Message $msg
1638 * @param IContextSource $context
1639 * @param array $params
1640 * @return Message|null
1642 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1643 if ( is_string( $msg ) ) {
1644 $msg = wfMessage( $msg );
1645 } elseif ( is_array( $msg ) ) {
1646 $msg = call_user_func_array( 'wfMessage', $msg );
1648 if ( !$msg instanceof Message
) {
1652 $msg->setContext( $context );
1654 $msg->params( $params );
1661 * Turn an array of message keys or key+param arrays into a Status
1663 * @param array $errors
1664 * @param User|null $user
1667 public function errorArrayToStatus( array $errors, User
$user = null ) {
1668 if ( $user === null ) {
1669 $user = $this->getUser();
1672 $status = Status
::newGood();
1673 foreach ( $errors as $error ) {
1674 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1675 $status->fatal( ApiMessage
::create(
1678 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1680 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1681 $status->fatal( ApiMessage
::create(
1682 'apierror-autoblocked',
1684 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1686 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1687 $status->fatal( ApiMessage
::create(
1688 'apierror-systemblocked',
1690 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1693 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1701 /************************************************************************//**
1702 * @name Warning and error reporting
1707 * Add a warning for this module.
1709 * Users should monitor this section to notice any changes in API. Multiple
1710 * calls to this function will result in multiple warning messages.
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::addWarning()
1717 * @param string|null $code See ApiErrorFormatter::addWarning()
1718 * @param array|null $data See ApiErrorFormatter::addWarning()
1720 public function addWarning( $msg, $code = null, $data = null ) {
1721 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1725 * Add a deprecation warning for this module.
1727 * A combination of $this->addWarning() and $this->logFeatureUsage()
1730 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1731 * @param string|null $feature See ApiBase::logFeatureUsage()
1732 * @param array|null $data See ApiErrorFormatter::addWarning()
1734 public function addDeprecation( $msg, $feature, $data = [] ) {
1735 $data = (array)$data;
1736 if ( $feature !== null ) {
1737 $data['feature'] = $feature;
1738 $this->logFeatureUsage( $feature );
1740 $this->addWarning( $msg, 'deprecation', $data );
1742 // No real need to deduplicate here, ApiErrorFormatter does that for
1743 // us (assuming the hook is deterministic).
1744 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1745 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1746 if ( count( $msgs ) > 1 ) {
1747 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1748 $msg = ( new RawMessage( $key ) )->params( $msgs );
1750 $msg = reset( $msgs );
1752 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1756 * Add an error for this module without aborting
1758 * If $msg is not an ApiMessage, the message code will be derived from the
1759 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1761 * @note If you want to abort processing, use self::dieWithError() instead.
1763 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1764 * @param string|null $code See ApiErrorFormatter::addError()
1765 * @param array|null $data See ApiErrorFormatter::addError()
1767 public function addError( $msg, $code = null, $data = null ) {
1768 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1772 * Add warnings and/or errors from a Status
1774 * @note If you want to abort processing, use self::dieStatus() instead.
1776 * @param StatusValue $status
1777 * @param string[] $types 'warning' and/or 'error'
1779 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1780 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1784 * Abort execution with an error
1786 * If $msg is not an ApiMessage, the message code will be derived from the
1787 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1790 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1791 * @param string|null $code See ApiErrorFormatter::addError()
1792 * @param array|null $data See ApiErrorFormatter::addError()
1793 * @param int|null $httpCode HTTP error code to use
1794 * @throws ApiUsageException always
1796 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1797 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1801 * Abort execution with an error derived from an exception
1804 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1805 * @param array $options See ApiErrorFormatter::getMessageFromException()
1806 * @throws ApiUsageException always
1808 public function dieWithException( $exception, array $options = [] ) {
1809 $this->dieWithError(
1810 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1815 * Adds a warning to the output, else dies
1817 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1818 * @param bool $enforceLimits Whether this is an enforce (die)
1820 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1821 if ( $enforceLimits ) {
1822 $this->dieWithError( $msg );
1824 $this->addWarning( $msg );
1829 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1830 * error handler and die with an error message including block info.
1833 * @param Block $block The block used to generate the ApiUsageException
1834 * @throws ApiUsageException always
1836 public function dieBlocked( Block
$block ) {
1837 // Die using the appropriate message depending on block type
1838 if ( $block->getType() == Block
::TYPE_AUTO
) {
1839 $this->dieWithError(
1840 'apierror-autoblocked',
1842 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1845 $this->dieWithError(
1848 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1854 * Throw an ApiUsageException based on the Status object.
1857 * @since 1.29 Accepts a StatusValue
1858 * @param StatusValue $status
1859 * @throws ApiUsageException always
1861 public function dieStatus( StatusValue
$status ) {
1862 if ( $status->isGood() ) {
1863 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1866 throw new ApiUsageException( $this, $status );
1870 * Helper function for readonly errors
1872 * @throws ApiUsageException always
1874 public function dieReadOnly() {
1875 $this->dieWithError(
1876 'apierror-readonly',
1878 [ 'readonlyreason' => wfReadOnlyReason() ]
1883 * Helper function for permission-denied errors
1885 * @param string|string[] $rights
1886 * @param User|null $user
1887 * @throws ApiUsageException if the user doesn't have any of the rights.
1888 * The error message is based on $rights[0].
1890 public function checkUserRightsAny( $rights, $user = null ) {
1892 $user = $this->getUser();
1894 $rights = (array)$rights;
1895 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1896 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1901 * Helper function for permission-denied errors
1903 * @param Title $title
1904 * @param string|string[] $actions
1905 * @param User|null $user
1906 * @throws ApiUsageException if the user doesn't have all of the rights.
1908 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
1910 $user = $this->getUser();
1914 foreach ( (array)$actions as $action ) {
1915 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1918 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1923 * Will only set a warning instead of failing if the global $wgDebugAPI
1924 * is set to true. Otherwise behaves exactly as self::dieWithError().
1927 * @param string|array|Message $msg
1928 * @param string|null $code
1929 * @param array|null $data
1930 * @param int|null $httpCode
1931 * @throws ApiUsageException
1933 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1934 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1935 $this->dieWithError( $msg, $code, $data, $httpCode );
1937 $this->addWarning( $msg, $code, $data );
1942 * Die with the 'badcontinue' error.
1944 * This call is common enough to make it into the base method.
1946 * @param bool $condition Will only die if this value is true
1947 * @throws ApiUsageException
1950 protected function dieContinueUsageIf( $condition ) {
1952 $this->dieWithError( 'apierror-badcontinue' );
1957 * Internal code errors should be reported with this method
1958 * @param string $method Method or function name
1959 * @param string $message Error message
1960 * @throws MWException always
1962 protected static function dieDebug( $method, $message ) {
1963 throw new MWException( "Internal error in $method: $message" );
1967 * Write logging information for API features to a debug log, for usage
1969 * @note Consider using $this->addDeprecation() instead to both warn and log.
1970 * @param string $feature Feature being used.
1972 public function logFeatureUsage( $feature ) {
1973 $request = $this->getRequest();
1974 $s = '"' . addslashes( $feature ) . '"' .
1975 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1976 ' "' . $request->getIP() . '"' .
1977 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1978 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1979 wfDebugLog( 'api-feature-usage', $s, 'private' );
1984 /************************************************************************//**
1985 * @name Help message generation
1990 * Return the description message.
1992 * @return string|array|Message
1994 protected function getDescriptionMessage() {
1995 return "apihelp-{$this->getModulePath()}-description";
1999 * Get final module description, after hooks have had a chance to tweak it as
2002 * @since 1.25, returns Message[] rather than string[]
2005 public function getFinalDescription() {
2006 $desc = $this->getDescription();
2008 // Avoid PHP 7.1 warning of passing $this by reference
2010 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2011 $desc = self
::escapeWikiText( $desc );
2012 if ( is_array( $desc ) ) {
2013 $desc = implode( "\n", $desc );
2015 $desc = (string)$desc;
2018 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2019 $this->getModulePrefix(),
2020 $this->getModuleName(),
2021 $this->getModulePath(),
2023 if ( !$msg->exists() ) {
2024 $msg = $this->msg( 'api-help-fallback-description', $desc );
2028 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2034 * Get final list of parameters, after hooks have had a chance to
2035 * tweak it as needed.
2037 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2038 * @return array|bool False on no parameters
2039 * @since 1.21 $flags param added
2041 public function getFinalParams( $flags = 0 ) {
2042 $params = $this->getAllowedParams( $flags );
2047 if ( $this->needsToken() ) {
2048 $params['token'] = [
2049 ApiBase
::PARAM_TYPE
=> 'string',
2050 ApiBase
::PARAM_REQUIRED
=> true,
2051 ApiBase
::PARAM_SENSITIVE
=> true,
2052 ApiBase
::PARAM_HELP_MSG
=> [
2053 'api-help-param-token',
2054 $this->needsToken(),
2056 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2059 // Avoid PHP 7.1 warning of passing $this by reference
2061 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2067 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2070 * @since 1.25, returns array of Message[] rather than array of string[]
2071 * @return array Keys are parameter names, values are arrays of Message objects
2073 public function getFinalParamDescription() {
2074 $prefix = $this->getModulePrefix();
2075 $name = $this->getModuleName();
2076 $path = $this->getModulePath();
2078 $desc = $this->getParamDescription();
2080 // Avoid PHP 7.1 warning of passing $this by reference
2082 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2087 $desc = self
::escapeWikiText( $desc );
2089 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2091 foreach ( $params as $param => $settings ) {
2092 if ( !is_array( $settings ) ) {
2096 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2097 if ( is_array( $d ) ) {
2098 // Special handling for prop parameters
2099 $d = array_map( function ( $line ) {
2100 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2101 $line = "\n;{$m[1]}:{$m[2]}";
2105 $d = implode( ' ', $d );
2108 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2109 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2111 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2112 if ( !$msg->exists() ) {
2113 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2116 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2117 [ $prefix, $param, $name, $path ] );
2119 self
::dieDebug( __METHOD__
,
2120 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2122 $msgs[$param] = [ $msg ];
2124 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2125 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2126 self
::dieDebug( __METHOD__
,
2127 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2129 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2130 self
::dieDebug( __METHOD__
,
2131 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2132 'ApiBase::PARAM_TYPE is an array' );
2135 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2136 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2137 if ( isset( $valueMsgs[$value] ) ) {
2138 $msg = $valueMsgs[$value];
2140 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2142 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2143 [ $prefix, $param, $name, $path, $value ] );
2145 $m = new ApiHelpParamValueMessage(
2147 [ $m->getKey(), 'api-help-param-no-description' ],
2150 $msgs[$param][] = $m->setContext( $this->getContext() );
2152 self
::dieDebug( __METHOD__
,
2153 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2158 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2159 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2160 self
::dieDebug( __METHOD__
,
2161 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2163 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2164 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2165 [ $prefix, $param, $name, $path ] );
2167 $msgs[$param][] = $m;
2169 self
::dieDebug( __METHOD__
,
2170 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2176 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2182 * Generates the list of flags for the help screen and for action=paraminfo
2184 * Corresponding messages: api-help-flag-deprecated,
2185 * api-help-flag-internal, api-help-flag-readrights,
2186 * api-help-flag-writerights, api-help-flag-mustbeposted
2190 protected function getHelpFlags() {
2193 if ( $this->isDeprecated() ) {
2194 $flags[] = 'deprecated';
2196 if ( $this->isInternal() ) {
2197 $flags[] = 'internal';
2199 if ( $this->isReadMode() ) {
2200 $flags[] = 'readrights';
2202 if ( $this->isWriteMode() ) {
2203 $flags[] = 'writerights';
2205 if ( $this->mustBePosted() ) {
2206 $flags[] = 'mustbeposted';
2213 * Returns information about the source of this module, if known
2215 * Returned array is an array with the following keys:
2216 * - path: Install path
2217 * - name: Extension name, or "MediaWiki" for core
2218 * - namemsg: (optional) i18n message key for a display name
2219 * - license-name: (optional) Name of license
2221 * @return array|null
2223 protected function getModuleSourceInfo() {
2226 if ( $this->mModuleSource
!== false ) {
2227 return $this->mModuleSource
;
2230 // First, try to find where the module comes from...
2231 $rClass = new ReflectionClass( $this );
2232 $path = $rClass->getFileName();
2235 $this->mModuleSource
= null;
2238 $path = realpath( $path ) ?
: $path;
2240 // Build map of extension directories to extension info
2241 if ( self
::$extensionInfo === null ) {
2242 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2243 self
::$extensionInfo = [
2244 realpath( __DIR__
) ?
: __DIR__
=> [
2246 'name' => 'MediaWiki',
2247 'license-name' => 'GPL-2.0+',
2249 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2250 realpath( $extDir ) ?
: $extDir => null,
2256 'license-name' => null,
2258 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2259 foreach ( $group as $ext ) {
2260 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2261 // This shouldn't happen, but does anyway.
2265 $extpath = $ext['path'];
2266 if ( !is_dir( $extpath ) ) {
2267 $extpath = dirname( $extpath );
2269 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2270 array_intersect_key( $ext, $keep );
2273 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2274 $extpath = $ext['path'];
2275 if ( !is_dir( $extpath ) ) {
2276 $extpath = dirname( $extpath );
2278 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2279 array_intersect_key( $ext, $keep );
2283 // Now traverse parent directories until we find a match or run out of
2286 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2288 $this->mModuleSource
= self
::$extensionInfo[$path];
2289 return $this->mModuleSource
;
2293 $path = dirname( $path );
2294 } while ( $path !== $oldpath );
2296 // No idea what extension this might be.
2297 $this->mModuleSource
= null;
2302 * Called from ApiHelp before the pieces are joined together and returned.
2304 * This exists mainly for ApiMain to add the Permissions and Credits
2305 * sections. Other modules probably don't need it.
2307 * @param string[] &$help Array of help data
2308 * @param array $options Options passed to ApiHelp::getHelp
2309 * @param array &$tocData If a TOC is being generated, this array has keys
2310 * as anchors in the page and values as for Linker::generateTOC().
2312 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2317 /************************************************************************//**
2323 * Returns the description string for this module
2325 * Ignored if an i18n message exists for
2326 * "apihelp-{$this->getModulePath()}-description".
2328 * @deprecated since 1.25
2329 * @return Message|string|array|false
2331 protected function getDescription() {
2336 * Returns an array of parameter descriptions.
2338 * For each parameter, ignored if an i18n message exists for the parameter.
2339 * By default that message is
2340 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2341 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2342 * self::getFinalParams().
2344 * @deprecated since 1.25
2345 * @return array|bool False on no parameter descriptions
2347 protected function getParamDescription() {
2352 * Returns usage examples for this module.
2354 * Return value as an array is either:
2355 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2357 * - sequential numeric keys with even-numbered keys being display-text
2358 * and odd-numbered keys being partial urls
2359 * - partial URLs as keys with display-text (string or array-to-be-joined)
2361 * Return value as a string is the same as an array with a numeric key and
2362 * that value, and boolean false means "no examples".
2364 * @deprecated since 1.25, use getExamplesMessages() instead
2365 * @return bool|string|array
2367 protected function getExamples() {
2372 * @deprecated since 1.25, always returns empty string
2373 * @param IDatabase|bool $db
2376 public function getModuleProfileName( $db = false ) {
2377 wfDeprecated( __METHOD__
, '1.25' );
2382 * @deprecated since 1.25
2384 public function profileIn() {
2385 // No wfDeprecated() yet because extensions call this and might need to
2386 // keep doing so for BC.
2390 * @deprecated since 1.25
2392 public function profileOut() {
2393 // No wfDeprecated() yet because extensions call this and might need to
2394 // keep doing so for BC.
2398 * @deprecated since 1.25
2400 public function safeProfileOut() {
2401 wfDeprecated( __METHOD__
, '1.25' );
2405 * @deprecated since 1.25, always returns 0
2408 public function getProfileTime() {
2409 wfDeprecated( __METHOD__
, '1.25' );
2414 * @deprecated since 1.25
2416 public function profileDBIn() {
2417 wfDeprecated( __METHOD__
, '1.25' );
2421 * @deprecated since 1.25
2423 public function profileDBOut() {
2424 wfDeprecated( __METHOD__
, '1.25' );
2428 * @deprecated since 1.25, always returns 0
2431 public function getProfileDBTime() {
2432 wfDeprecated( __METHOD__
, '1.25' );
2437 * Call wfTransactionalTimeLimit() if this request was POSTed
2440 protected function useTransactionalTimeLimit() {
2441 if ( $this->getRequest()->wasPosted() ) {
2442 wfTransactionalTimeLimit();
2447 * @deprecated since 1.29, use ApiBase::addWarning() instead
2448 * @param string $warning Warning message
2450 public function setWarning( $warning ) {
2451 $msg = new ApiRawMessage( $warning, 'warning' );
2452 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2456 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2457 * error handler and die with an error message.
2459 * @deprecated since 1.29, use self::dieWithError() instead
2460 * @param string $description One-line human-readable description of the
2461 * error condition, e.g., "The API requires a valid action parameter"
2462 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2463 * automated identification of the error, e.g., 'unknown_action'
2464 * @param int $httpRespCode HTTP response code
2465 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2466 * @throws ApiUsageException always
2468 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2469 $this->dieWithError(
2470 new RawMessage( '$1', [ $description ] ),
2478 * Get error (as code, string) from a Status object.
2481 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2482 * @param Status $status
2483 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2484 * @return array Array of code and error string
2485 * @throws MWException
2487 public function getErrorFromStatus( $status, &$extraData = null ) {
2488 if ( $status->isGood() ) {
2489 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2492 $errors = $status->getErrorsByType( 'error' );
2494 // No errors? Assume the warnings should be treated as errors
2495 $errors = $status->getErrorsByType( 'warning' );
2498 // Still no errors? Punt
2499 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2502 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2503 $msg = $errors[0]['message'];
2505 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2507 if ( !$msg instanceof IApiMessage
) {
2508 $key = $msg->getKey();
2509 $params = $msg->getParams();
2510 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2511 $msg = ApiMessage
::create( $params );
2516 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2521 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2522 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2523 * API codes and message texts, and a few interfaces required poking
2524 * something in here. Now we're repurposing it to map those same strings
2525 * to i18n messages, and declaring that any interface that requires poking
2526 * at this is broken and needs replacing ASAP.
2528 private static $messageMap = [
2529 'unknownerror' => 'apierror-unknownerror',
2530 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2531 'ns-specialprotected' => 'ns-specialprotected',
2532 'protectedinterface' => 'protectedinterface',
2533 'namespaceprotected' => 'namespaceprotected',
2534 'customcssprotected' => 'customcssprotected',
2535 'customjsprotected' => 'customjsprotected',
2536 'cascadeprotected' => 'cascadeprotected',
2537 'protectedpagetext' => 'protectedpagetext',
2538 'protect-cantedit' => 'protect-cantedit',
2539 'deleteprotected' => 'deleteprotected',
2540 'badaccess-group0' => 'badaccess-group0',
2541 'badaccess-groups' => 'badaccess-groups',
2542 'titleprotected' => 'titleprotected',
2543 'nocreate-loggedin' => 'nocreate-loggedin',
2544 'nocreatetext' => 'nocreatetext',
2545 'movenologintext' => 'movenologintext',
2546 'movenotallowed' => 'movenotallowed',
2547 'confirmedittext' => 'confirmedittext',
2548 'blockedtext' => 'apierror-blocked',
2549 'autoblockedtext' => 'apierror-autoblocked',
2550 'systemblockedtext' => 'apierror-systemblocked',
2551 'actionthrottledtext' => 'apierror-ratelimited',
2552 'alreadyrolled' => 'alreadyrolled',
2553 'cantrollback' => 'cantrollback',
2554 'readonlytext' => 'readonlytext',
2555 'sessionfailure' => 'sessionfailure',
2556 'cannotdelete' => 'cannotdelete',
2557 'notanarticle' => 'apierror-missingtitle',
2558 'selfmove' => 'selfmove',
2559 'immobile_namespace' => 'apierror-immobilenamespace',
2560 'articleexists' => 'articleexists',
2561 'hookaborted' => 'hookaborted',
2562 'cantmove-titleprotected' => 'cantmove-titleprotected',
2563 'imagenocrossnamespace' => 'imagenocrossnamespace',
2564 'imagetypemismatch' => 'imagetypemismatch',
2565 'ip_range_invalid' => 'ip_range_invalid',
2566 'range_block_disabled' => 'range_block_disabled',
2567 'nosuchusershort' => 'nosuchusershort',
2568 'badipaddress' => 'badipaddress',
2569 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2570 'ipb_already_blocked' => 'ipb_already_blocked',
2571 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2572 'ipb_cant_unblock' => 'ipb_cant_unblock',
2573 'mailnologin' => 'apierror-cantsend',
2574 'ipbblocked' => 'ipbblocked',
2575 'ipbnounblockself' => 'ipbnounblockself',
2576 'usermaildisabled' => 'usermaildisabled',
2577 'blockedemailuser' => 'apierror-blockedfrommail',
2578 'notarget' => 'apierror-notarget',
2579 'noemail' => 'noemail',
2580 'rcpatroldisabled' => 'rcpatroldisabled',
2581 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2582 'delete-toobig' => 'delete-toobig',
2583 'movenotallowedfile' => 'movenotallowedfile',
2584 'userrights-no-interwiki' => 'userrights-no-interwiki',
2585 'userrights-nodatabase' => 'userrights-nodatabase',
2586 'nouserspecified' => 'nouserspecified',
2587 'noname' => 'noname',
2588 'summaryrequired' => 'apierror-summaryrequired',
2589 'import-rootpage-invalid' => 'import-rootpage-invalid',
2590 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2591 'readrequired' => 'apierror-readapidenied',
2592 'writedisabled' => 'apierror-noapiwrite',
2593 'writerequired' => 'apierror-writeapidenied',
2594 'missingparam' => 'apierror-missingparam',
2595 'invalidtitle' => 'apierror-invalidtitle',
2596 'nosuchpageid' => 'apierror-nosuchpageid',
2597 'nosuchrevid' => 'apierror-nosuchrevid',
2598 'nosuchuser' => 'nosuchusershort',
2599 'invaliduser' => 'apierror-invaliduser',
2600 'invalidexpiry' => 'apierror-invalidexpiry',
2601 'pastexpiry' => 'apierror-pastexpiry',
2602 'create-titleexists' => 'apierror-create-titleexists',
2603 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2604 'cantblock' => 'apierror-cantblock',
2605 'canthide' => 'apierror-canthide',
2606 'cantblock-email' => 'apierror-cantblock-email',
2607 'cantunblock' => 'apierror-permissiondenied-generic',
2608 'cannotundelete' => 'cannotundelete',
2609 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2610 'createonly-exists' => 'apierror-articleexists',
2611 'nocreate-missing' => 'apierror-missingtitle',
2612 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2613 'nosuchrcid' => 'apierror-nosuchrcid',
2614 'nosuchlogid' => 'apierror-nosuchlogid',
2615 'protect-invalidaction' => 'apierror-protect-invalidaction',
2616 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2617 'toofewexpiries' => 'apierror-toofewexpiries',
2618 'cantimport' => 'apierror-cantimport',
2619 'cantimport-upload' => 'apierror-cantimport-upload',
2620 'importnofile' => 'importnofile',
2621 'importuploaderrorsize' => 'importuploaderrorsize',
2622 'importuploaderrorpartial' => 'importuploaderrorpartial',
2623 'importuploaderrortemp' => 'importuploaderrortemp',
2624 'importcantopen' => 'importcantopen',
2625 'import-noarticle' => 'import-noarticle',
2626 'importbadinterwiki' => 'importbadinterwiki',
2627 'import-unknownerror' => 'apierror-import-unknownerror',
2628 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2629 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2630 'mustbeposted' => 'apierror-mustbeposted',
2631 'show' => 'apierror-show',
2632 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2633 'invalidoldimage' => 'apierror-invalidoldimage',
2634 'nodeleteablefile' => 'apierror-nodeleteablefile',
2635 'fileexists-forbidden' => 'fileexists-forbidden',
2636 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2637 'filerevert-badversion' => 'filerevert-badversion',
2638 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2639 'noimageredirect-logged' => 'apierror-noimageredirect',
2640 'spamdetected' => 'apierror-spamdetected',
2641 'contenttoobig' => 'apierror-contenttoobig',
2642 'noedit-anon' => 'apierror-noedit-anon',
2643 'noedit' => 'apierror-noedit',
2644 'wasdeleted' => 'apierror-pagedeleted',
2645 'blankpage' => 'apierror-emptypage',
2646 'editconflict' => 'editconflict',
2647 'hashcheckfailed' => 'apierror-badmd5',
2648 'missingtext' => 'apierror-notext',
2649 'emptynewsection' => 'apierror-emptynewsection',
2650 'revwrongpage' => 'apierror-revwrongpage',
2651 'undo-failure' => 'undo-failure',
2652 'content-not-allowed-here' => 'content-not-allowed-here',
2653 'edit-hook-aborted' => 'edit-hook-aborted',
2654 'edit-gone-missing' => 'edit-gone-missing',
2655 'edit-conflict' => 'edit-conflict',
2656 'edit-already-exists' => 'edit-already-exists',
2657 'invalid-file-key' => 'apierror-invalid-file-key',
2658 'nouploadmodule' => 'apierror-nouploadmodule',
2659 'uploaddisabled' => 'uploaddisabled',
2660 'copyuploaddisabled' => 'copyuploaddisabled',
2661 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2662 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2663 'filename-tooshort' => 'filename-tooshort',
2664 'filename-toolong' => 'filename-toolong',
2665 'illegal-filename' => 'illegal-filename',
2666 'filetype-missing' => 'filetype-missing',
2667 'mustbeloggedin' => 'apierror-mustbeloggedin',
2671 * @deprecated do not use
2672 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2673 * @return ApiMessage
2675 private function parseMsgInternal( $error ) {
2676 $msg = Message
::newFromSpecifier( $error );
2677 if ( !$msg instanceof IApiMessage
) {
2678 $key = $msg->getKey();
2679 if ( isset( self
::$messageMap[$key] ) ) {
2680 $params = $msg->getParams();
2681 array_unshift( $params, self
::$messageMap[$key] );
2683 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2685 $msg = ApiMessage
::create( $params );
2691 * Return the error message related to a certain array
2692 * @deprecated since 1.29
2693 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2694 * @return [ 'code' => code, 'info' => info ]
2696 public function parseMsg( $error ) {
2697 // Check whether someone passed the whole array, instead of one element as
2698 // documented. This breaks if it's actually an array of fallback keys, but
2699 // that's long-standing misbehavior introduced in r87627 to incorrectly
2701 if ( is_array( $error ) ) {
2702 $first = reset( $error );
2703 if ( is_array( $first ) ) {
2704 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2709 $msg = $this->parseMsgInternal( $error );
2711 'code' => $msg->getApiCode(),
2712 'info' => ApiErrorFormatter
::stripMarkup(
2713 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2715 'data' => $msg->getApiData()
2720 * Output the error message related to a certain array
2721 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2722 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2723 * @throws ApiUsageException always
2725 public function dieUsageMsg( $error ) {
2726 $this->dieWithError( $this->parseMsgInternal( $error ) );
2730 * Will only set a warning instead of failing if the global $wgDebugAPI
2731 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2732 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2733 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2734 * @throws ApiUsageException
2737 public function dieUsageMsgOrDebug( $error ) {
2738 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2745 * For really cool vim folding this needs to be at the end:
2746 * vim: foldmarker=@{,@} foldmethod=marker