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\MediaWikiServices
;
24 use Wikimedia\Rdbms\IDatabase
;
27 * This abstract class implements many basic API functions, and is the base of
29 * The class functions are divided into several areas of functionality:
31 * Module parameters: Derived classes can define getAllowedParams() to specify
32 * which parameters to expect, how to parse and validate them.
34 * Self-documentation: code to allow the API to document its own state
38 abstract class ApiBase
extends ContextSource
{
40 use ApiBlockInfoTrait
;
43 * @name Constants for ::getAllowedParams() arrays
44 * These constants are keys in the arrays returned by ::getAllowedParams()
45 * and accepted by ::getParameterFromSettings() that define how the
46 * parameters coming in from the request are to be interpreted.
50 /** (null|boolean|integer|string) Default value of the parameter. */
53 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
54 const PARAM_ISMULTI
= 1;
57 * (string|string[]) Either an array of allowed value strings, or a string
58 * type as described below. If not specified, will be determined from the
61 * Supported string types are:
62 * - boolean: A boolean parameter, returned as false if the parameter is
63 * omitted and true if present (even with a falsey value, i.e. it works
64 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
65 * Cannot be used with PARAM_ISMULTI.
66 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
67 * PARAM_RANGE_ENFORCE.
68 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
69 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
70 * specified. Cannot be used with PARAM_ISMULTI.
71 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
72 * support easily specifying all namespaces.
74 * - password: Any non-empty string. Input value is private or sensitive.
75 * <input type="password"> would be an appropriate HTML form field.
76 * - string: Any non-empty string, not expected to be very long or contain newlines.
77 * <input type="text"> would be an appropriate HTML form field.
78 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
79 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
80 * used with PARAM_ISMULTI.
81 * - text: Any non-empty string, expected to be very long or contain newlines.
82 * <textarea> would be an appropriate HTML form field.
83 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
84 * string 'now' representing the current timestamp. Will be returned in
86 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
87 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
88 * Cannot be used with PARAM_ISMULTI.
92 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
96 * (integer) Max value allowed for the parameter for users with the
97 * apihighlimits right, for PARAM_TYPE 'limit'.
101 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
104 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
105 const PARAM_ALLOW_DUPLICATES
= 6;
107 /** (boolean) Is the parameter deprecated (will show a warning)? */
108 const PARAM_DEPRECATED
= 7;
111 * (boolean) Is the parameter required?
114 const PARAM_REQUIRED
= 8;
117 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
120 const PARAM_RANGE_ENFORCE
= 9;
123 * (string|array|Message) Specify an alternative i18n documentation message
124 * for this parameter. Default is apihelp-{$path}-param-{$param}.
127 const PARAM_HELP_MSG
= 10;
130 * ((string|array|Message)[]) Specify additional i18n messages to append to
131 * the normal message for this parameter.
134 const PARAM_HELP_MSG_APPEND
= 11;
137 * (array) Specify additional information tags for the parameter. Value is
138 * an array of arrays, with the first member being the 'tag' for the info
139 * and the remaining members being the values. In the help, this is
140 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
141 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
144 const PARAM_HELP_MSG_INFO
= 12;
147 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
148 * those values to page titles which will be linked in the help.
151 const PARAM_VALUE_LINKS
= 13;
154 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
155 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
156 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
157 * Specify an empty array to use the default message key for all values.
160 const PARAM_HELP_MSG_PER_VALUE
= 14;
163 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
164 * submodule paths. Default is to use all modules in
165 * $this->getModuleManager() in the group matching the parameter name.
168 const PARAM_SUBMODULE_MAP
= 15;
171 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
172 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
175 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
178 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
179 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
180 * every possible value. If a string is set, it will be used in place of the asterisk.
183 const PARAM_ALL
= 17;
186 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
189 const PARAM_EXTRA_NAMESPACES
= 18;
192 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
193 * always sensitive regardless of the value of this field.
196 const PARAM_SENSITIVE
= 19;
199 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
200 * Keys are the deprecated parameter values, values define the warning
201 * message to emit: either boolean true (to use a default message) or a
202 * $msg for ApiBase::makeMessage().
205 const PARAM_DEPRECATED_VALUES
= 20;
208 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
211 const PARAM_ISMULTI_LIMIT1
= 21;
214 * (integer) Maximum number of values, for users with the apihighimits right.
215 * Must be used with PARAM_ISMULTI.
218 const PARAM_ISMULTI_LIMIT2
= 22;
221 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
224 const PARAM_MAX_BYTES
= 23;
227 * (integer) Maximum length of a string in characters (unicode codepoints).
230 const PARAM_MAX_CHARS
= 24;
233 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
234 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
235 * which the replacement values are taken.
237 * For example, a parameter "foo-{ns}-{title}" could be defined with
238 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
239 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
241 * All placeholders must be present in the parameter's name. Each target parameter must have
242 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
243 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
244 * A parameter cannot target itself.
248 const PARAM_TEMPLATE_VARS
= 25;
252 const ALL_DEFAULT_STRING
= '*';
254 /** Fast query, standard limit. */
255 const LIMIT_BIG1
= 500;
256 /** Fast query, apihighlimits limit. */
257 const LIMIT_BIG2
= 5000;
258 /** Slow query, standard limit. */
259 const LIMIT_SML1
= 50;
260 /** Slow query, apihighlimits limit. */
261 const LIMIT_SML2
= 500;
264 * getAllowedParams() flag: When set, the result could take longer to generate,
265 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
268 const GET_VALUES_FOR_HELP
= 1;
270 /** @var array Maps extension paths to info arrays */
271 private static $extensionInfo = null;
273 /** @var int[][][] Cache for self::filterIDs() */
274 private static $filterIDsCache = [];
276 /** $var array Map of web UI block messages to corresponding API messages and codes */
277 private static $blockMsgMap = [
278 'blockedtext' => [ 'apierror-blocked', 'blocked' ],
279 'blockedtext-partial' => [ 'apierror-blocked', 'blocked' ],
280 'autoblockedtext' => [ 'apierror-autoblocked', 'autoblocked' ],
281 'systemblockedtext' => [ 'apierror-systemblocked', 'blocked' ],
285 private $mMainModule;
287 private $mModuleName, $mModulePrefix;
288 private $mReplicaDB = null;
289 private $mParamCache = [];
290 /** @var array|null|bool */
291 private $mModuleSource = false;
294 * @param ApiMain $mainModule
295 * @param string $moduleName Name of this module
296 * @param string $modulePrefix Prefix to use for parameter names
298 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
299 $this->mMainModule
= $mainModule;
300 $this->mModuleName
= $moduleName;
301 $this->mModulePrefix
= $modulePrefix;
303 if ( !$this->isMain() ) {
304 $this->setContext( $mainModule->getContext() );
308 /************************************************************************//**
309 * @name Methods to implement
314 * Evaluates the parameters, performs the requested query, and sets up
315 * the result. Concrete implementations of ApiBase must override this
316 * method to provide whatever functionality their module offers.
317 * Implementations must not produce any output on their own and are not
318 * expected to handle any errors.
320 * The execute() method will be invoked directly by ApiMain immediately
321 * before the result of the module is output. Aside from the
322 * constructor, implementations should assume that no other methods
323 * will be called externally on the module before the result is
326 * The result data should be stored in the ApiResult object available
327 * through getResult().
329 abstract public function execute();
332 * Get the module manager, or null if this module has no sub-modules
334 * @return ApiModuleManager
336 public function getModuleManager() {
341 * If the module may only be used with a certain format module,
342 * it should override this method to return an instance of that formatter.
343 * A value of null means the default format will be used.
344 * @note Do not use this just because you don't want to support non-json
345 * formats. This should be used only when there is a fundamental
346 * requirement for a specific format.
347 * @return mixed Instance of a derived class of ApiFormatBase, or null
349 public function getCustomPrinter() {
354 * Returns usage examples for this module.
356 * Return value has query strings as keys, with values being either strings
357 * (message key), arrays (message key + parameter), or Message objects.
359 * Do not call this base class implementation when overriding this method.
364 protected function getExamplesMessages() {
369 * Return links to more detailed help pages about the module.
370 * @since 1.25, returning boolean false is deprecated
371 * @return string|array
373 public function getHelpUrls() {
378 * Returns an array of allowed parameters (parameter name) => (default
379 * value) or (parameter name) => (array with PARAM_* constants as keys)
380 * Don't call this function directly: use getFinalParams() to allow
381 * hooks to modify parameters as needed.
383 * Some derived classes may choose to handle an integer $flags parameter
384 * in the overriding methods. Callers of this method can pass zero or
385 * more OR-ed flags like GET_VALUES_FOR_HELP.
389 protected function getAllowedParams( /* $flags = 0 */ ) {
390 // int $flags is not declared because it causes "Strict standards"
391 // warning. Most derived classes do not implement it.
396 * Indicates if this module needs maxlag to be checked
399 public function shouldCheckMaxlag() {
404 * Indicates whether this module requires read rights
407 public function isReadMode() {
412 * Indicates whether this module requires write mode
414 * This should return true for modules that may require synchronous database writes.
415 * Modules that do not need such writes should also not rely on master database access,
416 * since only read queries are needed and each master DB is a single point of failure.
417 * Additionally, requests that only need replica DBs can be efficiently routed to any
418 * datacenter via the Promise-Non-Write-API-Action header.
422 public function isWriteMode() {
427 * Indicates whether this module must be called with a POST request
430 public function mustBePosted() {
431 return $this->needsToken() !== false;
435 * Indicates whether this module is deprecated
439 public function isDeprecated() {
444 * Indicates whether this module is "internal"
445 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
449 public function isInternal() {
454 * Returns the token type this module requires in order to execute.
456 * Modules are strongly encouraged to use the core 'csrf' type unless they
457 * have specialized security needs. If the token type is not one of the
458 * core types, you must use the ApiQueryTokensRegisterTypes hook to
461 * Returning a non-falsey value here will force the addition of an
462 * appropriate 'token' parameter in self::getFinalParams(). Also,
463 * self::mustBePosted() must return true when tokens are used.
465 * In previous versions of MediaWiki, true was a valid return value.
466 * Returning true will generate errors indicating that the API module needs
469 * @return string|false
471 public function needsToken() {
476 * Fetch the salt used in the Web UI corresponding to this module.
478 * Only override this if the Web UI uses a token with a non-constant salt.
481 * @param array $params All supplied parameters for the module
482 * @return string|array|null
484 protected function getWebUITokenSalt( array $params ) {
489 * Returns data for HTTP conditional request mechanisms.
492 * @param string $condition Condition being queried:
493 * - last-modified: Return a timestamp representing the maximum of the
494 * last-modified dates for all resources involved in the request. See
495 * RFC 7232 § 2.2 for semantics.
496 * - etag: Return an entity-tag representing the state of all resources involved
497 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
498 * @return string|bool|null As described above, or null if no value is available.
500 public function getConditionalRequestData( $condition ) {
506 /************************************************************************//**
507 * @name Data access methods
512 * Get the name of the module being executed by this instance
515 public function getModuleName() {
516 return $this->mModuleName
;
520 * Get parameter prefix (usually two letters or an empty string).
523 public function getModulePrefix() {
524 return $this->mModulePrefix
;
528 * Get the main module
531 public function getMain() {
532 return $this->mMainModule
;
536 * Returns true if this module is the main module ($this === $this->mMainModule),
540 public function isMain() {
541 return $this === $this->mMainModule
;
545 * Get the parent of this module
547 * @return ApiBase|null
549 public function getParent() {
550 return $this->isMain() ?
null : $this->getMain();
554 * Returns true if the current request breaks the same-origin policy.
556 * For example, json with callbacks.
558 * https://en.wikipedia.org/wiki/Same-origin_policy
563 public function lacksSameOriginSecurity() {
564 // Main module has this method overridden
565 // Safety - avoid infinite loop:
566 if ( $this->isMain() ) {
567 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
570 return $this->getMain()->lacksSameOriginSecurity();
574 * Get the path to this module
579 public function getModulePath() {
580 if ( $this->isMain() ) {
582 } elseif ( $this->getParent()->isMain() ) {
583 return $this->getModuleName();
585 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
590 * Get a module from its module path
593 * @param string $path
594 * @return ApiBase|null
595 * @throws ApiUsageException
597 public function getModuleFromPath( $path ) {
598 $module = $this->getMain();
599 if ( $path === 'main' ) {
603 $parts = explode( '+', $path );
604 if ( count( $parts ) === 1 ) {
605 // In case the '+' was typed into URL, it resolves as a space
606 $parts = explode( ' ', $path );
609 $count = count( $parts );
610 for ( $i = 0; $i < $count; $i++
) {
612 $manager = $parent->getModuleManager();
613 if ( $manager === null ) {
614 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
615 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
617 $module = $manager->getModule( $parts[$i] );
619 if ( $module === null ) {
620 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
622 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
632 * Get the result object
635 public function getResult() {
636 // Main module has getResult() method overridden
637 // Safety - avoid infinite loop:
638 if ( $this->isMain() ) {
639 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
642 return $this->getMain()->getResult();
646 * Get the error formatter
647 * @return ApiErrorFormatter
649 public function getErrorFormatter() {
650 // Main module has getErrorFormatter() method overridden
651 // Safety - avoid infinite loop:
652 if ( $this->isMain() ) {
653 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
656 return $this->getMain()->getErrorFormatter();
660 * Gets a default replica DB connection object
663 protected function getDB() {
664 if ( !isset( $this->mReplicaDB
) ) {
665 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
668 return $this->mReplicaDB
;
672 * Get the continuation manager
673 * @return ApiContinuationManager|null
675 public function getContinuationManager() {
676 // Main module has getContinuationManager() method overridden
677 // Safety - avoid infinite loop:
678 if ( $this->isMain() ) {
679 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
682 return $this->getMain()->getContinuationManager();
686 * Set the continuation manager
687 * @param ApiContinuationManager|null $manager
689 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
690 // Main module has setContinuationManager() method overridden
691 // Safety - avoid infinite loop:
692 if ( $this->isMain() ) {
693 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
696 $this->getMain()->setContinuationManager( $manager );
701 /************************************************************************//**
702 * @name Parameter handling
707 * Indicate if the module supports dynamically-determined parameters that
708 * cannot be included in self::getAllowedParams().
709 * @return string|array|Message|null Return null if the module does not
710 * support additional dynamic parameters, otherwise return a message
713 public function dynamicParameterDocumentation() {
718 * This method mangles parameter name based on the prefix supplied to the constructor.
719 * Override this method to change parameter name during runtime
720 * @param string|string[] $paramName Parameter name
721 * @return string|string[] Prefixed parameter name
722 * @since 1.29 accepts an array of strings
724 public function encodeParamName( $paramName ) {
725 if ( is_array( $paramName ) ) {
726 return array_map( function ( $name ) {
727 return $this->mModulePrefix
. $name;
730 return $this->mModulePrefix
. $paramName;
735 * Using getAllowedParams(), this function makes an array of the values
736 * provided by the user, with key being the name of the variable, and
737 * value - validated value from user or default. limits will not be
738 * parsed if $parseLimit is set to false; use this when the max
739 * limit is not definitive yet, e.g. when getting revisions.
740 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
741 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
742 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
743 * Returned parameter values might be ApiUsageException instances.
746 public function extractRequestParams( $options = [] ) {
747 if ( is_bool( $options ) ) {
748 $options = [ 'parseLimit' => $options ];
751 'parseLimit' => true,
755 $parseLimit = (bool)$options['parseLimit'];
757 // Cache parameters, for performance and to avoid T26564.
758 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
759 $params = $this->getFinalParams() ?
: [];
763 // Process all non-templates and save templates for secondary
766 foreach ( $params as $paramName => $paramSettings ) {
767 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
768 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
771 $results[$paramName] = $this->getParameterFromSettings(
772 $paramName, $paramSettings, $parseLimit
774 } catch ( ApiUsageException
$ex ) {
775 $results[$paramName] = $ex;
780 // Now process all the templates by successively replacing the
781 // placeholders with all client-supplied values.
782 // This bit duplicates JavaScript logic in
783 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
784 // If you update this, see if that needs updating too.
785 while ( $toProcess ) {
786 list( $name, $targets, $settings ) = array_shift( $toProcess );
788 foreach ( $targets as $placeholder => $target ) {
789 if ( !array_key_exists( $target, $results ) ) {
790 // The target wasn't processed yet, try the next one.
791 // If all hit this case, the parameter has no expansions.
794 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
795 // The target was processed but has no (valid) values.
796 // That means it has no expansions.
800 // Expand this target in the name and all other targets,
801 // then requeue if there are more targets left or put in
802 // $results if all are done.
803 unset( $targets[$placeholder] );
804 $placeholder = '{' . $placeholder . '}';
805 // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
806 foreach ( $results[$target] as $value ) {
807 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
808 // Skip values that make invalid parameter names.
809 $encTargetName = $this->encodeParamName( $target );
810 if ( !isset( $warned[$encTargetName][$value] ) ) {
811 $warned[$encTargetName][$value] = true;
813 'apiwarn-ignoring-invalid-templated-value',
814 wfEscapeWikiText( $encTargetName ),
815 wfEscapeWikiText( $value ),
821 $newName = str_replace( $placeholder, $value, $name );
824 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
825 } catch ( ApiUsageException
$ex ) {
826 $results[$newName] = $ex;
830 foreach ( $targets as $k => $v ) {
831 $newTargets[$k] = str_replace( $placeholder, $value, $v );
833 $toProcess[] = [ $newName, $newTargets, $settings ];
840 $this->mParamCache
[$parseLimit] = $results;
843 $ret = $this->mParamCache
[$parseLimit];
844 if ( !$options['safeMode'] ) {
845 foreach ( $ret as $v ) {
846 if ( $v instanceof ApiUsageException
) {
852 return $this->mParamCache
[$parseLimit];
856 * Get a value for the given parameter
857 * @param string $paramName Parameter name
858 * @param bool $parseLimit See extractRequestParams()
859 * @return mixed Parameter value
861 protected function getParameter( $paramName, $parseLimit = true ) {
862 $ret = $this->extractRequestParams( [
863 'parseLimit' => $parseLimit,
866 if ( $ret instanceof ApiUsageException
) {
873 * Die if none or more than one of a certain set of parameters is set and not false.
875 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
876 * @param string $required,... Names of parameters of which exactly one must be set
878 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
879 $required = func_get_args();
880 array_shift( $required );
882 $intersection = array_intersect( array_keys( array_filter( $params,
883 [ $this, 'parameterNotEmpty' ] ) ), $required );
885 if ( count( $intersection ) > 1 ) {
886 $this->dieWithError( [
887 'apierror-invalidparammix',
888 Message
::listParam( array_map(
890 return '<var>' . $this->encodeParamName( $p ) . '</var>';
892 array_values( $intersection )
894 count( $intersection ),
896 } elseif ( count( $intersection ) == 0 ) {
897 $this->dieWithError( [
898 'apierror-missingparam-one-of',
899 Message
::listParam( array_map(
901 return '<var>' . $this->encodeParamName( $p ) . '</var>';
903 array_values( $required )
911 * Die if more than one of a certain set of parameters is set and not false.
913 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
914 * @param string $required,... Names of parameters of which at most one must be set
916 public function requireMaxOneParameter( $params, $required /*...*/ ) {
917 $required = func_get_args();
918 array_shift( $required );
920 $intersection = array_intersect( array_keys( array_filter( $params,
921 [ $this, 'parameterNotEmpty' ] ) ), $required );
923 if ( count( $intersection ) > 1 ) {
924 $this->dieWithError( [
925 'apierror-invalidparammix',
926 Message
::listParam( array_map(
928 return '<var>' . $this->encodeParamName( $p ) . '</var>';
930 array_values( $intersection )
932 count( $intersection ),
938 * Die if none of a certain set of parameters is set and not false.
941 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
942 * @param string $required,... Names of parameters of which at least one must be set
944 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
945 $required = func_get_args();
946 array_shift( $required );
948 $intersection = array_intersect(
949 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
953 if ( count( $intersection ) == 0 ) {
954 $this->dieWithError( [
955 'apierror-missingparam-at-least-one-of',
956 Message
::listParam( array_map(
958 return '<var>' . $this->encodeParamName( $p ) . '</var>';
960 array_values( $required )
968 * Die if any of the specified parameters were found in the query part of
969 * the URL rather than the post body.
971 * @param string[] $params Parameters to check
972 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
974 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
975 // Skip if $wgDebugAPI is set or we're in internal mode
976 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
980 $queryValues = $this->getRequest()->getQueryValues();
982 foreach ( $params as $param ) {
983 if ( $prefix !== 'noprefix' ) {
984 $param = $this->encodeParamName( $param );
986 if ( array_key_exists( $param, $queryValues ) ) {
987 $badParams[] = $param;
993 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
999 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
1001 * @param object $x Parameter to check is not null/false
1004 private function parameterNotEmpty( $x ) {
1005 return !is_null( $x ) && $x !== false;
1009 * Get a WikiPage object from a title or pageid param, if possible.
1010 * Can die, if no param is set or if the title or page id is not valid.
1012 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1013 * @param bool|string $load Whether load the object's state from the database:
1014 * - false: don't load (if the pageid is given, it will still be loaded)
1015 * - 'fromdb': load from a replica DB
1016 * - 'fromdbmaster': load from the master database
1019 public function getTitleOrPageId( $params, $load = false ) {
1020 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1023 if ( isset( $params['title'] ) ) {
1024 $titleObj = Title
::newFromText( $params['title'] );
1025 if ( !$titleObj ||
$titleObj->isExternal() ) {
1026 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1028 if ( !$titleObj->canExist() ) {
1029 $this->dieWithError( 'apierror-pagecannotexist' );
1031 $pageObj = WikiPage
::factory( $titleObj );
1032 if ( $load !== false ) {
1033 $pageObj->loadPageData( $load );
1035 } elseif ( isset( $params['pageid'] ) ) {
1036 if ( $load === false ) {
1039 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1041 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1049 * Get a Title object from a title or pageid param, if possible.
1050 * Can die, if no param is set or if the title or page id is not valid.
1053 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1056 public function getTitleFromTitleOrPageId( $params ) {
1057 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1060 if ( isset( $params['title'] ) ) {
1061 $titleObj = Title
::newFromText( $params['title'] );
1062 if ( !$titleObj ||
$titleObj->isExternal() ) {
1063 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1066 } elseif ( isset( $params['pageid'] ) ) {
1067 $titleObj = Title
::newFromID( $params['pageid'] );
1069 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1077 * Return true if we're to watch the page, false if not, null if no change.
1078 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1079 * @param Title $titleObj The page under consideration
1080 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1081 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1084 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1085 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1087 switch ( $watchlist ) {
1095 # If the user is already watching, don't bother checking
1096 if ( $userWatching ) {
1099 # If no user option was passed, use watchdefault and watchcreations
1100 if ( is_null( $userOption ) ) {
1101 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1102 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1105 # Watch the article based on the user preference
1106 return $this->getUser()->getBoolOption( $userOption );
1109 return $userWatching;
1112 return $userWatching;
1117 * Using the settings determine the value for the given parameter
1119 * @param string $paramName Parameter name
1120 * @param array|mixed $paramSettings Default value or an array of settings
1121 * using PARAM_* constants.
1122 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1123 * @return mixed Parameter value
1125 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1126 // Some classes may decide to change parameter names
1127 $encParamName = $this->encodeParamName( $paramName );
1130 if ( !is_array( $paramSettings ) ) {
1132 self
::PARAM_DFLT
=> $paramSettings,
1136 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1137 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1138 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1139 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1140 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1141 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1142 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1143 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1144 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1145 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1147 // When type is not given, and no choices, the type is the same as $default
1148 if ( !isset( $type ) ) {
1149 if ( isset( $default ) ) {
1150 $type = gettype( $default );
1152 $type = 'NULL'; // allow everything
1156 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1157 $this->getMain()->markParamsSensitive( $encParamName );
1160 if ( $type == 'boolean' ) {
1161 if ( isset( $default ) && $default !== false ) {
1162 // Having a default value of anything other than 'false' is not allowed
1165 "Boolean param $encParamName's default is set to '$default'. " .
1166 'Boolean parameters must default to false.'
1170 $value = $this->getMain()->getCheck( $encParamName );
1172 } elseif ( $type == 'upload' ) {
1173 if ( isset( $default ) ) {
1174 // Having a default value is not allowed
1177 "File upload param $encParamName's default is set to " .
1178 "'$default'. File upload parameters may not have a default." );
1181 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1183 $value = $this->getMain()->getUpload( $encParamName );
1184 $provided = $value->exists();
1185 if ( !$value->exists() ) {
1186 // This will get the value without trying to normalize it
1187 // (because trying to normalize a large binary file
1188 // accidentally uploaded as a field fails spectacularly)
1189 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1190 if ( $value !== null ) {
1191 $this->dieWithError(
1192 [ 'apierror-badupload', $encParamName ],
1193 "badupload_{$encParamName}"
1198 $value = $this->getMain()->getVal( $encParamName, $default );
1199 $provided = $this->getMain()->getCheck( $encParamName );
1201 if ( isset( $value ) && $type == 'namespace' ) {
1202 $type = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1203 getValidNamespaces();
1204 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1205 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1207 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1209 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1210 // specify all namespaces irrespective of PARAM_ALL.
1213 if ( isset( $value ) && $type == 'submodule' ) {
1214 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1215 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1217 $type = $this->getModuleManager()->getNames( $paramName );
1221 $request = $this->getMain()->getRequest();
1222 $rawValue = $request->getRawVal( $encParamName );
1223 if ( $rawValue === null ) {
1224 $rawValue = $default;
1227 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1228 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1230 // This loses the potential checkTitleEncoding() transformation done by
1231 // WebRequest for $_GET. Let's call that a feature.
1232 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1234 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1238 // Check for NFC normalization, and warn
1239 if ( $rawValue !== $value ) {
1240 $this->handleParamNormalization( $paramName, $value, $rawValue );
1244 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1245 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1248 "For param $encParamName, PARAM_ALL collides with a possible value" );
1250 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1251 $value = $this->parseMultiValue(
1255 is_array( $type ) ?
$type : null,
1256 $allowAll ?
$allSpecifier : null,
1262 if ( isset( $value ) ) {
1263 // More validation only when choices were not given
1264 // choices were validated in parseMultiValue()
1265 if ( !is_array( $type ) ) {
1267 case 'NULL': // nothing to do
1272 if ( $required && $value === '' ) {
1273 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1276 case 'integer': // Force everything using intval() and optionally validate limits
1277 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1278 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1279 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1281 if ( is_array( $value ) ) {
1282 $value = array_map( 'intval', $value );
1283 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1284 foreach ( $value as &$v ) {
1285 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1289 $value = (int)$value;
1290 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1291 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1296 if ( !$parseLimit ) {
1297 // Don't do any validation whatsoever
1300 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1301 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1305 "MAX1 or MAX2 are not defined for the limit $encParamName"
1309 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1311 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1312 if ( $value == 'max' ) {
1313 $value = $this->getMain()->canApiHighLimits()
1314 ?
$paramSettings[self
::PARAM_MAX2
]
1315 : $paramSettings[self
::PARAM_MAX
];
1316 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1318 $value = (int)$value;
1319 $this->validateLimit(
1323 $paramSettings[self
::PARAM_MAX
],
1324 $paramSettings[self
::PARAM_MAX2
]
1330 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1334 if ( is_array( $value ) ) {
1335 foreach ( $value as $key => $val ) {
1336 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1339 $value = $this->validateTimestamp( $value, $encParamName );
1343 if ( is_array( $value ) ) {
1344 foreach ( $value as $key => $val ) {
1345 $value[$key] = $this->validateUser( $val, $encParamName );
1348 $value = $this->validateUser( $value, $encParamName );
1351 case 'upload': // nothing to do
1354 // If change tagging was requested, check that the tags are valid.
1355 if ( !is_array( $value ) && !$multi ) {
1356 $value = [ $value ];
1358 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1359 if ( !$tagsStatus->isGood() ) {
1360 $this->dieStatus( $tagsStatus );
1364 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1368 // Throw out duplicates if requested
1369 if ( !$dupes && is_array( $value ) ) {
1370 $value = array_unique( $value );
1373 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1374 foreach ( (array)$value as $val ) {
1375 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1376 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1378 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1379 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1381 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1382 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1384 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1385 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1390 // Set a warning if a deprecated parameter has been passed
1391 if ( $deprecated && $provided ) {
1392 $feature = $encParamName;
1394 while ( !$m->isMain() ) {
1395 $p = $m->getParent();
1396 $name = $m->getModuleName();
1397 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1398 $feature = "{$param}={$name}&{$feature}";
1401 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1404 // Set a warning if a deprecated parameter value has been passed
1405 $usedDeprecatedValues = $deprecatedValues && $provided
1406 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1408 if ( $usedDeprecatedValues ) {
1409 $feature = "$encParamName=";
1411 while ( !$m->isMain() ) {
1412 $p = $m->getParent();
1413 $name = $m->getModuleName();
1414 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1415 $feature = "{$param}={$name}&{$feature}";
1418 foreach ( $usedDeprecatedValues as $v ) {
1419 $msg = $deprecatedValues[$v];
1420 if ( $msg === true ) {
1421 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1423 $this->addDeprecation( $msg, "$feature$v" );
1426 } elseif ( $required ) {
1427 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1434 * Handle when a parameter was Unicode-normalized
1436 * @param string $paramName Unprefixed parameter name
1437 * @param string $value Input that will be used.
1438 * @param string $rawValue Input before normalization.
1440 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1441 $encParamName = $this->encodeParamName( $paramName );
1442 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1446 * Split a multi-valued parameter string, like explode()
1448 * @param string $value
1452 protected function explodeMultiValue( $value, $limit ) {
1453 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1455 $value = substr( $value, 1 );
1460 return explode( $sep, $value, $limit );
1464 * Return an array of values that were given in a 'a|b|c' notation,
1465 * after it optionally validates them against the list allowed values.
1467 * @param string $valueName The name of the parameter (for error
1469 * @param mixed $value The value being parsed
1470 * @param bool $allowMultiple Can $value contain more than one value
1472 * @param string[]|null $allowedValues An array of values to check against. If
1473 * null, all values are accepted.
1474 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1475 * if this behavior should not be allowed
1476 * @param int|null $limit1 Maximum number of values, for normal users.
1477 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1478 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1480 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1481 $allSpecifier = null, $limit1 = null, $limit2 = null
1483 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1486 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1487 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1489 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1490 // because it unstubs $wgUser
1491 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1492 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1496 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1497 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1499 return $allowedValues;
1502 if ( count( $valuesList ) > $sizeLimit ) {
1503 $this->dieWithError(
1504 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1505 "too-many-$valueName"
1509 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1510 // T35482 - Allow entries with | in them for non-multiple values
1511 if ( in_array( $value, $allowedValues, true ) ) {
1515 $values = array_map( function ( $v ) {
1516 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1517 }, $allowedValues );
1518 $this->dieWithError( [
1519 'apierror-multival-only-one-of',
1521 Message
::listParam( $values ),
1523 ], "multival_$valueName" );
1526 if ( is_array( $allowedValues ) ) {
1527 // Check for unknown values
1528 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1529 if ( count( $unknown ) ) {
1530 if ( $allowMultiple ) {
1531 $this->addWarning( [
1532 'apiwarn-unrecognizedvalues',
1534 Message
::listParam( $unknown, 'comma' ),
1538 $this->dieWithError(
1539 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1540 "unknown_$valueName"
1544 // Now throw them out
1545 $valuesList = array_intersect( $valuesList, $allowedValues );
1548 return $allowMultiple ?
$valuesList : $valuesList[0];
1552 * Validate the value against the minimum and user/bot maximum limits.
1553 * Prints usage info on failure.
1554 * @param string $paramName Parameter name
1555 * @param int &$value Parameter value
1556 * @param int|null $min Minimum value
1557 * @param int|null $max Maximum value for users
1558 * @param int|null $botMax Maximum value for sysops/bots
1559 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1561 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1562 $enforceLimits = false
1564 if ( !is_null( $min ) && $value < $min ) {
1565 $msg = ApiMessage
::create(
1566 [ 'apierror-integeroutofrange-belowminimum',
1567 $this->encodeParamName( $paramName ), $min, $value ],
1568 'integeroutofrange',
1569 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1571 $this->warnOrDie( $msg, $enforceLimits );
1575 // Minimum is always validated, whereas maximum is checked only if not
1576 // running in internal call mode
1577 if ( $this->getMain()->isInternalMode() ) {
1581 // Optimization: do not check user's bot status unless really needed -- skips db query
1582 // assumes $botMax >= $max
1583 if ( !is_null( $max ) && $value > $max ) {
1584 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1585 if ( $value > $botMax ) {
1586 $msg = ApiMessage
::create(
1587 [ 'apierror-integeroutofrange-abovebotmax',
1588 $this->encodeParamName( $paramName ), $botMax, $value ],
1589 'integeroutofrange',
1590 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1592 $this->warnOrDie( $msg, $enforceLimits );
1596 $msg = ApiMessage
::create(
1597 [ 'apierror-integeroutofrange-abovemax',
1598 $this->encodeParamName( $paramName ), $max, $value ],
1599 'integeroutofrange',
1600 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1602 $this->warnOrDie( $msg, $enforceLimits );
1609 * Validate and normalize parameters of type 'timestamp'
1610 * @param string $value Parameter value
1611 * @param string $encParamName Parameter name
1612 * @return string Validated and normalized parameter
1614 protected function validateTimestamp( $value, $encParamName ) {
1615 // Confusing synonyms for the current time accepted by wfTimestamp()
1616 // (wfTimestamp() also accepts various non-strings and the string of 14
1617 // ASCII NUL bytes, but those can't get here)
1619 $this->addDeprecation(
1620 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1621 'unclear-"now"-timestamp'
1623 return wfTimestamp( TS_MW
);
1626 // Explicit synonym for the current time
1627 if ( $value === 'now' ) {
1628 return wfTimestamp( TS_MW
);
1631 $timestamp = wfTimestamp( TS_MW
, $value );
1632 if ( $timestamp === false ) {
1633 $this->dieWithError(
1634 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1635 "badtimestamp_{$encParamName}"
1643 * Validate the supplied token.
1646 * @param string $token Supplied token
1647 * @param array $params All supplied parameters for the module
1649 * @throws MWException
1651 final public function validateToken( $token, array $params ) {
1652 $tokenType = $this->needsToken();
1653 $salts = ApiQueryTokens
::getTokenTypeSalts();
1654 if ( !isset( $salts[$tokenType] ) ) {
1655 throw new MWException(
1656 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1657 'without registering it'
1661 $tokenObj = ApiQueryTokens
::getToken(
1662 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1664 if ( $tokenObj->match( $token ) ) {
1668 $webUiSalt = $this->getWebUITokenSalt( $params );
1669 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1681 * Validate and normalize parameters of type 'user'
1682 * @param string $value Parameter value
1683 * @param string $encParamName Parameter name
1684 * @return string Validated and normalized parameter
1686 private function validateUser( $value, $encParamName ) {
1687 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1691 $name = User
::getCanonicalName( $value, 'valid' );
1692 if ( $name !== false ) {
1697 // We allow ranges as well, for blocks.
1698 IP
::isIPAddress( $value ) ||
1699 // See comment for User::isIP. We don't just call that function
1700 // here because it also returns true for things like
1701 // 300.300.300.300 that are neither valid usernames nor valid IP
1704 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1708 return IP
::sanitizeIP( $value );
1711 $this->dieWithError(
1712 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1713 "baduser_{$encParamName}"
1719 /************************************************************************//**
1720 * @name Utility methods
1725 * Set a watch (or unwatch) based the based on a watchlist parameter.
1726 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1727 * @param Title $titleObj The article's title to change
1728 * @param string|null $userOption The user option to consider when $watch=preferences
1730 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1731 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1732 if ( $value === null ) {
1736 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1740 * Gets the user for whom to get the watchlist
1742 * @param array $params
1745 public function getWatchlistUser( $params ) {
1746 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1747 $user = User
::newFromName( $params['owner'], false );
1748 if ( !( $user && $user->getId() ) ) {
1749 $this->dieWithError(
1750 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1753 $token = $user->getOption( 'watchlisttoken' );
1754 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1755 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1758 if ( !$this->getUser()->isLoggedIn() ) {
1759 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1761 $this->checkUserRightsAny( 'viewmywatchlist' );
1762 $user = $this->getUser();
1769 * Create a Message from a string or array
1771 * A string is used as a message key. An array has the message key as the
1772 * first value and message parameters as subsequent values.
1775 * @param string|array|Message $msg
1776 * @param IContextSource $context
1777 * @param array|null $params
1778 * @return Message|null
1780 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1781 if ( is_string( $msg ) ) {
1782 $msg = wfMessage( $msg );
1783 } elseif ( is_array( $msg ) ) {
1784 $msg = wfMessage( ...$msg );
1786 if ( !$msg instanceof Message
) {
1790 $msg->setContext( $context );
1792 $msg->params( $params );
1799 * Turn an array of message keys or key+param arrays into a Status
1801 * @param array $errors
1802 * @param User|null $user
1805 public function errorArrayToStatus( array $errors, User
$user = null ) {
1806 if ( $user === null ) {
1807 $user = $this->getUser();
1810 $status = Status
::newGood();
1811 foreach ( $errors as $error ) {
1812 if ( !is_array( $error ) ) {
1813 $error = [ $error ];
1815 if ( is_string( $error[0] ) && isset( self
::$blockMsgMap[$error[0]] ) && $user->getBlock() ) {
1816 list( $msg, $code ) = self
::$blockMsgMap[$error[0]];
1817 $status->fatal( ApiMessage
::create( $msg, $code,
1818 [ 'blockinfo' => $this->getBlockInfo( $user->getBlock() ) ]
1821 $status->fatal( ...$error );
1828 * Add block info to block messages in a Status
1830 * @param StatusValue $status
1831 * @param User|null $user
1833 public function addBlockInfoToStatus( StatusValue
$status, User
$user = null ) {
1834 if ( $user === null ) {
1835 $user = $this->getUser();
1838 foreach ( self
::$blockMsgMap as $msg => list( $apiMsg, $code ) ) {
1839 if ( $status->hasMessage( $msg ) && $user->getBlock() ) {
1840 $status->replaceMessage( $msg, ApiMessage
::create( $apiMsg, $code,
1841 [ 'blockinfo' => $this->getBlockInfo( $user->getBlock() ) ]
1848 * Call wfTransactionalTimeLimit() if this request was POSTed
1851 protected function useTransactionalTimeLimit() {
1852 if ( $this->getRequest()->wasPosted() ) {
1853 wfTransactionalTimeLimit();
1858 * Filter out-of-range values from a list of positive integer IDs
1860 * @param array $fields Array of pairs of table and field to check
1861 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1862 * expected to be stringified ints.
1863 * @return (string|int)[] Filtered IDs.
1865 protected function filterIDs( $fields, array $ids ) {
1868 foreach ( $fields as list( $table, $field ) ) {
1869 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1870 $row = self
::$filterIDsCache[$table][$field];
1872 $row = $this->getDB()->selectRow(
1875 'min_id' => "MIN($field)",
1876 'max_id' => "MAX($field)",
1881 self
::$filterIDsCache[$table][$field] = $row;
1883 $min = min( $min, $row->min_id
);
1884 $max = max( $max, $row->max_id
);
1886 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1887 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1888 && $id >= $min && $id <= $max;
1894 /************************************************************************//**
1895 * @name Warning and error reporting
1900 * Add a warning for this module.
1902 * Users should monitor this section to notice any changes in API. Multiple
1903 * calls to this function will result in multiple warning messages.
1905 * If $msg is not an ApiMessage, the message code will be derived from the
1906 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1909 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1910 * @param string|null $code See ApiErrorFormatter::addWarning()
1911 * @param array|null $data See ApiErrorFormatter::addWarning()
1913 public function addWarning( $msg, $code = null, $data = null ) {
1914 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1918 * Add a deprecation warning for this module.
1920 * A combination of $this->addWarning() and $this->logFeatureUsage()
1923 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1924 * @param string|null $feature See ApiBase::logFeatureUsage()
1925 * @param array|null $data See ApiErrorFormatter::addWarning()
1927 public function addDeprecation( $msg, $feature, $data = [] ) {
1928 $data = (array)$data;
1929 if ( $feature !== null ) {
1930 $data['feature'] = $feature;
1931 $this->logFeatureUsage( $feature );
1933 $this->addWarning( $msg, 'deprecation', $data );
1935 // No real need to deduplicate here, ApiErrorFormatter does that for
1936 // us (assuming the hook is deterministic).
1937 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1938 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1939 if ( count( $msgs ) > 1 ) {
1940 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1941 $msg = ( new RawMessage( $key ) )->params( $msgs );
1943 $msg = reset( $msgs );
1945 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1949 * Add an error for this module without aborting
1951 * If $msg is not an ApiMessage, the message code will be derived from the
1952 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1954 * @note If you want to abort processing, use self::dieWithError() instead.
1956 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1957 * @param string|null $code See ApiErrorFormatter::addError()
1958 * @param array|null $data See ApiErrorFormatter::addError()
1960 public function addError( $msg, $code = null, $data = null ) {
1961 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1965 * Add warnings and/or errors from a Status
1967 * @note If you want to abort processing, use self::dieStatus() instead.
1969 * @param StatusValue $status
1970 * @param string[] $types 'warning' and/or 'error'
1971 * @param string[] $filter Message keys to filter out (since 1.33)
1973 public function addMessagesFromStatus(
1974 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1976 $this->getErrorFormatter()->addMessagesFromStatus(
1977 $this->getModulePath(), $status, $types, $filter
1982 * Abort execution with an error
1984 * If $msg is not an ApiMessage, the message code will be derived from the
1985 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1988 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1989 * @param string|null $code See ApiErrorFormatter::addError()
1990 * @param array|null $data See ApiErrorFormatter::addError()
1991 * @param int|null $httpCode HTTP error code to use
1992 * @throws ApiUsageException always
1994 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1995 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1999 * Abort execution with an error derived from an exception
2002 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
2003 * @param array $options See ApiErrorFormatter::getMessageFromException()
2004 * @throws ApiUsageException always
2006 public function dieWithException( $exception, array $options = [] ) {
2007 $this->dieWithError(
2008 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
2013 * Adds a warning to the output, else dies
2015 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2016 * @param bool $enforceLimits Whether this is an enforce (die)
2018 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2019 if ( $enforceLimits ) {
2020 $this->dieWithError( $msg );
2022 $this->addWarning( $msg );
2027 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2028 * error handler and die with an error message including block info.
2031 * @param Block $block The block used to generate the ApiUsageException
2032 * @throws ApiUsageException always
2034 public function dieBlocked( Block
$block ) {
2035 // Die using the appropriate message depending on block type
2036 if ( $block->getType() == Block
::TYPE_AUTO
) {
2037 $this->dieWithError(
2038 'apierror-autoblocked',
2040 [ 'blockinfo' => $this->getBlockInfo( $block ) ]
2042 } elseif ( !$block->isSitewide() ) {
2043 $this->dieWithError(
2044 'apierror-blocked-partial',
2046 [ 'blockinfo' => $this->getBlockInfo( $block ) ]
2049 $this->dieWithError(
2052 [ 'blockinfo' => $this->getBlockInfo( $block ) ]
2058 * Throw an ApiUsageException based on the Status object.
2061 * @since 1.29 Accepts a StatusValue
2062 * @param StatusValue $status
2063 * @throws ApiUsageException always
2065 public function dieStatus( StatusValue
$status ) {
2066 if ( $status->isGood() ) {
2067 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2070 // ApiUsageException needs a fatal status, but this method has
2071 // historically accepted any non-good status. Convert it if necessary.
2072 $status->setOK( false );
2073 if ( !$status->getErrorsByType( 'error' ) ) {
2074 $newStatus = Status
::newGood();
2075 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2076 $newStatus->fatal( $err['message'], ...$err['params'] );
2078 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2079 $newStatus->fatal( 'unknownerror-nocode' );
2081 $status = $newStatus;
2084 $this->addBlockInfoToStatus( $status );
2085 throw new ApiUsageException( $this, $status );
2089 * Helper function for readonly errors
2091 * @throws ApiUsageException always
2093 public function dieReadOnly() {
2094 $this->dieWithError(
2095 'apierror-readonly',
2097 [ 'readonlyreason' => wfReadOnlyReason() ]
2102 * Helper function for permission-denied errors
2104 * @param string|string[] $rights
2105 * @param User|null $user
2106 * @throws ApiUsageException if the user doesn't have any of the rights.
2107 * The error message is based on $rights[0].
2109 public function checkUserRightsAny( $rights, $user = null ) {
2111 $user = $this->getUser();
2113 $rights = (array)$rights;
2114 if ( !$user->isAllowedAny( ...$rights ) ) {
2115 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2120 * Helper function for permission-denied errors
2122 * @since 1.33 Changed the third parameter from $user to $options.
2123 * @param Title $title
2124 * @param string|string[] $actions
2125 * @param array $options Additional options
2126 * - user: (User) User to use rather than $this->getUser()
2127 * - autoblock: (bool, default false) Whether to spread autoblocks
2128 * For compatibility, passing a User object is treated as the value for the 'user' option.
2129 * @throws ApiUsageException if the user doesn't have all of the rights.
2131 public function checkTitleUserPermissions( Title
$title, $actions, $options = [] ) {
2132 if ( !is_array( $options ) ) {
2133 wfDeprecated( '$user as the third parameter to ' . __METHOD__
, '1.33' );
2134 $options = [ 'user' => $options ];
2136 $user = $options['user'] ??
$this->getUser();
2139 foreach ( (array)$actions as $action ) {
2140 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2144 if ( !empty( $options['autoblock'] ) ) {
2145 $user->spreadAnyEditBlock();
2148 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2153 * Will only set a warning instead of failing if the global $wgDebugAPI
2154 * is set to true. Otherwise behaves exactly as self::dieWithError().
2157 * @param string|array|Message $msg
2158 * @param string|null $code
2159 * @param array|null $data
2160 * @param int|null $httpCode
2161 * @throws ApiUsageException
2163 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2164 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2165 $this->dieWithError( $msg, $code, $data, $httpCode );
2167 $this->addWarning( $msg, $code, $data );
2172 * Die with the 'badcontinue' error.
2174 * This call is common enough to make it into the base method.
2176 * @param bool $condition Will only die if this value is true
2177 * @throws ApiUsageException
2180 protected function dieContinueUsageIf( $condition ) {
2182 $this->dieWithError( 'apierror-badcontinue' );
2187 * Internal code errors should be reported with this method
2188 * @param string $method Method or function name
2189 * @param string $message Error message
2190 * @throws MWException always
2192 protected static function dieDebug( $method, $message ) {
2193 throw new MWException( "Internal error in $method: $message" );
2197 * Write logging information for API features to a debug log, for usage
2199 * @note Consider using $this->addDeprecation() instead to both warn and log.
2200 * @param string $feature Feature being used.
2202 public function logFeatureUsage( $feature ) {
2203 static $loggedFeatures = [];
2205 // Only log each feature once per request. We can get multiple calls from calls to
2206 // extractRequestParams() with different values for 'parseLimit', for example.
2207 if ( isset( $loggedFeatures[$feature] ) ) {
2210 $loggedFeatures[$feature] = true;
2212 $request = $this->getRequest();
2214 'feature' => $feature,
2215 // Spaces to underscores in 'username' for historical reasons.
2216 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
2217 'ip' => $request->getIP(),
2218 'referer' => (string)$request->getHeader( 'Referer' ),
2219 'agent' => $this->getMain()->getUserAgent(),
2222 // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
2223 $s = '"' . addslashes( $ctx['feature'] ) . '"' .
2224 ' "' . wfUrlencode( $ctx['username'] ) . '"' .
2225 ' "' . $ctx['ip'] . '"' .
2226 ' "' . addslashes( $ctx['referer'] ) . '"' .
2227 ' "' . addslashes( $ctx['agent'] ) . '"';
2229 wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
2234 /************************************************************************//**
2235 * @name Help message generation
2240 * Return the summary message.
2242 * This is a one-line description of the module, suitable for display in a
2246 * @return string|array|Message
2248 protected function getSummaryMessage() {
2249 return "apihelp-{$this->getModulePath()}-summary";
2253 * Return the extended help text message.
2255 * This is additional text to display at the top of the help section, below
2259 * @return string|array|Message
2261 protected function getExtendedDescription() {
2263 "apihelp-{$this->getModulePath()}-extended-description",
2264 'api-help-no-extended-description',
2269 * Get final module summary
2274 public function getFinalSummary() {
2275 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2276 $this->getModulePrefix(),
2277 $this->getModuleName(),
2278 $this->getModulePath(),
2284 * Get final module description, after hooks have had a chance to tweak it as
2287 * @since 1.25, returns Message[] rather than string[]
2290 public function getFinalDescription() {
2291 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2292 $this->getModulePrefix(),
2293 $this->getModuleName(),
2294 $this->getModulePath(),
2296 $extendedDescription = self
::makeMessage(
2297 $this->getExtendedDescription(), $this->getContext(), [
2298 $this->getModulePrefix(),
2299 $this->getModuleName(),
2300 $this->getModulePath(),
2304 $msgs = [ $summary, $extendedDescription ];
2306 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2312 * Get final list of parameters, after hooks have had a chance to
2313 * tweak it as needed.
2315 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2316 * @return array|bool False on no parameters
2317 * @since 1.21 $flags param added
2319 public function getFinalParams( $flags = 0 ) {
2320 $params = $this->getAllowedParams( $flags );
2325 if ( $this->needsToken() ) {
2326 $params['token'] = [
2327 self
::PARAM_TYPE
=> 'string',
2328 self
::PARAM_REQUIRED
=> true,
2329 self
::PARAM_SENSITIVE
=> true,
2330 self
::PARAM_HELP_MSG
=> [
2331 'api-help-param-token',
2332 $this->needsToken(),
2334 ] +
( $params['token'] ??
[] );
2337 // Avoid PHP 7.1 warning of passing $this by reference
2339 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2345 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2348 * @since 1.25, returns array of Message[] rather than array of string[]
2349 * @return array Keys are parameter names, values are arrays of Message objects
2351 public function getFinalParamDescription() {
2352 $prefix = $this->getModulePrefix();
2353 $name = $this->getModuleName();
2354 $path = $this->getModulePath();
2356 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2358 foreach ( $params as $param => $settings ) {
2359 if ( !is_array( $settings ) ) {
2363 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2364 $msg = $settings[self
::PARAM_HELP_MSG
];
2366 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2368 $msg = self
::makeMessage( $msg, $this->getContext(),
2369 [ $prefix, $param, $name, $path ] );
2371 self
::dieDebug( __METHOD__
,
2372 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2374 $msgs[$param] = [ $msg ];
2376 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2377 $settings[self
::PARAM_TYPE
] === 'submodule'
2379 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2380 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2382 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2384 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2385 $map[$submoduleName] = $prefix . $submoduleName;
2390 $deprecatedSubmodules = [];
2391 foreach ( $map as $v => $m ) {
2392 $arr = &$submodules;
2393 $isDeprecated = false;
2396 $submod = $this->getModuleFromPath( $m );
2398 $summary = $submod->getFinalSummary();
2399 $isDeprecated = $submod->isDeprecated();
2400 if ( $isDeprecated ) {
2401 $arr = &$deprecatedSubmodules;
2404 } catch ( ApiUsageException
$ex ) {
2408 $key = $summary->getKey();
2409 $params = $summary->getParams();
2411 $key = 'api-help-undocumented-module';
2414 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2415 $arr[] = $m->setContext( $this->getContext() );
2417 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2418 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2419 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2420 self
::dieDebug( __METHOD__
,
2421 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2423 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2424 self
::dieDebug( __METHOD__
,
2425 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2426 'ApiBase::PARAM_TYPE is an array' );
2429 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2430 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2432 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2433 if ( isset( $valueMsgs[$value] ) ) {
2434 $msg = $valueMsgs[$value];
2436 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2438 $m = self
::makeMessage( $msg, $this->getContext(),
2439 [ $prefix, $param, $name, $path, $value ] );
2441 $m = new ApiHelpParamValueMessage(
2443 [ $m->getKey(), 'api-help-param-no-description' ],
2445 isset( $deprecatedValues[$value] )
2447 $msgs[$param][] = $m->setContext( $this->getContext() );
2449 self
::dieDebug( __METHOD__
,
2450 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2455 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2456 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2457 self
::dieDebug( __METHOD__
,
2458 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2460 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2461 $m = self
::makeMessage( $m, $this->getContext(),
2462 [ $prefix, $param, $name, $path ] );
2464 $msgs[$param][] = $m;
2466 self
::dieDebug( __METHOD__
,
2467 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2473 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2479 * Generates the list of flags for the help screen and for action=paraminfo
2481 * Corresponding messages: api-help-flag-deprecated,
2482 * api-help-flag-internal, api-help-flag-readrights,
2483 * api-help-flag-writerights, api-help-flag-mustbeposted
2487 protected function getHelpFlags() {
2490 if ( $this->isDeprecated() ) {
2491 $flags[] = 'deprecated';
2493 if ( $this->isInternal() ) {
2494 $flags[] = 'internal';
2496 if ( $this->isReadMode() ) {
2497 $flags[] = 'readrights';
2499 if ( $this->isWriteMode() ) {
2500 $flags[] = 'writerights';
2502 if ( $this->mustBePosted() ) {
2503 $flags[] = 'mustbeposted';
2510 * Returns information about the source of this module, if known
2512 * Returned array is an array with the following keys:
2513 * - path: Install path
2514 * - name: Extension name, or "MediaWiki" for core
2515 * - namemsg: (optional) i18n message key for a display name
2516 * - license-name: (optional) Name of license
2518 * @return array|null
2520 protected function getModuleSourceInfo() {
2523 if ( $this->mModuleSource
!== false ) {
2524 return $this->mModuleSource
;
2527 // First, try to find where the module comes from...
2528 $rClass = new ReflectionClass( $this );
2529 $path = $rClass->getFileName();
2532 $this->mModuleSource
= null;
2535 $path = realpath( $path ) ?
: $path;
2537 // Build map of extension directories to extension info
2538 if ( self
::$extensionInfo === null ) {
2539 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2540 self
::$extensionInfo = [
2541 realpath( __DIR__
) ?
: __DIR__
=> [
2543 'name' => 'MediaWiki',
2544 'license-name' => 'GPL-2.0-or-later',
2546 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2547 realpath( $extDir ) ?
: $extDir => null,
2553 'license-name' => null,
2555 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2556 foreach ( $group as $ext ) {
2557 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2558 // This shouldn't happen, but does anyway.
2562 $extpath = $ext['path'];
2563 if ( !is_dir( $extpath ) ) {
2564 $extpath = dirname( $extpath );
2566 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2567 array_intersect_key( $ext, $keep );
2570 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2571 $extpath = $ext['path'];
2572 if ( !is_dir( $extpath ) ) {
2573 $extpath = dirname( $extpath );
2575 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2576 array_intersect_key( $ext, $keep );
2580 // Now traverse parent directories until we find a match or run out of
2583 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2585 $this->mModuleSource
= self
::$extensionInfo[$path];
2586 return $this->mModuleSource
;
2590 $path = dirname( $path );
2591 } while ( $path !== $oldpath );
2593 // No idea what extension this might be.
2594 $this->mModuleSource
= null;
2599 * Called from ApiHelp before the pieces are joined together and returned.
2601 * This exists mainly for ApiMain to add the Permissions and Credits
2602 * sections. Other modules probably don't need it.
2604 * @param string[] &$help Array of help data
2605 * @param array $options Options passed to ApiHelp::getHelp
2606 * @param array &$tocData If a TOC is being generated, this array has keys
2607 * as anchors in the page and values as for Linker::generateTOC().
2609 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2614 /************************************************************************//**
2620 * Returns the description string for this module
2622 * Ignored if an i18n message exists for
2623 * "apihelp-{$this->getModulePath()}-description".
2625 * @deprecated since 1.25
2626 * @return Message|string|array|false
2628 protected function getDescription() {
2629 wfDeprecated( __METHOD__
, '1.25' );
2634 * Returns an array of parameter descriptions.
2636 * For each parameter, ignored if an i18n message exists for the parameter.
2637 * By default that message is
2638 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2639 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2640 * self::getFinalParams().
2642 * @deprecated since 1.25
2643 * @return array|bool False on no parameter descriptions
2645 protected function getParamDescription() {
2646 wfDeprecated( __METHOD__
, '1.25' );
2651 * Returns usage examples for this module.
2653 * Return value as an array is either:
2654 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2656 * - sequential numeric keys with even-numbered keys being display-text
2657 * and odd-numbered keys being partial urls
2658 * - partial URLs as keys with display-text (string or array-to-be-joined)
2660 * Return value as a string is the same as an array with a numeric key and
2661 * that value, and boolean false means "no examples".
2663 * @deprecated since 1.25, use getExamplesMessages() instead
2664 * @return bool|string|array
2666 protected function getExamples() {
2667 wfDeprecated( __METHOD__
, '1.25' );
2672 * Return the description message.
2674 * This is additional text to display on the help page after the summary.
2676 * @deprecated since 1.30
2677 * @return string|array|Message
2679 protected function getDescriptionMessage() {
2680 wfDeprecated( __METHOD__
, '1.30' );
2682 "apihelp-{$this->getModulePath()}-description",
2683 "apihelp-{$this->getModulePath()}-summary",
2688 * Truncate an array to a certain length.
2689 * @deprecated since 1.32, no replacement
2690 * @param array &$arr Array to truncate
2691 * @param int $limit Maximum length
2692 * @return bool True if the array was truncated, false otherwise
2694 public static function truncateArray( &$arr, $limit ) {
2695 wfDeprecated( __METHOD__
, '1.32' );
2697 while ( count( $arr ) > $limit ) {
2709 * For really cool vim folding this needs to be at the end:
2710 * vim: foldmarker=@{,@} foldmethod=marker