Debian Codegraph @

includes/api/Validator/ApiParamValidator.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Api\Validator;
4
5 use Exception;
6 use MediaWiki\Api\ApiBase;
7 use MediaWiki\Api\ApiMain;
8 use MediaWiki\Api\ApiMessage;
9 use MediaWiki\Api\ApiUsageException;
10 use MediaWiki\Message\Converter as MessageConverter;
11 use MediaWiki\Message\Message;
12 use MediaWiki\ParamValidator\TypeDef\NamespaceDef;
13 use MediaWiki\ParamValidator\TypeDef\TagsDef;
14 use MediaWiki\ParamValidator\TypeDef\TitleDef;
15 use MediaWiki\ParamValidator\TypeDef\UserDef;
16 use Wikimedia\Message\DataMessageValue;
17 use Wikimedia\Message\MessageValue;
18 use Wikimedia\ObjectFactory\ObjectFactory;
19 use Wikimedia\ParamValidator\ParamValidator;
20 use Wikimedia\ParamValidator\TypeDef\EnumDef;
21 use Wikimedia\ParamValidator\TypeDef\ExpiryDef;
22 use Wikimedia\ParamValidator\TypeDef\IntegerDef;
23 use Wikimedia\ParamValidator\TypeDef\LimitDef;
24 use Wikimedia\ParamValidator\TypeDef\PasswordDef;
25 use Wikimedia\ParamValidator\TypeDef\PresenceBooleanDef;
26 use Wikimedia\ParamValidator\TypeDef\StringDef;
27 use Wikimedia\ParamValidator\TypeDef\TimestampDef;
28 use Wikimedia\ParamValidator\TypeDef\UploadDef;
29 use Wikimedia\ParamValidator\ValidationException;
30 use Wikimedia\RequestTimeout\TimeoutException;
31
32 /**
33 * This wraps a bunch of the API-specific parameter validation logic.
34 *
35 * It's intended to be used in ApiMain by composition.
36 *
37 * @since 1.35
38 * @ingroup API
39 */
40 class ApiParamValidator {
41
42 /** @var ParamValidator */
43 private $paramValidator;
44
45 /** @var MessageConverter */
46 private $messageConverter;
47
48 /** Type defs for ParamValidator */
49 private const TYPE_DEFS = [
50 'boolean' => [ 'class' => PresenceBooleanDef::class ],
51 'enum' => [ 'class' => EnumDef::class ],
52 'expiry' => [ 'class' => ExpiryDef::class ],
53 'integer' => [ 'class' => IntegerDef::class ],
54 'limit' => [ 'class' => LimitDef::class ],
55 'namespace' => [
56 'class' => NamespaceDef::class,
57 'services' => [ 'NamespaceInfo' ],
58 ],
59 'NULL' => [
60 'class' => StringDef::class,
61 'args' => [ [
62 StringDef::OPT_ALLOW_EMPTY => true,
63 ] ],
64 ],
65 'password' => [ 'class' => PasswordDef::class ],
66 // Unlike 'string', the 'raw' type will not be subject to Unicode
67 // NFC normalization.
68 'raw' => [ 'class' => StringDef::class ],
69 'string' => [ 'class' => StringDef::class ],
70 'submodule' => [ 'class' => SubmoduleDef::class ],
71 'tags' => [
72 'class' => TagsDef::class,
73 'services' => [ 'ChangeTagsStore' ],
74 ],
75 'text' => [ 'class' => StringDef::class ],
76 'timestamp' => [
77 'class' => TimestampDef::class,
78 'args' => [ [
79 'defaultFormat' => TS_MW,
80 ] ],
81 ],
82 'title' => [
83 'class' => TitleDef::class,
84 'services' => [ 'TitleFactory' ],
85 ],
86 'user' => [
87 'class' => UserDef::class,
88 'services' => [ 'UserIdentityLookup', 'TitleParser', 'UserNameUtils' ]
89 ],
90 'upload' => [ 'class' => UploadDef::class ],
91 ];
92
93 /**
94 * @internal
95 * @param ApiMain $main
96 * @param ObjectFactory $objectFactory
97 */
98 public function __construct( ApiMain $main, ObjectFactory $objectFactory ) {
99 $this->paramValidator = new ParamValidator(
100 new ApiParamValidatorCallbacks( $main ),
101 $objectFactory,
102 [
103 'typeDefs' => self::TYPE_DEFS,
104 'ismultiLimits' => [ ApiBase::LIMIT_SML1, ApiBase::LIMIT_SML2 ],
105 ]
106 );
107 $this->messageConverter = new MessageConverter();
108 }
109
110 /**
111 * List known type names
112 * @return string[]
113 */
114 public function knownTypes(): array {
115 return $this->paramValidator->knownTypes();
116 }
117
118 /**
119 * Map deprecated styles for messages for ParamValidator
120 * @param array $settings
121 * @return array
122 */
123 private function mapDeprecatedSettingsMessages( array $settings ): array {
124 if ( isset( $settings[EnumDef::PARAM_DEPRECATED_VALUES] ) ) {
125 foreach ( $settings[EnumDef::PARAM_DEPRECATED_VALUES] as &$v ) {
126 if ( $v === null || $v === true || $v instanceof MessageValue ) {
127 continue;
128 }
129
130 // Convert the message specification to a DataMessageValue. Flag in the data
131 // that it was so converted, so ApiParamValidatorCallbacks::recordCondition() can
132 // take that into account.
133 $msg = $this->messageConverter->convertMessage( ApiMessage::create( $v ) );
134 $v = DataMessageValue::new(
135 $msg->getKey(),
136 $msg->getParams(),
137 'bogus',
138 [ '💩' => 'back-compat' ]
139 );
140 }
141 unset( $v );
142 }
143
144 return $settings;
145 }
146
147 /**
148 * Adjust certain settings where ParamValidator differs from historical Action API behavior
149 * @param array|mixed $settings
150 * @return array
151 */
152 public function normalizeSettings( $settings ): array {
153 if ( is_array( $settings ) ) {
154 if ( !isset( $settings[ParamValidator::PARAM_IGNORE_UNRECOGNIZED_VALUES] ) ) {
155 $settings[ParamValidator::PARAM_IGNORE_UNRECOGNIZED_VALUES] = true;
156 }
157
158 if ( !isset( $settings[IntegerDef::PARAM_IGNORE_RANGE] ) ) {
159 $settings[IntegerDef::PARAM_IGNORE_RANGE] = empty( $settings[ApiBase::PARAM_RANGE_ENFORCE] );
160 }
161
162 $settings = $this->mapDeprecatedSettingsMessages( $settings );
163 }
164
165 return $this->paramValidator->normalizeSettings( $settings );
166 }
167
168 /**
169 * Check an API settings message
170 * @param ApiBase $module
171 * @param string $key
172 * @param string|array|Message $value Message definition, see Message::newFromSpecifier()
173 * @param array &$ret
174 */
175 private function checkSettingsMessage( ApiBase $module, string $key, $value, array &$ret ): void {
176 try {
177 $msg = Message::newFromSpecifier( $value );
178 $ret['messages'][] = $this->messageConverter->convertMessage( $msg );
179 } catch ( TimeoutException $e ) {
180 throw $e;
181 } catch ( Exception $e ) {
182 $ret['issues'][] = "Message specification for $key is not valid";
183 }
184 }
185
186 /**
187 * Check settings for the Action API.
188 * @param ApiBase $module
189 * @param array $params All module params to test
190 * @param string $name Parameter to test
191 * @param array $options Options array
192 * @return array As for ParamValidator::checkSettings()
193 */
194 public function checkSettings(
195 ApiBase $module, array $params, string $name, array $options
196 ): array {
197 $options['module'] = $module;
198 $settings = $params[$name];
199 if ( is_array( $settings ) ) {
200 $settings = $this->mapDeprecatedSettingsMessages( $settings );
201 }
202 $ret = $this->paramValidator->checkSettings(
203 $module->encodeParamName( $name ), $settings, $options
204 );
205
206 $ret['allowedKeys'] = array_merge( $ret['allowedKeys'], [
207 ApiBase::PARAM_RANGE_ENFORCE, ApiBase::PARAM_HELP_MSG, ApiBase::PARAM_HELP_MSG_APPEND,
208 ApiBase::PARAM_HELP_MSG_INFO, ApiBase::PARAM_HELP_MSG_PER_VALUE, ApiBase::PARAM_TEMPLATE_VARS,
209 ] );
210
211 if ( !is_array( $settings ) ) {
212 $settings = [];
213 }
214
215 if ( !is_bool( $settings[ApiBase::PARAM_RANGE_ENFORCE] ?? false ) ) {
216 $ret['issues'][ApiBase::PARAM_RANGE_ENFORCE] = 'PARAM_RANGE_ENFORCE must be boolean, got '
217 . gettype( $settings[ApiBase::PARAM_RANGE_ENFORCE] );
218 }
219
220 $path = $module->getModulePath();
221 $this->checkSettingsMessage(
222 $module, 'PARAM_HELP_MSG', $settings[ApiBase::PARAM_HELP_MSG] ?? "apihelp-$path-param-$name", $ret
223 );
224
225 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
226 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
227 $ret['issues'][ApiBase::PARAM_HELP_MSG_APPEND] = 'PARAM_HELP_MSG_APPEND must be an array, got '
228 . gettype( $settings[ApiBase::PARAM_HELP_MSG_APPEND] );
229 } else {
230 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $k => $v ) {
231 $this->checkSettingsMessage( $module, "PARAM_HELP_MSG_APPEND[$k]", $v, $ret );
232 }
233 }
234 }
235
236 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_INFO] ) ) {
237 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_INFO] ) ) {
238 $ret['issues'][ApiBase::PARAM_HELP_MSG_INFO] = 'PARAM_HELP_MSG_INFO must be an array, got '
239 . gettype( $settings[ApiBase::PARAM_HELP_MSG_INFO] );
240 } else {
241 foreach ( $settings[ApiBase::PARAM_HELP_MSG_INFO] as $k => $v ) {
242 if ( !is_array( $v ) ) {
243 $ret['issues'][] = "PARAM_HELP_MSG_INFO[$k] must be an array, got " . gettype( $v );
244 } elseif ( !is_string( $v[0] ) ) {
245 $ret['issues'][] = "PARAM_HELP_MSG_INFO[$k][0] must be a string, got " . gettype( $v[0] );
246 } else {
247 $v[0] = "apihelp-{$path}-paraminfo-{$v[0]}";
248 $this->checkSettingsMessage( $module, "PARAM_HELP_MSG_INFO[$k]", $v, $ret );
249 }
250 }
251 }
252 }
253
254 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
255 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
256 $ret['issues'][ApiBase::PARAM_HELP_MSG_PER_VALUE] = 'PARAM_HELP_MSG_PER_VALUE must be an array,'
257 . ' got ' . gettype( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] );
258 } elseif ( !is_array( $settings[ParamValidator::PARAM_TYPE] ?? '' ) ) {
259 $ret['issues'][ApiBase::PARAM_HELP_MSG_PER_VALUE] = 'PARAM_HELP_MSG_PER_VALUE can only be used '
260 . 'with PARAM_TYPE as an array';
261 } else {
262 $values = array_map( 'strval', $settings[ParamValidator::PARAM_TYPE] );
263 foreach ( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] as $k => $v ) {
264 if ( !in_array( (string)$k, $values, true ) ) {
265 // Or should this be allowed?
266 $ret['issues'][] = "PARAM_HELP_MSG_PER_VALUE contains \"$k\", which is not in PARAM_TYPE.";
267 }
268 $this->checkSettingsMessage( $module, "PARAM_HELP_MSG_PER_VALUE[$k]", $v, $ret );
269 }
270 foreach ( $settings[ParamValidator::PARAM_TYPE] as $p ) {
271 if ( array_key_exists( $p, $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
272 continue;
273 }
274 $path = $module->getModulePath();
275 $this->checkSettingsMessage(
276 $module,
277 "PARAM_HELP_MSG_PER_VALUE[$p]",
278 "apihelp-$path-paramvalue-$name-$p",
279 $ret
280 );
281 }
282 }
283 }
284
285 if ( isset( $settings[ApiBase::PARAM_TEMPLATE_VARS] ) ) {
286 if ( !is_array( $settings[ApiBase::PARAM_TEMPLATE_VARS] ) ) {
287 $ret['issues'][ApiBase::PARAM_TEMPLATE_VARS] = 'PARAM_TEMPLATE_VARS must be an array,'
288 . ' got ' . gettype( $settings[ApiBase::PARAM_TEMPLATE_VARS] );
289 } elseif ( $settings[ApiBase::PARAM_TEMPLATE_VARS] === [] ) {
290 $ret['issues'][ApiBase::PARAM_TEMPLATE_VARS] = 'PARAM_TEMPLATE_VARS cannot be the empty array';
291 } else {
292 foreach ( $settings[ApiBase::PARAM_TEMPLATE_VARS] as $key => $target ) {
293 if ( !preg_match( '/^[^{}]+$/', $key ) ) {
294 $ret['issues'][] = "PARAM_TEMPLATE_VARS keys may not contain '{' or '}', got \"$key\"";
295 } elseif ( !str_contains( $name, '{' . $key . '}' ) ) {
296 $ret['issues'][] = "Parameter name must contain PARAM_TEMPLATE_VARS key {{$key}}";
297 }
298 if ( !is_string( $target ) && !is_int( $target ) ) {
299 $ret['issues'][] = "PARAM_TEMPLATE_VARS[$key] has invalid target type " . gettype( $target );
300 } elseif ( !isset( $params[$target] ) ) {
301 $ret['issues'][] = "PARAM_TEMPLATE_VARS[$key] target parameter \"$target\" does not exist";
302 } else {
303 $settings2 = $params[$target];
304 if ( empty( $settings2[ParamValidator::PARAM_ISMULTI] ) ) {
305 $ret['issues'][] = "PARAM_TEMPLATE_VARS[$key] target parameter \"$target\" must have "
306 . 'PARAM_ISMULTI = true';
307 }
308 if ( isset( $settings2[ApiBase::PARAM_TEMPLATE_VARS] ) ) {
309 if ( $target === $name ) {
310 $ret['issues'][] = "PARAM_TEMPLATE_VARS[$key] cannot target the parameter itself";
311 }
312 if ( array_diff(
313 $settings2[ApiBase::PARAM_TEMPLATE_VARS],
314 $settings[ApiBase::PARAM_TEMPLATE_VARS]
315 ) ) {
316 $ret['issues'][] = "PARAM_TEMPLATE_VARS[$key]: Target's "
317 . 'PARAM_TEMPLATE_VARS must be a subset of the original';
318 }
319 }
320 }
321 }
322
323 $keys = implode( '|', array_map(
324 static function ( $key ) {
325 return preg_quote( $key, '/' );
326 },
327 array_keys( $settings[ApiBase::PARAM_TEMPLATE_VARS] )
328 ) );
329 if ( !preg_match( '/^(?>[^{}]+|\{(?:' . $keys . ')\})+$/', $name ) ) {
330 $ret['issues'][] = "Parameter name may not contain '{' or '}' other than '
331 . 'as defined by PARAM_TEMPLATE_VARS";
332 }
333 }
334 } elseif ( !preg_match( '/^[^{}]+$/', $name ) ) {
335 $ret['issues'][] = "Parameter name may not contain '{' or '}' without PARAM_TEMPLATE_VARS";
336 }
337
338 return $ret;
339 }
340
341 /**
342 * Convert a ValidationException to an ApiUsageException
343 * @param ApiBase $module
344 * @param ValidationException $ex
345 * @throws ApiUsageException always
346 * @return never
347 */
348 private function convertValidationException( ApiBase $module, ValidationException $ex ) {
349 $mv = $ex->getFailureMessage();
350 throw ApiUsageException::newWithMessage(
351 $module,
352 $this->messageConverter->convertMessageValue( $mv ),
353 $mv->getCode(),
354 $mv->getData(),
355 0,
356 $ex
357 );
358 }
359
360 /**
361 * Get and validate a value
362 * @param ApiBase $module
363 * @param string $name Parameter name, unprefixed
364 * @param array|mixed $settings Default value or an array of settings
365 * using PARAM_* constants.
366 * @param array $options Options array
367 * @return mixed Validated parameter value
368 * @throws ApiUsageException if the value is invalid
369 */
370 public function getValue( ApiBase $module, string $name, $settings, array $options = [] ) {
371 $options['module'] = $module;
372 $name = $module->encodeParamName( $name );
373 $settings = $this->normalizeSettings( $settings );
374 try {
375 return $this->paramValidator->getValue( $name, $settings, $options );
376 } catch ( ValidationException $ex ) {
377 $this->convertValidationException( $module, $ex );
378 }
379 }
380
381 /**
382 * Validate a parameter value using a settings array
383 *
384 * @param ApiBase $module
385 * @param string $name Parameter name, unprefixed
386 * @param mixed $value Parameter value
387 * @param array|mixed $settings Default value or an array of settings
388 * using PARAM_* constants.
389 * @param array $options Options array
390 * @return mixed Validated parameter value(s)
391 * @throws ApiUsageException if the value is invalid
392 */
393 public function validateValue(
394 ApiBase $module, string $name, $value, $settings, array $options = []
395 ) {
396 $options['module'] = $module;
397 $name = $module->encodeParamName( $name );
398 $settings = $this->normalizeSettings( $settings );
399 try {
400 return $this->paramValidator->validateValue( $name, $value, $settings, $options );
401 } catch ( ValidationException $ex ) {
402 $this->convertValidationException( $module, $ex );
403 }
404 }
405
406 /**
407 * Describe parameter settings in a machine-readable format.
408 *
409 * @param ApiBase $module
410 * @param string $name Parameter name.
411 * @param array|mixed $settings Default value or an array of settings
412 * using PARAM_* constants.
413 * @param array $options Options array.
414 * @return array
415 */
416 public function getParamInfo( ApiBase $module, string $name, $settings, array $options ): array {
417 $options['module'] = $module;
418 $name = $module->encodeParamName( $name );
419 return $this->paramValidator->getParamInfo( $name, $settings, $options );
420 }
421
422 /**
423 * Describe parameter settings in human-readable format
424 *
425 * @param ApiBase $module
426 * @param string $name Parameter name being described.
427 * @param array|mixed $settings Default value or an array of settings
428 * using PARAM_* constants.
429 * @param array $options Options array.
430 * @return Message[]
431 */
432 public function getHelpInfo( ApiBase $module, string $name, $settings, array $options ): array {
433 $options['module'] = $module;
434 $name = $module->encodeParamName( $name );
435
436 $ret = $this->paramValidator->getHelpInfo( $name, $settings, $options );
437 foreach ( $ret as &$m ) {
438 $k = $m->getKey();
439 $m = $this->messageConverter->convertMessageValue( $m );
440 if ( str_starts_with( $k, 'paramvalidator-help-' ) ) {
441 $m = new Message(
442 [ 'api-help-param-' . substr( $k, 20 ), $k ],
443 $m->getParams()
444 );
445 }
446 }
447 '@phan-var Message[] $ret'; // The above loop converts it
448
449 return $ret;
450 }
451 }