Merge "ResourceLoader: Deprecate ResourceLoader::makeConfigSetScript"
[mediawiki.git] / includes / api / ApiBase.php
blob6ef7f8741bbe4a7216186c70b7be49bc1e4e6903
1 <?php
2 /**
3 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 namespace MediaWiki\Api;
25 use InvalidArgumentException;
26 use LogicException;
27 use MediaWiki\Api\Validator\SubmoduleDef;
28 use MediaWiki\Block\Block;
29 use MediaWiki\Context\ContextSource;
30 use MediaWiki\Context\IContextSource;
31 use MediaWiki\HookContainer\HookContainer;
32 use MediaWiki\Language\RawMessage;
33 use MediaWiki\MainConfigNames;
34 use MediaWiki\MediaWikiServices;
35 use MediaWiki\Message\Message;
36 use MediaWiki\Page\PageIdentity;
37 use MediaWiki\ParamValidator\TypeDef\NamespaceDef;
38 use MediaWiki\Permissions\Authority;
39 use MediaWiki\Permissions\PermissionManager;
40 use MediaWiki\Permissions\PermissionStatus;
41 use MediaWiki\Registration\ExtensionRegistry;
42 use MediaWiki\Specials\SpecialVersion;
43 use MediaWiki\Status\Status;
44 use MediaWiki\Title\Title;
45 use MediaWiki\User\User;
46 use MediaWiki\User\UserRigorOptions;
47 use MWException;
48 use ReflectionClass;
49 use StatusValue;
50 use stdClass;
51 use Throwable;
52 use Wikimedia\Message\MessageSpecifier;
53 use Wikimedia\ParamValidator\ParamValidator;
54 use Wikimedia\ParamValidator\TypeDef\EnumDef;
55 use Wikimedia\ParamValidator\TypeDef\IntegerDef;
56 use Wikimedia\ParamValidator\TypeDef\StringDef;
57 use Wikimedia\Rdbms\IReadableDatabase;
58 use Wikimedia\Timestamp\TimestampException;
59 use WikiPage;
61 /**
62 * This abstract class implements many basic API functions, and is the base of
63 * all API classes.
65 * The class functions are divided into several areas of functionality:
67 * Module parameters: Derived classes can define getAllowedParams() to specify
68 * which parameters to expect, how to parse and validate them.
70 * Self-documentation: code to allow the API to document its own state
72 * @stable to extend
74 * @ingroup API
76 abstract class ApiBase extends ContextSource {
78 use ApiBlockInfoTrait;
80 /** @var HookContainer */
81 private $hookContainer;
83 /** @var ApiHookRunner */
84 private $hookRunner;
86 /**
87 * @name Old constants for ::getAllowedParams() arrays
88 * @{
91 /**
92 * @deprecated since 1.35, use ParamValidator::PARAM_DEFAULT instead
94 public const PARAM_DFLT = ParamValidator::PARAM_DEFAULT;
95 /**
96 * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI instead
98 public const PARAM_ISMULTI = ParamValidator::PARAM_ISMULTI;
99 /**
100 * @deprecated since 1.35, use ParamValidator::PARAM_TYPE instead
102 public const PARAM_TYPE = ParamValidator::PARAM_TYPE;
104 * @deprecated since 1.35, use IntegerDef::PARAM_MAX instead
106 public const PARAM_MAX = IntegerDef::PARAM_MAX;
108 * @deprecated since 1.35, use IntegerDef::PARAM_MAX2 instead
110 public const PARAM_MAX2 = IntegerDef::PARAM_MAX2;
112 * @deprecated since 1.35, use IntegerDef::PARAM_MIN instead
114 public const PARAM_MIN = IntegerDef::PARAM_MIN;
116 * @deprecated since 1.35, use ParamValidator::PARAM_ALLOW_DUPLICATES instead
118 public const PARAM_ALLOW_DUPLICATES = ParamValidator::PARAM_ALLOW_DUPLICATES;
120 * @deprecated since 1.35, use ParamValidator::PARAM_DEPRECATED instead
122 public const PARAM_DEPRECATED = ParamValidator::PARAM_DEPRECATED;
124 * @deprecated since 1.35, use ParamValidator::PARAM_REQUIRED instead
126 public const PARAM_REQUIRED = ParamValidator::PARAM_REQUIRED;
128 * @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_MAP instead
130 public const PARAM_SUBMODULE_MAP = SubmoduleDef::PARAM_SUBMODULE_MAP;
132 * @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX instead
134 public const PARAM_SUBMODULE_PARAM_PREFIX = SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX;
136 * @deprecated since 1.35, use ParamValidator::PARAM_ALL instead
138 public const PARAM_ALL = ParamValidator::PARAM_ALL;
140 * @deprecated since 1.35, use NamespaceDef::PARAM_EXTRA_NAMESPACES instead
142 public const PARAM_EXTRA_NAMESPACES = NamespaceDef::PARAM_EXTRA_NAMESPACES;
144 * @deprecated since 1.35, use ParamValidator::PARAM_SENSITIVE instead
146 public const PARAM_SENSITIVE = ParamValidator::PARAM_SENSITIVE;
148 * @deprecated since 1.35, use EnumDef::PARAM_DEPRECATED_VALUES instead
150 public const PARAM_DEPRECATED_VALUES = EnumDef::PARAM_DEPRECATED_VALUES;
152 * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT1 instead
154 public const PARAM_ISMULTI_LIMIT1 = ParamValidator::PARAM_ISMULTI_LIMIT1;
156 * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT2 instead
158 public const PARAM_ISMULTI_LIMIT2 = ParamValidator::PARAM_ISMULTI_LIMIT2;
160 * @deprecated since 1.35, use StringDef::PARAM_MAX_BYTES instead
162 public const PARAM_MAX_BYTES = StringDef::PARAM_MAX_BYTES;
164 * @deprecated since 1.35, use StringDef::PARAM_MAX_CHARS instead
166 public const PARAM_MAX_CHARS = StringDef::PARAM_MAX_CHARS;
167 /** @} */
170 * (boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
171 * @deprecated since 1.35
173 public const PARAM_RANGE_ENFORCE = 'api-param-range-enforce';
175 // region API-specific constants for ::getAllowedParams() arrays
176 /** @name API-specific constants for ::getAllowedParams() arrays */
179 * (string|array|Message) Specify an alternative i18n documentation message
180 * for this parameter. Default is apihelp-{$path}-param-{$param}.
181 * See Message::newFromSpecifier() for a description of allowed values.
182 * @since 1.25
184 public const PARAM_HELP_MSG = 'api-param-help-msg';
187 * ((string|array|Message)[]) Specify additional i18n messages to append to
188 * the normal message for this parameter.
189 * See Message::newFromSpecifier() for a description of allowed values.
190 * @since 1.25
192 public const PARAM_HELP_MSG_APPEND = 'api-param-help-msg-append';
195 * (array) Specify additional information tags for the parameter.
196 * The value is an array of arrays, with the first member being the 'tag' for the info
197 * and the remaining members being the values. In the help, this is
198 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
199 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
200 * @since 1.25
202 public const PARAM_HELP_MSG_INFO = 'api-param-help-msg-info';
205 * Deprecated and unused.
206 * @since 1.25
207 * @deprecated since 1.35
209 public const PARAM_VALUE_LINKS = 'api-param-value-links';
212 * ((string|array|Message)[]) When PARAM_TYPE is an array, or 'string'
213 * with PARAM_ISMULTI, this is an array mapping parameter values to help messages.
214 * See Message::newFromSpecifier() for a description of allowed values.
216 * When PARAM_TYPE is an array, any value not having a mapping will use
217 * the apihelp-{$path}-paramvalue-{$param}-{$value} message. (This means
218 * you can use an empty array to use the default message key for all
219 * values.)
221 * @since 1.25
222 * @note Use with PARAM_TYPE = 'string' is allowed since 1.40.
224 public const PARAM_HELP_MSG_PER_VALUE = 'api-param-help-msg-per-value';
227 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
228 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
229 * which the replacement values are taken.
231 * For example, a parameter "foo-{ns}-{title}" could be defined with
232 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
233 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
235 * All placeholders must be present in the parameter's name. Each target parameter must have
236 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
237 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
238 * A parameter cannot target itself.
240 * @since 1.32
242 public const PARAM_TEMPLATE_VARS = 'param-template-vars';
244 // endregion -- end of API-specific constants for ::getAllowedParams() arrays
246 public const ALL_DEFAULT_STRING = '*';
248 /** Fast query, standard limit. */
249 public const LIMIT_BIG1 = 500;
250 /** Fast query, apihighlimits limit. */
251 public const LIMIT_BIG2 = 5000;
252 /** Slow query, standard limit. */
253 public const LIMIT_SML1 = 50;
254 /** Slow query, apihighlimits limit. */
255 public const LIMIT_SML2 = 500;
258 * getAllowedParams() flag: When this is set, the result could take longer to generate,
259 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
260 * @since 1.21
262 public const GET_VALUES_FOR_HELP = 1;
264 /** @var array Maps extension paths to info arrays */
265 private static $extensionInfo = null;
267 /** @var stdClass[][] Cache for self::filterIDs() */
268 private static $filterIDsCache = [];
270 /** @var array Map of web UI block messages which magically gain machine-readable block info */
271 private const BLOCK_CODE_MAP = [
272 'blockedtext' => true,
273 'blockedtext-partial' => true,
274 'autoblockedtext' => true,
275 'systemblockedtext' => true,
276 'blockedtext-composite' => true,
277 'blockedtext-tempuser' => true,
278 'autoblockedtext-tempuser' => true,
281 /** @var array Map of web UI block messages to corresponding API messages and codes */
282 private const MESSAGE_CODE_MAP = [
283 'actionthrottled' => [ 'apierror-ratelimited', 'ratelimited' ],
284 'actionthrottledtext' => [ 'apierror-ratelimited', 'ratelimited' ],
287 /** @var ApiMain */
288 private $mMainModule;
290 // Adding inline type hints for these two fields is non-trivial because
291 // of tests that create mocks for ApiBase subclasses and use
292 // disableOriginalConstructor(): in those cases the constructor here is never
293 // hit and thus these will be empty and any uses will raise a "Typed property
294 // must not be accessed before initialization" error.
295 /** @var string */
296 private $mModuleName;
297 /** @var string */
298 private $mModulePrefix;
300 /** @var IReadableDatabase|null */
301 private $mReplicaDB = null;
303 * @var array
305 private $mParamCache = [];
306 /** @var array|null|false */
307 private $mModuleSource = false;
310 * @stable to call
311 * @param ApiMain $mainModule
312 * @param string $moduleName Name of this module
313 * @param string $modulePrefix Prefix to use for parameter names
315 public function __construct( ApiMain $mainModule, string $moduleName, string $modulePrefix = '' ) {
316 $this->mMainModule = $mainModule;
317 $this->mModuleName = $moduleName;
318 $this->mModulePrefix = $modulePrefix;
320 if ( !$this->isMain() ) {
321 $this->setContext( $mainModule->getContext() );
325 /***************************************************************************/
326 // region Methods to implement
327 /** @name Methods to implement */
330 * Evaluates the parameters, performs the requested query, and sets up
331 * the result. Concrete implementations of ApiBase must override this
332 * method to provide whatever functionality their module offers.
333 * Implementations must not produce any output on their own and are not
334 * expected to handle any errors.
336 * The execute() method will be invoked directly by ApiMain immediately
337 * before the result of the module is output. Aside from the
338 * constructor, implementations should assume that no other methods
339 * will be called externally on the module before the result is
340 * processed.
342 * The result data should be stored in the ApiResult object available
343 * through getResult().
345 abstract public function execute();
348 * Get the module manager, or null if this module has no submodules.
350 * @since 1.21
351 * @stable to override
352 * @return ApiModuleManager|null
354 public function getModuleManager() {
355 return null;
359 * If the module may only be used with a certain format module,
360 * it should override this method to return an instance of that formatter.
361 * A value of null means the default format will be used.
363 * @note Do not use this just because you don't want to support non-json
364 * formats. This should be used only when there is a fundamental
365 * requirement for a specific format.
367 * @stable to override
368 * @return ApiFormatBase|null An instance of a class derived from ApiFormatBase, or null
370 public function getCustomPrinter() {
371 return null;
375 * Returns usage examples for this module.
377 * Return value has query strings as keys, with values being either strings
378 * (message key), arrays (message key + parameter), or Message objects.
380 * Do not call this base class implementation when overriding this method.
382 * @since 1.25
383 * @stable to override
384 * @return array
386 protected function getExamplesMessages() {
387 return [];
391 * Return links to more detailed help pages about the module.
393 * @since 1.25, returning boolean false is deprecated
394 * @stable to override
395 * @return string|array
397 public function getHelpUrls() {
398 return [];
402 * Returns an array of allowed parameters (parameter name) => (default
403 * value) or (parameter name) => (array with PARAM_* constants as keys)
404 * Don't call this function directly: use getFinalParams() to allow
405 * hooks to modify parameters as needed.
407 * Some derived classes may choose to handle an integer $flags parameter
408 * in the overriding methods. Callers of this method can pass zero or
409 * more OR-ed flags like GET_VALUES_FOR_HELP.
411 * @stable to override
412 * @return array
414 protected function getAllowedParams( /* $flags = 0 */ ) {
415 // $flags is not declared because it causes "Strict standards"
416 // warning. Most derived classes do not implement it.
417 return [];
421 * Indicates if this module needs maxlag to be checked.
423 * @stable to override
424 * @return bool
426 public function shouldCheckMaxlag() {
427 return true;
431 * Indicates whether this module requires read rights.
433 * @stable to override
434 * @return bool
436 public function isReadMode() {
437 return true;
441 * Indicates whether this module requires write access to the wiki.
443 * API modules must override this method to return true if the operation they will
444 * perform is not "safe" per RFC 7231 section 4.2.1. A module's operation is "safe"
445 * if it is essentially read-only, i.e. the client does not request nor expect any
446 * state change that would be observable in the responses to future requests.
448 * Implementations of this method must always return the same value, regardless of
449 * the parameters passed to the constructor or system state.
451 * Modules that do not require POST requests should only perform "safe" operations.
452 * Note that some modules might require POST requests because they need to support
453 * large input parameters and not because they perform non-"safe" operations.
455 * The information provided by this method is used to perform authorization checks.
456 * It can also be used to enforce proper routing of supposedly "safe" POST requests
457 * to the closest datacenter via the Promise-Non-Write-API-Action header.
459 * @see mustBePosted()
460 * @see needsToken()
462 * @stable to override
463 * @return bool
465 public function isWriteMode() {
466 return false;
470 * Indicates whether this module must be called with a POST request.
472 * Implementations of this method must always return the same value,
473 * regardless of the parameters passed to the constructor or system state.
475 * @stable to override
476 * @return bool
478 public function mustBePosted() {
479 return $this->needsToken() !== false;
483 * Indicates whether this module is deprecated.
485 * @since 1.25
486 * @stable to override
487 * @return bool
489 public function isDeprecated() {
490 return false;
494 * Indicates whether this module is considered to be "internal".
496 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
498 * @since 1.25
499 * @stable to override
500 * @return bool
502 public function isInternal() {
503 return false;
507 * Returns the token type this module requires in order to execute.
509 * Modules are strongly encouraged to use the core 'csrf' type unless they
510 * have specialized security needs. If the token type is not one of the
511 * core types, you must use the ApiQueryTokensRegisterTypes hook to
512 * register it.
514 * Returning a non-falsey value here will force the addition of an
515 * appropriate 'token' parameter in self::getFinalParams(). Also,
516 * self::mustBePosted() must return true when tokens are used.
518 * In previous versions of MediaWiki, true was a valid return value.
519 * Returning true will generate errors indicating that the API module needs
520 * updating.
522 * @stable to override
523 * @return string|false
525 public function needsToken() {
526 return false;
530 * Fetch the salt used in the Web UI corresponding to this module.
532 * Only override this if the Web UI uses a token with a non-constant salt.
534 * @since 1.24
535 * @param array $params All supplied parameters for the module
536 * @stable to override
537 * @return string|array|null
539 protected function getWebUITokenSalt( array $params ) {
540 return null;
544 * Returns data for HTTP conditional request mechanisms.
546 * @since 1.26
547 * @stable to override
548 * @param string $condition Condition being queried:
549 * - last-modified: Return a timestamp representing the maximum of the
550 * last-modified dates for all resources involved in the request. See
551 * RFC 7232 § 2.2 for semantics.
552 * - etag: Return an entity-tag representing the state of all resources involved
553 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
554 * @return string|bool|null As described above, or null if no value is available.
556 public function getConditionalRequestData( $condition ) {
557 return null;
560 // endregion -- end of methods to implement
562 /***************************************************************************/
563 // region Data access methods
564 /** @name Data access methods */
567 * Get the name of the module being executed by this instance.
569 * @return string
571 public function getModuleName() {
572 return $this->mModuleName;
576 * Get parameter prefix (usually two letters or an empty string).
578 * @return string
580 public function getModulePrefix() {
581 return $this->mModulePrefix;
585 * Get the main module.
587 * @return ApiMain
589 public function getMain() {
590 return $this->mMainModule;
594 * Returns true if this module is the main module ($this === $this->mMainModule),
595 * false otherwise.
597 * @return bool
599 public function isMain() {
600 return $this === $this->mMainModule;
604 * Get the parent of this module.
606 * @stable to override
607 * @since 1.25
608 * @return ApiBase|null
610 public function getParent() {
611 return $this->isMain() ? null : $this->getMain();
615 * Used to avoid infinite loops - the ApiMain class should override some
616 * methods, if it doesn't and uses the default ApiBase implementation, which
617 * just calls the same method for the ApiMain instance, it'll lead to an infinite loop
619 * @param string $methodName used for debug messages
621 private function dieIfMain( string $methodName ) {
622 if ( $this->isMain() ) {
623 self::dieDebug( $methodName, 'base method was called on main module.' );
628 * Returns true if the current request breaks the same-origin policy.
630 * For example, json with callbacks.
632 * https://en.wikipedia.org/wiki/Same-origin_policy
634 * @since 1.25
635 * @return bool
637 public function lacksSameOriginSecurity() {
638 // The Main module has this method overridden, avoid infinite loops
639 $this->dieIfMain( __METHOD__ );
641 return $this->getMain()->lacksSameOriginSecurity();
645 * Get the path to this module.
647 * @since 1.25
648 * @return string
650 public function getModulePath() {
651 if ( $this->isMain() ) {
652 return 'main';
655 if ( $this->getParent()->isMain() ) {
656 return $this->getModuleName();
659 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
663 * Get a module from its module path.
665 * @since 1.25
666 * @param string $path
667 * @return ApiBase|null
668 * @throws ApiUsageException
670 public function getModuleFromPath( $path ) {
671 $module = $this->getMain();
672 if ( $path === 'main' ) {
673 return $module;
676 $parts = explode( '+', $path );
677 if ( count( $parts ) === 1 ) {
678 // In case the '+' was typed into URL, it resolves as a space
679 $parts = explode( ' ', $path );
682 foreach ( $parts as $i => $v ) {
683 $parent = $module;
684 $manager = $parent->getModuleManager();
685 if ( $manager === null ) {
686 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
687 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
689 $module = $manager->getModule( $v );
691 if ( $module === null ) {
692 $errorPath = $i
693 ? implode( '+', array_slice( $parts, 0, $i ) )
694 : $parent->getModuleName();
695 $this->dieWithError(
696 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $v ) ],
697 'badmodule'
702 return $module;
706 * Get the result object.
708 * @return ApiResult
710 public function getResult() {
711 // The Main module has this method overridden, avoid infinite loops
712 $this->dieIfMain( __METHOD__ );
714 return $this->getMain()->getResult();
718 * @stable to override
719 * @return ApiErrorFormatter
721 public function getErrorFormatter() {
722 // The Main module has this method overridden, avoid infinite loops
723 $this->dieIfMain( __METHOD__ );
725 return $this->getMain()->getErrorFormatter();
729 * Gets a default replica DB connection object.
731 * @stable to override
732 * @return IReadableDatabase
734 protected function getDB() {
735 if ( !$this->mReplicaDB ) {
736 $this->mReplicaDB = MediaWikiServices::getInstance()
737 ->getConnectionProvider()
738 ->getReplicaDatabase( false, 'api' );
741 return $this->mReplicaDB;
745 * @return ApiContinuationManager|null
747 public function getContinuationManager() {
748 // The Main module has this method overridden, avoid infinite loops
749 $this->dieIfMain( __METHOD__ );
751 return $this->getMain()->getContinuationManager();
755 * @param ApiContinuationManager|null $manager
757 public function setContinuationManager( ?ApiContinuationManager $manager = null ) {
758 // The Main module has this method overridden, avoid infinite loops
759 $this->dieIfMain( __METHOD__ );
761 $this->getMain()->setContinuationManager( $manager );
765 * Obtain a PermissionManager instance that subclasses may use in their authorization checks.
767 * @since 1.34
768 * @return PermissionManager
770 protected function getPermissionManager(): PermissionManager {
771 return MediaWikiServices::getInstance()->getPermissionManager();
775 * Get a HookContainer, for running extension hooks or for hook metadata.
777 * @since 1.35
778 * @return HookContainer
780 protected function getHookContainer() {
781 if ( !$this->hookContainer ) {
782 $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
784 return $this->hookContainer;
788 * Get an ApiHookRunner for running core API hooks.
790 * @internal This is for use by core only. Hook interfaces may be removed
791 * without notice.
792 * @since 1.35
793 * @return ApiHookRunner
795 protected function getHookRunner() {
796 if ( !$this->hookRunner ) {
797 $this->hookRunner = new ApiHookRunner( $this->getHookContainer() );
799 return $this->hookRunner;
802 // endregion -- end of data access methods
804 /***************************************************************************/
805 // region Parameter handling
806 /** @name Parameter handling */
809 * Indicate if the module supports dynamically-determined parameters that
810 * cannot be included in self::getAllowedParams().
811 * @stable to override
812 * @return string|array|Message|null Return null if the module does not
813 * support additional dynamic parameters, otherwise return a message
814 * describing them.
815 * See Message::newFromSpecifier() for a description of allowed values.
817 public function dynamicParameterDocumentation() {
818 return null;
822 * This method mangles parameter name based on the prefix supplied to the constructor.
823 * Override this method to change parameter name during runtime.
825 * @param string|string[] $paramName Parameter name
826 * @return string|string[] Prefixed parameter name
827 * @since 1.29 accepts an array of strings
829 public function encodeParamName( $paramName ) {
830 if ( is_array( $paramName ) ) {
831 return array_map( function ( $name ) {
832 return $this->mModulePrefix . $name;
833 }, $paramName );
836 return $this->mModulePrefix . $paramName;
840 * Using getAllowedParams(), this function makes an array of the values
841 * provided by the user, with the key being the name of the variable, and
842 * value - validated value from user or default. limits will not be
843 * parsed if $parseLimit is set to false; use this when the max
844 * limit is not definitive yet, e.g. when getting revisions.
845 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
846 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
847 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
848 * Returned parameter values might be ApiUsageException instances.
849 * @return array
851 public function extractRequestParams( $options = [] ) {
852 if ( is_bool( $options ) ) {
853 $options = [ 'parseLimit' => $options ];
855 $options += [
856 'parseLimit' => true,
857 'safeMode' => false,
860 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
861 $parseLimit = (bool)$options['parseLimit'];
862 $cacheKey = (int)$parseLimit;
864 // Cache parameters, for performance and to avoid T26564.
865 if ( !isset( $this->mParamCache[$cacheKey] ) ) {
866 $params = $this->getFinalParams() ?: [];
867 $results = [];
868 $warned = [];
870 // Process all non-templates and save templates for secondary
871 // processing.
872 $toProcess = [];
873 foreach ( $params as $paramName => $paramSettings ) {
874 if ( isset( $paramSettings[self::PARAM_TEMPLATE_VARS] ) ) {
875 $toProcess[] = [ $paramName, $paramSettings[self::PARAM_TEMPLATE_VARS], $paramSettings ];
876 } else {
877 try {
878 $results[$paramName] = $this->getParameterFromSettings(
879 $paramName, $paramSettings, $parseLimit
881 } catch ( ApiUsageException $ex ) {
882 $results[$paramName] = $ex;
887 // Now process all the templates by successively replacing the
888 // placeholders with all client-supplied values.
889 // This bit duplicates JavaScript logic in
890 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
891 // If you update this, see if that needs updating too.
892 while ( $toProcess ) {
893 [ $name, $targets, $settings ] = array_shift( $toProcess );
895 foreach ( $targets as $placeholder => $target ) {
896 if ( !array_key_exists( $target, $results ) ) {
897 // The target wasn't processed yet, try the next one.
898 // If all hit this case, the parameter has no expansions.
899 continue;
901 if ( !is_array( $results[$target] ) || !$results[$target] ) {
902 // The target was processed but has no (valid) values.
903 // That means it has no expansions.
904 break;
907 // Expand this target in the name and all other targets,
908 // then requeue if there are more targets left or put in
909 // $results if all are done.
910 unset( $targets[$placeholder] );
911 $placeholder = '{' . $placeholder . '}';
912 // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
913 foreach ( $results[$target] as $value ) {
914 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
915 // Skip values that make invalid parameter names.
916 $encTargetName = $this->encodeParamName( $target );
917 if ( !isset( $warned[$encTargetName][$value] ) ) {
918 $warned[$encTargetName][$value] = true;
919 $this->addWarning( [
920 'apiwarn-ignoring-invalid-templated-value',
921 wfEscapeWikiText( $encTargetName ),
922 wfEscapeWikiText( $value ),
923 ] );
925 continue;
928 $newName = str_replace( $placeholder, $value, $name );
929 if ( !$targets ) {
930 try {
931 $results[$newName] = $this->getParameterFromSettings(
932 $newName,
933 $settings,
934 $parseLimit
936 } catch ( ApiUsageException $ex ) {
937 $results[$newName] = $ex;
939 } else {
940 $newTargets = [];
941 foreach ( $targets as $k => $v ) {
942 $newTargets[$k] = str_replace( $placeholder, $value, $v );
944 $toProcess[] = [ $newName, $newTargets, $settings ];
947 break;
951 $this->mParamCache[$cacheKey] = $results;
954 $ret = $this->mParamCache[$cacheKey];
955 if ( !$options['safeMode'] ) {
956 foreach ( $ret as $v ) {
957 if ( $v instanceof ApiUsageException ) {
958 throw $v;
963 return $this->mParamCache[$cacheKey];
967 * Get a value for the given parameter.
969 * @param string $paramName Parameter name
970 * @param bool $parseLimit See extractRequestParams()
971 * @return mixed Parameter value
973 protected function getParameter( $paramName, $parseLimit = true ) {
974 $ret = $this->extractRequestParams( [
975 'parseLimit' => $parseLimit,
976 'safeMode' => true,
977 ] )[$paramName];
978 if ( $ret instanceof ApiUsageException ) {
979 throw $ret;
981 return $ret;
985 * Die if 0 or more than one of a certain set of parameters is set and not false.
987 * @param array $params User provided parameter set, as from $this->extractRequestParams()
988 * @param string ...$required Names of parameters of which exactly one must be set
990 public function requireOnlyOneParameter( $params, ...$required ) {
991 $intersection = array_intersect( array_keys( array_filter( $params,
992 [ $this, 'parameterNotEmpty' ] ) ), $required );
994 if ( count( $intersection ) > 1 ) {
995 $this->dieWithError( [
996 'apierror-invalidparammix',
997 Message::listParam( array_map(
998 function ( $p ) {
999 return '<var>' . $this->encodeParamName( $p ) . '</var>';
1001 array_values( $intersection )
1002 ) ),
1003 count( $intersection ),
1004 ] );
1005 } elseif ( count( $intersection ) == 0 ) {
1006 $this->dieWithError( [
1007 'apierror-missingparam-one-of',
1008 Message::listParam( array_map(
1009 function ( $p ) {
1010 return '<var>' . $this->encodeParamName( $p ) . '</var>';
1012 $required
1013 ) ),
1014 count( $required ),
1015 ], 'missingparam' );
1020 * Dies if more than one parameter from a certain set of parameters are set and not false.
1022 * @param array $params User provided parameters set, as from $this->extractRequestParams()
1023 * @param string ...$required Parameter names that cannot have more than one set
1025 public function requireMaxOneParameter( $params, ...$required ) {
1026 $intersection = array_intersect( array_keys( array_filter( $params,
1027 [ $this, 'parameterNotEmpty' ] ) ), $required );
1029 if ( count( $intersection ) > 1 ) {
1030 $this->dieWithError( [
1031 'apierror-invalidparammix',
1032 Message::listParam( array_map(
1033 function ( $p ) {
1034 return '<var>' . $this->encodeParamName( $p ) . '</var>';
1036 array_values( $intersection )
1037 ) ),
1038 count( $intersection ),
1039 ] );
1044 * Die if 0 of a certain set of parameters is set and not false.
1046 * @since 1.23
1047 * @param array $params User provided parameters set, as from $this->extractRequestParams()
1048 * @param string ...$required Names of parameters of which at least one must be set
1050 public function requireAtLeastOneParameter( $params, ...$required ) {
1051 $intersection = array_intersect(
1052 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
1053 $required
1056 if ( count( $intersection ) == 0 ) {
1057 $this->dieWithError( [
1058 'apierror-missingparam-at-least-one-of',
1059 Message::listParam( array_map(
1060 function ( $p ) {
1061 return '<var>' . $this->encodeParamName( $p ) . '</var>';
1063 $required
1064 ) ),
1065 count( $required ),
1066 ], 'missingparam' );
1071 * Die with an "invalid param mix" error if the parameters contain the trigger parameter and
1072 * any of the conflicting parameters.
1074 * @since 1.44
1076 * @param array $params User provided parameters set, as from $this->extractRequestParams()
1077 * @param string $trigger The name of the trigger parameter
1078 * @param string|string[] $conflicts The conflicting parameter or a list
1079 * of conflicting parameters
1081 public function requireNoConflictingParameters( $params, $trigger, $conflicts ) {
1082 $triggerValue = $params[$trigger] ?? null;
1083 if ( $triggerValue === null || $triggerValue === false ) {
1084 return;
1086 $intersection = array_intersect(
1087 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
1088 (array)$conflicts
1090 if ( count( $intersection ) ) {
1091 $this->dieWithError( [
1092 'apierror-invalidparammix-cannotusewith',
1093 Message::listParam( array_map(
1094 function ( $p ) {
1095 return '<var>' . $this->encodeParamName( $p ) . '</var>';
1097 array_values( $intersection )
1098 ) ),
1099 $trigger,
1100 ] );
1105 * Die if any of the specified parameters were found in the query part of
1106 * the URL rather than the HTTP post body contents.
1108 * @since 1.28
1109 * @param string[] $params Parameters to check
1110 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
1112 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
1113 if ( !$this->mustBePosted() ) {
1114 // In order to allow client code to choose the correct method (GET or POST) depending *only*
1115 // on mustBePosted(), make sure that the module requires posting if any of its potential
1116 // parameters require posting.
1118 // TODO: Uncomment this
1119 // throw new LogicException( 'mustBePosted() must be true when using requirePostedParameters()' );
1121 // This seems to already be the case in all modules in practice, but deprecate it first just
1122 // in case.
1123 wfDeprecatedMsg( 'mustBePosted() must be true when using requirePostedParameters()',
1124 '1.42' );
1127 // Skip if $wgDebugAPI is set, or if we're in internal mode
1128 if ( $this->getConfig()->get( MainConfigNames::DebugAPI ) ||
1129 $this->getMain()->isInternalMode() ) {
1130 return;
1133 $queryValues = $this->getRequest()->getQueryValuesOnly();
1134 $badParams = [];
1135 foreach ( $params as $param ) {
1136 if ( $prefix !== 'noprefix' ) {
1137 $param = $this->encodeParamName( $param );
1139 if ( array_key_exists( $param, $queryValues ) ) {
1140 $badParams[] = $param;
1144 if ( $badParams ) {
1145 $this->dieWithError(
1146 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
1152 * Callback function used in requireOnlyOneParameter to check whether required parameters are set.
1154 * @param mixed $x Parameter to check is not null/false
1155 * @return bool
1157 private function parameterNotEmpty( $x ) {
1158 return $x !== null && $x !== false;
1162 * Attempts to load a WikiPage object from a title or pageid parameter, if possible.
1163 * It can die if no param is set or if the title or page ID is not valid.
1165 * @param array $params User provided parameter set, as from $this->extractRequestParams()
1166 * @param string|false $load Whether load the object's state from the database:
1167 * - false: don't load (if the pageid is given, it will still be loaded)
1168 * - 'fromdb': load from a replica DB
1169 * - 'fromdbmaster': load from the primary database
1170 * @return WikiPage
1172 public function getTitleOrPageId( $params, $load = false ) {
1173 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1175 $pageObj = null;
1176 if ( isset( $params['title'] ) ) {
1177 $titleObj = Title::newFromText( $params['title'] );
1178 if ( !$titleObj || $titleObj->isExternal() ) {
1179 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1181 if ( !$titleObj->canExist() ) {
1182 $this->dieWithError( 'apierror-pagecannotexist' );
1184 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
1185 $pageObj = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $titleObj );
1186 if ( $load !== false ) {
1187 $pageObj->loadPageData( $load );
1189 } elseif ( isset( $params['pageid'] ) ) {
1190 if ( $load === false ) {
1191 $load = 'fromdb';
1193 $pageObj = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromID( $params['pageid'], $load );
1194 if ( !$pageObj ) {
1195 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1199 // @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
1200 return $pageObj;
1204 * Get a Title object from a title or pageid param, if it is possible.
1205 * It can die if no param is set or if the title or page ID is not valid.
1207 * @since 1.29
1208 * @param array $params User provided parameter set, as from $this->extractRequestParams()
1209 * @return Title
1211 public function getTitleFromTitleOrPageId( $params ) {
1212 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1214 $titleObj = null;
1215 if ( isset( $params['title'] ) ) {
1216 $titleObj = Title::newFromText( $params['title'] );
1217 if ( !$titleObj || $titleObj->isExternal() ) {
1218 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1220 // @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
1221 return $titleObj;
1224 if ( isset( $params['pageid'] ) ) {
1225 $titleObj = Title::newFromID( $params['pageid'] );
1226 if ( !$titleObj ) {
1227 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1231 // @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
1232 return $titleObj;
1236 * Using the settings, determine the value for the given parameter.
1238 * @param string $name Parameter name
1239 * @param array|mixed $settings Default value or an array of settings
1240 * using PARAM_* constants.
1241 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1242 * @return mixed Parameter value
1244 protected function getParameterFromSettings( $name, $settings, $parseLimit ) {
1245 $validator = $this->getMain()->getParamValidator();
1246 $value = $validator->getValue( $this, $name, $settings, [
1247 'parse-limit' => $parseLimit,
1248 'raw' => ( $settings[ParamValidator::PARAM_TYPE] ?? '' ) === 'raw',
1249 ] );
1251 // @todo Deprecate and remove this, if possible.
1252 if ( $parseLimit && isset( $settings[ParamValidator::PARAM_TYPE] ) &&
1253 $settings[ParamValidator::PARAM_TYPE] === 'limit' &&
1254 $this->getMain()->getVal( $this->encodeParamName( $name ) ) === 'max'
1256 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1259 return $value;
1263 * Handle when a parameter was Unicode-normalized.
1265 * @since 1.28
1266 * @since 1.35 $paramName is prefixed
1267 * @internal For overriding by subclasses and use by ApiParamValidatorCallbacks only.
1268 * @param string $paramName Prefixed parameter name
1269 * @param string $value Input that will be used.
1270 * @param string $rawValue Input before normalization.
1272 public function handleParamNormalization( $paramName, $value, $rawValue ) {
1273 $this->addWarning( [ 'apiwarn-badutf8', $paramName ] );
1277 * Validate the supplied token.
1279 * @since 1.24
1280 * @param string $token Supplied token
1281 * @param array $params All supplied parameters for the module
1282 * @return bool
1284 final public function validateToken( $token, array $params ) {
1285 $tokenType = $this->needsToken();
1286 $salts = ApiQueryTokens::getTokenTypeSalts();
1287 if ( !isset( $salts[$tokenType] ) ) {
1288 throw new LogicException(
1289 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1290 'without registering it'
1294 $tokenObj = ApiQueryTokens::getToken(
1295 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1297 if ( $tokenObj->match( $token ) ) {
1298 return true;
1301 $webUiSalt = $this->getWebUITokenSalt( $params );
1303 return $webUiSalt !== null && $this->getUser()->matchEditToken(
1304 $token, $webUiSalt, $this->getRequest()
1308 // endregion -- end of parameter handling
1310 /***************************************************************************/
1311 // region Utility methods
1312 /** @name Utility methods */
1315 * Gets the user for whom to get the watchlist
1317 * @param array $params
1318 * @return User
1320 public function getWatchlistUser( $params ) {
1321 if ( $params['owner'] !== null && $params['token'] !== null ) {
1322 $services = MediaWikiServices::getInstance();
1323 $user = $services->getUserFactory()->newFromName( $params['owner'], UserRigorOptions::RIGOR_NONE );
1324 if ( !$user || !$user->isRegistered() ) {
1325 $this->dieWithError(
1326 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1329 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
1330 $token = $services->getUserOptionsLookup()->getOption( $user, 'watchlisttoken' );
1331 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1332 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1334 } else {
1335 $user = $this->getUser();
1336 if ( !$user->isRegistered() ) {
1337 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1339 $this->checkUserRightsAny( 'viewmywatchlist' );
1342 // @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
1343 return $user;
1347 * Create a Message from a string or array
1349 * A string is used as a message key. An array has the message key as the
1350 * first value and message parameters as subsequent values.
1352 * @since 1.25
1353 * @deprecated since 1.43, use ApiBase::msg()
1354 * @param string|array|Message $msg
1355 * @phan-param string|non-empty-array|Message $msg
1356 * @param IContextSource $context
1357 * @param array|null $params
1358 * @return Message|null
1360 public static function makeMessage( $msg, IContextSource $context, ?array $params = null ) {
1361 wfDeprecated( __METHOD__, '1.43' );
1362 if ( is_string( $msg ) ) {
1363 $msg = wfMessage( $msg );
1364 } elseif ( is_array( $msg ) ) {
1365 $msg = wfMessage( ...$msg );
1367 if ( !$msg instanceof Message ) {
1368 return null;
1371 $msg->setContext( $context );
1372 if ( $params ) {
1373 $msg->params( $params );
1376 return $msg;
1380 * Add block info to block messages in a Status
1381 * @since 1.33
1382 * @internal since 1.37, should become protected in the future.
1383 * @param StatusValue $status
1384 * @param Authority|null $user
1386 public function addBlockInfoToStatus( StatusValue $status, ?Authority $user = null ) {
1387 if ( $status instanceof PermissionStatus ) {
1388 $block = $status->getBlock();
1389 } else {
1390 $user = $user ?: $this->getAuthority();
1391 $block = $user->getBlock();
1394 if ( !$block ) {
1395 return;
1397 foreach ( $status->getMessages() as $msg ) {
1398 if ( isset( self::BLOCK_CODE_MAP[$msg->getKey()] ) ) {
1399 $status->replaceMessage( $msg->getKey(), ApiMessage::create(
1400 Message::newFromSpecifier( $msg ),
1401 $this->getBlockCode( $block ),
1402 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
1403 ) );
1409 * Call wfTransactionalTimeLimit() if this request was POSTed.
1411 * @since 1.26
1413 protected function useTransactionalTimeLimit() {
1414 if ( $this->getRequest()->wasPosted() ) {
1415 wfTransactionalTimeLimit();
1420 * Reset static caches of database state.
1422 * @internal For testing only
1424 public static function clearCacheForTest(): void {
1425 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1426 throw new LogicException( 'Not allowed outside tests' );
1428 self::$filterIDsCache = [];
1432 * Filter out-of-range values from a list of positive integer IDs
1434 * @since 1.33
1435 * @param string[][] $fields Array of table and field pairs to check
1436 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1437 * expected to be stringified integers.
1438 * @return (string|int)[] Filtered IDs.
1440 protected function filterIDs( $fields, array $ids ) {
1441 $min = INF;
1442 $max = 0;
1443 foreach ( $fields as [ $table, $field ] ) {
1444 if ( isset( self::$filterIDsCache[$table][$field] ) ) {
1445 $row = self::$filterIDsCache[$table][$field];
1446 } else {
1447 $row = $this->getDB()->newSelectQueryBuilder()
1448 ->select( [ 'min_id' => "MIN($field)", 'max_id' => "MAX($field)" ] )
1449 ->from( $table )
1450 ->caller( __METHOD__ )->fetchRow();
1451 self::$filterIDsCache[$table][$field] = $row;
1453 $min = min( $min, $row->min_id );
1454 $max = max( $max, $row->max_id );
1456 return array_filter( $ids, static function ( $id ) use ( $min, $max ) {
1457 return ( ( is_int( $id ) && $id >= 0 ) || ctype_digit( (string)$id ) )
1458 && $id >= $min && $id <= $max;
1459 } );
1462 // endregion -- end of utility methods
1464 /***************************************************************************/
1465 // region Warning and error reporting
1466 /** @name Warning and error reporting */
1469 * Add a warning for this module.
1471 * Users should monitor this section to notice any changes in the API.
1473 * Multiple calls to this function will result in multiple warning messages.
1475 * If $msg is not an ApiMessage, the message code will be derived from the
1476 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1478 * @since 1.29
1479 * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addWarning()
1480 * @param string|null $code See ApiErrorFormatter::addWarning()
1481 * @param array|null $data See ApiErrorFormatter::addWarning()
1483 public function addWarning( $msg, $code = null, $data = null ) {
1484 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1488 * Add a deprecation warning for this module.
1490 * A combination of $this->addWarning() and $this->logFeatureUsage()
1492 * @since 1.29
1493 * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addWarning()
1494 * @param string|null $feature See ApiBase::logFeatureUsage()
1495 * @param array|null $data See ApiErrorFormatter::addWarning()
1497 public function addDeprecation( $msg, $feature, $data = [] ) {
1498 $data = (array)$data;
1499 if ( $feature !== null ) {
1500 $data['feature'] = $feature;
1501 $this->logFeatureUsage( $feature );
1503 $this->addWarning( $msg, 'deprecation', $data );
1505 // No real need to deduplicate here, ApiErrorFormatter does that for
1506 // us (assuming the hook is deterministic).
1507 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1508 $this->getHookRunner()->onApiDeprecationHelp( $msgs );
1509 if ( count( $msgs ) > 1 ) {
1510 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1511 $msg = ( new RawMessage( $key ) )->params( $msgs );
1512 } else {
1513 $msg = reset( $msgs );
1515 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1519 * Add an error for this module without aborting
1521 * If $msg is not an ApiMessage, the message code will be derived from the
1522 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1524 * @note If you want to abort processing, use self::dieWithError() instead.
1525 * @since 1.29
1526 * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addError()
1527 * @param string|null $code See ApiErrorFormatter::addError()
1528 * @param array|null $data See ApiErrorFormatter::addError()
1530 public function addError( $msg, $code = null, $data = null ) {
1531 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1535 * Add warnings and/or errors from a Status
1537 * @note If you want to abort processing, use self::dieStatus() instead.
1538 * @since 1.29
1539 * @param StatusValue $status
1540 * @param string[] $types 'warning' and/or 'error'
1541 * @param string[] $filter Message keys to filter out (since 1.33)
1543 public function addMessagesFromStatus(
1544 StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
1546 $this->getErrorFormatter()->addMessagesFromStatus(
1547 $this->getModulePath(), $status, $types, $filter
1552 * Abort execution with an error
1554 * If $msg is not an ApiMessage, the message code will be derived from the
1555 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1557 * @since 1.29
1558 * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addError()
1559 * @param string|null $code See ApiErrorFormatter::addError()
1560 * @param array|null $data See ApiErrorFormatter::addError()
1561 * @param int $httpCode HTTP error code to use
1562 * @throws ApiUsageException always
1563 * @return never
1565 public function dieWithError( $msg, $code = null, $data = null, $httpCode = 0 ) {
1566 throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1570 * Abort execution with an error derived from a throwable
1572 * @since 1.29
1573 * @param Throwable $exception See ApiErrorFormatter::getMessageFromException()
1574 * @param array $options See ApiErrorFormatter::getMessageFromException()
1575 * @throws ApiUsageException always
1576 * @return never
1578 public function dieWithException( Throwable $exception, array $options = [] ) {
1579 $this->dieWithError(
1580 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1585 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1586 * error handler and die with an error message including block info.
1588 * @since 1.27
1589 * @param Block $block The block used to generate the ApiUsageException
1590 * @throws ApiUsageException always
1591 * @return never
1593 public function dieBlocked( Block $block ) {
1594 $blockErrorFormatter = MediaWikiServices::getInstance()->getFormatterFactory()
1595 ->getBlockErrorFormatter( $this->getContext() );
1597 $msg = $blockErrorFormatter->getMessage(
1598 $block,
1599 $this->getUser(),
1600 null,
1601 $this->getRequest()->getIP()
1604 $this->dieWithError(
1605 $msg,
1606 $this->getBlockCode( $block ),
1607 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
1612 * Throw an ApiUsageException based on the Status object.
1614 * @since 1.22
1615 * @since 1.29 Accepts a StatusValue
1616 * @param StatusValue $status
1617 * @throws ApiUsageException always
1618 * @return never
1620 public function dieStatus( StatusValue $status ) {
1621 if ( $status->isGood() ) {
1622 throw new InvalidArgumentException( 'Successful status passed to ApiBase::dieStatus' );
1625 foreach ( self::MESSAGE_CODE_MAP as $msg => [ $apiMsg, $code ] ) {
1626 if ( $status->hasMessage( $msg ) ) {
1627 $status->replaceMessage( $msg, ApiMessage::create( $apiMsg, $code ) );
1631 if (
1632 $status instanceof PermissionStatus
1633 && $status->isRateLimitExceeded()
1634 && !$status->hasMessage( 'apierror-ratelimited' )
1636 $status->fatal( ApiMessage::create( 'apierror-ratelimited', 'ratelimited' ) );
1639 // ApiUsageException needs a fatal status, but this method has
1640 // historically accepted any non-good status. Convert it if necessary.
1641 $status->setOK( false );
1642 if ( !$status->getMessages( 'error' ) ) {
1643 $newStatus = Status::newGood();
1644 foreach ( $status->getMessages( 'warning' ) as $err ) {
1645 $newStatus->fatal( $err );
1647 if ( !$newStatus->getMessages( 'error' ) ) {
1648 $newStatus->fatal( 'unknownerror-nocode' );
1650 $status = $newStatus;
1653 $this->addBlockInfoToStatus( $status );
1655 throw new ApiUsageException( $this, $status );
1659 * Helper function for readonly errors.
1661 * @throws ApiUsageException always
1662 * @return never
1664 public function dieReadOnly() {
1665 $this->dieWithError(
1666 'apierror-readonly',
1667 'readonly',
1668 [ 'readonlyreason' => MediaWikiServices::getInstance()->getReadOnlyMode()->getReason() ]
1673 * Helper function for permission-denied errors.
1675 * @since 1.29
1676 * @param string|string[] $rights
1677 * @throws ApiUsageException if the user doesn't have any of the rights.
1678 * The error message is based on $rights[0].
1680 public function checkUserRightsAny( $rights ) {
1681 $rights = (array)$rights;
1682 if ( !$this->getAuthority()->isAllowedAny( ...$rights ) ) {
1683 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1688 * Helper function for permission-denied errors.
1690 * @param PageIdentity $pageIdentity
1691 * @param string|string[] $actions
1692 * @param array $options Additional options
1693 * - user: (User) User to use rather than $this->getUser().
1694 * - autoblock: (bool, default false) Whether to spread autoblocks.
1695 * @phan-param array{user?:User,autoblock?:bool} $options
1697 * @throws ApiUsageException if the user doesn't have all the necessary rights.
1699 * @since 1.29
1700 * @since 1.33 Changed the third parameter from $user to $options.
1701 * @since 1.36 deprecated passing LinkTarget as first parameter
1703 public function checkTitleUserPermissions(
1704 PageIdentity $pageIdentity,
1705 $actions,
1706 array $options = []
1708 $authority = $options['user'] ?? $this->getAuthority();
1709 $status = new PermissionStatus();
1710 foreach ( (array)$actions as $action ) {
1711 if ( $this->isWriteMode() ) {
1712 $authority->authorizeWrite( $action, $pageIdentity, $status );
1713 } else {
1714 $authority->authorizeRead( $action, $pageIdentity, $status );
1717 if ( !$status->isGood() ) {
1718 if ( !empty( $options['autoblock'] ) ) {
1719 $this->getUser()->spreadAnyEditBlock();
1721 $this->dieStatus( $status );
1726 * Will only set a warning instead of failing if the global $wgDebugAPI
1727 * is set to true.
1729 * Otherwise, it behaves exactly as self::dieWithError().
1731 * @since 1.29
1732 * @param string|array|Message $msg Message definition, see Message::newFromSpecifier()
1733 * @param string|null $code
1734 * @param array|null $data
1735 * @param int|null $httpCode
1736 * @throws ApiUsageException
1738 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1739 if ( $this->getConfig()->get( MainConfigNames::DebugAPI ) !== true ) {
1740 $this->dieWithError( $msg, $code, $data, $httpCode ?? 0 );
1741 } else {
1742 $this->addWarning( $msg, $code, $data );
1747 * Parse the 'continue' parameter in the usual format and validate the types of each part,
1748 * or die with the 'badcontinue' error if the format, types, or the number of parts is wrong.
1750 * @param string $continue Value of 'continue' parameter obtained from extractRequestParams()
1751 * @param string[] $types Types of the expected parts in order, 'string', 'int' or 'timestamp'
1752 * @return mixed[] Array containing strings, integers or timestamps
1753 * @throws ApiUsageException
1754 * @since 1.40
1756 protected function parseContinueParamOrDie( string $continue, array $types ): array {
1757 $cont = explode( '|', $continue );
1758 $this->dieContinueUsageIf( count( $cont ) != count( $types ) );
1760 foreach ( $cont as $i => &$value ) {
1761 switch ( $types[$i] ) {
1762 case 'string':
1763 // Do nothing
1764 break;
1765 case 'int':
1766 $this->dieContinueUsageIf( $value !== (string)(int)$value );
1767 $value = (int)$value;
1768 break;
1769 case 'timestamp':
1770 try {
1771 $dbTs = $this->getDB()->timestamp( $value );
1772 } catch ( TimestampException $ex ) {
1773 $dbTs = false;
1775 $this->dieContinueUsageIf( $value !== $dbTs );
1776 break;
1777 default:
1778 throw new InvalidArgumentException( "Unknown type '{$types[$i]}'" );
1782 return $cont;
1786 * Die with the 'badcontinue' error.
1788 * This call is common enough to make it into the base method.
1790 * @param bool $condition Will only die if this value is true
1791 * @throws ApiUsageException
1792 * @since 1.21
1793 * @phan-assert-false-condition $condition
1795 protected function dieContinueUsageIf( $condition ) {
1796 if ( $condition ) {
1797 $this->dieWithError( 'apierror-badcontinue' );
1802 * Internal code errors should be reported with this method.
1804 * @param string $method Method or function name
1805 * @param string $message Error message
1806 * @return never
1808 protected static function dieDebug( $method, $message ) {
1809 throw new MWException( "Internal error in $method: $message" );
1813 * Write logging information for API features to a debug log, for usage
1814 * analysis.
1816 * @note Consider using $this->addDeprecation() instead to both warn and log.
1817 * @param string $feature Feature being used.
1819 public function logFeatureUsage( $feature ) {
1820 static $loggedFeatures = [];
1822 // Only log each feature once per request. We can get multiple calls from calls to
1823 // extractRequestParams() with different values for 'parseLimit', for example.
1824 if ( isset( $loggedFeatures[$feature] ) ) {
1825 return;
1827 $loggedFeatures[$feature] = true;
1829 $request = $this->getRequest();
1830 $ctx = [
1831 'feature' => $feature,
1832 // Replace spaces with underscores in 'username' for historical reasons.
1833 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
1834 'clientip' => $request->getIP(),
1835 'referer' => (string)$request->getHeader( 'Referer' ),
1836 'agent' => $this->getMain()->getUserAgent(),
1839 // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
1840 $s = '"' . addslashes( $ctx['feature'] ) . '"' .
1841 ' "' . wfUrlencode( $ctx['username'] ) . '"' .
1842 ' "' . $ctx['clientip'] . '"' .
1843 ' "' . addslashes( $ctx['referer'] ) . '"' .
1844 ' "' . addslashes( $ctx['agent'] ) . '"';
1846 wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
1848 $this->getHookRunner()->onApiLogFeatureUsage(
1849 $feature,
1851 'userName' => $this->getUser()->getName(),
1852 'userAgent' => $this->getMain()->getUserAgent(),
1853 'ipAddress' => $request->getIP()
1858 // endregion -- end of warning and error reporting
1860 /***************************************************************************/
1861 // region Help message generation
1862 /** @name Help message generation */
1865 * Return the summary message.
1867 * This is a one-line description of the module, suitable for display in a
1868 * list of modules.
1870 * @since 1.30
1871 * @stable to override
1872 * @return string|array|Message Message definition, see Message::newFromSpecifier()
1874 protected function getSummaryMessage() {
1875 return "apihelp-{$this->getModulePath()}-summary";
1879 * Return the extended help text message.
1881 * This is additional text to display at the top of the help section, below
1882 * the summary.
1884 * @since 1.30
1885 * @stable to override
1886 * @return string|array|Message Message definition, see Message::newFromSpecifier().
1887 * When returning an array, the definition may also specify fallback keys.
1889 protected function getExtendedDescription() {
1890 return [ [
1891 "apihelp-{$this->getModulePath()}-extended-description",
1892 'api-help-no-extended-description',
1893 ] ];
1897 * Get the final module summary
1899 * @since 1.30
1900 * @stable to override
1901 * @return Message
1903 public function getFinalSummary() {
1904 return $this->msg(
1905 Message::newFromSpecifier( $this->getSummaryMessage() ),
1906 $this->getModulePrefix(),
1907 $this->getModuleName(),
1908 $this->getModulePath(),
1913 * Get the final module description, after hooks have had a chance to tweak it as
1914 * needed.
1916 * @since 1.25, returns Message[] rather than string[]
1917 * @return Message[]
1919 public function getFinalDescription() {
1920 $summary = $this->msg(
1921 Message::newFromSpecifier( $this->getSummaryMessage() ),
1922 $this->getModulePrefix(),
1923 $this->getModuleName(),
1924 $this->getModulePath(),
1926 $extendedDesc = $this->getExtendedDescription();
1927 if ( is_array( $extendedDesc ) && is_array( $extendedDesc[0] ) ) {
1928 // The definition in getExtendedDescription() may also specify fallback keys. This is weird,
1929 // and it was never needed for other API doc messages, so it's only supported here.
1930 $extendedDesc = Message::newFallbackSequence( $extendedDesc[0] )
1931 ->params( array_slice( $extendedDesc, 1 ) );
1933 $extendedDesc = $this->msg(
1934 Message::newFromSpecifier( $extendedDesc ),
1935 $this->getModulePrefix(),
1936 $this->getModuleName(),
1937 $this->getModulePath(),
1940 $msgs = [ $summary, $extendedDesc ];
1942 $this->getHookRunner()->onAPIGetDescriptionMessages( $this, $msgs );
1944 return $msgs;
1948 * Get the final list of parameters, after hooks have had a chance to
1949 * tweak it as needed.
1951 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1952 * @return array
1953 * @since 1.21 $flags param added
1955 public function getFinalParams( $flags = 0 ) {
1956 // @phan-suppress-next-line PhanParamTooMany
1957 $params = $this->getAllowedParams( $flags );
1958 if ( !$params ) {
1959 $params = [];
1962 if ( $this->needsToken() ) {
1963 $params['token'] = [
1964 ParamValidator::PARAM_TYPE => 'string',
1965 ParamValidator::PARAM_REQUIRED => true,
1966 ParamValidator::PARAM_SENSITIVE => true,
1967 self::PARAM_HELP_MSG => [
1968 'api-help-param-token',
1969 $this->needsToken(),
1971 ] + ( $params['token'] ?? [] );
1974 $this->getHookRunner()->onAPIGetAllowedParams( $this, $params, $flags );
1976 return $params;
1980 * Get final parameter descriptions, after hooks have had a chance to tweak it as
1981 * needed.
1983 * @since 1.25, returns array of Message[] rather than array of string[]
1984 * @return array Keys are parameter names, values are arrays of Message objects
1986 public function getFinalParamDescription() {
1987 $prefix = $this->getModulePrefix();
1988 $name = $this->getModuleName();
1989 $path = $this->getModulePath();
1991 $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
1992 $msgs = [];
1993 foreach ( $params as $param => $settings ) {
1994 if ( !is_array( $settings ) ) {
1995 $settings = [];
1998 $msg = isset( $settings[self::PARAM_HELP_MSG] )
1999 ? Message::newFromSpecifier( $settings[self::PARAM_HELP_MSG] )
2000 : Message::newFallbackSequence( [ "apihelp-$path-param-$param", 'api-help-param-no-description' ] );
2001 $msg = $this->msg( $msg, $prefix, $param, $name, $path );
2002 $msgs[$param] = [ $msg ];
2004 if ( isset( $settings[ParamValidator::PARAM_TYPE] ) &&
2005 $settings[ParamValidator::PARAM_TYPE] === 'submodule'
2007 if ( isset( $settings[SubmoduleDef::PARAM_SUBMODULE_MAP] ) ) {
2008 $map = $settings[SubmoduleDef::PARAM_SUBMODULE_MAP];
2009 } else {
2010 $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
2011 $map = [];
2012 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2013 $map[$submoduleName] = $prefix . $submoduleName;
2017 $submodules = [];
2018 $submoduleFlags = []; // for sorting: higher flags are sorted later
2019 $submoduleNames = []; // for sorting: lexicographical, ascending
2020 foreach ( $map as $v => $m ) {
2021 $isDeprecated = false;
2022 $isInternal = false;
2023 $summary = null;
2024 try {
2025 $submod = $this->getModuleFromPath( $m );
2026 if ( $submod ) {
2027 $summary = $submod->getFinalSummary();
2028 $isDeprecated = $submod->isDeprecated();
2029 $isInternal = $submod->isInternal();
2031 } catch ( ApiUsageException $ex ) {
2032 // Ignore
2034 if ( $summary ) {
2035 $key = $summary->getKey();
2036 $params = $summary->getParams();
2037 } else {
2038 $key = 'api-help-undocumented-module';
2039 $params = [ $m ];
2041 $m = new ApiHelpParamValueMessage(
2042 "[[Special:ApiHelp/$m|$v]]",
2043 $key,
2044 $params,
2045 $isDeprecated,
2046 $isInternal
2048 $submodules[] = $m->setContext( $this->getContext() );
2049 $submoduleFlags[] = ( $isDeprecated ? 1 : 0 ) | ( $isInternal ? 2 : 0 );
2050 $submoduleNames[] = $v;
2052 // sort $submodules by $submoduleFlags and $submoduleNames
2053 array_multisort( $submoduleFlags, $submoduleNames, $submodules );
2054 $msgs[$param] = array_merge( $msgs[$param], $submodules );
2055 } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2056 if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2057 self::dieDebug( __METHOD__,
2058 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2060 $isArrayOfStrings = is_array( $settings[ParamValidator::PARAM_TYPE] )
2061 || (
2062 $settings[ParamValidator::PARAM_TYPE] === 'string'
2063 && ( $settings[ParamValidator::PARAM_ISMULTI] ?? false )
2065 if ( !$isArrayOfStrings ) {
2066 self::dieDebug( __METHOD__,
2067 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2068 'ParamValidator::PARAM_TYPE is an array or it is \'string\' and ' .
2069 'ParamValidator::PARAM_ISMULTI is true' );
2072 $values = is_array( $settings[ParamValidator::PARAM_TYPE] ) ?
2073 $settings[ParamValidator::PARAM_TYPE] :
2074 array_keys( $settings[self::PARAM_HELP_MSG_PER_VALUE] );
2075 $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
2076 $deprecatedValues = $settings[EnumDef::PARAM_DEPRECATED_VALUES] ?? [];
2078 foreach ( $values as $value ) {
2079 $msg = Message::newFromSpecifier( $valueMsgs[$value] ?? "apihelp-$path-paramvalue-$param-$value" );
2080 $m = $this->msg( $msg, [ $prefix, $param, $name, $path, $value ] );
2081 $m = new ApiHelpParamValueMessage(
2082 $value,
2083 // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
2084 [ $m->getKey(), 'api-help-param-no-description' ],
2085 $m->getParams(),
2086 isset( $deprecatedValues[$value] )
2088 $msgs[$param][] = $m->setContext( $this->getContext() );
2092 if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2093 if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2094 self::dieDebug( __METHOD__,
2095 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2097 foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2098 $m = $this->msg( Message::newFromSpecifier( $m ), [ $prefix, $param, $name, $path ] );
2099 $msgs[$param][] = $m;
2104 $this->getHookRunner()->onAPIGetParamDescriptionMessages( $this, $msgs );
2106 return $msgs;
2110 * Generates the list of flags for the help screen and for action=paraminfo.
2112 * Corresponding messages: api-help-flag-deprecated,
2113 * api-help-flag-internal, api-help-flag-readrights,
2114 * api-help-flag-writerights, api-help-flag-mustbeposted
2116 * @return string[]
2118 protected function getHelpFlags() {
2119 $flags = [];
2121 if ( $this->isDeprecated() ) {
2122 $flags[] = 'deprecated';
2124 if ( $this->isInternal() ) {
2125 $flags[] = 'internal';
2127 if ( $this->isReadMode() ) {
2128 $flags[] = 'readrights';
2130 if ( $this->isWriteMode() ) {
2131 $flags[] = 'writerights';
2133 if ( $this->mustBePosted() ) {
2134 $flags[] = 'mustbeposted';
2137 return $flags;
2141 * Returns information about the source of this module, if known
2143 * Returned array is an array with the following keys:
2144 * - path: Install path
2145 * - name: Extension name, or "MediaWiki" for core
2146 * - namemsg: (optional) i18n message key for a display name
2147 * - license-name: (optional) Name of license
2149 * @return array|null
2151 protected function getModuleSourceInfo() {
2152 if ( $this->mModuleSource !== false ) {
2153 return $this->mModuleSource;
2156 // First, try to find where the module comes from...
2157 $rClass = new ReflectionClass( $this );
2158 $path = $rClass->getFileName();
2159 if ( !$path ) {
2160 // No path known?
2161 $this->mModuleSource = null;
2162 return null;
2164 $path = realpath( $path ) ?: $path;
2166 // Build a map of extension directories to extension info
2167 if ( self::$extensionInfo === null ) {
2168 $extDir = $this->getConfig()->get( MainConfigNames::ExtensionDirectory );
2169 $baseDir = MW_INSTALL_PATH;
2170 self::$extensionInfo = [
2171 realpath( __DIR__ ) ?: __DIR__ => [
2172 'path' => $baseDir,
2173 'name' => 'MediaWiki',
2174 'license-name' => 'GPL-2.0-or-later',
2176 realpath( "$baseDir/extensions" ) ?: "$baseDir/extensions" => null,
2177 realpath( $extDir ) ?: $extDir => null,
2179 $keep = [
2180 'path' => null,
2181 'name' => null,
2182 'namemsg' => null,
2183 'license-name' => null,
2185 $credits = SpecialVersion::getCredits( ExtensionRegistry::getInstance(), $this->getConfig() );
2186 foreach ( $credits as $group ) {
2187 foreach ( $group as $ext ) {
2188 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2189 // This shouldn't happen, but does anyway.
2190 continue;
2193 $extpath = $ext['path'];
2194 if ( !is_dir( $extpath ) ) {
2195 $extpath = dirname( $extpath );
2197 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2198 array_intersect_key( $ext, $keep );
2203 // Now traverse parent directories until we find a match or run out of parents.
2204 do {
2205 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2206 // Found it!
2207 $this->mModuleSource = self::$extensionInfo[$path];
2208 return $this->mModuleSource;
2211 $oldpath = $path;
2212 $path = dirname( $path );
2213 } while ( $path !== $oldpath );
2215 // No idea what extension this might be.
2216 $this->mModuleSource = null;
2217 return null;
2221 * Called from ApiHelp before the pieces are joined together and returned.
2223 * This exists mainly for ApiMain to add the Permissions and Credits
2224 * sections. Other modules probably don't need it.
2226 * @stable to override
2227 * @param string[] &$help Array of help data
2228 * @param array $options Options passed to ApiHelp::getHelp
2229 * @param array &$tocData If a TOC is being generated, this array has keys
2230 * as anchors in the page and values as for SectionMetadata::fromLegacy().
2232 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2235 // endregion -- end of help message generation
2240 * This file uses VisualStudio style region/endregion fold markers which are
2241 * recognised by PHPStorm. If modelines are enabled, the following editor
2242 * configuration will also enable folding in vim, if it is in the last 5 lines
2243 * of the file. We also use "@name" which creates sections in Doxygen.
2245 * vim: foldmarker=//\ region,//\ endregion foldmethod=marker
2248 /** @deprecated class alias since 1.43 */
2249 class_alias( ApiBase::class, 'ApiBase' );