Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
46.40% covered (danger)
46.40%
316 / 681
46.15% covered (danger)
46.15%
36 / 78
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiBase
46.47% covered (danger)
46.47%
316 / 680
46.15% covered (danger)
46.15%
36 / 78
9300.12
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 execute
n/a
0 / 0
n/a
0 / 0
0
 getModuleManager
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getCustomPrinter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 shouldCheckMaxlag
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isReadMode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isWriteMode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 mustBePosted
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isDeprecated
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 deprecationMsg
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 needsToken
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getWebUITokenSalt
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getConditionalRequestData
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getModuleName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getModulePrefix
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getMain
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isMain
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getParent
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 dieIfMain
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 lacksSameOriginSecurity
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getModulePath
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 getModuleFromPath
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
56
 getResult
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getErrorFormatter
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getDB
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 getContinuationManager
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setContinuationManager
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getPermissionManager
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getHookContainer
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getHookRunner
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 dynamicParameterDocumentation
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 encodeParamName
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
2.86
 extractRequestParams
95.16% covered (success)
95.16%
59 / 62
0.00% covered (danger)
0.00%
0 / 1
21
 getParameter
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 requireOnlyOneParameter
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
3
 requireMaxOneParameter
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 requireAtLeastOneParameter
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 requireNoConflictingParameters
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
20
 requirePostedParameters
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
72
 parameterNotEmpty
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getTitleOrPageId
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
9.01
 getTitleFromTitleOrPageId
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
6
 getParameterFromSettings
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 handleParamNormalization
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 validateToken
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
 getWatchlistUser
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
72
 useTransactionalTimeLimit
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 clearCacheForTest
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 filterIDs
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 addWarning
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addDeprecation
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
3.04
 addError
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addMessagesFromStatus
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 dieWithError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 dieWithException
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 dieBlocked
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 dieStatus
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
10.14
 dieReadOnly
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 checkUserRightsAny
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 checkTitleUserPermissions
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 dieWithErrorOrDebug
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 parseContinueParamOrDie
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 dieContinueUsageIf
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 dieDebug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 logFeatureUsage
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
2
 getSummaryMessage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getExtendedDescription
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getFinalSummary
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 getFinalDescription
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
12
 getFinalParams
33.33% covered (danger)
33.33%
5 / 15
0.00% covered (danger)
0.00%
0 / 1
5.67
 getFinalParamDescription
