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