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