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