51.02% covered (warning)
51.02%
50 / 98
0.00% covered (danger)
0.00%
0 / 1
120.12
 getHelpFlags
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 getModuleSourceInfo
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
240
 modifyHelp
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 recordUnifiedMetrics
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2/**
3 * Copyright Â© 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Api;
10
11use InvalidArgumentException;
12use LogicException;
13use MediaWiki\Api\Validator\SubmoduleDef;
14use MediaWiki\Block\Block;
15use MediaWiki\Context\ContextSource;
16use MediaWiki\HookContainer\HookContainer;
17use MediaWiki\Language\RawMessage;
18use MediaWiki\MainConfigNames;
19use MediaWiki\MediaWikiServices;
20use MediaWiki\Message\Message;
21use MediaWiki\Page\PageIdentity;
22use MediaWiki\Page\WikiPage;
23use MediaWiki\ParamValidator\TypeDef\NamespaceDef;
24use MediaWiki\Permissions\PermissionManager;
25use MediaWiki\Permissions\PermissionStatus;
26use MediaWiki\Registration\ExtensionRegistry;
27use MediaWiki\Specials\SpecialVersion;
28use MediaWiki\Status\Status;
29use MediaWiki\Title\Title;
30use MediaWiki\User\User;
31use MediaWiki\User\UserRigorOptions;
32use ReflectionClass;
33use StatusValue;
34use stdClass;
35use Throwable;
36use Wikimedia\Message\MessageSpecifier;
37use Wikimedia\ParamValidator\ParamValidator;
38use Wikimedia\ParamValidator\TypeDef\EnumDef;
39use Wikimedia\ParamValidator\TypeDef\IntegerDef;
40use Wikimedia\ParamValidator\TypeDef\StringDef;
41use Wikimedia\Rdbms\IReadableDatabase;
42use Wikimedia\Timestamp\TimestampException;
43
44/**
45 * This abstract class implements many basic API functions, and is the base of
46 * all API classes.
47 *
48 * The class functions are divided into several areas of functionality:
49 *
50 * Module parameters: Derived classes can define getAllowedParams() to specify
51 *  which parameters to expect, how to parse and validate them.
52 *
53 * Self-documentation: code to allow the API to document its own state
54 *
55 * @stable to extend
56 *
57 * @ingroup API
58 */
59abstract class ApiBase extends ContextSource {
60
61    /** @var HookContainer */
62    private $hookContainer;
63
64    /** @var ApiHookRunner */
65    private $hookRunner;
66
67    /**
68     * @name   Old constants for ::getAllowedParams() arrays
69     * @{
70     */
71
72    /**
73     * @deprecated since 1.35, use ParamValidator::PARAM_DEFAULT instead
74     */
75    public const PARAM_DFLT = ParamValidator::PARAM_DEFAULT;
76    /**
77     * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI instead
78     */
79    public const PARAM_ISMULTI = ParamValidator::PARAM_ISMULTI;
80    /**
81     * @deprecated since 1.35, use ParamValidator::PARAM_TYPE instead
82     */
83    public const PARAM_TYPE = ParamValidator::PARAM_TYPE;
84    /**
85     * @deprecated since 1.35, use IntegerDef::PARAM_MAX instead
86     */
87    public const PARAM_MAX = IntegerDef::PARAM_MAX;
88    /**
89     * @deprecated since 1.35, use IntegerDef::PARAM_MAX2 instead
90     */
91    public const PARAM_MAX2 = IntegerDef::PARAM_MAX2;
92    /**
93     * @deprecated since 1.35, use IntegerDef::PARAM_MIN instead
94     */
95    public const PARAM_MIN = IntegerDef::PARAM_MIN;
96    /**
97     * @deprecated since 1.35, use ParamValidator::PARAM_ALLOW_DUPLICATES instead
98     */
99    public const PARAM_ALLOW_DUPLICATES = ParamValidator::PARAM_ALLOW_DUPLICATES;
100    /**
101     * @deprecated since 1.35, use ParamValidator::PARAM_DEPRECATED instead
102     */
103    public const PARAM_DEPRECATED = ParamValidator::PARAM_DEPRECATED;
104    /**
105     * @deprecated since 1.35, use ParamValidator::PARAM_REQUIRED instead
106     */
107    public const PARAM_REQUIRED = ParamValidator::PARAM_REQUIRED;
108    /**
109     * @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_MAP instead
110     */
111    public const PARAM_SUBMODULE_MAP = SubmoduleDef::PARAM_SUBMODULE_MAP;
112    /**
113     * @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX instead
114     */
115    public const PARAM_SUBMODULE_PARAM_PREFIX = SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX;
116    /**
117     * @deprecated since 1.35, use ParamValidator::PARAM_ALL instead
118     */
119    public const PARAM_ALL = ParamValidator::PARAM_ALL;
120    /**
121     * @deprecated since 1.35, use NamespaceDef::PARAM_EXTRA_NAMESPACES instead
122     */
123    public const PARAM_EXTRA_NAMESPACES = NamespaceDef::PARAM_EXTRA_NAMESPACES;
124    /**
125     * @deprecated since 1.35, use ParamValidator::PARAM_SENSITIVE instead
126     */
127    public const PARAM_SENSITIVE = ParamValidator::PARAM_SENSITIVE;
128    /**
129     * @deprecated since 1.35, use EnumDef::PARAM_DEPRECATED_VALUES instead
130     */
131    public const PARAM_DEPRECATED_VALUES = EnumDef::PARAM_DEPRECATED_VALUES;
132    /**
133     * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT1 instead
134     */
135    public const PARAM_ISMULTI_LIMIT1 = ParamValidator::PARAM_ISMULTI_LIMIT1;
136    /**
137     * @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT2 instead
138     */
139    public const PARAM_ISMULTI_LIMIT2 = ParamValidator::PARAM_ISMULTI_LIMIT2;
140    /**
141     * @deprecated since 1.35, use StringDef::PARAM_MAX_BYTES instead
142     */
143    public const PARAM_MAX_BYTES = StringDef::PARAM_MAX_BYTES;
144    /**
145     * @deprecated since 1.35, use StringDef::PARAM_MAX_CHARS instead
146     */
147    public const PARAM_MAX_CHARS = StringDef::PARAM_MAX_CHARS;
148    /** @} */
149
150    /**
151     * (boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
152     * @deprecated since 1.35
153     */
154    public const PARAM_RANGE_ENFORCE = 'api-param-range-enforce';
155
156    // region   API-specific constants for ::getAllowedParams() arrays
157    /** @name   API-specific constants for ::getAllowedParams() arrays */
158
159    /**
160     * (string|array|Message) Specify an alternative i18n documentation message
161     * for this parameter. Default is apihelp-{$path}-param-{$param}.
162     * See Message::newFromSpecifier() for a description of allowed values.
163     * @since 1.25
164     */
165    public const PARAM_HELP_MSG = 'api-param-help-msg';
166
167    /**
168     * ((string|array|Message)[]) Specify additional i18n messages to append to
169     * the normal message for this parameter.
170     * See Message::newFromSpecifier() for a description of allowed values.
171     * @since 1.25
172     */
173    public const PARAM_HELP_MSG_APPEND = 'api-param-help-msg-append';
174
175    /**
176     * (array) Specify additional information tags for the parameter.
177     * The value is an array of arrays, with the first member being the 'tag' for the info
178     * and the remaining members being the values. In the help, this is
179     * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
180     * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
181     * @since 1.25
182     */
183    public const PARAM_HELP_MSG_INFO = 'api-param-help-msg-info';
184
185    /**
186     * Deprecated and unused.
187     * @since 1.25
188     * @deprecated since 1.35
189     */
190    public const PARAM_VALUE_LINKS = 'api-param-value-links';
191
192    /**
193     * ((string|array|Message)[]) When PARAM_TYPE is an array, or 'string'
194     * with PARAM_ISMULTI, this is an array mapping parameter values to help messages.
195     * See Message::newFromSpecifier() for a description of allowed values.
196     *
197     * When PARAM_TYPE is an array, any value not having a mapping will use
198     * the apihelp-{$path}-paramvalue-{$param}-{$value} message. (This means
199     * you can use an empty array to use the default message key for all
200     * values.)
201     *
202     * @since 1.25
203     * @note Use with PARAM_TYPE = 'string' is allowed since 1.40.
204     */
205    public const PARAM_HELP_MSG_PER_VALUE = 'api-param-help-msg-per-value';
206
207    /**
208     * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
209     * placeholders in the parameter name and values are the names of (unprefixed) parameters from
210     * which the replacement values are taken.
211     *
212     * For example, a parameter "foo-{ns}-{title}" could be defined with
213     * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
214     * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
215     *
216     * All placeholders must be present in the parameter's name. Each target parameter must have
217     * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
218     * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
219     * A parameter cannot target itself.
220     *
221     * @since 1.32
222     */
223    public const PARAM_TEMPLATE_VARS = 'param-template-vars';
224
225    // endregion -- end of API-specific constants for ::getAllowedParams() arrays
226
227    public const ALL_DEFAULT_STRING = '*';
228
229    /** Fast query, standard limit. */
230    public const LIMIT_BIG1 = 500;
231    /** Fast query, apihighlimits limit. */
232    public const LIMIT_BIG2 = 5000;
233    /** Slow query, standard limit. */
234    public const LIMIT_SML1 = 50;
235    /** Slow query, apihighlimits limit. */
236    public const LIMIT_SML2 = 500;
237
238    /**
239     * getAllowedParams() flag: When this is set, the result could take longer to generate,
240     * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
241     * @since 1.21
242     */
243    public const GET_VALUES_FOR_HELP = 1;
244
245    /** @var array Maps extension paths to info arrays */
246    private static $extensionInfo = null;
247
248    /** @var stdClass[][] Cache for self::filterIDs() */
249    private static $filterIDsCache = [];
250
251    /** @var array Map of web UI block messages to corresponding API messages and codes */
252    private const MESSAGE_CODE_MAP = [
253        'actionthrottled' => [ 'apierror-ratelimited', 'ratelimited' ],
254        'actionthrottledtext' => [ 'apierror-ratelimited', 'ratelimited' ],
255    ];
256
257    /** @var ApiMain */
258    private $mMainModule;
259
260    // Adding inline type hints for these two fields is non-trivial because
261    // of tests that create mocks for ApiBase subclasses and use
262    // disableOriginalConstructor(): in those cases the constructor here is never
263    // hit and thus these will be empty and any uses will raise a "Typed property
264    // must not be accessed before initialization" error.
265    /** @var string */
266    private $mModuleName;
267    /** @var string */
268    private $mModulePrefix;
269
270    /** @var IReadableDatabase|null */
271    private $mReplicaDB = null;
272    /**
273     * @var array
274     */
275    private $mParamCache = [];
276    /** @var array|null|false */
277    private $mModuleSource = false;
278
279    /**
280     * @stable to call
281     * @param ApiMain $mainModule
282     * @param string $moduleName Name of this module
283     * @param string $modulePrefix Prefix to use for parameter names
284     */
285    public function __construct( ApiMain $mainModule, string $moduleName, string $modulePrefix = '' ) {
286        $this->mMainModule = $mainModule;
287        $this->mModuleName = $moduleName;
288        $this->mModulePrefix = $modulePrefix;
289
290        if ( !$this->isMain() ) {
291            $this->setContext( $mainModule->getContext() );
292        }
293    }
294
295    /***************************************************************************/
296    // region   Methods to implement
297    /** @name   Methods to implement */
298
299    /**
300     * Evaluates the parameters, performs the requested query, and sets up
301     * the result. Concrete implementations of ApiBase must override this
302     * method to provide whatever functionality their module offers.
303     * Implementations must not produce any output on their own and are not
304     * expected to handle any errors.
305     *
306     * The execute() method will be invoked directly by ApiMain immediately
307     * before the result of the module is output. Aside from the
308     * constructor, implementations should assume that no other methods
309     * will be called externally on the module before the result is
310     * processed.
311     *
312     * The result data should be stored in the ApiResult object available
313     * through getResult().
314     */
315    abstract public function execute();
316
317    /**
318     * Get the module manager, or null if this module has no submodules.
319     *
320     * @since 1.21
321     * @stable to override
322     * @return ApiModuleManager|null
323     */
324    public function getModuleManager() {
325        return null;
326    }
327
328    /**
329     * If the module may only be used with a certain format module,
330     * it should override this method to return an instance of that formatter.
331     * A value of null means the default format will be used.
332     *
333     * @note Do not use this just because you don't want to support non-json
334     * formats. This should be used only when there is a fundamental
335     * requirement for a specific format.
336     *
337     * @stable to override
338     * @return ApiFormatBase|null An instance of a class derived from ApiFormatBase, or null
339     */
340    public function getCustomPrinter() {
341        return null;
342    }
343
344    /**
345     * Returns usage examples for this module.
346     *
347     * Return value has query strings as keys, with values being either strings
348     * (message key), arrays (message key + parameter), or Message objects.
349     *
350     * Do not call this base class implementation when overriding this method.
351     *
352     * @since 1.25
353     * @stable to override
354     * @return array
355     */
356    protected function getExamplesMessages() {
357        return [];
358    }
359
360    /**
361     * Return links to more detailed help pages about the module.
362     *
363     * @since 1.25, returning boolean false is deprecated
364     * @stable to override
365     * @return string|array
366     */
367    public function getHelpUrls() {
368        return [];
369    }
370
371    /**
372     * Returns an array of allowed parameters (parameter name) => (default
373     * value) or (parameter name) => (array with PARAM_* constants as keys)
374     * Don't call this function directly: use getFinalParams() to allow
375     * hooks to modify parameters as needed.
376     *
377     * Some derived classes may choose to handle an integer $flags parameter
378     * in the overriding methods. Callers of this method can pass zero or
379     * more OR-ed flags like GET_VALUES_FOR_HELP.
380     *
381     * @stable to override
382     * @return array
383     */
384    protected function getAllowedParams( /* $flags = 0 */ ) {
385        // $flags is not declared because it causes "Strict standards"
386        // warning. Most derived classes do not implement it.
387        return [];
388    }
389
390    /**
391     * Indicates if this module needs maxlag to be checked.
392     *
393     * @stable to override
394     * @return bool
395     */
396    public function shouldCheckMaxlag() {
397        return true;
398    }
399
400    /**
401     * Indicates whether this module requires read rights.
402     *
403     * @stable to override
404     * @return bool
405     */
406    public function isReadMode() {
407        return true;
408    }
409
410    /**
411     * Indicates whether this module requires write access to the wiki.
412     *
413     * API modules must override this method to return true if the operation they will
414     * perform is not "safe" per RFC 7231 section 4.2.1. A module's operation is "safe"
415     * if it is essentially read-only, i.e. the client does not request nor expect any
416     * state change that would be observable in the responses to future requests.
417     *
418     * Implementations of this method must always return the same value, regardless of
419     * the parameters passed to the constructor or system state.
420     *
421     * Modules that do not require POST requests should only perform "safe" operations.
422     * Note that some modules might require POST requests because they need to support
423     * large input parameters and not because they perform non-"safe" operations.
424     *
425     * The information provided by this method is used to perform authorization checks.
426     * It can also be used to enforce proper routing of supposedly "safe" POST requests
427     * to the closest datacenter via the Promise-Non-Write-API-Action header.
428     *
429     * @see mustBePosted()
430     * @see needsToken()
431     *
432     * @stable to override
433     * @return bool
434     */
435    public function isWriteMode() {
436        return false;
437    }
438
439    /**
440     * Indicates whether this module must be called with a POST request.
441     *
442     * Implementations of this method must always return the same value,
443     * regardless of the parameters passed to the constructor or system state.
444     *
445     * @stable to override
446     * @return bool
447     */
448    public function mustBePosted() {
449        return $this->needsToken() !== false;
450    }
451
452    /**
453     * Indicates whether this module is deprecated.
454     *
455     * Consider overriding `::deprecationMsg()` instead to provide
456     * a reason for the deprecation and a replacement.
457     *
458     * @since 1.25
459     * @stable to override
460     * @return bool
461     */
462    public function isDeprecated() {
463        return $this->deprecationMsg() !== null;
464    }
465
466    /**
467     * Returns a MessageSpecifier describing the deprecation if this module
468     * is deprecated, or returns null if this module is not deprecated
469     * or a description is not available.
470     *
471     * @since 1.46
472     * @stable to override
473     */
474    public function deprecationMsg(): ?MessageSpecifier {
475        return null;
476    }
477
478    /**
479     * Indicates whether this module is considered to be "internal".
480     *
481     * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
482     *
483     * @since 1.25
484     * @stable to override
485     * @return bool
486     */
487    public function isInternal() {
488        return false;
489    }
490
491    /**
492     * Returns the token type this module requires in order to execute.
493     *
494     * Modules are strongly encouraged to use the core 'csrf' type unless they
495     * have specialized security needs. If the token type is not one of the
496     * core types, you must use the ApiQueryTokensRegisterTypes hook to
497     * register it.
498     *
499     * Returning a non-falsey value here will force the addition of an
500     * appropriate 'token' parameter in self::getFinalParams(). Also,
501     * self::mustBePosted() must return true when tokens are used.
502     *
503     * In previous versions of MediaWiki, true was a valid return value.
504     * Returning true will generate errors indicating that the API module needs
505     * updating.
506     *
507     * @stable to override
508     * @return string|false
509     */
510    public function needsToken() {
511        return false;
512    }
513
514    /**
515     * Fetch the salt used in the Web UI corresponding to this module.
516     *
517     * Only override this if the Web UI uses a token with a non-constant salt.
518     *
519     * @since 1.24
520     * @param array $params All supplied parameters for the module
521     * @stable to override
522     * @return string|array|null
523     */
524    protected function getWebUITokenSalt( array $params ) {
525        return null;
526    }
527
528    /**
529     * Returns data for HTTP conditional request mechanisms.
530     *
531     * @since 1.26
532     * @stable to override
533     * @param string $condition Condition being queried:
534     *  - last-modified: Return a timestamp representing the maximum of the
535     *    last-modified dates for all resources involved in the request. See
536     *    RFC 7232 Â§ 2.2 for semantics.
537     *  - etag: Return an entity-tag representing the state of all resources involved
538     *    in the request. Quotes must be included. See RFC 7232 Â§ 2.3 for semantics.
539     * @return string|bool|null As described above, or null if no value is available.
540     */
541    public function getConditionalRequestData( $condition ) {
542        return null;
543    }
544
545    // endregion -- end of methods to implement
546
547    /***************************************************************************/
548    // region   Data access methods
549    /** @name   Data access methods */
550
551    /**
552     * Get the name of the module being executed by this instance.
553     *
554     * @return string
555     */
556    public function getModuleName() {
557        return $this->mModuleName;
558    }
559
560    /**
561     * Get parameter prefix (usually two letters or an empty string).
562     *
563     * @return string
564     */
565    public function getModulePrefix() {
566        return $this->mModulePrefix;
567    }
568
569    /**
570     * Get the main module.
571     *
572     * @return ApiMain
573     */
574    public function getMain() {
575        return $this->mMainModule;
576    }
577
578    /**
579     * Returns true if this module is the main module ($this === $this->mMainModule),
580     * false otherwise.
581     *
582     * @return bool
583     */
584    public function isMain() {
585        return $this === $this->mMainModule;
586    }
587
588    /**
589     * Get the parent of this module.
590     *
591     * @stable to override
592     * @since 1.25
593     * @return ApiBase|null
594     */
595    public function getParent() {
596        return $this->isMain() ? null : $this->getMain();
597    }
598
599    /**
600     * Used to avoid infinite loops - the ApiMain class should override some
601     * methods, if it doesn't and uses the default ApiBase implementation, which
602     * just calls the same method for the ApiMain instance, it'll lead to an infinite loop
603     *
604     * @param string $methodName used for debug messages
605     */
606    private function dieIfMain( string $methodName ) {
607        if ( $this->isMain() ) {
608            self::dieDebug( $methodName, 'base method was called on main module.' );
609        }
610    }
611
612    /**
613     * Returns true if the current request breaks the same-origin policy.
614     *
615     * For example, json with callbacks.
616     *
617     * https://en.wikipedia.org/wiki/Same-origin_policy
618     *
619     * @since 1.25
620     * @return bool
621     */
622    public function lacksSameOriginSecurity() {
623        // The Main module has this method overridden, avoid infinite loops
624        $this->dieIfMain( __METHOD__ );
625
626        return $this->getMain()->lacksSameOriginSecurity();
627    }
628
629    /**
630     * Get the path to this module.
631     *
632     * @since 1.25
633     * @return string
634     */
635    public function getModulePath() {
636        if ( $this->isMain() ) {
637            return 'main';
638        }
639
640        if ( $this->getParent()->isMain() ) {
641            return $this->getModuleName();
642        }
643
644        return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
645    }
646
647    /**
648     * Get a module from its module path.
649     *
650     * @since 1.25
651     * @param string $path
652     * @return ApiBase|null
653     * @throws ApiUsageException
654     */
655    public function getModuleFromPath( $path ) {
656        $module = $this->getMain();
657        if ( $path === 'main' ) {
658            return $module;
659        }
660
661        $parts = explode( '+', $path );
662        if ( count( $parts ) === 1 ) {
663            // In case the '+' was typed into URL, it resolves as a space
664            $parts = explode( ' ', $path );
665        }
666
667        foreach ( $parts as $i => $v ) {
668            $parent = $module;
669            $manager = $parent->getModuleManager();
670            if ( $manager === null ) {
671                $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
672                $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
673            }
674            $module = $manager->getModule( $v );
675
676            if ( $module === null ) {
677                $errorPath = $i
678                    ? implode( '+', array_slice( $parts, 0, $i ) )
679                    : $parent->getModuleName();
680                $this->dieWithError(
681                    [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $v ) ],
682                    'badmodule'
683                );
684            }
685        }
686
687        return $module;
688    }
689
690    /**
691     * Get the result object.
692     *
693     * @return ApiResult
694     */
695    public function getResult() {
696        // The Main module has this method overridden, avoid infinite loops
697        $this->dieIfMain( __METHOD__ );
698
699        return $this->getMain()->getResult();
700    }
701
702    /**
703     * @stable to override
704     * @return ApiErrorFormatter
705     */
706    public function getErrorFormatter() {
707        // The Main module has this method overridden, avoid infinite loops
708        $this->dieIfMain( __METHOD__ );
709
710        return $this->getMain()->getErrorFormatter();
711    }
712
713    /**
714     * Gets a default replica DB connection object.
715     *
716     * @stable to override
717     * @return IReadableDatabase
718     */
719    protected function getDB() {
720        if ( !$this->mReplicaDB ) {
721            $this->mReplicaDB = MediaWikiServices::getInstance()
722                ->getConnectionProvider()
723                ->getReplicaDatabase();
724        }
725
726        return $this->mReplicaDB;
727    }
728
729    /**
730     * @return ApiContinuationManager|null
731     */
732    public function getContinuationManager() {
733        // The Main module has this method overridden, avoid infinite loops
734        $this->dieIfMain( __METHOD__ );
735
736        return $this->getMain()->getContinuationManager();
737    }
738
739    /**
740     * @param ApiContinuationManager|null $manager
741     */
742    public function setContinuationManager( ?ApiContinuationManager $manager = null ) {
743        // The Main module has this method overridden, avoid infinite loops
744        $this->dieIfMain( __METHOD__ );
745
746        $this->getMain()->setContinuationManager( $manager );
747    }
748
749    /**
750     * Obtain a PermissionManager instance that subclasses may use in their authorization checks.
751     *
752     * @since 1.34
753     * @return PermissionManager
754     */
755    protected function getPermissionManager(): PermissionManager {
756        return MediaWikiServices::getInstance()->getPermissionManager();
757    }
758
759    /**
760     * Get a HookContainer, for running extension hooks or for hook metadata.
761     *
762     * @since 1.35
763     * @return HookContainer
764     */
765    protected function getHookContainer() {
766        if ( !$this->hookContainer ) {
767            $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
768        }
769        return $this->hookContainer;
770    }
771
772    /**
773     * Get an ApiHookRunner for running core API hooks.
774     *
775     * @internal This is for use by core only. Hook interfaces may be removed
776     *  without notice.
777     * @since 1.35
778     * @return ApiHookRunner
779     */
780    protected function getHookRunner() {
781        if ( !$this->hookRunner ) {
782            $this->hookRunner = new ApiHookRunner( $this->getHookContainer() );
783        }
784        return $this->hookRunner;
785    }
786
787    // endregion -- end of data access methods
788
789    /***************************************************************************/
790    // region   Parameter handling
791    /** @name   Parameter handling */
792
793    /**
794     * Indicate if the module supports dynamically-determined parameters that
795     * cannot be included in self::getAllowedParams().
796     * @stable to override
797     * @return string|array|Message|null Return null if the module does not
798     *  support additional dynamic parameters, otherwise return a message
799     *  describing them.
800     *  See Message::newFromSpecifier() for a description of allowed values.
801     */
802    public function dynamicParameterDocumentation() {
803        return null;
804    }
805
806    /**
807     * This method mangles parameter name based on the prefix supplied to the constructor.
808     * Override this method to change parameter name during runtime.
809     *
810     * @param string|string[] $paramName Parameter name
811     * @return string|string[] Prefixed parameter name
812     * @since 1.29 accepts an array of strings
813     */
814    public function encodeParamName( $paramName ) {
815        if ( is_array( $paramName ) ) {
816            return array_map( function ( $name ) {
817                return $this->mModulePrefix . $name;
818            }, $paramName );
819        }
820
821        return $this->mModulePrefix . $paramName;
822    }
823
824    /**
825     * Using getAllowedParams(), this function makes an array of the values
826     * provided by the user, with the key being the name of the variable, and
827     * value - validated value from user or default. limits will not be
828     * parsed if $parseLimit is set to false; use this when the max
829     * limit is not definitive yet, e.g. when getting revisions.
830     * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
831     *  - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
832     *  - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
833     *    Returned parameter values might be ApiUsageException instances.
834     * @return array
835     */
836    public function extractRequestParams( $options = [] ) {
837        if ( is_bool( $options ) ) {
838            $options = [ 'parseLimit' => $options ];
839        }
840        $options += [
841            'parseLimit' => true,
842            'safeMode' => false,
843        ];
844
845        $parseLimit = (bool)$options['parseLimit'];
846        $cacheKey = (int)$parseLimit;
847
848        // Cache parameters, for performance and to avoid T26564.
849        if ( !isset( $this->mParamCache[$cacheKey] ) ) {
850            $params = $this->getFinalParams() ?: [];
851            $results = [];
852            $warned = [];
853
854            // Process all non-templates and save templates for secondary
855            // processing.
856            $toProcess = [];
857            foreach ( $params as $paramName => $paramSettings ) {
858                if ( isset( $paramSettings[self::PARAM_TEMPLATE_VARS] ) ) {
859                    $toProcess[] = [ $paramName, $paramSettings[self::PARAM_TEMPLATE_VARS], $paramSettings ];
860                } else {
861                    try {
862                        $results[$paramName] = $this->getParameterFromSettings(
863                            $paramName, $paramSettings, $parseLimit
864                        );
865                    } catch ( ApiUsageException $ex ) {
866                        $results[$paramName] = $ex;
867                    }
868                }
869            }
870
871            // Now process all the templates by successively replacing the
872            // placeholders with all client-supplied values.
873            // This bit duplicates JavaScript logic in
874            // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
875            // If you update this, see if that needs updating too.
876            while ( $toProcess ) {
877                [ $name, $targets, $settings ] = array_shift( $toProcess );
878
879                foreach ( $targets as $placeholder => $target ) {
880                    if ( !array_key_exists( $target, $results ) ) {
881                        // The target wasn't processed yet, try the next one.
882                        // If all hit this case, the parameter has no expansions.
883                        continue;
884                    }
885                    if ( !is_array( $results[$target] ) || !$results[$target] ) {
886                        // The target was processed but has no (valid) values.
887                        // That means it has no expansions.
888                        break;
889                    }
890
891                    // Expand this target in the name and all other targets,
892                    // then requeue if there are more targets left or put in
893                    // $results if all are done.
894                    unset( $targets[$placeholder] );
895                    $placeholder = '{' . $placeholder . '}';
896                    // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
897                    foreach ( $results[$target] as $value ) {
898                        if ( !preg_match( '/^[^{}]*$/', $value ) ) {
899                            // Skip values that make invalid parameter names.
900                            $encTargetName = $this->encodeParamName( $target );
901                            if ( !isset( $warned[$encTargetName][$value] ) ) {
902                                $warned[$encTargetName][$value] = true;
903                                $this->addWarning( [
904                                    'apiwarn-ignoring-invalid-templated-value',
905                                    wfEscapeWikiText( $encTargetName ),
906                                    wfEscapeWikiText( $value ),
907                                ] );
908                            }
909                            continue;
910                        }
911
912                        $newName = str_replace( $placeholder, $value, $name );
913                        if ( !$targets ) {
914                            try {
915                                $results[$newName] = $this->getParameterFromSettings(
916                                    $newName,
917                                    $settings,
918                                    $parseLimit
919                                );
920                            } catch ( ApiUsageException $ex ) {
921                                $results[$newName] = $ex;
922                            }
923                        } else {
924                            $newTargets = [];
925                            foreach ( $targets as $k => $v ) {
926                                $newTargets[$k] = str_replace( $placeholder, $value, $v );
927                            }
928                            $toProcess[] = [ $newName, $newTargets, $settings ];
929                        }
930                    }
931                    break;
932                }
933            }
934
935            $this->mParamCache[$cacheKey] = $results;
936        }
937
938        $ret = $this->mParamCache[$cacheKey];
939        if ( !$options['safeMode'] ) {
940            foreach ( $ret as $v ) {
941                if ( $v instanceof ApiUsageException ) {
942                    throw $v;
943                }
944            }
945        }
946
947        return $this->mParamCache[$cacheKey];
948    }
949
950    /**
951     * Get a value for the given parameter.
952     *
953     * @param string $paramName Parameter name
954     * @param bool $parseLimit See extractRequestParams()
955     * @return mixed Parameter value
956     */
957    protected function getParameter( $paramName, $parseLimit = true ) {
958        $ret = $this->extractRequestParams( [
959            'parseLimit' => $parseLimit,
960            'safeMode' => true,
961        ] )[$paramName];
962        if ( $ret instanceof ApiUsageException ) {
963            throw $ret;
964        }
965        return $ret;
966    }
967
968    /**
969     * Die if 0 or more than one of a certain set of parameters is set and not false.
970     *
971     * @param array $params User provided parameter set, as from $this->extractRequestParams()
972     * @param string ...$required Names of parameters of which exactly one must be set
973     */
974    public function requireOnlyOneParameter( $params, ...$required ) {
975        $intersection = array_intersect(
976            array_keys( array_filter( $params, $this->parameterNotEmpty( ... ) ) ),
977            $required
978        );
979
980        if ( count( $intersection ) > 1 ) {
981            $this->dieWithError( [
982                'apierror-invalidparammix',
983                Message::listParam( array_map(
984                    function ( $p ) {
985                        return '<var>' . $this->encodeParamName( $p ) . '</var>';
986                    },
987                    array_values( $intersection )
988                ) ),
989                count( $intersection ),
990            ] );
991        } elseif ( count( $intersection ) == 0 ) {
992            $this->dieWithError( [
993                'apierror-missingparam-one-of',
994                Message::listParam( array_map(
995                    function ( $p ) {
996                        return '<var>' . $this->encodeParamName( $p ) . '</var>';
997                    },
998                    $required
999                ) ),
1000                count( $required ),
1001            ], 'missingparam' );
1002        }
1003    }
1004
1005    /**
1006     * Dies if more than one parameter from a certain set of parameters are set and not false.
1007     *
1008     * @param array $params User provided parameters set, as from $this->extractRequestParams()
1009     * @param string ...$required Parameter names that cannot have more than one set
1010     */
1011    public function requireMaxOneParameter( $params, ...$required ) {
1012        $intersection = array_intersect(
1013            array_keys( array_filter( $params, $this->parameterNotEmpty( ... ) ) ),
1014            $required
1015        );
1016
1017        if ( count( $intersection ) > 1 ) {
1018            $this->dieWithError( [
1019                'apierror-invalidparammix',
1020                Message::listParam( array_map(
1021                    function ( $p ) {
1022                        return '<var>' . $this->encodeParamName( $p ) . '</var>';
1023                    },
1024                    array_values( $intersection )
1025                ) ),
1026                count( $intersection ),
1027            ] );
1028        }
1029    }
1030
1031    /**
1032     * Die if 0 of a certain set of parameters is set and not false.
1033     *
1034     * @since 1.23
1035     * @param array $params User provided parameters set, as from $this->extractRequestParams()
1036     * @param string ...$required Names of parameters of which at least one must be set
1037     */
1038    public function requireAtLeastOneParameter( $params, ...$required ) {
1039        $intersection = array_intersect(
1040            array_keys( array_filter( $params, $this->parameterNotEmpty( ... ) ) ),
1041            $required
1042        );
1043
1044        if ( count( $intersection ) == 0 ) {
1045            $this->dieWithError( [
1046                'apierror-missingparam-at-least-one-of',
1047                Message::listParam( array_map(
1048                    function ( $p ) {
1049                        return '<var>' . $this->encodeParamName( $p ) . '</var>';
1050                    },
1051                    $required
1052                ) ),
1053                count( $required ),
1054            ], 'missingparam' );
1055        }
1056    }
1057
1058    /**
1059     * Die with an "invalid param mix" error if the parameters contain the trigger parameter and
1060     * any of the conflicting parameters.
1061     *
1062     * @since 1.44
1063     *
1064     * @param array $params User provided parameters set, as from $this->extractRequestParams()
1065     * @param string $trigger The name of the trigger parameter
1066     * @param string|string[] $conflicts The conflicting parameter or a list
1067     *   of conflicting parameters
1068     */
1069    public function requireNoConflictingParameters( $params, $trigger, $conflicts ) {
1070        $triggerValue = $params[$trigger] ?? null;
1071        if ( $triggerValue === null || $triggerValue === false ) {
1072            return;
1073        }
1074        $intersection = array_intersect(
1075            array_keys( array_filter( $params, $this->parameterNotEmpty( ... ) ) ),
1076            (array)$conflicts
1077        );
1078        if ( count( $intersection ) ) {
1079            $this->dieWithError( [
1080                'apierror-invalidparammix-cannotusewith',
1081                Message::listParam( array_map(
1082                    function ( $p ) {
1083                        return '<var>' . $this->encodeParamName( $p ) . '</var>';
1084                    },
1085                    array_values( $intersection )
1086                ) ),
1087                $trigger,
1088            ] );
1089        }
1090    }
1091
1092    /**
1093     * Die if any of the specified parameters were found in the query part of
1094     * the URL rather than the HTTP post body contents.
1095     *
1096     * @since 1.28
1097     * @param string[] $params Parameters to check
1098     * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
1099     */
1100    public function requirePostedParameters( $params, $prefix = 'prefix' ) {
1101        if ( !$this->mustBePosted() ) {
1102            // In order to allow client code to choose the correct method (GET or POST) depending *only*
1103            // on mustBePosted(), make sure that the module requires posting if any of its potential
1104            // parameters require posting.
1105
1106            // TODO: Uncomment this
1107            // throw new LogicException( 'mustBePosted() must be true when using requirePostedParameters()' );
1108
1109            // This seems to already be the case in all modules in practice, but deprecate it first just
1110            // in case.
1111            wfDeprecatedMsg( 'mustBePosted() must be true when using requirePostedParameters()',
1112                '1.42' );
1113        }
1114
1115        // Skip if $wgDebugAPI is set, or if we're in internal mode
1116        if ( $this->getConfig()->get( MainConfigNames::DebugAPI ) ||
1117        $this->getMain()->isInternalMode() ) {
1118            return;
1119        }
1120
1121        $queryValues = $this->getRequest()->getQueryValuesOnly();
1122        $badParams = [];
1123        foreach ( $params as $param ) {
1124            if ( $prefix !== 'noprefix' ) {
1125                $param = $this->encodeParamName( $param );
1126            }
1127            if ( array_key_exists( $param, $queryValues ) ) {
1128                $badParams[] = $param;
1129            }
1130        }
1131
1132        if ( $badParams ) {
1133            $this->dieWithError(
1134                [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
1135            );
1136        }
1137    }
1138
1139    /**
1140     * Callback function used in requireOnlyOneParameter to check whether required parameters are set.
1141     *
1142     * @param mixed $x Parameter to check is not null/false
1143     * @return bool
1144     */
1145    private function parameterNotEmpty( $x ) {
1146        return $x !== null && $x !== false;
1147    }
1148
1149    /**
1150     * Attempts to load a WikiPage object from a title or pageid parameter, if possible.
1151     * It can die if no param is set or if the title or page ID is not valid.
1152     *
1153     * @param array $params User provided parameter set, as from $this->extractRequestParams()
1154     * @param string|false $load Whether load the object's state from the database:
1155     *  - false: don't load (if the pageid is given, it will still be loaded)
1156     *  - 'fromdb': load from a replica DB
1157     *  - 'fromdbmaster': load from the primary database
1158     * @return WikiPage
1159     */
1160    public function getTitleOrPageId( $params, $load = false ) {
1161        $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1162
1163        $pageObj = null;
1164        if ( isset( $params['title'] ) ) {
1165            $titleObj = Title::newFromText( $params['title'] );
1166            if ( !$titleObj || $titleObj->isExternal() ) {
1167                $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1168            }
1169            if ( !$titleObj->canExist() ) {
1170                $this->dieWithError( 'apierror-pagecannotexist' );
1171            }
1172            $pageObj = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $titleObj );
1173            if ( $load !== false ) {
1174                $pageObj->loadPageData( $load );
1175            }
1176        } elseif ( isset( $params['pageid'] ) ) {
1177            if ( $load === false ) {
1178                $load = 'fromdb';
1179            }
1180            $pageObj = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromID( $params['pageid'], $load );
1181            if ( !$pageObj ) {
1182                $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1183            }
1184        }
1185
1186        // @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
1187        return $pageObj;
1188    }
1189
1190    /**
1191     * Get a Title object from a title or pageid param, if it is possible.
1192     * It can die if no param is set or if the title or page ID is not valid.
1193     *
1194     * @since 1.29
1195     * @param array $params User provided parameter set, as from $this->extractRequestParams()
1196     * @return Title
1197     */
1198    public function getTitleFromTitleOrPageId( $params ) {
1199        $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1200
1201        $titleObj = null;
1202        if ( isset( $params['title'] ) ) {
1203            $titleObj = Title::newFromText( $params['title'] );
1204            if ( !$titleObj || $titleObj->isExternal() ) {
1205                $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1206            }
1207            return $titleObj;
1208        }
1209
1210        if ( isset( $params['pageid'] ) ) {
1211            $titleObj = Title::newFromID( $params['pageid'] );
1212            if ( !$titleObj ) {
1213                $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1214            }
1215        }
1216
1217        // @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
1218        return $titleObj;
1219    }
1220
1221    /**
1222     * Using the settings, determine the value for the given parameter.
1223     *
1224     * @param string $name Parameter name
1225     * @param array|mixed $settings Default value or an array of settings
1226     *  using PARAM_* constants.
1227     * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1228     * @return mixed Parameter value
1229     */
1230    protected function getParameterFromSettings( $name, $settings, $parseLimit ) {
1231        $validator = $this->getMain()->getParamValidator();
1232        $value = $validator->getValue( $this, $name, $settings, [
1233            'parse-limit' => $parseLimit,
1234            'raw' => ( $settings[ParamValidator::PARAM_TYPE] ?? '' ) === 'raw',
1235        ] );
1236
1237        // @todo Deprecate and remove this, if possible.
1238        if ( $parseLimit && isset( $settings[ParamValidator::PARAM_TYPE] ) &&
1239            $settings[ParamValidator::PARAM_TYPE] === 'limit' &&
1240            $this->getMain()->getVal( $this->encodeParamName( $name ) ) === 'max'
1241        ) {
1242            $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1243        }
1244
1245        return $value;
1246    }
1247
1248    /**
1249     * Handle when a parameter was Unicode-normalized.
1250     *
1251     * @since 1.28
1252     * @since 1.35 $paramName is prefixed
1253     * @internal For overriding by subclasses and use by ApiParamValidatorCallbacks only.
1254     * @param string $paramName Prefixed parameter name
1255     * @param string $value Input that will be used.
1256     * @param string $rawValue Input before normalization.
1257     */
1258    public function handleParamNormalization( $paramName, $value, $rawValue ) {
1259        $this->addWarning( [ 'apiwarn-badutf8', $paramName ] );
1260    }
1261
1262    /**
1263     * Validate the supplied token.
1264     *
1265     * @since 1.24
1266     * @param string $token Supplied token
1267     * @param array $params All supplied parameters for the module
1268     * @return bool
1269     */
1270    final public function validateToken( $token, array $params ) {
1271        $tokenType = $this->needsToken();
1272        $salts = ApiQueryTokens::getTokenTypeSalts();
1273        if ( !isset( $salts[$tokenType] ) ) {
1274            throw new LogicException(
1275                "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1276                    'without registering it'
1277            );
1278        }
1279
1280        $tokenObj = ApiQueryTokens::getToken(
1281            $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1282        );
1283        if ( $tokenObj->match( $token ) ) {
1284            return true;
1285        }
1286
1287        $webUiSalt = $this->getWebUITokenSalt( $params );
1288
1289        return $webUiSalt !== null && $this->getUser()->matchEditToken(
1290            $token, $webUiSalt, $this->getRequest()
1291        );
1292    }
1293
1294    // endregion -- end of parameter handling
1295
1296    /***************************************************************************/
1297    // region   Utility methods
1298    /** @name   Utility methods */
1299
1300    /**
1301     * Gets the user for whom to get the watchlist
1302     *
1303     * @param array $params
1304     * @return User
1305     */
1306    public function getWatchlistUser( $params ) {
1307        if ( $params['owner'] !== null && $params['token'] !== null ) {
1308            $services = MediaWikiServices::getInstance();
1309            $user = $services->getUserFactory()->newFromName( $params['owner'], UserRigorOptions::RIGOR_NONE );
1310            if ( !$user || !$user->isRegistered() ) {
1311                $this->dieWithError(
1312                    [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1313                );
1314            }
1315            $token = $services->getUserOptionsLookup()->getOption( $user, 'watchlisttoken' );
1316            if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1317                $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1318            }
1319        } else {
1320            $user = $this->getUser();
1321            if ( !$user->isRegistered() ) {
1322                $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1323            }
1324            $this->checkUserRightsAny( 'viewmywatchlist' );
1325        }
1326
1327        return $user;
1328    }
1329
1330    /**
1331     * Call wfTransactionalTimeLimit() if this request was POSTed.
1332     *
1333     * @since 1.26
1334     */
1335    protected function useTransactionalTimeLimit() {
1336        if ( $this->getRequest()->wasPosted() ) {
1337            wfTransactionalTimeLimit();
1338        }
1339    }
1340
1341    /**
1342     * Reset static caches of database state.
1343     *
1344     * @internal For testing only
1345     */
1346    public static function clearCacheForTest(): void {
1347        if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1348            throw new LogicException( 'Not allowed outside tests' );
1349        }
1350        self::$filterIDsCache = [];
1351    }
1352
1353    /**
1354     * Filter out-of-range values from a list of positive integer IDs
1355     *
1356     * @since 1.33
1357     * @param string[][] $fields Array of table and field pairs to check
1358     * @param (string|int)[] $ids IDs to filter. Strings in the array are
1359     *  expected to be stringified integers.
1360     * @return (string|int)[] Filtered IDs.
1361     */
1362    protected function filterIDs( $fields, array $ids ) {
1363        $min = INF;
1364        $max = 0;
1365        foreach ( $fields as [ $table, $field ] ) {
1366            if ( isset( self::$filterIDsCache[$table][$field] ) ) {
1367                $row = self::$filterIDsCache[$table][$field];
1368            } else {
1369                $row = $this->getDB()->newSelectQueryBuilder()
1370                    ->select( [ 'min_id' => "MIN($field)", 'max_id' => "MAX($field)" ] )
1371                    ->from( $table )
1372                    ->caller( __METHOD__ )->fetchRow();
1373                self::$filterIDsCache[$table][$field] = $row;
1374            }
1375            $min = min( $min, $row->min_id );
1376            $max = max( $max, $row->max_id );
1377        }
1378        return array_filter( $ids, static function ( $id ) use ( $min, $max ) {
1379            return ( ( is_int( $id ) && $id >= 0 ) || ctype_digit( (string)$id ) )
1380                && $id >= $min && $id <= $max;
1381        } );
1382    }
1383
1384    // endregion -- end of utility methods
1385
1386    /***************************************************************************/
1387    // region   Warning and error reporting
1388    /** @name   Warning and error reporting */
1389
1390    /**
1391     * Add a warning for this module.
1392     *
1393     * Users should monitor this section to notice any changes in the API.
1394     *
1395     * Multiple calls to this function will result in multiple warning messages.
1396     *
1397     * If $msg is not an ApiMessage, the message code will be derived from the
1398     * message key by stripping any "apiwarn-" or "apierror-" prefix.
1399     *
1400     * @since 1.29
1401     * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addWarning()
1402     * @param string|null $code See ApiErrorFormatter::addWarning()
1403     * @param array|null $data See ApiErrorFormatter::addWarning()
1404     */
1405    public function addWarning( $msg, $code = null, $data = null ) {
1406        $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1407    }
1408
1409    /**
1410     * Add a deprecation warning for this module.
1411     *
1412     * A combination of $this->addWarning() and $this->logFeatureUsage()
1413     *
1414     * @since 1.29
1415     * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addWarning()
1416     *   Consider passing `$this->deprecationMsg()` here.
1417     * @param string|null $feature See ApiBase::logFeatureUsage()
1418     * @param array|null $data See ApiErrorFormatter::addWarning()
1419     */
1420    public function addDeprecation( $msg, $feature, $data = [] ) {
1421        $data = (array)$data;
1422        if ( $feature !== null ) {
1423            $data['feature'] = $feature;
1424            $this->logFeatureUsage( $feature );
1425        }
1426        $this->addWarning( $msg, 'deprecation', $data );
1427
1428        // No real need to deduplicate here, ApiErrorFormatter does that for
1429        // us (assuming the hook is deterministic).
1430        $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1431        $this->getHookRunner()->onApiDeprecationHelp( $msgs );
1432        if ( count( $msgs ) > 1 ) {
1433            $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1434            $msg = ( new RawMessage( $key ) )->params( $msgs );
1435        } else {
1436            $msg = reset( $msgs );
1437        }
1438        $this->getMain()->addWarning( $msg, 'deprecation-help' );
1439    }
1440
1441    /**
1442     * Add an error for this module without aborting
1443     *
1444     * If $msg is not an ApiMessage, the message code will be derived from the
1445     * message key by stripping any "apiwarn-" or "apierror-" prefix.
1446     *
1447     * @note If you want to abort processing, use self::dieWithError() instead.
1448     * @since 1.29
1449     * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addError()
1450     * @param string|null $code See ApiErrorFormatter::addError()
1451     * @param array|null $data See ApiErrorFormatter::addError()
1452     */
1453    public function addError( $msg, $code = null, $data = null ) {
1454        $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1455    }
1456
1457    /**
1458     * Add warnings and/or errors from a Status
1459     *
1460     * @note If you want to abort processing, use self::dieStatus() instead.
1461     * @since 1.29
1462     * @param StatusValue $status
1463     * @param string[] $types 'warning' and/or 'error'
1464     * @param string[] $filter Message keys to filter out (since 1.33)
1465     */
1466    public function addMessagesFromStatus(
1467        StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
1468    ) {
1469        $this->getErrorFormatter()->addMessagesFromStatus(
1470            $this->getModulePath(), $status, $types, $filter
1471        );
1472    }
1473
1474    /**
1475     * Abort execution with an error
1476     *
1477     * If $msg is not an ApiMessage, the message code will be derived from the
1478     * message key by stripping any "apiwarn-" or "apierror-" prefix.
1479     *
1480     * @since 1.29
1481     * @param string|array|MessageSpecifier $msg See ApiErrorFormatter::addError()
1482     * @param string|null $code See ApiErrorFormatter::addError()
1483     * @param array|null $data See ApiErrorFormatter::addError()
1484     * @param int $httpCode HTTP error code to use
1485     * @throws ApiUsageException always
1486     * @return never
1487     */
1488    public function dieWithError( $msg, $code = null, $data = null, $httpCode = 0 ): never {
1489        throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1490    }
1491
1492    /**
1493     * Abort execution with an error derived from a throwable
1494     *
1495     * @since 1.29
1496     * @param Throwable $exception See ApiErrorFormatter::getMessageFromException()
1497     * @param array $options See ApiErrorFormatter::getMessageFromException()
1498     * @throws ApiUsageException always
1499     * @return never
1500     */
1501    public function dieWithException( Throwable $exception, array $options = [] ): never {
1502        $this->dieWithError(
1503            $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1504        );
1505    }
1506
1507    /**
1508     * Throw an ApiUsageException, which will (if uncaught) call the main module's
1509     * error handler and die with an error message including block info.
1510     *
1511     * @since 1.27
1512     * @param Block $block The block used to generate the ApiUsageException
1513     * @throws ApiUsageException always
1514     * @return never
1515     */
1516    public function dieBlocked( Block $block ): never {
1517        $blockErrorFormatter = MediaWikiServices::getInstance()->getFormatterFactory()
1518            ->getBlockErrorFormatter( $this->getContext() );
1519
1520        $msg = $blockErrorFormatter->getMessage(
1521            $block,
1522            $this->getUser(),
1523            null,
1524            $this->getRequest()->getIP()
1525        );
1526
1527        $this->dieWithError( $msg );
1528    }
1529
1530    /**
1531     * Throw an ApiUsageException based on the Status object.
1532     *
1533     * @since 1.22
1534     * @since 1.29 Accepts a StatusValue
1535     * @param StatusValue $status
1536     * @throws ApiUsageException always
1537     * @return never
1538     */
1539    public function dieStatus( StatusValue $status ): never {
1540        if ( $status->isGood() ) {
1541            throw new InvalidArgumentException( 'Successful status passed to ApiBase::dieStatus' );
1542        }
1543
1544        foreach ( self::MESSAGE_CODE_MAP as $msg => [ $apiMsg, $code ] ) {
1545            if ( $status->hasMessage( $msg ) ) {
1546                $status->replaceMessage( $msg, ApiMessage::create( $apiMsg, $code ) );
1547            }
1548        }
1549
1550        if (
1551            $status instanceof PermissionStatus
1552            && $status->isRateLimitExceeded()
1553            && !$status->hasMessage( 'apierror-ratelimited' )
1554        ) {
1555            $status->fatal( ApiMessage::create( 'apierror-ratelimited', 'ratelimited' ) );
1556        }
1557
1558        // ApiUsageException needs a fatal status, but this method has
1559        // historically accepted any non-good status. Convert it if necessary.
1560        $status->setOK( false );
1561        if ( !$status->getMessages( 'error' ) ) {
1562            $newStatus = Status::newGood();
1563            foreach ( $status->getMessages( 'warning' ) as $err ) {
1564                $newStatus->fatal( $err );
1565            }
1566            if ( !$newStatus->getMessages( 'error' ) ) {
1567                $newStatus->fatal( 'unknownerror-nocode' );
1568            }
1569            $status = $newStatus;
1570        }
1571
1572        throw new ApiUsageException( $this, $status );
1573    }
1574
1575    /**
1576     * Helper function for readonly errors.
1577     *
1578     * @throws ApiUsageException always
1579     * @return never
1580     */
1581    public function dieReadOnly(): never {
1582        $this->dieWithError(
1583            'apierror-readonly',
1584            'readonly',
1585            [ 'readonlyreason' => MediaWikiServices::getInstance()->getReadOnlyMode()->getReason() ]
1586        );
1587    }
1588
1589    /**
1590     * Helper function for permission-denied errors.
1591     *
1592     * @since 1.29
1593     * @param string|string[] $rights
1594     * @throws ApiUsageException if the user doesn't have any of the rights.
1595     *  The error message is based on $rights[0].
1596     */
1597    public function checkUserRightsAny( $rights ) {
1598        $rights = (array)$rights;
1599        if ( !$this->getAuthority()->isAllowedAny( ...$rights ) ) {
1600            $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1601        }
1602    }
1603
1604    /**
1605     * Helper function for permission-denied errors.
1606     *
1607     * @param PageIdentity $pageIdentity
1608     * @param string|string[] $actions
1609     * @param array $options Additional options
1610     *  - user: (User) User to use rather than $this->getUser().
1611     *  - autoblock: (bool, default false) Whether to spread autoblocks.
1612     * @phan-param array{user?:User,autoblock?:bool} $options
1613     *
1614     * @throws ApiUsageException if the user doesn't have all the necessary rights.
1615     *
1616     * @since 1.29
1617     * @since 1.33 Changed the third parameter from $user to $options.
1618     * @since 1.36 deprecated passing LinkTarget as first parameter
1619     */
1620    public function checkTitleUserPermissions(
1621        PageIdentity $pageIdentity,
1622        $actions,
1623        array $options = []
1624    ) {
1625        $authority = $options['user'] ?? $this->getAuthority();
1626        $status = new PermissionStatus();
1627        foreach ( (array)$actions as $action ) {
1628            if ( $this->isWriteMode() ) {
1629                $authority->authorizeWrite( $action, $pageIdentity, $status );
1630            } else {
1631                $authority->authorizeRead( $action, $pageIdentity, $status );
1632            }
1633        }
1634        if ( !$status->isGood() ) {
1635            if ( !empty( $options['autoblock'] ) ) {
1636                $this->getUser()->spreadAnyEditBlock();
1637            }
1638            $this->dieStatus( $status );
1639        }
1640    }
1641
1642    /**
1643     * Will only set a warning instead of failing if the global $wgDebugAPI
1644     * is set to true.
1645     *
1646     * Otherwise, it behaves exactly as self::dieWithError().
1647     *
1648     * @since 1.29
1649     * @param string|array|Message $msg Message definition, see Message::newFromSpecifier()
1650     * @param string|null $code
1651     * @param array|null $data
1652     * @param int|null $httpCode
1653     * @throws ApiUsageException
1654     */
1655    public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1656        if ( $this->getConfig()->get( MainConfigNames::DebugAPI ) !== true ) {
1657            $this->dieWithError( $msg, $code, $data, $httpCode ?? 0 );
1658        } else {
1659            $this->addWarning( $msg, $code, $data );
1660        }
1661    }
1662
1663    /**
1664     * Parse the 'continue' parameter in the usual format and validate the types of each part,
1665     * or die with the 'badcontinue' error if the format, types, or the number of parts is wrong.
1666     *
1667     * @param string $continue Value of 'continue' parameter obtained from extractRequestParams()
1668     * @param string[] $types Types of the expected parts in order, 'string', 'int' or 'timestamp'
1669     * @return mixed[] Array containing strings, integers or timestamps
1670     * @throws ApiUsageException
1671     * @since 1.40
1672     */
1673    protected function parseContinueParamOrDie( string $continue, array $types ): array {
1674        $cont = explode( '|', $continue );
1675        $this->dieContinueUsageIf( count( $cont ) != count( $types ) );
1676
1677        foreach ( $cont as $i => &$value ) {
1678            switch ( $types[$i] ) {
1679                case 'string':
1680                    // Do nothing
1681                    break;
1682                case 'int':
1683                    $this->dieContinueUsageIf( $value !== (string)(int)$value );
1684                    $value = (int)$value;
1685                    break;
1686                case 'timestamp':
1687                    try {
1688                        $dbTs = $this->getDB()->timestamp( $value );
1689                    } catch ( TimestampException ) {
1690                        $dbTs = false;
1691                    }
1692                    $this->dieContinueUsageIf( $value !== $dbTs );
1693                    break;
1694                default:
1695                    throw new InvalidArgumentException( "Unknown type '{$types[$i]}'" );
1696            }
1697        }
1698
1699        return $cont;
1700    }
1701
1702    /**
1703     * Die with the 'badcontinue' error.
1704     *
1705     * This call is common enough to make it into the base method.
1706     *
1707     * @param bool $condition Will only die if this value is true
1708     * @throws ApiUsageException
1709     * @since 1.21
1710     * @phan-assert-false-condition $condition
1711     */
1712    protected function dieContinueUsageIf( $condition ) {
1713        if ( $condition ) {
1714            $this->dieWithError( 'apierror-badcontinue' );
1715        }
1716    }
1717
1718    /**
1719     * Internal code errors should be reported with this method.
1720     *
1721     * @param string $method Method or function name
1722     * @param string $message Error message
1723     * @return never
1724     */
1725    protected static function dieDebug( $method, $message ): never {
1726        throw new LogicException( "Internal error in $method: $message" );
1727    }
1728
1729    /**
1730     * Write logging information for API features to a debug log, for usage
1731     * analysis.
1732     *
1733     * @note Consider using $this->addDeprecation() instead to both warn and log.
1734     * @param string $feature Feature being used.
1735     */
1736    public function logFeatureUsage( $feature ) {
1737        static $loggedFeatures = [];
1738
1739        // Only log each feature once per request. We can get multiple calls from calls to
1740        // extractRequestParams() with different values for 'parseLimit', for example.
1741        if ( isset( $loggedFeatures[$feature] ) ) {
1742            return;
1743        }
1744        $loggedFeatures[$feature] = true;
1745
1746        $request = $this->getRequest();
1747        $ctx = [
1748            'feature' => $feature,
1749            // Replace spaces with underscores in 'username' for historical reasons.
1750            'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
1751            'clientip' => $request->getIP(),
1752            'referer' => (string)$request->getHeader( 'Referer' ),
1753            'agent' => $this->getMain()->getUserAgent(),
1754        ];
1755
1756        // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
1757        $s = '"' . addslashes( $ctx['feature'] ) . '"' .
1758            ' "' . wfUrlencode( $ctx['username'] ) . '"' .
1759            ' "' . $ctx['clientip'] . '"' .
1760            ' "' . addslashes( $ctx['referer'] ) . '"' .
1761            ' "' . addslashes( $ctx['agent'] ) . '"';
1762
1763        wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
1764
1765        $this->getHookRunner()->onApiLogFeatureUsage(
1766            $feature,
1767            [
1768                'userName' => $this->getUser()->getName(),
1769                'userAgent' => $this->getMain()->getUserAgent(),
1770                'ipAddress' => $request->getIP()
1771            ]
1772        );
1773    }
1774
1775    // endregion -- end of warning and error reporting
1776
1777    /***************************************************************************/
1778    // region   Help message generation
1779    /** @name   Help message generation */
1780
1781    /**
1782     * Return the summary message.
1783     *
1784     * This is a one-line description of the module, suitable for display in a
1785     * list of modules.
1786     *
1787     * @since 1.30
1788     * @stable to override
1789     * @return string|array|Message Message definition, see Message::newFromSpecifier()
1790     */
1791    protected function getSummaryMessage() {
1792        return "apihelp-{$this->getModulePath()}-summary";
1793    }
1794
1795    /**
1796     * Return the extended help text message.
1797     *
1798     * This is additional text to display at the top of the help section, below
1799     * the summary.
1800     *
1801     * @since 1.30
1802     * @stable to override
1803     * @return string|array|Message Message definition, see Message::newFromSpecifier().
1804     *   When returning an array, the definition may also specify fallback keys.
1805     */
1806    protected function getExtendedDescription() {
1807        return [ [
1808            "apihelp-{$this->getModulePath()}-extended-description",
1809            'api-help-no-extended-description',
1810        ] ];
1811    }
1812
1813    /**
1814     * Get the final module summary
1815     *
1816     * @since 1.30
1817     * @stable to override
1818     * @return Message
1819     */
1820    public function getFinalSummary() {
1821        return $this->msg(
1822            Message::newFromSpecifier( $this->getSummaryMessage() ),
1823            $this->getModulePrefix(),
1824            $this->getModuleName(),
1825            $this->getModulePath(),
1826        );
1827    }
1828
1829    /**
1830     * Get the final module description, after hooks have had a chance to tweak it as
1831     * needed.
1832     *
1833     * @since 1.25, returns Message[] rather than string[]
1834     * @return Message[]
1835     */
1836    public function getFinalDescription() {
1837        $summary = $this->msg(
1838            Message::newFromSpecifier( $this->getSummaryMessage() ),
1839            $this->getModulePrefix(),
1840            $this->getModuleName(),
1841            $this->getModulePath(),
1842        );
1843        $extendedDesc = $this->getExtendedDescription();
1844        if ( is_array( $extendedDesc ) && is_array( $extendedDesc[0] ) ) {
1845            // The definition in getExtendedDescription() may also specify fallback keys. This is weird,
1846            // and it was never needed for other API doc messages, so it's only supported here.
1847            $extendedDesc = Message::newFallbackSequence( $extendedDesc[0] )
1848                ->params( array_slice( $extendedDesc, 1 ) );
1849        }
1850        $extendedDesc = $this->msg(
1851            Message::newFromSpecifier( $extendedDesc ),
1852            $this->getModulePrefix(),
1853            $this->getModuleName(),
1854            $this->getModulePath(),
1855        );
1856
1857        $msgs = [ $summary, $extendedDesc ];
1858
1859        $this->getHookRunner()->onAPIGetDescriptionMessages( $this, $msgs );
1860
1861        return $msgs;
1862    }
1863
1864    /**
1865     * Get the final list of parameters, after hooks have had a chance to
1866     * tweak it as needed.
1867     *
1868     * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1869     * @return array
1870     * @since 1.21 $flags param added
1871     */
1872    public function getFinalParams( $flags = 0 ) {
1873        // @phan-suppress-next-line PhanParamTooMany
1874        $params = $this->getAllowedParams( $flags );
1875        if ( !$params ) {
1876            $params = [];
1877        }
1878
1879        if ( $this->needsToken() ) {
1880            $params['token'] = [
1881                ParamValidator::PARAM_TYPE => 'string',
1882                ParamValidator::PARAM_REQUIRED => true,
1883                ParamValidator::PARAM_SENSITIVE => true,
1884                self::PARAM_HELP_MSG => [
1885                    'api-help-param-token',
1886                    $this->needsToken(),
1887                ],
1888            ] + ( $params['token'] ?? [] );
1889        }
1890
1891        $this->getHookRunner()->onAPIGetAllowedParams( $this, $params, $flags );
1892
1893        return $params;
1894    }
1895
1896    /**
1897     * Get final parameter descriptions, after hooks have had a chance to tweak it as
1898     * needed.
1899     *
1900     * @since 1.25, returns array of Message[] rather than array of string[]
1901     * @return array Keys are parameter names, values are arrays of Message objects
1902     */
1903    public function getFinalParamDescription() {
1904        $prefix = $this->getModulePrefix();
1905        $name = $this->getModuleName();
1906        $path = $this->getModulePath();
1907
1908        $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
1909        $msgs = [];
1910        foreach ( $params as $param => $settings ) {
1911            if ( !is_array( $settings ) ) {
1912                $settings = [];
1913            }
1914
1915            $msg = isset( $settings[self::PARAM_HELP_MSG] )
1916                ? Message::newFromSpecifier( $settings[self::PARAM_HELP_MSG] )
1917                : Message::newFallbackSequence( [ "apihelp-$path-param-$param", 'api-help-param-no-description' ] );
1918            $msg = $this->msg( $msg, $prefix, $param, $name, $path );
1919            $msgs[$param] = [ $msg ];
1920
1921            if ( isset( $settings[ParamValidator::PARAM_TYPE] ) &&
1922                $settings[ParamValidator::PARAM_TYPE] === 'submodule'
1923            ) {
1924                if ( isset( $settings[SubmoduleDef::PARAM_SUBMODULE_MAP] ) ) {
1925                    $map = $settings[SubmoduleDef::PARAM_SUBMODULE_MAP];
1926                } else {
1927                    $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
1928                    $map = [];
1929                    foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
1930                        $map[$submoduleName] = $prefix . $submoduleName;
1931                    }
1932                }
1933
1934                $submodules = [];
1935                $submoduleFlags = []; // for sorting: higher flags are sorted later
1936                $submoduleNames = []; // for sorting: lexicographical, ascending
1937                foreach ( $map as $v => $m ) {
1938                    $isDeprecated = false;
1939                    $isInternal = false;
1940                    $summary = null;
1941                    try {
1942                        $submod = $this->getModuleFromPath( $m );
1943                        if ( $submod ) {
1944                            $summary = $submod->getFinalSummary();
1945                            $isDeprecated = $submod->isDeprecated();
1946                            $isInternal = $submod->isInternal();
1947                            if ( $isDeprecated ) {
1948                                // Provide a deprecation message if available
1949                                $isDeprecated = $submod->deprecationMsg() ??
1950                                    $isDeprecated;
1951                            }
1952                        }
1953                    } catch ( ApiUsageException ) {
1954                        // Ignore
1955                    }
1956                    if ( $summary ) {
1957                        $key = $summary->getKey();
1958                        $params = $summary->getParams();
1959                    } else {
1960                        $key = 'api-help-undocumented-module';
1961                        $params = [ $m ];
1962                    }
1963                    $m = new ApiHelpParamValueMessage(
1964                        "[[Special:ApiHelp/$m|$v]]",
1965                        $key,
1966                        $params,
1967                        $isDeprecated,
1968                        $isInternal
1969                    );
1970                    $submodules[] = $m->setContext( $this->getContext() );
1971                    $submoduleFlags[] = ( $isDeprecated ? 1 : 0 ) | ( $isInternal ? 2 : 0 );
1972                    $submoduleNames[] = $v;
1973                }
1974                // sort $submodules by $submoduleFlags and $submoduleNames
1975                array_multisort( $submoduleFlags, $submoduleNames, $submodules );
1976                $msgs[$param] = array_merge( $msgs[$param], $submodules );
1977            } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
1978                // ! keep these checks in sync with \MediaWiki\Api\Validator\ApiParamValidator::checkSettings
1979                if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
1980                    self::dieDebug( __METHOD__,
1981                        'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
1982                }
1983                $isArrayOfStrings = is_array( $settings[ParamValidator::PARAM_TYPE] )
1984                    || (
1985                        $settings[ParamValidator::PARAM_TYPE] === 'string'
1986                        && ( $settings[ParamValidator::PARAM_ISMULTI] ?? false )
1987                    );
1988                if ( !$isArrayOfStrings ) {
1989                    self::dieDebug( __METHOD__,
1990                        'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
1991                        'ParamValidator::PARAM_TYPE is an array or it is \'string\' and ' .
1992                        'ParamValidator::PARAM_ISMULTI is true' );
1993                }
1994
1995                $values = is_array( $settings[ParamValidator::PARAM_TYPE] ) ?
1996                    $settings[ParamValidator::PARAM_TYPE] :
1997                    array_keys( $settings[self::PARAM_HELP_MSG_PER_VALUE] );
1998                $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
1999                $deprecatedValues = $settings[EnumDef::PARAM_DEPRECATED_VALUES] ?? [];
2000                $internalValues = $settings[EnumDef::PARAM_INTERNAL_VALUES] ?? [];
2001
2002                foreach ( $values as $value ) {
2003                    $msg = Message::newFromSpecifier( $valueMsgs[$value] ?? "apihelp-$path-paramvalue-$param-$value" );
2004                    $m = $this->msg( $msg, [ $prefix, $param, $name, $path, $value ] );
2005                    $deprecationMsg = $deprecatedValues[$value] ?? false;
2006                    $deprecationMsg = (
2007                        is_bool( $deprecationMsg ) || $deprecationMsg instanceof MessageSpecifier
2008                    ) ? $deprecationMsg : ApiMessage::create( $deprecationMsg );
2009
2010                    $m = new ApiHelpParamValueMessage(
2011                        $value,
2012                        // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
2013                        [ $m->getKey(), 'api-help-param-no-description' ],
2014                        $m->getParams(),
2015                        deprecated: $deprecationMsg,
2016                        internal: $internalValues[$value] ?? false,
2017                    );
2018                    $msgs[$param][] = $m->setContext( $this->getContext() );
2019                }
2020            }
2021
2022            if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2023                if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2024                    self::dieDebug( __METHOD__,
2025                        'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2026                }
2027                foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2028                    $m = $this->msg( Message::newFromSpecifier( $m ), [ $prefix, $param, $name, $path ] );
2029                    $msgs[$param][] = $m;
2030                }
2031            }
2032        }
2033
2034        $this->getHookRunner()->onAPIGetParamDescriptionMessages( $this, $msgs );
2035
2036        return $msgs;
2037    }
2038
2039    /**
2040     * Generates the list of flags for the help screen and for action=paraminfo.
2041     *
2042     * Corresponding messages: api-help-flag-deprecated,
2043     * api-help-flag-internal, api-help-flag-readrights,
2044     * api-help-flag-writerights, api-help-flag-mustbeposted
2045     *
2046     * @return string[]
2047     */
2048    protected function getHelpFlags() {
2049        $flags = [];
2050
2051        if ( $this->isDeprecated() ) {
2052            $flags[] = 'deprecated';
2053        }
2054        if ( $this->isInternal() ) {
2055            $flags[] = 'internal';
2056        }
2057        if ( $this->isReadMode() ) {
2058            $flags[] = 'readrights';
2059        }
2060        if ( $this->isWriteMode() ) {
2061            $flags[] = 'writerights';
2062        }
2063        if ( $this->mustBePosted() ) {
2064            $flags[] = 'mustbeposted';
2065        }
2066
2067        return $flags;
2068    }
2069
2070    /**
2071     * Returns information about the source of this module, if known
2072     *
2073     * Returned array is an array with the following keys:
2074     *  - path: Install path
2075     *  - name: Extension name, or "MediaWiki" for core
2076     *  - namemsg: (optional) i18n message key for a display name
2077     *  - license-name: (optional) Name of license
2078     *
2079     * @return array|null
2080     */
2081    protected function getModuleSourceInfo() {
2082        if ( $this->mModuleSource !== false ) {
2083            return $this->mModuleSource;
2084        }
2085
2086        // First, try to find where the module comes from...
2087        $rClass = new ReflectionClass( $this );
2088        $path = $rClass->getFileName();
2089        if ( !$path ) {
2090            // No path known?
2091            $this->mModuleSource = null;
2092            return null;
2093        }
2094        $path = realpath( $path ) ?: $path;
2095
2096        // Build a map of extension directories to extension info
2097        if ( self::$extensionInfo === null ) {
2098            $extDir = $this->getConfig()->get( MainConfigNames::ExtensionDirectory );
2099            $baseDir = MW_INSTALL_PATH;
2100            self::$extensionInfo = [
2101                realpath( __DIR__ ) ?: __DIR__ => [
2102                    'path' => $baseDir,
2103                    'name' => 'MediaWiki',
2104                    'license-name' => 'GPL-2.0-or-later',
2105                ],
2106                realpath( "$baseDir/extensions" ) ?: "$baseDir/extensions" => null,
2107                realpath( $extDir ) ?: $extDir => null,
2108            ];
2109            $keep = [
2110                'path' => null,
2111                'name' => null,
2112                'namemsg' => null,
2113                'license-name' => null,
2114            ];
2115            $credits = SpecialVersion::getCredits( ExtensionRegistry::getInstance(), $this->getConfig() );
2116            foreach ( $credits as $group ) {
2117                foreach ( $group as $ext ) {
2118                    if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2119                        // This shouldn't happen, but does anyway.
2120                        continue;
2121                    }
2122
2123                    $extpath = $ext['path'];
2124                    if ( !is_dir( $extpath ) ) {
2125                        $extpath = dirname( $extpath );
2126                    }
2127                    self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2128                        array_intersect_key( $ext, $keep );
2129                }
2130            }
2131        }
2132
2133        // Now traverse parent directories until we find a match or run out of parents.
2134        do {
2135            if ( array_key_exists( $path, self::$extensionInfo ) ) {
2136                // Found it!
2137                $this->mModuleSource = self::$extensionInfo[$path];
2138                return $this->mModuleSource;
2139            }
2140
2141            $oldpath = $path;
2142            $path = dirname( $path );
2143        } while ( $path !== $oldpath );
2144
2145        // No idea what extension this might be.
2146        $this->mModuleSource = null;
2147        return null;
2148    }
2149
2150    /**
2151     * Called from ApiHelp before the pieces are joined together and returned.
2152     *
2153     * This exists mainly for ApiMain to add the Permissions and Credits
2154     * sections. Other modules probably don't need it.
2155     *
2156     * @deprecated since 1.47
2157     *
2158     * @stable to override
2159     * @param string[] &$help Array of help data
2160     * @param array $options Options passed to ApiHelp::getHelp
2161     * @param array &$tocData If a TOC is being generated, this array has keys
2162     *   as anchors in the page and SectionMetadata values.
2163     */
2164    public function modifyHelp( array &$help, array $options, array &$tocData ) {
2165        wfDeprecated( __METHOD__, '1.47' );
2166    }
2167
2168    // endregion -- end of help message generation
2169
2170    /***************************************************************************/
2171    // region   Data Unified metrics
2172    /** @name   Data Unified metrics methods */
2173
2174    /**
2175     * Record unified metrics for the API
2176     *
2177     * @param array $detailLabels Additional or override labels for the metrics
2178     */
2179    protected function recordUnifiedMetrics( $detailLabels = [] ) {
2180        // The concept of "module" is different in Action API and REST API
2181        // in REST API, it represents the "collection" of endpoints
2182        // in Action API, it represents the "module" of the API (or an endpoint)
2183        // In order to make the metrics consistent, we want the module to also reflect
2184        // the "collection" of endpoints. The closest we can get is to use the namespace
2185        // of the API module, and get the area of the code or extension it belongs to.
2186        // If module exists, we'll take the namespace for it, otherwise fall back on
2187        // the current namespace. In both cases we'll remove the class name to only keep
2188        // the namespace.
2189        // Since this method can also be called from module classes (ApiQuery, etc)
2190        // we need to allow for accepting the submodule's class name, too, if it's given.
2191        $fullClass = get_class( $this );
2192        $moduleNamespace = substr( $fullClass, 0, strrpos( $fullClass, '\\' ) );
2193
2194        // Get the endpoint representation, which for the moment is the module name.
2195        $endpoint = $this->getModuleName();
2196
2197        // The "path" should give us useful and consistent information about the endpoint.
2198        // The ->getModulePath() method should give us a string wih the module parent and
2199        // its own name, which should be enough to identify the endpoint and work with
2200        // RegEx patterns to extract information from the path.
2201        $path = $this->getModulePath();
2202
2203        // Unified metrics
2204        $metricsLabels = array_merge( [
2205            // This should represent the "collection" of endpoints
2206            'api_module' => $moduleNamespace,
2207            // This is the endpoint that is being executed
2208            'api_endpoint' => $endpoint,
2209            'path' => $path,
2210            'method' => $this->getRequest()->getMethod(),
2211            'status' => "200", // Success
2212        ], $detailLabels );
2213
2214        $approvedLabels = [
2215            'api_module',
2216            'api_endpoint',
2217            'path',
2218            'method',
2219            'status',
2220        ];
2221
2222        // Hit metrics
2223        $metricHitStats = $this->getMain()->getStatsFactory()->getCounter( 'action_api_modules_hit_total' )
2224            ->setLabel( 'api_type', 'ACTION_API' );
2225        foreach ( $approvedLabels as $label ) {
2226            // Set a fallback value for empty strings
2227            $value = (
2228                array_key_exists( $label, $metricsLabels ) &&
2229                is_string( $metricsLabels[$label] ) &&
2230                trim( $metricsLabels[$label] ) !== ''
2231            ) ? $metricsLabels[$label] : 'EMPTY_VALUE';
2232            $metricHitStats->setLabel( $label, $value );
2233        }
2234        $metricHitStats->increment();
2235    }
2236
2237    // endregion -- end of Unified metrics methods
2238}
2239
2240/*
2241 * This file uses VisualStudio style region/endregion fold markers which are
2242 * recognised by PHPStorm. If modelines are enabled, the following editor
2243 * configuration will also enable folding in vim, if it is in the last 5 lines
2244 * of the file. We also use "@name" which creates sections in Doxygen.
2245 *
2246 * vim: foldmarker=//\ region,//\ endregion foldmethod=marker
2247 */
2248
2249/** @deprecated class alias since 1.43 */
2250class_alias( ApiBase::class, 'ApiBase' );