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
23 use MediaWiki\Api\ApiHookRunner
;
24 use MediaWiki\Api\Validator\SubmoduleDef
;
25 use MediaWiki\Block\Block
;
26 use MediaWiki\HookContainer\HookContainer
;
27 use MediaWiki\Language\RawMessage
;
28 use MediaWiki\MainConfigNames
;
29 use MediaWiki\MediaWikiServices
;
30 use MediaWiki\Page\PageIdentity
;
31 use MediaWiki\ParamValidator\TypeDef\NamespaceDef
;
32 use MediaWiki\Permissions\Authority
;
33 use MediaWiki\Permissions\PermissionManager
;
34 use MediaWiki\Permissions\PermissionStatus
;
35 use MediaWiki\Specials\SpecialVersion
;
36 use MediaWiki\Status\Status
;
37 use MediaWiki\Title\Title
;
38 use MediaWiki\User\User
;
39 use MediaWiki\User\UserRigorOptions
;
40 use Wikimedia\ParamValidator\ParamValidator
;
41 use Wikimedia\ParamValidator\TypeDef\EnumDef
;
42 use Wikimedia\ParamValidator\TypeDef\IntegerDef
;
43 use Wikimedia\ParamValidator\TypeDef\StringDef
;
44 use Wikimedia\Rdbms\IReadableDatabase
;
45 use Wikimedia\Timestamp\TimestampException
;
48 * This abstract class implements many basic API functions, and is the base of
51 * The class functions are divided into several areas of functionality:
53 * Module parameters: Derived classes can define getAllowedParams() to specify
54 * which parameters to expect, how to parse and validate them.
56 * Self-documentation: code to allow the API to document its own state
62 abstract class ApiBase
extends ContextSource
{
64 use ApiBlockInfoTrait
;
66 /** @var HookContainer */
67 private $hookContainer;
69 /** @var ApiHookRunner */
73 * @name Old constants for ::getAllowedParams() arrays
78 * @deprecated since 1.35, use ParamValidator::PARAM_DEFAULT instead
80 public const PARAM_DFLT
= ParamValidator
::PARAM_DEFAULT
;
82 * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI instead
84 public const PARAM_ISMULTI
= ParamValidator
::PARAM_ISMULTI
;
86 * @deprecated since 1.35, use ParamValidator::PARAM_TYPE instead
88 public const PARAM_TYPE
= ParamValidator
::PARAM_TYPE
;
90 * @deprecated since 1.35, use IntegerDef::PARAM_MAX instead
92 public const PARAM_MAX
= IntegerDef
::PARAM_MAX
;
94 * @deprecated since 1.35, use IntegerDef::PARAM_MAX2 instead
96 public const PARAM_MAX2
= IntegerDef
::PARAM_MAX2
;
98 * @deprecated since 1.35, use IntegerDef::PARAM_MIN instead
100 public const PARAM_MIN
= IntegerDef
::PARAM_MIN
;
102 * @deprecated since 1.35, use ParamValidator::PARAM_ALLOW_DUPLICATES instead
104 public const PARAM_ALLOW_DUPLICATES
= ParamValidator
::PARAM_ALLOW_DUPLICATES
;
106 * @deprecated since 1.35, use ParamValidator::PARAM_DEPRECATED instead
108 public const PARAM_DEPRECATED
= ParamValidator
::PARAM_DEPRECATED
;
110 * @deprecated since 1.35, use ParamValidator::PARAM_REQUIRED instead
112 public const PARAM_REQUIRED
= ParamValidator
::PARAM_REQUIRED
;
114 * @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_MAP instead
116 public const PARAM_SUBMODULE_MAP
= SubmoduleDef
::PARAM_SUBMODULE_MAP
;
118 * @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX instead
120 public const PARAM_SUBMODULE_PARAM_PREFIX
= SubmoduleDef
::PARAM_SUBMODULE_PARAM_PREFIX
;
122 * @deprecated since 1.35, use ParamValidator::PARAM_ALL instead
124 public const PARAM_ALL
= ParamValidator
::PARAM_ALL
;
126 * @deprecated since 1.35, use NamespaceDef::PARAM_EXTRA_NAMESPACES instead
128 public const PARAM_EXTRA_NAMESPACES
= NamespaceDef
::PARAM_EXTRA_NAMESPACES
;
130 * @deprecated since 1.35, use ParamValidator::PARAM_SENSITIVE instead
132 public const PARAM_SENSITIVE
= ParamValidator
::PARAM_SENSITIVE
;
134 * @deprecated since 1.35, use EnumDef::PARAM_DEPRECATED_VALUES instead
136 public const PARAM_DEPRECATED_VALUES
= EnumDef
::PARAM_DEPRECATED_VALUES
;
138 * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT1 instead
140 public const PARAM_ISMULTI_LIMIT1
= ParamValidator
::PARAM_ISMULTI_LIMIT1
;
142 * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT2 instead
144 public const PARAM_ISMULTI_LIMIT2
= ParamValidator
::PARAM_ISMULTI_LIMIT2
;
146 * @deprecated since 1.35, use StringDef::PARAM_MAX_BYTES instead
148 public const PARAM_MAX_BYTES
= StringDef
::PARAM_MAX_BYTES
;
150 * @deprecated since 1.35, use StringDef::PARAM_MAX_CHARS instead
152 public const PARAM_MAX_CHARS
= StringDef
::PARAM_MAX_CHARS
;
156 * (boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
157 * @deprecated since 1.35
159 public const PARAM_RANGE_ENFORCE
= 'api-param-range-enforce';
161 // region API-specific constants for ::getAllowedParams() arrays
162 /** @name API-specific constants for ::getAllowedParams() arrays */
165 * (string|array|Message) Specify an alternative i18n documentation message
166 * for this parameter. Default is apihelp-{$path}-param-{$param}.
169 public const PARAM_HELP_MSG
= 'api-param-help-msg';
172 * ((string|array|Message)[]) Specify additional i18n messages to append to
173 * the normal message for this parameter.
176 public const PARAM_HELP_MSG_APPEND
= 'api-param-help-msg-append';
179 * (array) Specify additional information tags for the parameter.
180 * The value is an array of arrays, with the first member being the 'tag' for the info
181 * and the remaining members being the values. In the help, this is
182 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
183 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
186 public const PARAM_HELP_MSG_INFO
= 'api-param-help-msg-info';
189 * Deprecated and unused.
191 * @deprecated since 1.35
193 public const PARAM_VALUE_LINKS
= 'api-param-value-links';
196 * ((string|array|Message)[]) When PARAM_TYPE is an array, or 'string'
197 * with PARAM_ISMULTI, this is an array mapping parameter values to help
198 * message specifiers (to be passed to ApiBase::makeMessage()) about
201 * When PARAM_TYPE is an array, any value not having a mapping will use
202 * the apihelp-{$path}-paramvalue-{$param}-{$value} message. (This means
203 * you can use an empty array to use the default message key for all
207 * @note Use with PARAM_TYPE = 'string' is allowed since 1.40.
209 public const PARAM_HELP_MSG_PER_VALUE
= 'api-param-help-msg-per-value';
212 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
213 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
214 * which the replacement values are taken.
216 * For example, a parameter "foo-{ns}-{title}" could be defined with
217 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
218 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
220 * All placeholders must be present in the parameter's name. Each target parameter must have
221 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
222 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
223 * A parameter cannot target itself.
227 public const PARAM_TEMPLATE_VARS
= 'param-template-vars';
229 // endregion -- end of API-specific constants for ::getAllowedParams() arrays
231 public const ALL_DEFAULT_STRING
= '*';
233 /** Fast query, standard limit. */
234 public const LIMIT_BIG1
= 500;
235 /** Fast query, apihighlimits limit. */
236 public const LIMIT_BIG2
= 5000;
237 /** Slow query, standard limit. */
238 public const LIMIT_SML1
= 50;
239 /** Slow query, apihighlimits limit. */
240 public const LIMIT_SML2
= 500;
243 * getAllowedParams() flag: When this is set, the result could take longer to generate,
244 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
247 public const GET_VALUES_FOR_HELP
= 1;
249 /** @var array Maps extension paths to info arrays */
250 private static $extensionInfo = null;
252 /** @var stdClass[][] Cache for self::filterIDs() */
253 private static $filterIDsCache = [];
255 /** @var array Map of web UI block messages which magically gain machine-readable block info */
256 private const BLOCK_CODE_MAP
= [
257 'blockedtext' => true,
258 'blockedtext-partial' => true,
259 'autoblockedtext' => true,
260 'systemblockedtext' => true,
261 'blockedtext-composite' => true,
264 /** @var array Map of web UI block messages to corresponding API messages and codes */
265 private const MESSAGE_CODE_MAP
= [
266 'actionthrottled' => [ 'apierror-ratelimited', 'ratelimited' ],
267 'actionthrottledtext' => [ 'apierror-ratelimited', 'ratelimited' ],
271 private $mMainModule;
273 private $mModuleName, $mModulePrefix;
274 private $mReplicaDB = null;
278 private $mParamCache = [];
279 /** @var array|null|false */
280 private $mModuleSource = false;
284 * @param ApiMain $mainModule
285 * @param string $moduleName Name of this module
286 * @param string $modulePrefix Prefix to use for parameter names
288 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
289 $this->mMainModule
= $mainModule;
290 $this->mModuleName
= $moduleName;
291 $this->mModulePrefix
= $modulePrefix;
293 if ( !$this->isMain() ) {
294 $this->setContext( $mainModule->getContext() );
298 /***************************************************************************/
299 // region Methods to implement
300 /** @name Methods to implement */
303 * Evaluates the parameters, performs the requested query, and sets up
304 * the result. Concrete implementations of ApiBase must override this
305 * method to provide whatever functionality their module offers.
306 * Implementations must not produce any output on their own and are not
307 * expected to handle any errors.
309 * The execute() method will be invoked directly by ApiMain immediately
310 * before the result of the module is output. Aside from the
311 * constructor, implementations should assume that no other methods
312 * will be called externally on the module before the result is
315 * The result data should be stored in the ApiResult object available
316 * through getResult().
318 abstract public function execute();
321 * Get the module manager, or null if this module has no submodules.
324 * @stable to override
325 * @return ApiModuleManager|null
327 public function getModuleManager() {
332 * If the module may only be used with a certain format module,
333 * it should override this method to return an instance of that formatter.
334 * A value of null means the default format will be used.
336 * @note Do not use this just because you don't want to support non-json
337 * formats. This should be used only when there is a fundamental
338 * requirement for a specific format.
340 * @stable to override
341 * @return ApiFormatBase|null An instance of a class derived from ApiFormatBase, or null
343 public function getCustomPrinter() {
348 * Returns usage examples for this module.
350 * Return value has query strings as keys, with values being either strings
351 * (message key), arrays (message key + parameter), or Message objects.
353 * Do not call this base class implementation when overriding this method.
356 * @stable to override
359 protected function getExamplesMessages() {
364 * Return links to more detailed help pages about the module.
366 * @since 1.25, returning boolean false is deprecated
367 * @stable to override
368 * @return string|array
370 public function getHelpUrls() {
375 * Returns an array of allowed parameters (parameter name) => (default
376 * value) or (parameter name) => (array with PARAM_* constants as keys)
377 * Don't call this function directly: use getFinalParams() to allow
378 * hooks to modify parameters as needed.
380 * Some derived classes may choose to handle an integer $flags parameter
381 * in the overriding methods. Callers of this method can pass zero or
382 * more OR-ed flags like GET_VALUES_FOR_HELP.
384 * @stable to override
387 protected function getAllowedParams( /* $flags = 0 */ ) {
388 // $flags is not declared because it causes "Strict standards"
389 // warning. Most derived classes do not implement it.
394 * Indicates if this module needs maxlag to be checked.
396 * @stable to override
399 public function shouldCheckMaxlag() {
404 * Indicates whether this module requires read rights.
406 * @stable to override
409 public function isReadMode() {
414 * Indicates whether this module requires write mode.
416 * This should return true for modules that may require synchronous database writes.
417 * Modules that do not need such writes should also not rely on primary database access,
418 * since only read queries are needed and each primary DB is a single point of failure.
419 * Additionally, requests that only need replica DBs can be efficiently routed to any
420 * datacenter via the Promise-Non-Write-API-Action header.
422 * @stable to override
425 public function isWriteMode() {
430 * Indicates whether this module must be called with a POST request.
432 * @stable to override
435 public function mustBePosted() {
436 return $this->needsToken() !== false;
440 * Indicates whether this module is deprecated.
443 * @stable to override
446 public function isDeprecated() {
451 * Indicates whether this module is considered to be "internal".
453 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
456 * @stable to override
459 public function isInternal() {
464 * Returns the token type this module requires in order to execute.
466 * Modules are strongly encouraged to use the core 'csrf' type unless they
467 * have specialized security needs. If the token type is not one of the
468 * core types, you must use the ApiQueryTokensRegisterTypes hook to
471 * Returning a non-falsey value here will force the addition of an
472 * appropriate 'token' parameter in self::getFinalParams(). Also,
473 * self::mustBePosted() must return true when tokens are used.
475 * In previous versions of MediaWiki, true was a valid return value.
476 * Returning true will generate errors indicating that the API module needs
479 * @stable to override
480 * @return string|false
482 public function needsToken() {
487 * Fetch the salt used in the Web UI corresponding to this module.
489 * Only override this if the Web UI uses a token with a non-constant salt.
492 * @param array $params All supplied parameters for the module
493 * @stable to override
494 * @return string|array|null
496 protected function getWebUITokenSalt( array $params ) {
501 * Returns data for HTTP conditional request mechanisms.
504 * @stable to override
505 * @param string $condition Condition being queried:
506 * - last-modified: Return a timestamp representing the maximum of the
507 * last-modified dates for all resources involved in the request. See
508 * RFC 7232 § 2.2 for semantics.
509 * - etag: Return an entity-tag representing the state of all resources involved
510 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
511 * @return string|bool|null As described above, or null if no value is available.
513 public function getConditionalRequestData( $condition ) {
517 // endregion -- end of methods to implement
519 /***************************************************************************/
520 // region Data access methods
521 /** @name Data access methods */
524 * Get the name of the module being executed by this instance.
528 public function getModuleName() {
529 return $this->mModuleName
;
533 * Get parameter prefix (usually two letters or an empty string).
537 public function getModulePrefix() {
538 return $this->mModulePrefix
;
542 * Get the main module.
546 public function getMain() {
547 return $this->mMainModule
;
551 * Returns true if this module is the main module ($this === $this->mMainModule),
556 public function isMain() {
557 return $this === $this->mMainModule
;
561 * Get the parent of this module.
563 * @stable to override
565 * @return ApiBase|null
567 public function getParent() {
568 return $this->isMain() ?
null : $this->getMain();
572 * Used to avoid infinite loops - the ApiMain class should override some
573 * methods, if it doesn't and uses the default ApiBase implementation, which
574 * just calls the same method for the ApiMain instance, it'll lead to an infinite loop
576 * @param string $methodName used for debug messages
578 private function dieIfMain( string $methodName ) {
579 if ( $this->isMain() ) {
580 self
::dieDebug( $methodName, 'base method was called on main module.' );
585 * Returns true if the current request breaks the same-origin policy.
587 * For example, json with callbacks.
589 * https://en.wikipedia.org/wiki/Same-origin_policy
594 public function lacksSameOriginSecurity() {
595 // The Main module has this method overridden, avoid infinite loops
596 $this->dieIfMain( __METHOD__
);
598 return $this->getMain()->lacksSameOriginSecurity();
602 * Get the path to this module.
607 public function getModulePath() {
608 if ( $this->isMain() ) {
612 if ( $this->getParent()->isMain() ) {
613 return $this->getModuleName();
616 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
620 * Get a module from its module path.
623 * @param string $path
624 * @return ApiBase|null
625 * @throws ApiUsageException
627 public function getModuleFromPath( $path ) {
628 $module = $this->getMain();
629 if ( $path === 'main' ) {
633 $parts = explode( '+', $path );
634 if ( count( $parts ) === 1 ) {
635 // In case the '+' was typed into URL, it resolves as a space
636 $parts = explode( ' ', $path );
639 foreach ( $parts as $i => $v ) {
641 $manager = $parent->getModuleManager();
642 if ( $manager === null ) {
643 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
644 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
646 $module = $manager->getModule( $v );
648 if ( $module === null ) {
650 ?
implode( '+', array_slice( $parts, 0, $i ) )
651 : $parent->getModuleName();
653 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $v ) ],
663 * Get the result object.
667 public function getResult() {
668 // The Main module has this method overridden, avoid infinite loops
669 $this->dieIfMain( __METHOD__
);
671 return $this->getMain()->getResult();
675 * @stable to override
676 * @return ApiErrorFormatter
678 public function getErrorFormatter() {
679 // The Main module has this method overridden, avoid infinite loops
680 $this->dieIfMain( __METHOD__
);
682 return $this->getMain()->getErrorFormatter();
686 * Gets a default replica DB connection object.
688 * @stable to override
689 * @return IReadableDatabase
691 protected function getDB() {
692 if ( !isset( $this->mReplicaDB
) ) {
693 $this->mReplicaDB
= MediaWikiServices
::getInstance()
694 ->getDBLoadBalancerFactory()
695 ->getReplicaDatabase( false, 'api' );
698 return $this->mReplicaDB
;
702 * @return ApiContinuationManager|null
704 public function getContinuationManager() {
705 // The Main module has this method overridden, avoid infinite loops
706 $this->dieIfMain( __METHOD__
);
708 return $this->getMain()->getContinuationManager();
712 * @param ApiContinuationManager|null $manager
714 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
715 // The Main module has this method overridden, avoid infinite loops
716 $this->dieIfMain( __METHOD__
);
718 $this->getMain()->setContinuationManager( $manager );
722 * Obtain a PermissionManager instance that subclasses may use in their authorization checks.
725 * @return PermissionManager
727 protected function getPermissionManager(): PermissionManager
{
728 return MediaWikiServices
::getInstance()->getPermissionManager();
732 * Get a HookContainer, for running extension hooks or for hook metadata.
735 * @return HookContainer
737 protected function getHookContainer() {
738 if ( !$this->hookContainer
) {
739 $this->hookContainer
= MediaWikiServices
::getInstance()->getHookContainer();
741 return $this->hookContainer
;
745 * Get an ApiHookRunner for running core API hooks.
747 * @internal This is for use by core only. Hook interfaces may be removed
750 * @return ApiHookRunner
752 protected function getHookRunner() {
753 if ( !$this->hookRunner
) {
754 $this->hookRunner
= new ApiHookRunner( $this->getHookContainer() );
756 return $this->hookRunner
;
759 // endregion -- end of data access methods
761 /***************************************************************************/
762 // region Parameter handling
763 /** @name Parameter handling */
766 * Indicate if the module supports dynamically-determined parameters that
767 * cannot be included in self::getAllowedParams().
768 * @stable to override
769 * @return string|array|Message|null Return null if the module does not
770 * support additional dynamic parameters, otherwise return a message
773 public function dynamicParameterDocumentation() {
778 * This method mangles parameter name based on the prefix supplied to the constructor.
779 * Override this method to change parameter name during runtime.
781 * @param string|string[] $paramName Parameter name
782 * @return string|string[] Prefixed parameter name
783 * @since 1.29 accepts an array of strings
785 public function encodeParamName( $paramName ) {
786 if ( is_array( $paramName ) ) {
787 return array_map( function ( $name ) {
788 return $this->mModulePrefix
. $name;
792 return $this->mModulePrefix
. $paramName;
796 * Using getAllowedParams(), this function makes an array of the values
797 * provided by the user, with the key being the name of the variable, and
798 * value - validated value from user or default. limits will not be
799 * parsed if $parseLimit is set to false; use this when the max
800 * limit is not definitive yet, e.g. when getting revisions.
801 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
802 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
803 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
804 * Returned parameter values might be ApiUsageException instances.
807 public function extractRequestParams( $options = [] ) {
808 if ( is_bool( $options ) ) {
809 $options = [ 'parseLimit' => $options ];
812 'parseLimit' => true,
816 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
817 $parseLimit = (bool)$options['parseLimit'];
818 $cacheKey = (int)$parseLimit;
820 // Cache parameters, for performance and to avoid T26564.
821 if ( !isset( $this->mParamCache
[$cacheKey] ) ) {
822 $params = $this->getFinalParams() ?
: [];
826 // Process all non-templates and save templates for secondary
829 foreach ( $params as $paramName => $paramSettings ) {
830 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
831 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
834 $results[$paramName] = $this->getParameterFromSettings(
835 $paramName, $paramSettings, $parseLimit
837 } catch ( ApiUsageException
$ex ) {
838 $results[$paramName] = $ex;
843 // Now process all the templates by successively replacing the
844 // placeholders with all client-supplied values.
845 // This bit duplicates JavaScript logic in
846 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
847 // If you update this, see if that needs updating too.
848 while ( $toProcess ) {
849 [ $name, $targets, $settings ] = array_shift( $toProcess );
851 foreach ( $targets as $placeholder => $target ) {
852 if ( !array_key_exists( $target, $results ) ) {
853 // The target wasn't processed yet, try the next one.
854 // If all hit this case, the parameter has no expansions.
857 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
858 // The target was processed but has no (valid) values.
859 // That means it has no expansions.
863 // Expand this target in the name and all other targets,
864 // then requeue if there are more targets left or put in
865 // $results if all are done.
866 unset( $targets[$placeholder] );
867 $placeholder = '{' . $placeholder . '}';
868 // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
869 foreach ( $results[$target] as $value ) {
870 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
871 // Skip values that make invalid parameter names.
872 $encTargetName = $this->encodeParamName( $target );
873 if ( !isset( $warned[$encTargetName][$value] ) ) {
874 $warned[$encTargetName][$value] = true;
876 'apiwarn-ignoring-invalid-templated-value',
877 wfEscapeWikiText( $encTargetName ),
878 wfEscapeWikiText( $value ),
884 $newName = str_replace( $placeholder, $value, $name );
887 $results[$newName] = $this->getParameterFromSettings(
892 } catch ( ApiUsageException
$ex ) {
893 $results[$newName] = $ex;
897 foreach ( $targets as $k => $v ) {
898 $newTargets[$k] = str_replace( $placeholder, $value, $v );
900 $toProcess[] = [ $newName, $newTargets, $settings ];
907 $this->mParamCache
[$cacheKey] = $results;
910 $ret = $this->mParamCache
[$cacheKey];
911 if ( !$options['safeMode'] ) {
912 foreach ( $ret as $v ) {
913 if ( $v instanceof ApiUsageException
) {
919 return $this->mParamCache
[$cacheKey];
923 * Get a value for the given parameter.
925 * @param string $paramName Parameter name
926 * @param bool $parseLimit See extractRequestParams()
927 * @return mixed Parameter value
929 protected function getParameter( $paramName, $parseLimit = true ) {
930 $ret = $this->extractRequestParams( [
931 'parseLimit' => $parseLimit,
934 if ( $ret instanceof ApiUsageException
) {
941 * Die if 0 or more than one of a certain set of parameters is set and not false.
943 * @param array $params User provided parameter set, as from $this->extractRequestParams()
944 * @param string ...$required Names of parameters of which exactly one must be set
946 public function requireOnlyOneParameter( $params, ...$required ) {
947 $intersection = array_intersect( array_keys( array_filter( $params,
948 [ $this, 'parameterNotEmpty' ] ) ), $required );
950 if ( count( $intersection ) > 1 ) {
951 $this->dieWithError( [
952 'apierror-invalidparammix',
953 Message
::listParam( array_map(
955 return '<var>' . $this->encodeParamName( $p ) . '</var>';
957 array_values( $intersection )
959 count( $intersection ),
961 } elseif ( count( $intersection ) == 0 ) {
962 $this->dieWithError( [
963 'apierror-missingparam-one-of',
964 Message
::listParam( array_map(
966 return '<var>' . $this->encodeParamName( $p ) . '</var>';
976 * Dies if more than one parameter from a certain set of parameters are set and not false.
978 * @param array $params User provided parameters set, as from $this->extractRequestParams()
979 * @param string ...$required Parameter names that cannot have more than one set
981 public function requireMaxOneParameter( $params, ...$required ) {
982 $intersection = array_intersect( array_keys( array_filter( $params,
983 [ $this, 'parameterNotEmpty' ] ) ), $required );
985 if ( count( $intersection ) > 1 ) {
986 $this->dieWithError( [
987 'apierror-invalidparammix',
988 Message
::listParam( array_map(
990 return '<var>' . $this->encodeParamName( $p ) . '</var>';
992 array_values( $intersection )
994 count( $intersection ),
1000 * Die if 0 of a certain set of parameters is set and not false.
1003 * @param array $params User provided parameters set, as from $this->extractRequestParams()
1004 * @param string ...$required Names of parameters of which at least one must be set
1006 public function requireAtLeastOneParameter( $params, ...$required ) {
1007 $intersection = array_intersect(
1008 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
1012 if ( count( $intersection ) == 0 ) {
1013 $this->dieWithError( [
1014 'apierror-missingparam-at-least-one-of',
1015 Message
::listParam( array_map(
1017 return '<var>' . $this->encodeParamName( $p ) . '</var>';
1022 ], 'missingparam' );
1027 * Die if any of the specified parameters were found in the query part of
1028 * the URL rather than the HTTP post body contents.
1031 * @param string[] $params Parameters to check
1032 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
1034 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
1035 // Skip if $wgDebugAPI is set, or if we're in internal mode
1036 if ( $this->getConfig()->get( MainConfigNames
::DebugAPI
) ||
1037 $this->getMain()->isInternalMode() ) {
1041 $queryValues = $this->getRequest()->getQueryValuesOnly();
1043 foreach ( $params as $param ) {
1044 if ( $prefix !== 'noprefix' ) {
1045 $param = $this->encodeParamName( $param );
1047 if ( array_key_exists( $param, $queryValues ) ) {
1048 $badParams[] = $param;
1053 $this->dieWithError(
1054 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
1060 * Callback function used in requireOnlyOneParameter to check whether required parameters are set.
1062 * @param mixed $x Parameter to check is not null/false
1065 private function parameterNotEmpty( $x ) {
1066 return $x !== null && $x !== false;
1070 * Attempts to load a WikiPage object from a title or pageid parameter, if possible.
1071 * It can die if no param is set or if the title or page ID is not valid.
1073 * @param array $params User provided parameter set, as from $this->extractRequestParams()
1074 * @param string|false $load Whether load the object's state from the database:
1075 * - false: don't load (if the pageid is given, it will still be loaded)
1076 * - 'fromdb': load from a replica DB
1077 * - 'fromdbmaster': load from the primary database
1080 public function getTitleOrPageId( $params, $load = false ) {
1081 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1084 if ( isset( $params['title'] ) ) {
1085 $titleObj = Title
::newFromText( $params['title'] );
1086 if ( !$titleObj ||
$titleObj->isExternal() ) {
1087 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1089 if ( !$titleObj->canExist() ) {
1090 $this->dieWithError( 'apierror-pagecannotexist' );
1092 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
1093 $pageObj = MediaWikiServices
::getInstance()->getWikiPageFactory()->newFromTitle( $titleObj );
1094 if ( $load !== false ) {
1095 $pageObj->loadPageData( $load );
1097 } elseif ( isset( $params['pageid'] ) ) {
1098 if ( $load === false ) {
1101 $pageObj = MediaWikiServices
::getInstance()->getWikiPageFactory()->newFromID( $params['pageid'], $load );
1103 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1107 // @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
1112 * Get a Title object from a title or pageid param, if it is possible.
1113 * It can die if no param is set or if the title or page ID is not valid.
1116 * @param array $params User provided parameter set, as from $this->extractRequestParams()
1119 public function getTitleFromTitleOrPageId( $params ) {
1120 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1123 if ( isset( $params['title'] ) ) {
1124 $titleObj = Title
::newFromText( $params['title'] );
1125 if ( !$titleObj ||
$titleObj->isExternal() ) {
1126 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1128 // @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
1132 if ( isset( $params['pageid'] ) ) {
1133 $titleObj = Title
::newFromID( $params['pageid'] );
1135 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1139 // @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
1144 * Using the settings, determine the value for the given parameter.
1146 * @param string $name Parameter name
1147 * @param array|mixed $settings Default value or an array of settings
1148 * using PARAM_* constants.
1149 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1150 * @return mixed Parameter value
1152 protected function getParameterFromSettings( $name, $settings, $parseLimit ) {
1153 $validator = $this->getMain()->getParamValidator();
1154 $value = $validator->getValue( $this, $name, $settings, [
1155 'parse-limit' => $parseLimit,
1156 'raw' => ( $settings[ParamValidator
::PARAM_TYPE
] ??
'' ) === 'raw',
1159 // @todo Deprecate and remove this, if possible.
1160 if ( $parseLimit && isset( $settings[ParamValidator
::PARAM_TYPE
] ) &&
1161 $settings[ParamValidator
::PARAM_TYPE
] === 'limit' &&
1162 $this->getMain()->getVal( $this->encodeParamName( $name ) ) === 'max'
1164 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1171 * Handle when a parameter was Unicode-normalized.
1174 * @since 1.35 $paramName is prefixed
1175 * @internal For overriding by subclasses and use by ApiParamValidatorCallbacks only.
1176 * @param string $paramName Prefixed parameter name
1177 * @param string $value Input that will be used.
1178 * @param string $rawValue Input before normalization.
1180 public function handleParamNormalization( $paramName, $value, $rawValue ) {
1181 $this->addWarning( [ 'apiwarn-badutf8', $paramName ] );
1185 * Validate the supplied token.
1188 * @param string $token Supplied token
1189 * @param array $params All supplied parameters for the module
1192 final public function validateToken( $token, array $params ) {
1193 $tokenType = $this->needsToken();
1194 $salts = ApiQueryTokens
::getTokenTypeSalts();
1195 if ( !isset( $salts[$tokenType] ) ) {
1196 throw new LogicException(
1197 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1198 'without registering it'
1202 $tokenObj = ApiQueryTokens
::getToken(
1203 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1205 if ( $tokenObj->match( $token ) ) {
1209 $webUiSalt = $this->getWebUITokenSalt( $params );
1211 return $webUiSalt !== null && $this->getUser()->matchEditToken(
1212 $token, $webUiSalt, $this->getRequest()
1216 // endregion -- end of parameter handling
1218 /***************************************************************************/
1219 // region Utility methods
1220 /** @name Utility methods */
1223 * Gets the user for whom to get the watchlist
1225 * @param array $params
1228 public function getWatchlistUser( $params ) {
1229 if ( $params['owner'] !== null && $params['token'] !== null ) {
1230 $services = MediaWikiServices
::getInstance();
1231 $user = $services->getUserFactory()->newFromName( $params['owner'], UserRigorOptions
::RIGOR_NONE
);
1232 if ( !$user ||
!$user->isRegistered() ) {
1233 $this->dieWithError(
1234 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1237 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
1238 $token = $services->getUserOptionsLookup()->getOption( $user, 'watchlisttoken' );
1239 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1240 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1243 $user = $this->getUser();
1244 if ( !$user->isRegistered() ) {
1245 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1247 $this->checkUserRightsAny( 'viewmywatchlist' );
1250 // @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
1255 * Create a Message from a string or array
1257 * A string is used as a message key. An array has the message key as the
1258 * first value and message parameters as subsequent values.
1261 * @param string|array|Message $msg
1262 * @phan-param string|non-empty-array|Message $msg
1263 * @param IContextSource $context
1264 * @param array|null $params
1265 * @return Message|null
1267 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1268 if ( is_string( $msg ) ) {
1269 $msg = wfMessage( $msg );
1270 } elseif ( is_array( $msg ) ) {
1271 $msg = wfMessage( ...$msg );
1273 if ( !$msg instanceof Message
) {
1277 $msg->setContext( $context );
1279 $msg->params( $params );
1286 * Turn an array of messages into a Status.
1288 * @see ApiMessage::create
1291 * @param array $errors A list of message keys, MessageSpecifier objects,
1292 * or arrays containing the message key and parameters.
1293 * @param Authority|null $performer
1296 public function errorArrayToStatus( array $errors, Authority
$performer = null ) {
1297 $performer ??
= $this->getAuthority();
1298 $block = $performer->getBlock();
1300 $status = Status
::newGood();
1301 foreach ( $errors as $error ) {
1302 if ( !is_array( $error ) ) {
1303 $error = [ $error ];
1306 $head = reset( $error );
1307 $key = ( $head instanceof MessageSpecifier
) ?
$head->getKey() : (string)$head;
1309 if ( isset( self
::BLOCK_CODE_MAP
[$key] ) && $block ) {
1310 $status->fatal( ApiMessage
::create(
1312 $this->getBlockCode( $block ),
1313 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
1315 } elseif ( isset( self
::MESSAGE_CODE_MAP
[$key] ) ) {
1316 [ $msg, $code ] = self
::MESSAGE_CODE_MAP
[$key];
1317 $status->fatal( ApiMessage
::create( $msg, $code ) );
1319 // @phan-suppress-next-line PhanParamTooFewUnpack
1320 $status->fatal( ...$error );
1327 * Add block info to block messages in a Status
1329 * @internal since 1.37, should become protected in the future.
1330 * @param StatusValue $status
1331 * @param Authority|null $user
1333 public function addBlockInfoToStatus( StatusValue
$status, Authority
$user = null ) {
1334 if ( $status instanceof PermissionStatus
) {
1335 $block = $status->getBlock();
1337 $user = $user ?
: $this->getAuthority();
1338 $block = $user->getBlock();
1344 foreach ( $status->getErrors() as $error ) {
1345 $msgKey = $error['message'] instanceof MessageSpecifier ?
1346 $error['message']->getKey() :
1348 if ( isset( self
::BLOCK_CODE_MAP
[$msgKey] ) ) {
1349 $status->replaceMessage( $msgKey, ApiMessage
::create(
1351 $this->getBlockCode( $block ),
1352 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
1359 * Call wfTransactionalTimeLimit() if this request was POSTed.
1363 protected function useTransactionalTimeLimit() {
1364 if ( $this->getRequest()->wasPosted() ) {
1365 wfTransactionalTimeLimit();
1370 * Reset static caches of database state.
1372 * @internal For testing only
1374 public static function clearCacheForTest(): void
{
1375 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1376 throw new LogicException( 'Not allowed outside tests' );
1378 self
::$filterIDsCache = [];
1382 * Filter out-of-range values from a list of positive integer IDs
1385 * @param string[][] $fields Array of table and field pairs to check
1386 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1387 * expected to be stringified integers.
1388 * @return (string|int)[] Filtered IDs.
1390 protected function filterIDs( $fields, array $ids ) {
1393 foreach ( $fields as [ $table, $field ] ) {
1394 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1395 $row = self
::$filterIDsCache[$table][$field];
1397 $row = $this->getDB()->newSelectQueryBuilder()
1398 ->select( [ 'min_id' => "MIN($field)", 'max_id' => "MAX($field)" ] )
1400 ->caller( __METHOD__
)->fetchRow();
1401 self
::$filterIDsCache[$table][$field] = $row;
1403 $min = min( $min, $row->min_id
);
1404 $max = max( $max, $row->max_id
);
1406 return array_filter( $ids, static function ( $id ) use ( $min, $max ) {
1407 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( (string)$id ) )
1408 && $id >= $min && $id <= $max;
1412 // endregion -- end of utility methods
1414 /***************************************************************************/
1415 // region Warning and error reporting
1416 /** @name Warning and error reporting */
1419 * Add a warning for this module.
1421 * Users should monitor this section to notice any changes in the API.
1423 * Multiple calls to this function will result in multiple warning messages.
1425 * If $msg is not an ApiMessage, the message code will be derived from the
1426 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1429 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1430 * @param string|null $code See ApiErrorFormatter::addWarning()
1431 * @param array|null $data See ApiErrorFormatter::addWarning()
1433 public function addWarning( $msg, $code = null, $data = null ) {
1434 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1438 * Add a deprecation warning for this module.
1440 * A combination of $this->addWarning() and $this->logFeatureUsage()
1443 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1444 * @param string|null $feature See ApiBase::logFeatureUsage()
1445 * @param array|null $data See ApiErrorFormatter::addWarning()
1447 public function addDeprecation( $msg, $feature, $data = [] ) {
1448 $data = (array)$data;
1449 if ( $feature !== null ) {
1450 $data['feature'] = $feature;
1451 $this->logFeatureUsage( $feature );
1453 $this->addWarning( $msg, 'deprecation', $data );
1455 // No real need to deduplicate here, ApiErrorFormatter does that for
1456 // us (assuming the hook is deterministic).
1457 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1458 $this->getHookRunner()->onApiDeprecationHelp( $msgs );
1459 if ( count( $msgs ) > 1 ) {
1460 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1461 $msg = ( new RawMessage( $key ) )->params( $msgs );
1463 $msg = reset( $msgs );
1465 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1469 * Add an error for this module without aborting
1471 * If $msg is not an ApiMessage, the message code will be derived from the
1472 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1474 * @note If you want to abort processing, use self::dieWithError() instead.
1476 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1477 * @param string|null $code See ApiErrorFormatter::addError()
1478 * @param array|null $data See ApiErrorFormatter::addError()
1480 public function addError( $msg, $code = null, $data = null ) {
1481 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1485 * Add warnings and/or errors from a Status
1487 * @note If you want to abort processing, use self::dieStatus() instead.
1489 * @param StatusValue $status
1490 * @param string[] $types 'warning' and/or 'error'
1491 * @param string[] $filter Message keys to filter out (since 1.33)
1493 public function addMessagesFromStatus(
1494 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1496 $this->getErrorFormatter()->addMessagesFromStatus(
1497 $this->getModulePath(), $status, $types, $filter
1502 * Abort execution with an error
1504 * If $msg is not an ApiMessage, the message code will be derived from the
1505 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1508 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1509 * @param string|null $code See ApiErrorFormatter::addError()
1510 * @param array|null $data See ApiErrorFormatter::addError()
1511 * @param int $httpCode HTTP error code to use
1512 * @throws ApiUsageException always
1515 public function dieWithError( $msg, $code = null, $data = null, $httpCode = 0 ) {
1516 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1520 * Abort execution with an error derived from a throwable
1523 * @param Throwable $exception See ApiErrorFormatter::getMessageFromException()
1524 * @param array $options See ApiErrorFormatter::getMessageFromException()
1525 * @throws ApiUsageException always
1528 public function dieWithException( Throwable
$exception, array $options = [] ) {
1529 $this->dieWithError(
1530 // @phan-suppress-next-line PhanTypeMismatchArgument
1531 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1536 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1537 * error handler and die with an error message including block info.
1540 * @param Block $block The block used to generate the ApiUsageException
1541 * @throws ApiUsageException always
1544 public function dieBlocked( Block
$block ) {
1545 $blockErrorFormatter = MediaWikiServices
::getInstance()->getBlockErrorFormatter();
1547 $msg = $blockErrorFormatter->getMessage(
1550 $this->getLanguage(),
1551 $this->getRequest()->getIP()
1554 $this->dieWithError(
1556 $this->getBlockCode( $block ),
1557 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
1562 * Throw an ApiUsageException based on the Status object.
1565 * @since 1.29 Accepts a StatusValue
1566 * @param StatusValue $status
1567 * @throws ApiUsageException always
1570 public function dieStatus( StatusValue
$status ) {
1571 if ( $status->isGood() ) {
1572 throw new LogicException( 'Successful status passed to ApiBase::dieStatus' );
1575 foreach ( self
::MESSAGE_CODE_MAP
as $msg => [ $apiMsg, $code ] ) {
1576 if ( $status->hasMessage( $msg ) ) {
1577 $status->replaceMessage( $msg, ApiMessage
::create( $apiMsg, $code ) );
1582 $status instanceof PermissionStatus
1583 && $status->isRateLimitExceeded()
1584 && !$status->hasMessage( 'apierror-ratelimited' )
1586 $status->fatal( ApiMessage
::create( 'apierror-ratelimited', 'ratelimited' ) );
1589 // ApiUsageException needs a fatal status, but this method has
1590 // historically accepted any non-good status. Convert it if necessary.
1591 $status->setOK( false );
1592 if ( !$status->getErrorsByType( 'error' ) ) {
1593 $newStatus = Status
::newGood();
1594 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1595 $newStatus->fatal( $err['message'], ...$err['params'] );
1597 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1598 $newStatus->fatal( 'unknownerror-nocode' );
1600 $status = $newStatus;
1603 $this->addBlockInfoToStatus( $status );
1605 throw new ApiUsageException( $this, $status );
1609 * Helper function for readonly errors.
1611 * @throws ApiUsageException always
1614 public function dieReadOnly() {
1615 $this->dieWithError(
1616 'apierror-readonly',
1618 [ 'readonlyreason' => MediaWikiServices
::getInstance()->getReadOnlyMode()->getReason() ]
1623 * Helper function for permission-denied errors.
1626 * @param string|string[] $rights
1627 * @throws ApiUsageException if the user doesn't have any of the rights.
1628 * The error message is based on $rights[0].
1630 public function checkUserRightsAny( $rights ) {
1631 $rights = (array)$rights;
1632 if ( !$this->getAuthority()->isAllowedAny( ...$rights ) ) {
1633 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1638 * Helper function for permission-denied errors.
1640 * @param PageIdentity $pageIdentity
1641 * @param string|string[] $actions
1642 * @param array $options Additional options
1643 * - user: (User) User to use rather than $this->getUser().
1644 * - autoblock: (bool, default false) Whether to spread autoblocks.
1645 * @phan-param array{user?:User,autoblock?:bool} $options
1647 * @throws ApiUsageException if the user doesn't have all the necessary rights.
1650 * @since 1.33 Changed the third parameter from $user to $options.
1651 * @since 1.36 deprecated passing LinkTarget as first parameter
1653 public function checkTitleUserPermissions(
1654 PageIdentity
$pageIdentity,
1658 $authority = $options['user'] ??
$this->getAuthority();
1659 $status = new PermissionStatus();
1660 foreach ( (array)$actions as $action ) {
1661 if ( $this->isWriteMode() ) {
1662 $authority->authorizeWrite( $action, $pageIdentity, $status );
1664 $authority->authorizeRead( $action, $pageIdentity, $status );
1667 if ( !$status->isGood() ) {
1668 if ( !empty( $options['autoblock'] ) ) {
1669 $this->getUser()->spreadAnyEditBlock();
1671 $this->dieStatus( $status );
1676 * Will only set a warning instead of failing if the global $wgDebugAPI
1679 * Otherwise, it behaves exactly as self::dieWithError().
1682 * @param string|array|Message $msg
1683 * @param string|null $code
1684 * @param array|null $data
1685 * @param int|null $httpCode
1686 * @throws ApiUsageException
1688 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1689 if ( $this->getConfig()->get( MainConfigNames
::DebugAPI
) !== true ) {
1690 $this->dieWithError( $msg, $code, $data, $httpCode ??
0 );
1692 $this->addWarning( $msg, $code, $data );
1697 * Parse the 'continue' parameter in the usual format and validate the types of each part,
1698 * or die with the 'badcontinue' error if the format, types, or the number of parts is wrong.
1700 * @param string $continue Value of 'continue' parameter obtained from extractRequestParams()
1701 * @param string[] $types Types of the expected parts in order, 'string', 'int' or 'timestamp'
1702 * @return mixed[] Array containing strings, integers or timestamps
1703 * @throws ApiUsageException
1706 protected function parseContinueParamOrDie( string $continue, array $types ): array {
1707 $cont = explode( '|', $continue );
1708 $this->dieContinueUsageIf( count( $cont ) != count( $types ) );
1710 foreach ( $cont as $i => &$value ) {
1711 switch ( $types[$i] ) {
1716 $this->dieContinueUsageIf( $value !== (string)(int)$value );
1717 $value = (int)$value;
1721 $dbTs = $this->getDB()->timestamp( $value );
1722 } catch ( TimestampException
$ex ) {
1725 $this->dieContinueUsageIf( $value !== $dbTs );
1728 throw new InvalidArgumentException( "Unknown type '{$types[$i]}'" );
1736 * Die with the 'badcontinue' error.
1738 * This call is common enough to make it into the base method.
1740 * @param bool $condition Will only die if this value is true
1741 * @throws ApiUsageException
1743 * @phan-assert-false-condition $condition
1745 protected function dieContinueUsageIf( $condition ) {
1747 $this->dieWithError( 'apierror-badcontinue' );
1752 * Internal code errors should be reported with this method.
1754 * @param string $method Method or function name
1755 * @param string $message Error message
1756 * @throws MWException always
1759 protected static function dieDebug( $method, $message ) {
1760 throw new MWException( "Internal error in $method: $message" );
1764 * Write logging information for API features to a debug log, for usage
1767 * @note Consider using $this->addDeprecation() instead to both warn and log.
1768 * @param string $feature Feature being used.
1770 public function logFeatureUsage( $feature ) {
1771 static $loggedFeatures = [];
1773 // Only log each feature once per request. We can get multiple calls from calls to
1774 // extractRequestParams() with different values for 'parseLimit', for example.
1775 if ( isset( $loggedFeatures[$feature] ) ) {
1778 $loggedFeatures[$feature] = true;
1780 $request = $this->getRequest();
1782 'feature' => $feature,
1783 // Replace spaces with underscores in 'username' for historical reasons.
1784 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
1785 'clientip' => $request->getIP(),
1786 'referer' => (string)$request->getHeader( 'Referer' ),
1787 'agent' => $this->getMain()->getUserAgent(),
1790 // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
1791 $s = '"' . addslashes( $ctx['feature'] ) . '"' .
1792 ' "' . wfUrlencode( $ctx['username'] ) . '"' .
1793 ' "' . $ctx['clientip'] . '"' .
1794 ' "' . addslashes( $ctx['referer'] ) . '"' .
1795 ' "' . addslashes( $ctx['agent'] ) . '"';
1797 wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
1800 // endregion -- end of warning and error reporting
1802 /***************************************************************************/
1803 // region Help message generation
1804 /** @name Help message generation */
1807 * Return the summary message.
1809 * This is a one-line description of the module, suitable for display in a
1813 * @stable to override
1814 * @return string|array|Message
1816 protected function getSummaryMessage() {
1817 return "apihelp-{$this->getModulePath()}-summary";
1821 * Return the extended help text message.
1823 * This is additional text to display at the top of the help section, below
1827 * @stable to override
1828 * @return string|array|Message
1830 protected function getExtendedDescription() {
1832 "apihelp-{$this->getModulePath()}-extended-description",
1833 'api-help-no-extended-description',
1838 * Get the final module summary
1841 * @stable to override
1844 public function getFinalSummary() {
1845 return self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
1846 $this->getModulePrefix(),
1847 $this->getModuleName(),
1848 $this->getModulePath(),
1853 * Get the final module description, after hooks have had a chance to tweak it as
1856 * @since 1.25, returns Message[] rather than string[]
1859 public function getFinalDescription() {
1860 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
1861 $this->getModulePrefix(),
1862 $this->getModuleName(),
1863 $this->getModulePath(),
1865 $extendedDescription = self
::makeMessage(
1866 $this->getExtendedDescription(), $this->getContext(), [
1867 $this->getModulePrefix(),
1868 $this->getModuleName(),
1869 $this->getModulePath(),
1873 $msgs = [ $summary, $extendedDescription ];
1875 $this->getHookRunner()->onAPIGetDescriptionMessages( $this, $msgs );
1881 * Get the final list of parameters, after hooks have had a chance to
1882 * tweak it as needed.
1884 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1886 * @since 1.21 $flags param added
1888 public function getFinalParams( $flags = 0 ) {
1889 // @phan-suppress-next-line PhanParamTooMany
1890 $params = $this->getAllowedParams( $flags );
1895 if ( $this->needsToken() ) {
1896 $params['token'] = [
1897 ParamValidator
::PARAM_TYPE
=> 'string',
1898 ParamValidator
::PARAM_REQUIRED
=> true,
1899 ParamValidator
::PARAM_SENSITIVE
=> true,
1900 self
::PARAM_HELP_MSG
=> [
1901 'api-help-param-token',
1902 $this->needsToken(),
1904 ] +
( $params['token'] ??
[] );
1907 $this->getHookRunner()->onAPIGetAllowedParams( $this, $params, $flags );
1913 * Get final parameter descriptions, after hooks have had a chance to tweak it as
1916 * @since 1.25, returns array of Message[] rather than array of string[]
1917 * @return array Keys are parameter names, values are arrays of Message objects
1919 public function getFinalParamDescription() {
1920 $prefix = $this->getModulePrefix();
1921 $name = $this->getModuleName();
1922 $path = $this->getModulePath();
1924 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
1926 foreach ( $params as $param => $settings ) {
1927 if ( !is_array( $settings ) ) {
1931 $msg = $settings[self
::PARAM_HELP_MSG
]
1932 ??
$this->msg( [ "apihelp-$path-param-$param", 'api-help-param-no-description' ] );
1933 $msg = self
::makeMessage( $msg, $this->getContext(),
1934 [ $prefix, $param, $name, $path ] );
1936 self
::dieDebug( __METHOD__
,
1937 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
1939 $msgs[$param] = [ $msg ];
1941 if ( isset( $settings[ParamValidator
::PARAM_TYPE
] ) &&
1942 $settings[ParamValidator
::PARAM_TYPE
] === 'submodule'
1944 if ( isset( $settings[SubmoduleDef
::PARAM_SUBMODULE_MAP
] ) ) {
1945 $map = $settings[SubmoduleDef
::PARAM_SUBMODULE_MAP
];
1947 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
1949 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
1950 $map[$submoduleName] = $prefix . $submoduleName;
1955 $submoduleFlags = []; // for sorting: higher flags are sorted later
1956 $submoduleNames = []; // for sorting: lexicographical, ascending
1957 foreach ( $map as $v => $m ) {
1958 $isDeprecated = false;
1959 $isInternal = false;
1962 $submod = $this->getModuleFromPath( $m );
1964 $summary = $submod->getFinalSummary();
1965 $isDeprecated = $submod->isDeprecated();
1966 $isInternal = $submod->isInternal();
1968 } catch ( ApiUsageException
$ex ) {
1972 $key = $summary->getKey();
1973 $params = $summary->getParams();
1975 $key = 'api-help-undocumented-module';
1978 $m = new ApiHelpParamValueMessage(
1979 "[[Special:ApiHelp/$m|$v]]",
1985 $submodules[] = $m->setContext( $this->getContext() );
1986 $submoduleFlags[] = ( $isDeprecated ?
1 : 0 ) |
( $isInternal ?
2 : 0 );
1987 $submoduleNames[] = $v;
1989 // sort $submodules by $submoduleFlags and $submoduleNames
1990 array_multisort( $submoduleFlags, $submoduleNames, $submodules );
1991 $msgs[$param] = array_merge( $msgs[$param], $submodules );
1992 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
1993 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
1994 self
::dieDebug( __METHOD__
,
1995 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
1997 $isArrayOfStrings = is_array( $settings[ParamValidator
::PARAM_TYPE
] )
1999 $settings[ParamValidator
::PARAM_TYPE
] === 'string'
2000 && ( $settings[ParamValidator
::PARAM_ISMULTI
] ??
false )
2002 if ( !$isArrayOfStrings ) {
2003 self
::dieDebug( __METHOD__
,
2004 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2005 'ParamValidator::PARAM_TYPE is an array or it is \'string\' and ' .
2006 'ParamValidator::PARAM_ISMULTI is true' );
2009 $values = is_array( $settings[ParamValidator
::PARAM_TYPE
] ) ?
2010 $settings[ParamValidator
::PARAM_TYPE
] :
2011 array_keys( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] );
2012 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2013 $deprecatedValues = $settings[EnumDef
::PARAM_DEPRECATED_VALUES
] ??
[];
2015 foreach ( $values as $value ) {
2016 $msg = $valueMsgs[$value] ??
"apihelp-$path-paramvalue-$param-$value";
2017 $m = self
::makeMessage( $msg, $this->getContext(),
2018 [ $prefix, $param, $name, $path, $value ] );
2020 $m = new ApiHelpParamValueMessage(
2022 // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
2023 [ $m->getKey(), 'api-help-param-no-description' ],
2025 isset( $deprecatedValues[$value] )
2027 $msgs[$param][] = $m->setContext( $this->getContext() );
2029 self
::dieDebug( __METHOD__
,
2030 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2035 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2036 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2037 self
::dieDebug( __METHOD__
,
2038 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2040 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2041 $m = self
::makeMessage( $m, $this->getContext(),
2042 [ $prefix, $param, $name, $path ] );
2044 $msgs[$param][] = $m;
2046 self
::dieDebug( __METHOD__
,
2047 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2053 $this->getHookRunner()->onAPIGetParamDescriptionMessages( $this, $msgs );
2059 * Generates the list of flags for the help screen and for action=paraminfo.
2061 * Corresponding messages: api-help-flag-deprecated,
2062 * api-help-flag-internal, api-help-flag-readrights,
2063 * api-help-flag-writerights, api-help-flag-mustbeposted
2067 protected function getHelpFlags() {
2070 if ( $this->isDeprecated() ) {
2071 $flags[] = 'deprecated';
2073 if ( $this->isInternal() ) {
2074 $flags[] = 'internal';
2076 if ( $this->isReadMode() ) {
2077 $flags[] = 'readrights';
2079 if ( $this->isWriteMode() ) {
2080 $flags[] = 'writerights';
2082 if ( $this->mustBePosted() ) {
2083 $flags[] = 'mustbeposted';
2090 * Returns information about the source of this module, if known
2092 * Returned array is an array with the following keys:
2093 * - path: Install path
2094 * - name: Extension name, or "MediaWiki" for core
2095 * - namemsg: (optional) i18n message key for a display name
2096 * - license-name: (optional) Name of license
2098 * @return array|null
2100 protected function getModuleSourceInfo() {
2101 if ( $this->mModuleSource
!== false ) {
2102 return $this->mModuleSource
;
2105 // First, try to find where the module comes from...
2106 $rClass = new ReflectionClass( $this );
2107 $path = $rClass->getFileName();
2110 $this->mModuleSource
= null;
2113 $path = realpath( $path ) ?
: $path;
2115 // Build a map of extension directories to extension info
2116 if ( self
::$extensionInfo === null ) {
2117 $extDir = $this->getConfig()->get( MainConfigNames
::ExtensionDirectory
);
2118 $baseDir = $this->getConfig()->get( MainConfigNames
::BaseDirectory
);
2119 self
::$extensionInfo = [
2120 realpath( __DIR__
) ?
: __DIR__
=> [
2122 'name' => 'MediaWiki',
2123 'license-name' => 'GPL-2.0-or-later',
2125 realpath( "$baseDir/extensions" ) ?
: "$baseDir/extensions" => null,
2126 realpath( $extDir ) ?
: $extDir => null,
2132 'license-name' => null,
2134 $credits = SpecialVersion
::getCredits( ExtensionRegistry
::getInstance(), $this->getConfig() );
2135 foreach ( $credits as $group ) {
2136 foreach ( $group as $ext ) {
2137 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2138 // This shouldn't happen, but does anyway.
2142 $extpath = $ext['path'];
2143 if ( !is_dir( $extpath ) ) {
2144 $extpath = dirname( $extpath );
2146 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2147 array_intersect_key( $ext, $keep );
2152 // Now traverse parent directories until we find a match or run out of parents.
2154 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2156 $this->mModuleSource
= self
::$extensionInfo[$path];
2157 return $this->mModuleSource
;
2161 $path = dirname( $path );
2162 } while ( $path !== $oldpath );
2164 // No idea what extension this might be.
2165 $this->mModuleSource
= null;
2170 * Called from ApiHelp before the pieces are joined together and returned.
2172 * This exists mainly for ApiMain to add the Permissions and Credits
2173 * sections. Other modules probably don't need it.
2175 * @stable to override
2176 * @param string[] &$help Array of help data
2177 * @param array $options Options passed to ApiHelp::getHelp
2178 * @param array &$tocData If a TOC is being generated, this array has keys
2179 * as anchors in the page and values as for Linker::generateTOC().
2181 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2184 // endregion -- end of help message generation
2189 * This file uses VisualStudio style region/endregion fold markers which are
2190 * recognised by PHPStorm. If modelines are enabled, the following editor
2191 * configuration will also enable folding in vim, if it is in the last 5 lines
2192 * of the file. We also use "@name" which creates sections in Doxygen.
2194 * vim: foldmarker=//\ region,//\ endregion foldmethod=marker