Debian Codegraph @

includes/api/ApiBase.php

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