3 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
23 use MediaWiki\Block\AbstractBlock
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\IDatabase
;
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Self-documentation: code to allow the API to document its own state
39 abstract class ApiBase
extends ContextSource
{
41 use ApiBlockInfoTrait
;
44 * @name Constants for ::getAllowedParams() arrays
45 * These constants are keys in the arrays returned by ::getAllowedParams()
46 * and accepted by ::getParameterFromSettings() that define how the
47 * parameters coming in from the request are to be interpreted.
51 /** (null|boolean|integer|string) Default value of the parameter. */
54 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
55 const PARAM_ISMULTI
= 1;
58 * (string|string[]) Either an array of allowed value strings, or a string
59 * type as described below. If not specified, will be determined from the
62 * Supported string types are:
63 * - boolean: A boolean parameter, returned as false if the parameter is
64 * omitted and true if present (even with a falsey value, i.e. it works
65 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
66 * Cannot be used with PARAM_ISMULTI.
67 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
68 * PARAM_RANGE_ENFORCE.
69 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
70 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
71 * specified. Cannot be used with PARAM_ISMULTI.
72 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
73 * support easily specifying all namespaces.
75 * - password: Any non-empty string. Input value is private or sensitive.
76 * <input type="password"> would be an appropriate HTML form field.
77 * - string: Any non-empty string, not expected to be very long or contain newlines.
78 * <input type="text"> would be an appropriate HTML form field.
79 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
80 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
81 * used with PARAM_ISMULTI.
82 * - text: Any non-empty string, expected to be very long or contain newlines.
83 * <textarea> would be an appropriate HTML form field.
84 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
85 * string 'now' representing the current timestamp. Will be returned in
87 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
88 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
89 * Cannot be used with PARAM_ISMULTI.
93 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
97 * (integer) Max value allowed for the parameter for users with the
98 * apihighlimits right, for PARAM_TYPE 'limit'.
100 const PARAM_MAX2
= 4;
102 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
105 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
106 const PARAM_ALLOW_DUPLICATES
= 6;
108 /** (boolean) Is the parameter deprecated (will show a warning)? */
109 const PARAM_DEPRECATED
= 7;
112 * (boolean) Is the parameter required?
115 const PARAM_REQUIRED
= 8;
118 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
121 const PARAM_RANGE_ENFORCE
= 9;
124 * (string|array|Message) Specify an alternative i18n documentation message
125 * for this parameter. Default is apihelp-{$path}-param-{$param}.
128 const PARAM_HELP_MSG
= 10;
131 * ((string|array|Message)[]) Specify additional i18n messages to append to
132 * the normal message for this parameter.
135 const PARAM_HELP_MSG_APPEND
= 11;
138 * (array) Specify additional information tags for the parameter. Value is
139 * an array of arrays, with the first member being the 'tag' for the info
140 * and the remaining members being the values. In the help, this is
141 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
142 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
145 const PARAM_HELP_MSG_INFO
= 12;
148 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
149 * those values to page titles which will be linked in the help.
152 const PARAM_VALUE_LINKS
= 13;
155 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
156 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
157 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
158 * Specify an empty array to use the default message key for all values.
161 const PARAM_HELP_MSG_PER_VALUE
= 14;
164 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
165 * submodule paths. Default is to use all modules in
166 * $this->getModuleManager() in the group matching the parameter name.
169 const PARAM_SUBMODULE_MAP
= 15;
172 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
173 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
176 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
179 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
180 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
181 * every possible value. If a string is set, it will be used in place of the asterisk.
184 const PARAM_ALL
= 17;
187 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
190 const PARAM_EXTRA_NAMESPACES
= 18;
193 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
194 * always sensitive regardless of the value of this field.
197 const PARAM_SENSITIVE
= 19;
200 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
201 * Keys are the deprecated parameter values, values define the warning
202 * message to emit: either boolean true (to use a default message) or a
203 * $msg for ApiBase::makeMessage().
206 const PARAM_DEPRECATED_VALUES
= 20;
209 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
212 const PARAM_ISMULTI_LIMIT1
= 21;
215 * (integer) Maximum number of values, for users with the apihighimits right.
216 * Must be used with PARAM_ISMULTI.
219 const PARAM_ISMULTI_LIMIT2
= 22;
222 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
225 const PARAM_MAX_BYTES
= 23;
228 * (integer) Maximum length of a string in characters (unicode codepoints).
231 const PARAM_MAX_CHARS
= 24;
234 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
235 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
236 * which the replacement values are taken.
238 * For example, a parameter "foo-{ns}-{title}" could be defined with
239 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
240 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
242 * All placeholders must be present in the parameter's name. Each target parameter must have
243 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
244 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
245 * A parameter cannot target itself.
249 const PARAM_TEMPLATE_VARS
= 25;
253 const ALL_DEFAULT_STRING
= '*';
255 /** Fast query, standard limit. */
256 const LIMIT_BIG1
= 500;
257 /** Fast query, apihighlimits limit. */
258 const LIMIT_BIG2
= 5000;
259 /** Slow query, standard limit. */
260 const LIMIT_SML1
= 50;
261 /** Slow query, apihighlimits limit. */
262 const LIMIT_SML2
= 500;
265 * getAllowedParams() flag: When set, the result could take longer to generate,
266 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
269 const GET_VALUES_FOR_HELP
= 1;
271 /** @var array Maps extension paths to info arrays */
272 private static $extensionInfo = null;
274 /** @var int[][][] Cache for self::filterIDs() */
275 private static $filterIDsCache = [];
277 /** $var array Map of web UI block messages to corresponding API messages and codes */
278 private static $blockMsgMap = [
279 'blockedtext' => [ 'apierror-blocked', 'blocked' ],
280 'blockedtext-partial' => [ 'apierror-blocked', 'blocked' ],
281 'autoblockedtext' => [ 'apierror-autoblocked', 'autoblocked' ],
282 'systemblockedtext' => [ 'apierror-systemblocked', 'blocked' ],
286 private $mMainModule;
288 private $mModuleName, $mModulePrefix;
289 private $mReplicaDB = null;
290 private $mParamCache = [];
291 /** @var array|null|bool */
292 private $mModuleSource = false;
295 * @param ApiMain $mainModule
296 * @param string $moduleName Name of this module
297 * @param string $modulePrefix Prefix to use for parameter names
299 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
300 $this->mMainModule
= $mainModule;
301 $this->mModuleName
= $moduleName;
302 $this->mModulePrefix
= $modulePrefix;
304 if ( !$this->isMain() ) {
305 $this->setContext( $mainModule->getContext() );
309 /************************************************************************//**
310 * @name Methods to implement
315 * Evaluates the parameters, performs the requested query, and sets up
316 * the result. Concrete implementations of ApiBase must override this
317 * method to provide whatever functionality their module offers.
318 * Implementations must not produce any output on their own and are not
319 * expected to handle any errors.
321 * The execute() method will be invoked directly by ApiMain immediately
322 * before the result of the module is output. Aside from the
323 * constructor, implementations should assume that no other methods
324 * will be called externally on the module before the result is
327 * The result data should be stored in the ApiResult object available
328 * through getResult().
330 abstract public function execute();
333 * Get the module manager, or null if this module has no sub-modules
335 * @return ApiModuleManager
337 public function getModuleManager() {
342 * If the module may only be used with a certain format module,
343 * it should override this method to return an instance of that formatter.
344 * A value of null means the default format will be used.
345 * @note Do not use this just because you don't want to support non-json
346 * formats. This should be used only when there is a fundamental
347 * requirement for a specific format.
348 * @return mixed Instance of a derived class of ApiFormatBase, or null
350 public function getCustomPrinter() {
355 * Returns usage examples for this module.
357 * Return value has query strings as keys, with values being either strings
358 * (message key), arrays (message key + parameter), or Message objects.
360 * Do not call this base class implementation when overriding this method.
365 protected function getExamplesMessages() {
370 * Return links to more detailed help pages about the module.
371 * @since 1.25, returning boolean false is deprecated
372 * @return string|array
374 public function getHelpUrls() {
379 * Returns an array of allowed parameters (parameter name) => (default
380 * value) or (parameter name) => (array with PARAM_* constants as keys)
381 * Don't call this function directly: use getFinalParams() to allow
382 * hooks to modify parameters as needed.
384 * Some derived classes may choose to handle an integer $flags parameter
385 * in the overriding methods. Callers of this method can pass zero or
386 * more OR-ed flags like GET_VALUES_FOR_HELP.
390 protected function getAllowedParams( /* $flags = 0 */ ) {
391 // int $flags is not declared because it causes "Strict standards"
392 // warning. Most derived classes do not implement it.
397 * Indicates if this module needs maxlag to be checked
400 public function shouldCheckMaxlag() {
405 * Indicates whether this module requires read rights
408 public function isReadMode() {
413 * Indicates whether this module requires write mode
415 * This should return true for modules that may require synchronous database writes.
416 * Modules that do not need such writes should also not rely on master database access,
417 * since only read queries are needed and each master DB is a single point of failure.
418 * Additionally, requests that only need replica DBs can be efficiently routed to any
419 * datacenter via the Promise-Non-Write-API-Action header.
423 public function isWriteMode() {
428 * Indicates whether this module must be called with a POST request
431 public function mustBePosted() {
432 return $this->needsToken() !== false;
436 * Indicates whether this module is deprecated
440 public function isDeprecated() {
445 * Indicates whether this module is "internal"
446 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
450 public function isInternal() {
455 * Returns the token type this module requires in order to execute.
457 * Modules are strongly encouraged to use the core 'csrf' type unless they
458 * have specialized security needs. If the token type is not one of the
459 * core types, you must use the ApiQueryTokensRegisterTypes hook to
462 * Returning a non-falsey value here will force the addition of an
463 * appropriate 'token' parameter in self::getFinalParams(). Also,
464 * self::mustBePosted() must return true when tokens are used.
466 * In previous versions of MediaWiki, true was a valid return value.
467 * Returning true will generate errors indicating that the API module needs
470 * @return string|false
472 public function needsToken() {
477 * Fetch the salt used in the Web UI corresponding to this module.
479 * Only override this if the Web UI uses a token with a non-constant salt.
482 * @param array $params All supplied parameters for the module
483 * @return string|array|null
485 protected function getWebUITokenSalt( array $params ) {
490 * Returns data for HTTP conditional request mechanisms.
493 * @param string $condition Condition being queried:
494 * - last-modified: Return a timestamp representing the maximum of the
495 * last-modified dates for all resources involved in the request. See
496 * RFC 7232 § 2.2 for semantics.
497 * - etag: Return an entity-tag representing the state of all resources involved
498 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
499 * @return string|bool|null As described above, or null if no value is available.
501 public function getConditionalRequestData( $condition ) {
507 /************************************************************************//**
508 * @name Data access methods
513 * Get the name of the module being executed by this instance
516 public function getModuleName() {
517 return $this->mModuleName
;
521 * Get parameter prefix (usually two letters or an empty string).
524 public function getModulePrefix() {
525 return $this->mModulePrefix
;
529 * Get the main module
532 public function getMain() {
533 return $this->mMainModule
;
537 * Returns true if this module is the main module ($this === $this->mMainModule),
541 public function isMain() {
542 return $this === $this->mMainModule
;
546 * Get the parent of this module
548 * @return ApiBase|null
550 public function getParent() {
551 return $this->isMain() ?
null : $this->getMain();
555 * Returns true if the current request breaks the same-origin policy.
557 * For example, json with callbacks.
559 * https://en.wikipedia.org/wiki/Same-origin_policy
564 public function lacksSameOriginSecurity() {
565 // Main module has this method overridden
566 // Safety - avoid infinite loop:
567 if ( $this->isMain() ) {
568 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
571 return $this->getMain()->lacksSameOriginSecurity();
575 * Get the path to this module
580 public function getModulePath() {
581 if ( $this->isMain() ) {
583 } elseif ( $this->getParent()->isMain() ) {
584 return $this->getModuleName();
586 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
591 * Get a module from its module path
594 * @param string $path
595 * @return ApiBase|null
596 * @throws ApiUsageException
598 public function getModuleFromPath( $path ) {
599 $module = $this->getMain();
600 if ( $path === 'main' ) {
604 $parts = explode( '+', $path );
605 if ( count( $parts ) === 1 ) {
606 // In case the '+' was typed into URL, it resolves as a space
607 $parts = explode( ' ', $path );
610 $count = count( $parts );
611 for ( $i = 0; $i < $count; $i++
) {
613 $manager = $parent->getModuleManager();
614 if ( $manager === null ) {
615 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
616 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
618 $module = $manager->getModule( $parts[$i] );
620 if ( $module === null ) {
621 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
623 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
633 * Get the result object
636 public function getResult() {
637 // Main module has getResult() method overridden
638 // Safety - avoid infinite loop:
639 if ( $this->isMain() ) {
640 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
643 return $this->getMain()->getResult();
647 * Get the error formatter
648 * @return ApiErrorFormatter
650 public function getErrorFormatter() {
651 // Main module has getErrorFormatter() method overridden
652 // Safety - avoid infinite loop:
653 if ( $this->isMain() ) {
654 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
657 return $this->getMain()->getErrorFormatter();
661 * Gets a default replica DB connection object
664 protected function getDB() {
665 if ( !isset( $this->mReplicaDB
) ) {
666 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
669 return $this->mReplicaDB
;
673 * Get the continuation manager
674 * @return ApiContinuationManager|null
676 public function getContinuationManager() {
677 // Main module has getContinuationManager() method overridden
678 // Safety - avoid infinite loop:
679 if ( $this->isMain() ) {
680 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
683 return $this->getMain()->getContinuationManager();
687 * Set the continuation manager
688 * @param ApiContinuationManager|null $manager
690 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
691 // Main module has setContinuationManager() method overridden
692 // Safety - avoid infinite loop:
693 if ( $this->isMain() ) {
694 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
697 $this->getMain()->setContinuationManager( $manager );
702 /************************************************************************//**
703 * @name Parameter handling
708 * Indicate if the module supports dynamically-determined parameters that
709 * cannot be included in self::getAllowedParams().
710 * @return string|array|Message|null Return null if the module does not
711 * support additional dynamic parameters, otherwise return a message
714 public function dynamicParameterDocumentation() {
719 * This method mangles parameter name based on the prefix supplied to the constructor.
720 * Override this method to change parameter name during runtime
721 * @param string|string[] $paramName Parameter name
722 * @return string|string[] Prefixed parameter name
723 * @since 1.29 accepts an array of strings
725 public function encodeParamName( $paramName ) {
726 if ( is_array( $paramName ) ) {
727 return array_map( function ( $name ) {
728 return $this->mModulePrefix
. $name;
731 return $this->mModulePrefix
. $paramName;
736 * Using getAllowedParams(), this function makes an array of the values
737 * provided by the user, with key being the name of the variable, and
738 * value - validated value from user or default. limits will not be
739 * parsed if $parseLimit is set to false; use this when the max
740 * limit is not definitive yet, e.g. when getting revisions.
741 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
742 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
743 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
744 * Returned parameter values might be ApiUsageException instances.
747 public function extractRequestParams( $options = [] ) {
748 if ( is_bool( $options ) ) {
749 $options = [ 'parseLimit' => $options ];
752 'parseLimit' => true,
756 $parseLimit = (bool)$options['parseLimit'];
758 // Cache parameters, for performance and to avoid T26564.
759 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
760 $params = $this->getFinalParams() ?
: [];
764 // Process all non-templates and save templates for secondary
767 foreach ( $params as $paramName => $paramSettings ) {
768 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
769 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
772 $results[$paramName] = $this->getParameterFromSettings(
773 $paramName, $paramSettings, $parseLimit
775 } catch ( ApiUsageException
$ex ) {
776 $results[$paramName] = $ex;
781 // Now process all the templates by successively replacing the
782 // placeholders with all client-supplied values.
783 // This bit duplicates JavaScript logic in
784 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
785 // If you update this, see if that needs updating too.
786 while ( $toProcess ) {
787 list( $name, $targets, $settings ) = array_shift( $toProcess );
789 foreach ( $targets as $placeholder => $target ) {
790 if ( !array_key_exists( $target, $results ) ) {
791 // The target wasn't processed yet, try the next one.
792 // If all hit this case, the parameter has no expansions.
795 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
796 // The target was processed but has no (valid) values.
797 // That means it has no expansions.
801 // Expand this target in the name and all other targets,
802 // then requeue if there are more targets left or put in
803 // $results if all are done.
804 unset( $targets[$placeholder] );
805 $placeholder = '{' . $placeholder . '}';
806 // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
807 foreach ( $results[$target] as $value ) {
808 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
809 // Skip values that make invalid parameter names.
810 $encTargetName = $this->encodeParamName( $target );
811 if ( !isset( $warned[$encTargetName][$value] ) ) {
812 $warned[$encTargetName][$value] = true;
814 'apiwarn-ignoring-invalid-templated-value',
815 wfEscapeWikiText( $encTargetName ),
816 wfEscapeWikiText( $value ),
822 $newName = str_replace( $placeholder, $value, $name );
825 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
826 } catch ( ApiUsageException
$ex ) {
827 $results[$newName] = $ex;
831 foreach ( $targets as $k => $v ) {
832 $newTargets[$k] = str_replace( $placeholder, $value, $v );
834 $toProcess[] = [ $newName, $newTargets, $settings ];
841 $this->mParamCache
[$parseLimit] = $results;
844 $ret = $this->mParamCache
[$parseLimit];
845 if ( !$options['safeMode'] ) {
846 foreach ( $ret as $v ) {
847 if ( $v instanceof ApiUsageException
) {
853 return $this->mParamCache
[$parseLimit];
857 * Get a value for the given parameter
858 * @param string $paramName Parameter name
859 * @param bool $parseLimit See extractRequestParams()
860 * @return mixed Parameter value
862 protected function getParameter( $paramName, $parseLimit = true ) {
863 $ret = $this->extractRequestParams( [
864 'parseLimit' => $parseLimit,
867 if ( $ret instanceof ApiUsageException
) {
874 * Die if none or more than one of a certain set of parameters is set and not false.
876 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
877 * @param string $required,... Names of parameters of which exactly one must be set
879 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
880 $required = func_get_args();
881 array_shift( $required );
883 $intersection = array_intersect( array_keys( array_filter( $params,
884 [ $this, 'parameterNotEmpty' ] ) ), $required );
886 if ( count( $intersection ) > 1 ) {
887 $this->dieWithError( [
888 'apierror-invalidparammix',
889 Message
::listParam( array_map(
891 return '<var>' . $this->encodeParamName( $p ) . '</var>';
893 array_values( $intersection )
895 count( $intersection ),
897 } elseif ( count( $intersection ) == 0 ) {
898 $this->dieWithError( [
899 'apierror-missingparam-one-of',
900 Message
::listParam( array_map(
902 return '<var>' . $this->encodeParamName( $p ) . '</var>';
904 array_values( $required )
912 * Die if more than one of a certain set of parameters is set and not false.
914 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
915 * @param string $required,... Names of parameters of which at most one must be set
917 public function requireMaxOneParameter( $params, $required /*...*/ ) {
918 $required = func_get_args();
919 array_shift( $required );
921 $intersection = array_intersect( array_keys( array_filter( $params,
922 [ $this, 'parameterNotEmpty' ] ) ), $required );
924 if ( count( $intersection ) > 1 ) {
925 $this->dieWithError( [
926 'apierror-invalidparammix',
927 Message
::listParam( array_map(
929 return '<var>' . $this->encodeParamName( $p ) . '</var>';
931 array_values( $intersection )
933 count( $intersection ),
939 * Die if none of a certain set of parameters is set and not false.
942 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
943 * @param string $required,... Names of parameters of which at least one must be set
945 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
946 $required = func_get_args();
947 array_shift( $required );
949 $intersection = array_intersect(
950 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
954 if ( count( $intersection ) == 0 ) {
955 $this->dieWithError( [
956 'apierror-missingparam-at-least-one-of',
957 Message
::listParam( array_map(
959 return '<var>' . $this->encodeParamName( $p ) . '</var>';
961 array_values( $required )
969 * Die if any of the specified parameters were found in the query part of
970 * the URL rather than the post body.
972 * @param string[] $params Parameters to check
973 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
975 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
976 // Skip if $wgDebugAPI is set or we're in internal mode
977 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
981 $queryValues = $this->getRequest()->getQueryValues();
983 foreach ( $params as $param ) {
984 if ( $prefix !== 'noprefix' ) {
985 $param = $this->encodeParamName( $param );
987 if ( array_key_exists( $param, $queryValues ) ) {
988 $badParams[] = $param;
994 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
1000 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
1002 * @param object $x Parameter to check is not null/false
1005 private function parameterNotEmpty( $x ) {
1006 return !is_null( $x ) && $x !== false;
1010 * Get a WikiPage object from a title or pageid param, if possible.
1011 * Can die, if no param is set or if the title or page id is not valid.
1013 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1014 * @param bool|string $load Whether load the object's state from the database:
1015 * - false: don't load (if the pageid is given, it will still be loaded)
1016 * - 'fromdb': load from a replica DB
1017 * - 'fromdbmaster': load from the master database
1020 public function getTitleOrPageId( $params, $load = false ) {
1021 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1024 if ( isset( $params['title'] ) ) {
1025 $titleObj = Title
::newFromText( $params['title'] );
1026 if ( !$titleObj ||
$titleObj->isExternal() ) {
1027 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1029 if ( !$titleObj->canExist() ) {
1030 $this->dieWithError( 'apierror-pagecannotexist' );
1032 $pageObj = WikiPage
::factory( $titleObj );
1033 if ( $load !== false ) {
1034 $pageObj->loadPageData( $load );
1036 } elseif ( isset( $params['pageid'] ) ) {
1037 if ( $load === false ) {
1040 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1042 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1050 * Get a Title object from a title or pageid param, if possible.
1051 * Can die, if no param is set or if the title or page id is not valid.
1054 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1057 public function getTitleFromTitleOrPageId( $params ) {
1058 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1061 if ( isset( $params['title'] ) ) {
1062 $titleObj = Title
::newFromText( $params['title'] );
1063 if ( !$titleObj ||
$titleObj->isExternal() ) {
1064 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1067 } elseif ( isset( $params['pageid'] ) ) {
1068 $titleObj = Title
::newFromID( $params['pageid'] );
1070 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1078 * Return true if we're to watch the page, false if not, null if no change.
1079 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1080 * @param Title $titleObj The page under consideration
1081 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1082 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1085 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1086 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1088 switch ( $watchlist ) {
1096 # If the user is already watching, don't bother checking
1097 if ( $userWatching ) {
1100 # If no user option was passed, use watchdefault and watchcreations
1101 if ( is_null( $userOption ) ) {
1102 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1103 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1106 # Watch the article based on the user preference
1107 return $this->getUser()->getBoolOption( $userOption );
1110 return $userWatching;
1113 return $userWatching;
1118 * Using the settings determine the value for the given parameter
1120 * @param string $paramName Parameter name
1121 * @param array|mixed $paramSettings Default value or an array of settings
1122 * using PARAM_* constants.
1123 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1124 * @return mixed Parameter value
1126 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1127 // Some classes may decide to change parameter names
1128 $encParamName = $this->encodeParamName( $paramName );
1131 if ( !is_array( $paramSettings ) ) {
1133 self
::PARAM_DFLT
=> $paramSettings,
1137 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1138 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1139 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1140 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1141 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1142 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1143 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1144 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1145 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1146 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1148 // When type is not given, and no choices, the type is the same as $default
1149 if ( !isset( $type ) ) {
1150 if ( isset( $default ) ) {
1151 $type = gettype( $default );
1153 $type = 'NULL'; // allow everything
1157 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1158 $this->getMain()->markParamsSensitive( $encParamName );
1161 if ( $type == 'boolean' ) {
1162 if ( isset( $default ) && $default !== false ) {
1163 // Having a default value of anything other than 'false' is not allowed
1166 "Boolean param $encParamName's default is set to '$default'. " .
1167 'Boolean parameters must default to false.'
1171 $value = $this->getMain()->getCheck( $encParamName );
1173 } elseif ( $type == 'upload' ) {
1174 if ( isset( $default ) ) {
1175 // Having a default value is not allowed
1178 "File upload param $encParamName's default is set to " .
1179 "'$default'. File upload parameters may not have a default." );
1182 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1184 $value = $this->getMain()->getUpload( $encParamName );
1185 $provided = $value->exists();
1186 if ( !$value->exists() ) {
1187 // This will get the value without trying to normalize it
1188 // (because trying to normalize a large binary file
1189 // accidentally uploaded as a field fails spectacularly)
1190 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1191 if ( $value !== null ) {
1192 $this->dieWithError(
1193 [ 'apierror-badupload', $encParamName ],
1194 "badupload_{$encParamName}"
1199 $value = $this->getMain()->getVal( $encParamName, $default );
1200 $provided = $this->getMain()->getCheck( $encParamName );
1202 if ( isset( $value ) && $type == 'namespace' ) {
1203 $type = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1204 getValidNamespaces();
1205 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1206 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1208 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1210 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1211 // specify all namespaces irrespective of PARAM_ALL.
1214 if ( isset( $value ) && $type == 'submodule' ) {
1215 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1216 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1218 $type = $this->getModuleManager()->getNames( $paramName );
1222 $request = $this->getMain()->getRequest();
1223 $rawValue = $request->getRawVal( $encParamName );
1224 if ( $rawValue === null ) {
1225 $rawValue = $default;
1228 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1229 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1231 // This loses the potential checkTitleEncoding() transformation done by
1232 // WebRequest for $_GET. Let's call that a feature.
1233 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1235 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1239 // Check for NFC normalization, and warn
1240 if ( $rawValue !== $value ) {
1241 $this->handleParamNormalization( $paramName, $value, $rawValue );
1245 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1246 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1249 "For param $encParamName, PARAM_ALL collides with a possible value" );
1251 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1252 $value = $this->parseMultiValue(
1256 is_array( $type ) ?
$type : null,
1257 $allowAll ?
$allSpecifier : null,
1263 if ( isset( $value ) ) {
1264 // More validation only when choices were not given
1265 // choices were validated in parseMultiValue()
1266 if ( !is_array( $type ) ) {
1268 case 'NULL': // nothing to do
1273 if ( $required && $value === '' ) {
1274 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1277 case 'integer': // Force everything using intval() and optionally validate limits
1278 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1279 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1280 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1282 if ( is_array( $value ) ) {
1283 $value = array_map( 'intval', $value );
1284 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1285 foreach ( $value as &$v ) {
1286 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1290 $value = (int)$value;
1291 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1292 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1297 if ( !$parseLimit ) {
1298 // Don't do any validation whatsoever
1301 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1302 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1306 "MAX1 or MAX2 are not defined for the limit $encParamName"
1310 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1312 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1313 if ( $value == 'max' ) {
1314 $value = $this->getMain()->canApiHighLimits()
1315 ?
$paramSettings[self
::PARAM_MAX2
]
1316 : $paramSettings[self
::PARAM_MAX
];
1317 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1319 $value = (int)$value;
1320 $this->validateLimit(
1324 $paramSettings[self
::PARAM_MAX
],
1325 $paramSettings[self
::PARAM_MAX2
]
1331 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1335 if ( is_array( $value ) ) {
1336 foreach ( $value as $key => $val ) {
1337 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1340 $value = $this->validateTimestamp( $value, $encParamName );
1344 if ( is_array( $value ) ) {
1345 foreach ( $value as $key => $val ) {
1346 $value[$key] = $this->validateUser( $val, $encParamName );
1349 $value = $this->validateUser( $value, $encParamName );
1352 case 'upload': // nothing to do
1355 // If change tagging was requested, check that the tags are valid.
1356 if ( !is_array( $value ) && !$multi ) {
1357 $value = [ $value ];
1359 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1360 if ( !$tagsStatus->isGood() ) {
1361 $this->dieStatus( $tagsStatus );
1365 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1369 // Throw out duplicates if requested
1370 if ( !$dupes && is_array( $value ) ) {
1371 $value = array_unique( $value );
1374 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1375 foreach ( (array)$value as $val ) {
1376 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1377 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1379 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1380 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1382 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1383 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1385 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1386 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1391 // Set a warning if a deprecated parameter has been passed
1392 if ( $deprecated && $provided ) {
1393 $feature = $encParamName;
1395 while ( !$m->isMain() ) {
1396 $p = $m->getParent();
1397 $name = $m->getModuleName();
1398 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1399 $feature = "{$param}={$name}&{$feature}";
1402 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1405 // Set a warning if a deprecated parameter value has been passed
1406 $usedDeprecatedValues = $deprecatedValues && $provided
1407 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1409 if ( $usedDeprecatedValues ) {
1410 $feature = "$encParamName=";
1412 while ( !$m->isMain() ) {
1413 $p = $m->getParent();
1414 $name = $m->getModuleName();
1415 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1416 $feature = "{$param}={$name}&{$feature}";
1419 foreach ( $usedDeprecatedValues as $v ) {
1420 $msg = $deprecatedValues[$v];
1421 if ( $msg === true ) {
1422 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1424 $this->addDeprecation( $msg, "$feature$v" );
1427 } elseif ( $required ) {
1428 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1435 * Handle when a parameter was Unicode-normalized
1437 * @param string $paramName Unprefixed parameter name
1438 * @param string $value Input that will be used.
1439 * @param string $rawValue Input before normalization.
1441 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1442 $encParamName = $this->encodeParamName( $paramName );
1443 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1447 * Split a multi-valued parameter string, like explode()
1449 * @param string $value
1453 protected function explodeMultiValue( $value, $limit ) {
1454 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1456 $value = substr( $value, 1 );
1461 return explode( $sep, $value, $limit );
1465 * Return an array of values that were given in a 'a|b|c' notation,
1466 * after it optionally validates them against the list allowed values.
1468 * @param string $valueName The name of the parameter (for error
1470 * @param mixed $value The value being parsed
1471 * @param bool $allowMultiple Can $value contain more than one value
1473 * @param string[]|null $allowedValues An array of values to check against. If
1474 * null, all values are accepted.
1475 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1476 * if this behavior should not be allowed
1477 * @param int|null $limit1 Maximum number of values, for normal users.
1478 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1479 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1481 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1482 $allSpecifier = null, $limit1 = null, $limit2 = null
1484 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1487 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1488 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1490 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1491 // because it unstubs $wgUser
1492 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1493 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1497 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1498 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1500 return $allowedValues;
1503 if ( count( $valuesList ) > $sizeLimit ) {
1504 $this->dieWithError(
1505 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1506 "too-many-$valueName"
1510 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1511 // T35482 - Allow entries with | in them for non-multiple values
1512 if ( in_array( $value, $allowedValues, true ) ) {
1516 $values = array_map( function ( $v ) {
1517 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1518 }, $allowedValues );
1519 $this->dieWithError( [
1520 'apierror-multival-only-one-of',
1522 Message
::listParam( $values ),
1524 ], "multival_$valueName" );
1527 if ( is_array( $allowedValues ) ) {
1528 // Check for unknown values
1529 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1530 if ( count( $unknown ) ) {
1531 if ( $allowMultiple ) {
1532 $this->addWarning( [
1533 'apiwarn-unrecognizedvalues',
1535 Message
::listParam( $unknown, 'comma' ),
1539 $this->dieWithError(
1540 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1541 "unknown_$valueName"
1545 // Now throw them out
1546 $valuesList = array_intersect( $valuesList, $allowedValues );
1549 return $allowMultiple ?
$valuesList : $valuesList[0];
1553 * Validate the value against the minimum and user/bot maximum limits.
1554 * Prints usage info on failure.
1555 * @param string $paramName Parameter name
1556 * @param int &$value Parameter value
1557 * @param int|null $min Minimum value
1558 * @param int|null $max Maximum value for users
1559 * @param int|null $botMax Maximum value for sysops/bots
1560 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1562 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1563 $enforceLimits = false
1565 if ( !is_null( $min ) && $value < $min ) {
1566 $msg = ApiMessage
::create(
1567 [ 'apierror-integeroutofrange-belowminimum',
1568 $this->encodeParamName( $paramName ), $min, $value ],
1569 'integeroutofrange',
1570 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1572 $this->warnOrDie( $msg, $enforceLimits );
1576 // Minimum is always validated, whereas maximum is checked only if not
1577 // running in internal call mode
1578 if ( $this->getMain()->isInternalMode() ) {
1582 // Optimization: do not check user's bot status unless really needed -- skips db query
1583 // assumes $botMax >= $max
1584 if ( !is_null( $max ) && $value > $max ) {
1585 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1586 if ( $value > $botMax ) {
1587 $msg = ApiMessage
::create(
1588 [ 'apierror-integeroutofrange-abovebotmax',
1589 $this->encodeParamName( $paramName ), $botMax, $value ],
1590 'integeroutofrange',
1591 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1593 $this->warnOrDie( $msg, $enforceLimits );
1597 $msg = ApiMessage
::create(
1598 [ 'apierror-integeroutofrange-abovemax',
1599 $this->encodeParamName( $paramName ), $max, $value ],
1600 'integeroutofrange',
1601 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1603 $this->warnOrDie( $msg, $enforceLimits );
1610 * Validate and normalize parameters of type 'timestamp'
1611 * @param string $value Parameter value
1612 * @param string $encParamName Parameter name
1613 * @return string Validated and normalized parameter
1615 protected function validateTimestamp( $value, $encParamName ) {
1616 // Confusing synonyms for the current time accepted by wfTimestamp()
1617 // (wfTimestamp() also accepts various non-strings and the string of 14
1618 // ASCII NUL bytes, but those can't get here)
1620 $this->addDeprecation(
1621 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1622 'unclear-"now"-timestamp'
1624 return wfTimestamp( TS_MW
);
1627 // Explicit synonym for the current time
1628 if ( $value === 'now' ) {
1629 return wfTimestamp( TS_MW
);
1632 $timestamp = wfTimestamp( TS_MW
, $value );
1633 if ( $timestamp === false ) {
1634 $this->dieWithError(
1635 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1636 "badtimestamp_{$encParamName}"
1644 * Validate the supplied token.
1647 * @param string $token Supplied token
1648 * @param array $params All supplied parameters for the module
1650 * @throws MWException
1652 final public function validateToken( $token, array $params ) {
1653 $tokenType = $this->needsToken();
1654 $salts = ApiQueryTokens
::getTokenTypeSalts();
1655 if ( !isset( $salts[$tokenType] ) ) {
1656 throw new MWException(
1657 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1658 'without registering it'
1662 $tokenObj = ApiQueryTokens
::getToken(
1663 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1665 if ( $tokenObj->match( $token ) ) {
1669 $webUiSalt = $this->getWebUITokenSalt( $params );
1670 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1682 * Validate and normalize parameters of type 'user'
1683 * @param string $value Parameter value
1684 * @param string $encParamName Parameter name
1685 * @return string Validated and normalized parameter
1687 private function validateUser( $value, $encParamName ) {
1688 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1692 $name = User
::getCanonicalName( $value, 'valid' );
1693 if ( $name !== false ) {
1698 // We allow ranges as well, for blocks.
1699 IP
::isIPAddress( $value ) ||
1700 // See comment for User::isIP. We don't just call that function
1701 // here because it also returns true for things like
1702 // 300.300.300.300 that are neither valid usernames nor valid IP
1705 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1709 return IP
::sanitizeIP( $value );
1712 $this->dieWithError(
1713 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1714 "baduser_{$encParamName}"
1720 /************************************************************************//**
1721 * @name Utility methods
1726 * Set a watch (or unwatch) based the based on a watchlist parameter.
1727 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1728 * @param Title $titleObj The article's title to change
1729 * @param string|null $userOption The user option to consider when $watch=preferences
1731 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1732 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1733 if ( $value === null ) {
1737 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1741 * Gets the user for whom to get the watchlist
1743 * @param array $params
1746 public function getWatchlistUser( $params ) {
1747 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1748 $user = User
::newFromName( $params['owner'], false );
1749 if ( !( $user && $user->getId() ) ) {
1750 $this->dieWithError(
1751 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1754 $token = $user->getOption( 'watchlisttoken' );
1755 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1756 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1759 if ( !$this->getUser()->isLoggedIn() ) {
1760 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1762 $this->checkUserRightsAny( 'viewmywatchlist' );
1763 $user = $this->getUser();
1770 * Create a Message from a string or array
1772 * A string is used as a message key. An array has the message key as the
1773 * first value and message parameters as subsequent values.
1776 * @param string|array|Message $msg
1777 * @param IContextSource $context
1778 * @param array|null $params
1779 * @return Message|null
1781 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1782 if ( is_string( $msg ) ) {
1783 $msg = wfMessage( $msg );
1784 } elseif ( is_array( $msg ) ) {
1785 $msg = wfMessage( ...$msg );
1787 if ( !$msg instanceof Message
) {
1791 $msg->setContext( $context );
1793 $msg->params( $params );
1800 * Turn an array of message keys or key+param arrays into a Status
1802 * @param array $errors
1803 * @param User|null $user
1806 public function errorArrayToStatus( array $errors, User
$user = null ) {
1807 if ( $user === null ) {
1808 $user = $this->getUser();
1811 $status = Status
::newGood();
1812 foreach ( $errors as $error ) {
1813 if ( !is_array( $error ) ) {
1814 $error = [ $error ];
1816 if ( is_string( $error[0] ) && isset( self
::$blockMsgMap[$error[0]] ) && $user->getBlock() ) {
1817 list( $msg, $code ) = self
::$blockMsgMap[$error[0]];
1818 $status->fatal( ApiMessage
::create( $msg, $code,
1819 [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
1822 $status->fatal( ...$error );
1829 * Add block info to block messages in a Status
1831 * @param StatusValue $status
1832 * @param User|null $user
1834 public function addBlockInfoToStatus( StatusValue
$status, User
$user = null ) {
1835 if ( $user === null ) {
1836 $user = $this->getUser();
1839 foreach ( self
::$blockMsgMap as $msg => list( $apiMsg, $code ) ) {
1840 if ( $status->hasMessage( $msg ) && $user->getBlock() ) {
1841 $status->replaceMessage( $msg, ApiMessage
::create( $apiMsg, $code,
1842 [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
1849 * Call wfTransactionalTimeLimit() if this request was POSTed
1852 protected function useTransactionalTimeLimit() {
1853 if ( $this->getRequest()->wasPosted() ) {
1854 wfTransactionalTimeLimit();
1859 * Filter out-of-range values from a list of positive integer IDs
1861 * @param array $fields Array of pairs of table and field to check
1862 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1863 * expected to be stringified ints.
1864 * @return (string|int)[] Filtered IDs.
1866 protected function filterIDs( $fields, array $ids ) {
1869 foreach ( $fields as list( $table, $field ) ) {
1870 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1871 $row = self
::$filterIDsCache[$table][$field];
1873 $row = $this->getDB()->selectRow(
1876 'min_id' => "MIN($field)",
1877 'max_id' => "MAX($field)",
1882 self
::$filterIDsCache[$table][$field] = $row;
1884 $min = min( $min, $row->min_id
);
1885 $max = max( $max, $row->max_id
);
1887 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1888 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1889 && $id >= $min && $id <= $max;
1895 /************************************************************************//**
1896 * @name Warning and error reporting
1901 * Add a warning for this module.
1903 * Users should monitor this section to notice any changes in API. Multiple
1904 * calls to this function will result in multiple warning messages.
1906 * If $msg is not an ApiMessage, the message code will be derived from the
1907 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1910 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1911 * @param string|null $code See ApiErrorFormatter::addWarning()
1912 * @param array|null $data See ApiErrorFormatter::addWarning()
1914 public function addWarning( $msg, $code = null, $data = null ) {
1915 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1919 * Add a deprecation warning for this module.
1921 * A combination of $this->addWarning() and $this->logFeatureUsage()
1924 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1925 * @param string|null $feature See ApiBase::logFeatureUsage()
1926 * @param array|null $data See ApiErrorFormatter::addWarning()
1928 public function addDeprecation( $msg, $feature, $data = [] ) {
1929 $data = (array)$data;
1930 if ( $feature !== null ) {
1931 $data['feature'] = $feature;
1932 $this->logFeatureUsage( $feature );
1934 $this->addWarning( $msg, 'deprecation', $data );
1936 // No real need to deduplicate here, ApiErrorFormatter does that for
1937 // us (assuming the hook is deterministic).
1938 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1939 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1940 if ( count( $msgs ) > 1 ) {
1941 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1942 $msg = ( new RawMessage( $key ) )->params( $msgs );
1944 $msg = reset( $msgs );
1946 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1950 * Add an error for this module without aborting
1952 * If $msg is not an ApiMessage, the message code will be derived from the
1953 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1955 * @note If you want to abort processing, use self::dieWithError() instead.
1957 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1958 * @param string|null $code See ApiErrorFormatter::addError()
1959 * @param array|null $data See ApiErrorFormatter::addError()
1961 public function addError( $msg, $code = null, $data = null ) {
1962 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1966 * Add warnings and/or errors from a Status
1968 * @note If you want to abort processing, use self::dieStatus() instead.
1970 * @param StatusValue $status
1971 * @param string[] $types 'warning' and/or 'error'
1972 * @param string[] $filter Message keys to filter out (since 1.33)
1974 public function addMessagesFromStatus(
1975 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1977 $this->getErrorFormatter()->addMessagesFromStatus(
1978 $this->getModulePath(), $status, $types, $filter
1983 * Abort execution with an error
1985 * If $msg is not an ApiMessage, the message code will be derived from the
1986 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1989 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1990 * @param string|null $code See ApiErrorFormatter::addError()
1991 * @param array|null $data See ApiErrorFormatter::addError()
1992 * @param int|null $httpCode HTTP error code to use
1993 * @throws ApiUsageException always
1995 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1996 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
2000 * Abort execution with an error derived from an exception
2003 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
2004 * @param array $options See ApiErrorFormatter::getMessageFromException()
2005 * @throws ApiUsageException always
2007 public function dieWithException( $exception, array $options = [] ) {
2008 $this->dieWithError(
2009 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
2014 * Adds a warning to the output, else dies
2016 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2017 * @param bool $enforceLimits Whether this is an enforce (die)
2019 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2020 if ( $enforceLimits ) {
2021 $this->dieWithError( $msg );
2023 $this->addWarning( $msg );
2028 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2029 * error handler and die with an error message including block info.
2032 * @param AbstractBlock $block The block used to generate the ApiUsageException
2033 * @throws ApiUsageException always
2035 public function dieBlocked( AbstractBlock
$block ) {
2036 // Die using the appropriate message depending on block type
2037 if ( $block->getType() == Block
::TYPE_AUTO
) {
2038 $this->dieWithError(
2039 'apierror-autoblocked',
2041 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2043 } elseif ( !$block->isSitewide() ) {
2044 $this->dieWithError(
2045 'apierror-blocked-partial',
2047 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2050 $this->dieWithError(
2053 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2059 * Throw an ApiUsageException based on the Status object.
2062 * @since 1.29 Accepts a StatusValue
2063 * @param StatusValue $status
2064 * @throws ApiUsageException always
2066 public function dieStatus( StatusValue
$status ) {
2067 if ( $status->isGood() ) {
2068 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2071 // ApiUsageException needs a fatal status, but this method has
2072 // historically accepted any non-good status. Convert it if necessary.
2073 $status->setOK( false );
2074 if ( !$status->getErrorsByType( 'error' ) ) {
2075 $newStatus = Status
::newGood();
2076 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2077 $newStatus->fatal( $err['message'], ...$err['params'] );
2079 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2080 $newStatus->fatal( 'unknownerror-nocode' );
2082 $status = $newStatus;
2085 $this->addBlockInfoToStatus( $status );
2086 throw new ApiUsageException( $this, $status );
2090 * Helper function for readonly errors
2092 * @throws ApiUsageException always
2094 public function dieReadOnly() {
2095 $this->dieWithError(
2096 'apierror-readonly',
2098 [ 'readonlyreason' => wfReadOnlyReason() ]
2103 * Helper function for permission-denied errors
2105 * @param string|string[] $rights
2106 * @param User|null $user
2107 * @throws ApiUsageException if the user doesn't have any of the rights.
2108 * The error message is based on $rights[0].
2110 public function checkUserRightsAny( $rights, $user = null ) {
2112 $user = $this->getUser();
2114 $rights = (array)$rights;
2115 if ( !$user->isAllowedAny( ...$rights ) ) {
2116 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2121 * Helper function for permission-denied errors
2123 * @since 1.33 Changed the third parameter from $user to $options.
2124 * @param Title $title
2125 * @param string|string[] $actions
2126 * @param array $options Additional options
2127 * - user: (User) User to use rather than $this->getUser()
2128 * - autoblock: (bool, default false) Whether to spread autoblocks
2129 * For compatibility, passing a User object is treated as the value for the 'user' option.
2130 * @throws ApiUsageException if the user doesn't have all of the rights.
2132 public function checkTitleUserPermissions( Title
$title, $actions, $options = [] ) {
2133 if ( !is_array( $options ) ) {
2134 wfDeprecated( '$user as the third parameter to ' . __METHOD__
, '1.33' );
2135 $options = [ 'user' => $options ];
2137 $user = $options['user'] ??
$this->getUser();
2140 foreach ( (array)$actions as $action ) {
2141 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2145 if ( !empty( $options['autoblock'] ) ) {
2146 $user->spreadAnyEditBlock();
2149 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2154 * Will only set a warning instead of failing if the global $wgDebugAPI
2155 * is set to true. Otherwise behaves exactly as self::dieWithError().
2158 * @param string|array|Message $msg
2159 * @param string|null $code
2160 * @param array|null $data
2161 * @param int|null $httpCode
2162 * @throws ApiUsageException
2164 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2165 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2166 $this->dieWithError( $msg, $code, $data, $httpCode );
2168 $this->addWarning( $msg, $code, $data );
2173 * Die with the 'badcontinue' error.
2175 * This call is common enough to make it into the base method.
2177 * @param bool $condition Will only die if this value is true
2178 * @throws ApiUsageException
2181 protected function dieContinueUsageIf( $condition ) {
2183 $this->dieWithError( 'apierror-badcontinue' );
2188 * Internal code errors should be reported with this method
2189 * @param string $method Method or function name
2190 * @param string $message Error message
2191 * @throws MWException always
2193 protected static function dieDebug( $method, $message ) {
2194 throw new MWException( "Internal error in $method: $message" );
2198 * Write logging information for API features to a debug log, for usage
2200 * @note Consider using $this->addDeprecation() instead to both warn and log.
2201 * @param string $feature Feature being used.
2203 public function logFeatureUsage( $feature ) {
2204 static $loggedFeatures = [];
2206 // Only log each feature once per request. We can get multiple calls from calls to
2207 // extractRequestParams() with different values for 'parseLimit', for example.
2208 if ( isset( $loggedFeatures[$feature] ) ) {
2211 $loggedFeatures[$feature] = true;
2213 $request = $this->getRequest();
2215 'feature' => $feature,
2216 // Spaces to underscores in 'username' for historical reasons.
2217 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
2218 'ip' => $request->getIP(),
2219 'referer' => (string)$request->getHeader( 'Referer' ),
2220 'agent' => $this->getMain()->getUserAgent(),
2223 // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
2224 $s = '"' . addslashes( $ctx['feature'] ) . '"' .
2225 ' "' . wfUrlencode( $ctx['username'] ) . '"' .
2226 ' "' . $ctx['ip'] . '"' .
2227 ' "' . addslashes( $ctx['referer'] ) . '"' .
2228 ' "' . addslashes( $ctx['agent'] ) . '"';
2230 wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
2235 /************************************************************************//**
2236 * @name Help message generation
2241 * Return the summary message.
2243 * This is a one-line description of the module, suitable for display in a
2247 * @return string|array|Message
2249 protected function getSummaryMessage() {
2250 return "apihelp-{$this->getModulePath()}-summary";
2254 * Return the extended help text message.
2256 * This is additional text to display at the top of the help section, below
2260 * @return string|array|Message
2262 protected function getExtendedDescription() {
2264 "apihelp-{$this->getModulePath()}-extended-description",
2265 'api-help-no-extended-description',
2270 * Get final module summary
2275 public function getFinalSummary() {
2276 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2277 $this->getModulePrefix(),
2278 $this->getModuleName(),
2279 $this->getModulePath(),
2285 * Get final module description, after hooks have had a chance to tweak it as
2288 * @since 1.25, returns Message[] rather than string[]
2291 public function getFinalDescription() {
2292 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2293 $this->getModulePrefix(),
2294 $this->getModuleName(),
2295 $this->getModulePath(),
2297 $extendedDescription = self
::makeMessage(
2298 $this->getExtendedDescription(), $this->getContext(), [
2299 $this->getModulePrefix(),
2300 $this->getModuleName(),
2301 $this->getModulePath(),
2305 $msgs = [ $summary, $extendedDescription ];
2307 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2313 * Get final list of parameters, after hooks have had a chance to
2314 * tweak it as needed.
2316 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2317 * @return array|bool False on no parameters
2318 * @since 1.21 $flags param added
2320 public function getFinalParams( $flags = 0 ) {
2321 $params = $this->getAllowedParams( $flags );
2326 if ( $this->needsToken() ) {
2327 $params['token'] = [
2328 self
::PARAM_TYPE
=> 'string',
2329 self
::PARAM_REQUIRED
=> true,
2330 self
::PARAM_SENSITIVE
=> true,
2331 self
::PARAM_HELP_MSG
=> [
2332 'api-help-param-token',
2333 $this->needsToken(),
2335 ] +
( $params['token'] ??
[] );
2338 // Avoid PHP 7.1 warning of passing $this by reference
2340 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2346 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2349 * @since 1.25, returns array of Message[] rather than array of string[]
2350 * @return array Keys are parameter names, values are arrays of Message objects
2352 public function getFinalParamDescription() {
2353 $prefix = $this->getModulePrefix();
2354 $name = $this->getModuleName();
2355 $path = $this->getModulePath();
2357 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2359 foreach ( $params as $param => $settings ) {
2360 if ( !is_array( $settings ) ) {
2364 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2365 $msg = $settings[self
::PARAM_HELP_MSG
];
2367 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2369 $msg = self
::makeMessage( $msg, $this->getContext(),
2370 [ $prefix, $param, $name, $path ] );
2372 self
::dieDebug( __METHOD__
,
2373 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2375 $msgs[$param] = [ $msg ];
2377 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2378 $settings[self
::PARAM_TYPE
] === 'submodule'
2380 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2381 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2383 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2385 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2386 $map[$submoduleName] = $prefix . $submoduleName;
2391 $deprecatedSubmodules = [];
2392 foreach ( $map as $v => $m ) {
2393 $arr = &$submodules;
2394 $isDeprecated = false;
2397 $submod = $this->getModuleFromPath( $m );
2399 $summary = $submod->getFinalSummary();
2400 $isDeprecated = $submod->isDeprecated();
2401 if ( $isDeprecated ) {
2402 $arr = &$deprecatedSubmodules;
2405 } catch ( ApiUsageException
$ex ) {
2409 $key = $summary->getKey();
2410 $params = $summary->getParams();
2412 $key = 'api-help-undocumented-module';
2415 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2416 $arr[] = $m->setContext( $this->getContext() );
2418 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2419 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2420 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2421 self
::dieDebug( __METHOD__
,
2422 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2424 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2425 self
::dieDebug( __METHOD__
,
2426 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2427 'ApiBase::PARAM_TYPE is an array' );
2430 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2431 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2433 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2434 if ( isset( $valueMsgs[$value] ) ) {
2435 $msg = $valueMsgs[$value];
2437 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2439 $m = self
::makeMessage( $msg, $this->getContext(),
2440 [ $prefix, $param, $name, $path, $value ] );
2442 $m = new ApiHelpParamValueMessage(
2444 [ $m->getKey(), 'api-help-param-no-description' ],
2446 isset( $deprecatedValues[$value] )
2448 $msgs[$param][] = $m->setContext( $this->getContext() );
2450 self
::dieDebug( __METHOD__
,
2451 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2456 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2457 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2458 self
::dieDebug( __METHOD__
,
2459 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2461 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2462 $m = self
::makeMessage( $m, $this->getContext(),
2463 [ $prefix, $param, $name, $path ] );
2465 $msgs[$param][] = $m;
2467 self
::dieDebug( __METHOD__
,
2468 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2474 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2480 * Generates the list of flags for the help screen and for action=paraminfo
2482 * Corresponding messages: api-help-flag-deprecated,
2483 * api-help-flag-internal, api-help-flag-readrights,
2484 * api-help-flag-writerights, api-help-flag-mustbeposted
2488 protected function getHelpFlags() {
2491 if ( $this->isDeprecated() ) {
2492 $flags[] = 'deprecated';
2494 if ( $this->isInternal() ) {
2495 $flags[] = 'internal';
2497 if ( $this->isReadMode() ) {
2498 $flags[] = 'readrights';
2500 if ( $this->isWriteMode() ) {
2501 $flags[] = 'writerights';
2503 if ( $this->mustBePosted() ) {
2504 $flags[] = 'mustbeposted';
2511 * Returns information about the source of this module, if known
2513 * Returned array is an array with the following keys:
2514 * - path: Install path
2515 * - name: Extension name, or "MediaWiki" for core
2516 * - namemsg: (optional) i18n message key for a display name
2517 * - license-name: (optional) Name of license
2519 * @return array|null
2521 protected function getModuleSourceInfo() {
2524 if ( $this->mModuleSource
!== false ) {
2525 return $this->mModuleSource
;
2528 // First, try to find where the module comes from...
2529 $rClass = new ReflectionClass( $this );
2530 $path = $rClass->getFileName();
2533 $this->mModuleSource
= null;
2536 $path = realpath( $path ) ?
: $path;
2538 // Build map of extension directories to extension info
2539 if ( self
::$extensionInfo === null ) {
2540 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2541 self
::$extensionInfo = [
2542 realpath( __DIR__
) ?
: __DIR__
=> [
2544 'name' => 'MediaWiki',
2545 'license-name' => 'GPL-2.0-or-later',
2547 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2548 realpath( $extDir ) ?
: $extDir => null,
2554 'license-name' => null,
2556 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2557 foreach ( $group as $ext ) {
2558 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2559 // This shouldn't happen, but does anyway.
2563 $extpath = $ext['path'];
2564 if ( !is_dir( $extpath ) ) {
2565 $extpath = dirname( $extpath );
2567 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2568 array_intersect_key( $ext, $keep );
2571 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2572 $extpath = $ext['path'];
2573 if ( !is_dir( $extpath ) ) {
2574 $extpath = dirname( $extpath );
2576 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2577 array_intersect_key( $ext, $keep );
2581 // Now traverse parent directories until we find a match or run out of
2584 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2586 $this->mModuleSource
= self
::$extensionInfo[$path];
2587 return $this->mModuleSource
;
2591 $path = dirname( $path );
2592 } while ( $path !== $oldpath );
2594 // No idea what extension this might be.
2595 $this->mModuleSource
= null;
2600 * Called from ApiHelp before the pieces are joined together and returned.
2602 * This exists mainly for ApiMain to add the Permissions and Credits
2603 * sections. Other modules probably don't need it.
2605 * @param string[] &$help Array of help data
2606 * @param array $options Options passed to ApiHelp::getHelp
2607 * @param array &$tocData If a TOC is being generated, this array has keys
2608 * as anchors in the page and values as for Linker::generateTOC().
2610 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2615 /************************************************************************//**
2621 * Returns the description string for this module
2623 * Ignored if an i18n message exists for
2624 * "apihelp-{$this->getModulePath()}-description".
2626 * @deprecated since 1.25
2627 * @return Message|string|array|false
2629 protected function getDescription() {
2630 wfDeprecated( __METHOD__
, '1.25' );
2635 * Returns an array of parameter descriptions.
2637 * For each parameter, ignored if an i18n message exists for the parameter.
2638 * By default that message is
2639 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2640 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2641 * self::getFinalParams().
2643 * @deprecated since 1.25
2644 * @return array|bool False on no parameter descriptions
2646 protected function getParamDescription() {
2647 wfDeprecated( __METHOD__
, '1.25' );
2652 * Returns usage examples for this module.
2654 * Return value as an array is either:
2655 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2657 * - sequential numeric keys with even-numbered keys being display-text
2658 * and odd-numbered keys being partial urls
2659 * - partial URLs as keys with display-text (string or array-to-be-joined)
2661 * Return value as a string is the same as an array with a numeric key and
2662 * that value, and boolean false means "no examples".
2664 * @deprecated since 1.25, use getExamplesMessages() instead
2665 * @return bool|string|array
2667 protected function getExamples() {
2668 wfDeprecated( __METHOD__
, '1.25' );
2673 * Return the description message.
2675 * This is additional text to display on the help page after the summary.
2677 * @deprecated since 1.30
2678 * @return string|array|Message
2680 protected function getDescriptionMessage() {
2681 wfDeprecated( __METHOD__
, '1.30' );
2683 "apihelp-{$this->getModulePath()}-description",
2684 "apihelp-{$this->getModulePath()}-summary",
2692 * For really cool vim folding this needs to be at the end:
2693 * vim: foldmarker=@{,@} foldmethod=marker