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 Wikimedia\Rdbms\IDatabase
;
24 use MediaWiki\MediaWikiServices
;
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
{
41 * @name Constants for ::getAllowedParams() arrays
42 * These constants are keys in the arrays returned by ::getAllowedParams()
43 * and accepted by ::getParameterFromSettings() that define how the
44 * parameters coming in from the request are to be interpreted.
48 /** (null|boolean|integer|string) Default value of the parameter. */
51 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
52 const PARAM_ISMULTI
= 1;
55 * (string|string[]) Either an array of allowed value strings, or a string
56 * type as described below. If not specified, will be determined from the
59 * Supported string types are:
60 * - boolean: A boolean parameter, returned as false if the parameter is
61 * omitted and true if present (even with a falsey value, i.e. it works
62 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
63 * Cannot be used with PARAM_ISMULTI.
64 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
65 * PARAM_RANGE_ENFORCE.
66 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
67 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
68 * specified. Cannot be used with PARAM_ISMULTI.
69 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
70 * support easily specifying all namespaces.
72 * - password: Any non-empty string. Input value is private or sensitive.
73 * <input type="password"> would be an appropriate HTML form field.
74 * - string: Any non-empty string, not expected to be very long or contain newlines.
75 * <input type="text"> would be an appropriate HTML form field.
76 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
77 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
78 * used with PARAM_ISMULTI.
79 * - text: Any non-empty string, expected to be very long or contain newlines.
80 * <textarea> would be an appropriate HTML form field.
81 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
82 * string 'now' representing the current timestamp. Will be returned in
84 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
85 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
86 * Cannot be used with PARAM_ISMULTI.
90 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
94 * (integer) Max value allowed for the parameter for users with the
95 * apihighlimits right, for PARAM_TYPE 'limit'.
99 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
102 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
103 const PARAM_ALLOW_DUPLICATES
= 6;
105 /** (boolean) Is the parameter deprecated (will show a warning)? */
106 const PARAM_DEPRECATED
= 7;
109 * (boolean) Is the parameter required?
112 const PARAM_REQUIRED
= 8;
115 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
118 const PARAM_RANGE_ENFORCE
= 9;
121 * (string|array|Message) Specify an alternative i18n documentation message
122 * for this parameter. Default is apihelp-{$path}-param-{$param}.
125 const PARAM_HELP_MSG
= 10;
128 * ((string|array|Message)[]) Specify additional i18n messages to append to
129 * the normal message for this parameter.
132 const PARAM_HELP_MSG_APPEND
= 11;
135 * (array) Specify additional information tags for the parameter. Value is
136 * an array of arrays, with the first member being the 'tag' for the info
137 * and the remaining members being the values. In the help, this is
138 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
139 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
142 const PARAM_HELP_MSG_INFO
= 12;
145 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
146 * those values to page titles which will be linked in the help.
149 const PARAM_VALUE_LINKS
= 13;
152 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
153 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
154 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
155 * Specify an empty array to use the default message key for all values.
158 const PARAM_HELP_MSG_PER_VALUE
= 14;
161 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
162 * submodule paths. Default is to use all modules in
163 * $this->getModuleManager() in the group matching the parameter name.
166 const PARAM_SUBMODULE_MAP
= 15;
169 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
170 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
173 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
176 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
177 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
178 * every possible value. If a string is set, it will be used in place of the asterisk.
181 const PARAM_ALL
= 17;
184 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
187 const PARAM_EXTRA_NAMESPACES
= 18;
190 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
191 * always sensitive regardless of the value of this field.
194 const PARAM_SENSITIVE
= 19;
197 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
198 * Keys are the deprecated parameter values, values define the warning
199 * message to emit: either boolean true (to use a default message) or a
200 * $msg for ApiBase::makeMessage().
203 const PARAM_DEPRECATED_VALUES
= 20;
206 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
209 const PARAM_ISMULTI_LIMIT1
= 21;
212 * (integer) Maximum number of values, for users with the apihighimits right.
213 * Must be used with PARAM_ISMULTI.
216 const PARAM_ISMULTI_LIMIT2
= 22;
219 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
222 const PARAM_MAX_BYTES
= 23;
225 * (integer) Maximum length of a string in characters (unicode codepoints).
228 const PARAM_MAX_CHARS
= 24;
231 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
232 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
233 * which the replacement values are taken.
235 * For example, a parameter "foo-{ns}-{title}" could be defined with
236 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
237 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
239 * All placeholders must be present in the parameter's name. Each target parameter must have
240 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
241 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
242 * A parameter cannot target itself.
246 const PARAM_TEMPLATE_VARS
= 25;
250 const ALL_DEFAULT_STRING
= '*';
252 /** Fast query, standard limit. */
253 const LIMIT_BIG1
= 500;
254 /** Fast query, apihighlimits limit. */
255 const LIMIT_BIG2
= 5000;
256 /** Slow query, standard limit. */
257 const LIMIT_SML1
= 50;
258 /** Slow query, apihighlimits limit. */
259 const LIMIT_SML2
= 500;
262 * getAllowedParams() flag: When set, the result could take longer to generate,
263 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
266 const GET_VALUES_FOR_HELP
= 1;
268 /** @var array Maps extension paths to info arrays */
269 private static $extensionInfo = null;
271 /** @var int[][][] Cache for self::filterIDs() */
272 private static $filterIDsCache = [];
274 /** $var array Map of web UI block messages to corresponding API messages and codes */
275 private static $blockMsgMap = [
276 'blockedtext' => [ 'apierror-blocked', 'blocked' ],
277 'blockedtext-partial' => [ 'apierror-blocked', 'blocked' ],
278 'autoblockedtext' => [ 'apierror-autoblocked', 'autoblocked' ],
279 'systemblockedtext' => [ 'apierror-systemblocked', 'blocked' ],
283 private $mMainModule;
285 private $mModuleName, $mModulePrefix;
286 private $mReplicaDB = null;
287 private $mParamCache = [];
288 /** @var array|null|bool */
289 private $mModuleSource = false;
292 * @param ApiMain $mainModule
293 * @param string $moduleName Name of this module
294 * @param string $modulePrefix Prefix to use for parameter names
296 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
297 $this->mMainModule
= $mainModule;
298 $this->mModuleName
= $moduleName;
299 $this->mModulePrefix
= $modulePrefix;
301 if ( !$this->isMain() ) {
302 $this->setContext( $mainModule->getContext() );
306 /************************************************************************//**
307 * @name Methods to implement
312 * Evaluates the parameters, performs the requested query, and sets up
313 * the result. Concrete implementations of ApiBase must override this
314 * method to provide whatever functionality their module offers.
315 * Implementations must not produce any output on their own and are not
316 * expected to handle any errors.
318 * The execute() method will be invoked directly by ApiMain immediately
319 * before the result of the module is output. Aside from the
320 * constructor, implementations should assume that no other methods
321 * will be called externally on the module before the result is
324 * The result data should be stored in the ApiResult object available
325 * through getResult().
327 abstract public function execute();
330 * Get the module manager, or null if this module has no sub-modules
332 * @return ApiModuleManager
334 public function getModuleManager() {
339 * If the module may only be used with a certain format module,
340 * it should override this method to return an instance of that formatter.
341 * A value of null means the default format will be used.
342 * @note Do not use this just because you don't want to support non-json
343 * formats. This should be used only when there is a fundamental
344 * requirement for a specific format.
345 * @return mixed Instance of a derived class of ApiFormatBase, or null
347 public function getCustomPrinter() {
352 * Returns usage examples for this module.
354 * Return value has query strings as keys, with values being either strings
355 * (message key), arrays (message key + parameter), or Message objects.
357 * Do not call this base class implementation when overriding this method.
362 protected function getExamplesMessages() {
367 * Return links to more detailed help pages about the module.
368 * @since 1.25, returning boolean false is deprecated
369 * @return string|array
371 public function getHelpUrls() {
376 * Returns an array of allowed parameters (parameter name) => (default
377 * value) or (parameter name) => (array with PARAM_* constants as keys)
378 * Don't call this function directly: use getFinalParams() to allow
379 * hooks to modify parameters as needed.
381 * Some derived classes may choose to handle an integer $flags parameter
382 * in the overriding methods. Callers of this method can pass zero or
383 * more OR-ed flags like GET_VALUES_FOR_HELP.
387 protected function getAllowedParams( /* $flags = 0 */ ) {
388 // int $flags is not declared because it causes "Strict standards"
389 // warning. Most derived classes do not implement it.
394 * Indicates if this module needs maxlag to be checked
397 public function shouldCheckMaxlag() {
402 * Indicates whether this module requires read rights
405 public function isReadMode() {
410 * Indicates whether this module requires write mode
412 * This should return true for modules that may require synchronous database writes.
413 * Modules that do not need such writes should also not rely on master database access,
414 * since only read queries are needed and each master DB is a single point of failure.
415 * Additionally, requests that only need replica DBs can be efficiently routed to any
416 * datacenter via the Promise-Non-Write-API-Action header.
420 public function isWriteMode() {
425 * Indicates whether this module must be called with a POST request
428 public function mustBePosted() {
429 return $this->needsToken() !== false;
433 * Indicates whether this module is deprecated
437 public function isDeprecated() {
442 * Indicates whether this module is "internal"
443 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
447 public function isInternal() {
452 * Returns the token type this module requires in order to execute.
454 * Modules are strongly encouraged to use the core 'csrf' type unless they
455 * have specialized security needs. If the token type is not one of the
456 * core types, you must use the ApiQueryTokensRegisterTypes hook to
459 * Returning a non-falsey value here will force the addition of an
460 * appropriate 'token' parameter in self::getFinalParams(). Also,
461 * self::mustBePosted() must return true when tokens are used.
463 * In previous versions of MediaWiki, true was a valid return value.
464 * Returning true will generate errors indicating that the API module needs
467 * @return string|false
469 public function needsToken() {
474 * Fetch the salt used in the Web UI corresponding to this module.
476 * Only override this if the Web UI uses a token with a non-constant salt.
479 * @param array $params All supplied parameters for the module
480 * @return string|array|null
482 protected function getWebUITokenSalt( array $params ) {
487 * Returns data for HTTP conditional request mechanisms.
490 * @param string $condition Condition being queried:
491 * - last-modified: Return a timestamp representing the maximum of the
492 * last-modified dates for all resources involved in the request. See
493 * RFC 7232 § 2.2 for semantics.
494 * - etag: Return an entity-tag representing the state of all resources involved
495 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
496 * @return string|bool|null As described above, or null if no value is available.
498 public function getConditionalRequestData( $condition ) {
504 /************************************************************************//**
505 * @name Data access methods
510 * Get the name of the module being executed by this instance
513 public function getModuleName() {
514 return $this->mModuleName
;
518 * Get parameter prefix (usually two letters or an empty string).
521 public function getModulePrefix() {
522 return $this->mModulePrefix
;
526 * Get the main module
529 public function getMain() {
530 return $this->mMainModule
;
534 * Returns true if this module is the main module ($this === $this->mMainModule),
538 public function isMain() {
539 return $this === $this->mMainModule
;
543 * Get the parent of this module
545 * @return ApiBase|null
547 public function getParent() {
548 return $this->isMain() ?
null : $this->getMain();
552 * Returns true if the current request breaks the same-origin policy.
554 * For example, json with callbacks.
556 * https://en.wikipedia.org/wiki/Same-origin_policy
561 public function lacksSameOriginSecurity() {
562 // Main module has this method overridden
563 // Safety - avoid infinite loop:
564 if ( $this->isMain() ) {
565 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
568 return $this->getMain()->lacksSameOriginSecurity();
572 * Get the path to this module
577 public function getModulePath() {
578 if ( $this->isMain() ) {
580 } elseif ( $this->getParent()->isMain() ) {
581 return $this->getModuleName();
583 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
588 * Get a module from its module path
591 * @param string $path
592 * @return ApiBase|null
593 * @throws ApiUsageException
595 public function getModuleFromPath( $path ) {
596 $module = $this->getMain();
597 if ( $path === 'main' ) {
601 $parts = explode( '+', $path );
602 if ( count( $parts ) === 1 ) {
603 // In case the '+' was typed into URL, it resolves as a space
604 $parts = explode( ' ', $path );
607 $count = count( $parts );
608 for ( $i = 0; $i < $count; $i++
) {
610 $manager = $parent->getModuleManager();
611 if ( $manager === null ) {
612 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
613 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
615 $module = $manager->getModule( $parts[$i] );
617 if ( $module === null ) {
618 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
620 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
630 * Get the result object
633 public function getResult() {
634 // Main module has getResult() method overridden
635 // Safety - avoid infinite loop:
636 if ( $this->isMain() ) {
637 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
640 return $this->getMain()->getResult();
644 * Get the error formatter
645 * @return ApiErrorFormatter
647 public function getErrorFormatter() {
648 // Main module has getErrorFormatter() method overridden
649 // Safety - avoid infinite loop:
650 if ( $this->isMain() ) {
651 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
654 return $this->getMain()->getErrorFormatter();
658 * Gets a default replica DB connection object
661 protected function getDB() {
662 if ( !isset( $this->mReplicaDB
) ) {
663 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
666 return $this->mReplicaDB
;
670 * Get the continuation manager
671 * @return ApiContinuationManager|null
673 public function getContinuationManager() {
674 // Main module has getContinuationManager() method overridden
675 // Safety - avoid infinite loop:
676 if ( $this->isMain() ) {
677 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
680 return $this->getMain()->getContinuationManager();
684 * Set the continuation manager
685 * @param ApiContinuationManager|null $manager
687 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
688 // Main module has setContinuationManager() method overridden
689 // Safety - avoid infinite loop:
690 if ( $this->isMain() ) {
691 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
694 $this->getMain()->setContinuationManager( $manager );
699 /************************************************************************//**
700 * @name Parameter handling
705 * Indicate if the module supports dynamically-determined parameters that
706 * cannot be included in self::getAllowedParams().
707 * @return string|array|Message|null Return null if the module does not
708 * support additional dynamic parameters, otherwise return a message
711 public function dynamicParameterDocumentation() {
716 * This method mangles parameter name based on the prefix supplied to the constructor.
717 * Override this method to change parameter name during runtime
718 * @param string|string[] $paramName Parameter name
719 * @return string|string[] Prefixed parameter name
720 * @since 1.29 accepts an array of strings
722 public function encodeParamName( $paramName ) {
723 if ( is_array( $paramName ) ) {
724 return array_map( function ( $name ) {
725 return $this->mModulePrefix
. $name;
728 return $this->mModulePrefix
. $paramName;
733 * Using getAllowedParams(), this function makes an array of the values
734 * provided by the user, with key being the name of the variable, and
735 * value - validated value from user or default. limits will not be
736 * parsed if $parseLimit is set to false; use this when the max
737 * limit is not definitive yet, e.g. when getting revisions.
738 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
739 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
740 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
741 * Returned parameter values might be ApiUsageException instances.
744 public function extractRequestParams( $options = [] ) {
745 if ( is_bool( $options ) ) {
746 $options = [ 'parseLimit' => $options ];
749 'parseLimit' => true,
753 $parseLimit = (bool)$options['parseLimit'];
755 // Cache parameters, for performance and to avoid T26564.
756 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
757 $params = $this->getFinalParams() ?
: [];
761 // Process all non-templates and save templates for secondary
764 foreach ( $params as $paramName => $paramSettings ) {
765 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
766 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
769 $results[$paramName] = $this->getParameterFromSettings(
770 $paramName, $paramSettings, $parseLimit
772 } catch ( ApiUsageException
$ex ) {
773 $results[$paramName] = $ex;
778 // Now process all the templates by successively replacing the
779 // placeholders with all client-supplied values.
780 // This bit duplicates JavaScript logic in
781 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
782 // If you update this, see if that needs updating too.
783 while ( $toProcess ) {
784 list( $name, $targets, $settings ) = array_shift( $toProcess );
786 foreach ( $targets as $placeholder => $target ) {
787 if ( !array_key_exists( $target, $results ) ) {
788 // The target wasn't processed yet, try the next one.
789 // If all hit this case, the parameter has no expansions.
792 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
793 // The target was processed but has no (valid) values.
794 // That means it has no expansions.
798 // Expand this target in the name and all other targets,
799 // then requeue if there are more targets left or put in
800 // $results if all are done.
801 unset( $targets[$placeholder] );
802 $placeholder = '{' . $placeholder . '}';
803 foreach ( $results[$target] as $value ) {
804 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
805 // Skip values that make invalid parameter names.
806 $encTargetName = $this->encodeParamName( $target );
807 if ( !isset( $warned[$encTargetName][$value] ) ) {
808 $warned[$encTargetName][$value] = true;
810 'apiwarn-ignoring-invalid-templated-value',
811 wfEscapeWikiText( $encTargetName ),
812 wfEscapeWikiText( $value ),
818 $newName = str_replace( $placeholder, $value, $name );
821 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
822 } catch ( ApiUsageException
$ex ) {
823 $results[$newName] = $ex;
827 foreach ( $targets as $k => $v ) {
828 $newTargets[$k] = str_replace( $placeholder, $value, $v );
830 $toProcess[] = [ $newName, $newTargets, $settings ];
837 $this->mParamCache
[$parseLimit] = $results;
840 $ret = $this->mParamCache
[$parseLimit];
841 if ( !$options['safeMode'] ) {
842 foreach ( $ret as $v ) {
843 if ( $v instanceof ApiUsageException
) {
849 return $this->mParamCache
[$parseLimit];
853 * Get a value for the given parameter
854 * @param string $paramName Parameter name
855 * @param bool $parseLimit See extractRequestParams()
856 * @return mixed Parameter value
858 protected function getParameter( $paramName, $parseLimit = true ) {
859 $ret = $this->extractRequestParams( [
860 'parseLimit' => $parseLimit,
863 if ( $ret instanceof ApiUsageException
) {
870 * Die if none or more than one of a certain set of parameters is set and not false.
872 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
873 * @param string $required,... Names of parameters of which exactly one must be set
875 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
876 $required = func_get_args();
877 array_shift( $required );
879 $intersection = array_intersect( array_keys( array_filter( $params,
880 [ $this, 'parameterNotEmpty' ] ) ), $required );
882 if ( count( $intersection ) > 1 ) {
883 $this->dieWithError( [
884 'apierror-invalidparammix',
885 Message
::listParam( array_map(
887 return '<var>' . $this->encodeParamName( $p ) . '</var>';
889 array_values( $intersection )
891 count( $intersection ),
893 } elseif ( count( $intersection ) == 0 ) {
894 $this->dieWithError( [
895 'apierror-missingparam-one-of',
896 Message
::listParam( array_map(
898 return '<var>' . $this->encodeParamName( $p ) . '</var>';
900 array_values( $required )
908 * Die if more than one of a certain set of parameters is set and not false.
910 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
911 * @param string $required,... Names of parameters of which at most one must be set
913 public function requireMaxOneParameter( $params, $required /*...*/ ) {
914 $required = func_get_args();
915 array_shift( $required );
917 $intersection = array_intersect( array_keys( array_filter( $params,
918 [ $this, 'parameterNotEmpty' ] ) ), $required );
920 if ( count( $intersection ) > 1 ) {
921 $this->dieWithError( [
922 'apierror-invalidparammix',
923 Message
::listParam( array_map(
925 return '<var>' . $this->encodeParamName( $p ) . '</var>';
927 array_values( $intersection )
929 count( $intersection ),
935 * Die if none of a certain set of parameters is set and not false.
938 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
939 * @param string $required,... Names of parameters of which at least one must be set
941 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
942 $required = func_get_args();
943 array_shift( $required );
945 $intersection = array_intersect(
946 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
950 if ( count( $intersection ) == 0 ) {
951 $this->dieWithError( [
952 'apierror-missingparam-at-least-one-of',
953 Message
::listParam( array_map(
955 return '<var>' . $this->encodeParamName( $p ) . '</var>';
957 array_values( $required )
965 * Die if any of the specified parameters were found in the query part of
966 * the URL rather than the post body.
968 * @param string[] $params Parameters to check
969 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
971 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
972 // Skip if $wgDebugAPI is set or we're in internal mode
973 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
977 $queryValues = $this->getRequest()->getQueryValues();
979 foreach ( $params as $param ) {
980 if ( $prefix !== 'noprefix' ) {
981 $param = $this->encodeParamName( $param );
983 if ( array_key_exists( $param, $queryValues ) ) {
984 $badParams[] = $param;
990 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
996 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
998 * @param object $x Parameter to check is not null/false
1001 private function parameterNotEmpty( $x ) {
1002 return !is_null( $x ) && $x !== false;
1006 * Get a WikiPage object from a title or pageid param, if possible.
1007 * Can die, if no param is set or if the title or page id is not valid.
1009 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1010 * @param bool|string $load Whether load the object's state from the database:
1011 * - false: don't load (if the pageid is given, it will still be loaded)
1012 * - 'fromdb': load from a replica DB
1013 * - 'fromdbmaster': load from the master database
1016 public function getTitleOrPageId( $params, $load = false ) {
1017 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1020 if ( isset( $params['title'] ) ) {
1021 $titleObj = Title
::newFromText( $params['title'] );
1022 if ( !$titleObj ||
$titleObj->isExternal() ) {
1023 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1025 if ( !$titleObj->canExist() ) {
1026 $this->dieWithError( 'apierror-pagecannotexist' );
1028 $pageObj = WikiPage
::factory( $titleObj );
1029 if ( $load !== false ) {
1030 $pageObj->loadPageData( $load );
1032 } elseif ( isset( $params['pageid'] ) ) {
1033 if ( $load === false ) {
1036 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1038 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1046 * Get a Title object from a title or pageid param, if possible.
1047 * Can die, if no param is set or if the title or page id is not valid.
1050 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1053 public function getTitleFromTitleOrPageId( $params ) {
1054 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1057 if ( isset( $params['title'] ) ) {
1058 $titleObj = Title
::newFromText( $params['title'] );
1059 if ( !$titleObj ||
$titleObj->isExternal() ) {
1060 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1063 } elseif ( isset( $params['pageid'] ) ) {
1064 $titleObj = Title
::newFromID( $params['pageid'] );
1066 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1074 * Return true if we're to watch the page, false if not, null if no change.
1075 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1076 * @param Title $titleObj The page under consideration
1077 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1078 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1081 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1082 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1084 switch ( $watchlist ) {
1092 # If the user is already watching, don't bother checking
1093 if ( $userWatching ) {
1096 # If no user option was passed, use watchdefault and watchcreations
1097 if ( is_null( $userOption ) ) {
1098 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1099 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1102 # Watch the article based on the user preference
1103 return $this->getUser()->getBoolOption( $userOption );
1106 return $userWatching;
1109 return $userWatching;
1114 * Using the settings determine the value for the given parameter
1116 * @param string $paramName Parameter name
1117 * @param array|mixed $paramSettings Default value or an array of settings
1118 * using PARAM_* constants.
1119 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1120 * @return mixed Parameter value
1122 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1123 // Some classes may decide to change parameter names
1124 $encParamName = $this->encodeParamName( $paramName );
1127 if ( !is_array( $paramSettings ) ) {
1129 self
::PARAM_DFLT
=> $paramSettings,
1133 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1134 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1135 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1136 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1137 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1138 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1139 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1140 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1141 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1142 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1144 // When type is not given, and no choices, the type is the same as $default
1145 if ( !isset( $type ) ) {
1146 if ( isset( $default ) ) {
1147 $type = gettype( $default );
1149 $type = 'NULL'; // allow everything
1153 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1154 $this->getMain()->markParamsSensitive( $encParamName );
1157 if ( $type == 'boolean' ) {
1158 if ( isset( $default ) && $default !== false ) {
1159 // Having a default value of anything other than 'false' is not allowed
1162 "Boolean param $encParamName's default is set to '$default'. " .
1163 'Boolean parameters must default to false.'
1167 $value = $this->getMain()->getCheck( $encParamName );
1169 } elseif ( $type == 'upload' ) {
1170 if ( isset( $default ) ) {
1171 // Having a default value is not allowed
1174 "File upload param $encParamName's default is set to " .
1175 "'$default'. File upload parameters may not have a default." );
1178 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1180 $value = $this->getMain()->getUpload( $encParamName );
1181 $provided = $value->exists();
1182 if ( !$value->exists() ) {
1183 // This will get the value without trying to normalize it
1184 // (because trying to normalize a large binary file
1185 // accidentally uploaded as a field fails spectacularly)
1186 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1187 if ( $value !== null ) {
1188 $this->dieWithError(
1189 [ 'apierror-badupload', $encParamName ],
1190 "badupload_{$encParamName}"
1195 $value = $this->getMain()->getVal( $encParamName, $default );
1196 $provided = $this->getMain()->getCheck( $encParamName );
1198 if ( isset( $value ) && $type == 'namespace' ) {
1199 $type = MWNamespace
::getValidNamespaces();
1200 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1201 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1203 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1205 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1206 // specify all namespaces irrespective of PARAM_ALL.
1209 if ( isset( $value ) && $type == 'submodule' ) {
1210 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1211 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1213 $type = $this->getModuleManager()->getNames( $paramName );
1217 $request = $this->getMain()->getRequest();
1218 $rawValue = $request->getRawVal( $encParamName );
1219 if ( $rawValue === null ) {
1220 $rawValue = $default;
1223 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1224 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1226 // This loses the potential checkTitleEncoding() transformation done by
1227 // WebRequest for $_GET. Let's call that a feature.
1228 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1230 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1234 // Check for NFC normalization, and warn
1235 if ( $rawValue !== $value ) {
1236 $this->handleParamNormalization( $paramName, $value, $rawValue );
1240 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1241 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1244 "For param $encParamName, PARAM_ALL collides with a possible value" );
1246 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1247 $value = $this->parseMultiValue(
1251 is_array( $type ) ?
$type : null,
1252 $allowAll ?
$allSpecifier : null,
1258 if ( isset( $value ) ) {
1259 // More validation only when choices were not given
1260 // choices were validated in parseMultiValue()
1261 if ( !is_array( $type ) ) {
1263 case 'NULL': // nothing to do
1268 if ( $required && $value === '' ) {
1269 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1272 case 'integer': // Force everything using intval() and optionally validate limits
1273 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1274 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1275 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1277 if ( is_array( $value ) ) {
1278 $value = array_map( 'intval', $value );
1279 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1280 foreach ( $value as &$v ) {
1281 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1285 $value = (int)$value;
1286 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1287 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1292 if ( !$parseLimit ) {
1293 // Don't do any validation whatsoever
1296 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1297 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1301 "MAX1 or MAX2 are not defined for the limit $encParamName"
1305 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1307 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1308 if ( $value == 'max' ) {
1309 $value = $this->getMain()->canApiHighLimits()
1310 ?
$paramSettings[self
::PARAM_MAX2
]
1311 : $paramSettings[self
::PARAM_MAX
];
1312 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1314 $value = (int)$value;
1315 $this->validateLimit(
1319 $paramSettings[self
::PARAM_MAX
],
1320 $paramSettings[self
::PARAM_MAX2
]
1326 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1330 if ( is_array( $value ) ) {
1331 foreach ( $value as $key => $val ) {
1332 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1335 $value = $this->validateTimestamp( $value, $encParamName );
1339 if ( is_array( $value ) ) {
1340 foreach ( $value as $key => $val ) {
1341 $value[$key] = $this->validateUser( $val, $encParamName );
1344 $value = $this->validateUser( $value, $encParamName );
1347 case 'upload': // nothing to do
1350 // If change tagging was requested, check that the tags are valid.
1351 if ( !is_array( $value ) && !$multi ) {
1352 $value = [ $value ];
1354 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1355 if ( !$tagsStatus->isGood() ) {
1356 $this->dieStatus( $tagsStatus );
1360 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1364 // Throw out duplicates if requested
1365 if ( !$dupes && is_array( $value ) ) {
1366 $value = array_unique( $value );
1369 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1370 foreach ( (array)$value as $val ) {
1371 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1372 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1374 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1375 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1377 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1378 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1380 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1381 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1386 // Set a warning if a deprecated parameter has been passed
1387 if ( $deprecated && $provided ) {
1388 $feature = $encParamName;
1390 while ( !$m->isMain() ) {
1391 $p = $m->getParent();
1392 $name = $m->getModuleName();
1393 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1394 $feature = "{$param}={$name}&{$feature}";
1397 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1400 // Set a warning if a deprecated parameter value has been passed
1401 $usedDeprecatedValues = $deprecatedValues && $provided
1402 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1404 if ( $usedDeprecatedValues ) {
1405 $feature = "$encParamName=";
1407 while ( !$m->isMain() ) {
1408 $p = $m->getParent();
1409 $name = $m->getModuleName();
1410 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1411 $feature = "{$param}={$name}&{$feature}";
1414 foreach ( $usedDeprecatedValues as $v ) {
1415 $msg = $deprecatedValues[$v];
1416 if ( $msg === true ) {
1417 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1419 $this->addDeprecation( $msg, "$feature$v" );
1422 } elseif ( $required ) {
1423 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1430 * Handle when a parameter was Unicode-normalized
1432 * @param string $paramName Unprefixed parameter name
1433 * @param string $value Input that will be used.
1434 * @param string $rawValue Input before normalization.
1436 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1437 $encParamName = $this->encodeParamName( $paramName );
1438 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1442 * Split a multi-valued parameter string, like explode()
1444 * @param string $value
1448 protected function explodeMultiValue( $value, $limit ) {
1449 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1451 $value = substr( $value, 1 );
1456 return explode( $sep, $value, $limit );
1460 * Return an array of values that were given in a 'a|b|c' notation,
1461 * after it optionally validates them against the list allowed values.
1463 * @param string $valueName The name of the parameter (for error
1465 * @param mixed $value The value being parsed
1466 * @param bool $allowMultiple Can $value contain more than one value
1468 * @param string[]|null $allowedValues An array of values to check against. If
1469 * null, all values are accepted.
1470 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1471 * if this behavior should not be allowed
1472 * @param int|null $limit1 Maximum number of values, for normal users.
1473 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1474 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1476 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1477 $allSpecifier = null, $limit1 = null, $limit2 = null
1479 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1482 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1483 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1485 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1486 // because it unstubs $wgUser
1487 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1488 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1492 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1493 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1495 return $allowedValues;
1498 if ( count( $valuesList ) > $sizeLimit ) {
1499 $this->dieWithError(
1500 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1501 "too-many-$valueName"
1505 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1506 // T35482 - Allow entries with | in them for non-multiple values
1507 if ( in_array( $value, $allowedValues, true ) ) {
1511 $values = array_map( function ( $v ) {
1512 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1513 }, $allowedValues );
1514 $this->dieWithError( [
1515 'apierror-multival-only-one-of',
1517 Message
::listParam( $values ),
1519 ], "multival_$valueName" );
1522 if ( is_array( $allowedValues ) ) {
1523 // Check for unknown values
1524 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1525 if ( count( $unknown ) ) {
1526 if ( $allowMultiple ) {
1527 $this->addWarning( [
1528 'apiwarn-unrecognizedvalues',
1530 Message
::listParam( $unknown, 'comma' ),
1534 $this->dieWithError(
1535 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1536 "unknown_$valueName"
1540 // Now throw them out
1541 $valuesList = array_intersect( $valuesList, $allowedValues );
1544 return $allowMultiple ?
$valuesList : $valuesList[0];
1548 * Validate the value against the minimum and user/bot maximum limits.
1549 * Prints usage info on failure.
1550 * @param string $paramName Parameter name
1551 * @param int &$value Parameter value
1552 * @param int|null $min Minimum value
1553 * @param int|null $max Maximum value for users
1554 * @param int|null $botMax Maximum value for sysops/bots
1555 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1557 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1558 $enforceLimits = false
1560 if ( !is_null( $min ) && $value < $min ) {
1561 $msg = ApiMessage
::create(
1562 [ 'apierror-integeroutofrange-belowminimum',
1563 $this->encodeParamName( $paramName ), $min, $value ],
1564 'integeroutofrange',
1565 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1567 $this->warnOrDie( $msg, $enforceLimits );
1571 // Minimum is always validated, whereas maximum is checked only if not
1572 // running in internal call mode
1573 if ( $this->getMain()->isInternalMode() ) {
1577 // Optimization: do not check user's bot status unless really needed -- skips db query
1578 // assumes $botMax >= $max
1579 if ( !is_null( $max ) && $value > $max ) {
1580 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1581 if ( $value > $botMax ) {
1582 $msg = ApiMessage
::create(
1583 [ 'apierror-integeroutofrange-abovebotmax',
1584 $this->encodeParamName( $paramName ), $botMax, $value ],
1585 'integeroutofrange',
1586 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1588 $this->warnOrDie( $msg, $enforceLimits );
1592 $msg = ApiMessage
::create(
1593 [ 'apierror-integeroutofrange-abovemax',
1594 $this->encodeParamName( $paramName ), $max, $value ],
1595 'integeroutofrange',
1596 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1598 $this->warnOrDie( $msg, $enforceLimits );
1605 * Validate and normalize parameters of type 'timestamp'
1606 * @param string $value Parameter value
1607 * @param string $encParamName Parameter name
1608 * @return string Validated and normalized parameter
1610 protected function validateTimestamp( $value, $encParamName ) {
1611 // Confusing synonyms for the current time accepted by wfTimestamp()
1612 // (wfTimestamp() also accepts various non-strings and the string of 14
1613 // ASCII NUL bytes, but those can't get here)
1615 $this->addDeprecation(
1616 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1617 'unclear-"now"-timestamp'
1619 return wfTimestamp( TS_MW
);
1622 // Explicit synonym for the current time
1623 if ( $value === 'now' ) {
1624 return wfTimestamp( TS_MW
);
1627 $timestamp = wfTimestamp( TS_MW
, $value );
1628 if ( $timestamp === false ) {
1629 $this->dieWithError(
1630 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1631 "badtimestamp_{$encParamName}"
1639 * Validate the supplied token.
1642 * @param string $token Supplied token
1643 * @param array $params All supplied parameters for the module
1645 * @throws MWException
1647 final public function validateToken( $token, array $params ) {
1648 $tokenType = $this->needsToken();
1649 $salts = ApiQueryTokens
::getTokenTypeSalts();
1650 if ( !isset( $salts[$tokenType] ) ) {
1651 throw new MWException(
1652 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1653 'without registering it'
1657 $tokenObj = ApiQueryTokens
::getToken(
1658 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1660 if ( $tokenObj->match( $token ) ) {
1664 $webUiSalt = $this->getWebUITokenSalt( $params );
1665 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1677 * Validate and normalize parameters of type 'user'
1678 * @param string $value Parameter value
1679 * @param string $encParamName Parameter name
1680 * @return string Validated and normalized parameter
1682 private function validateUser( $value, $encParamName ) {
1683 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1687 $name = User
::getCanonicalName( $value, 'valid' );
1688 if ( $name !== false ) {
1693 // We allow ranges as well, for blocks.
1694 IP
::isIPAddress( $value ) ||
1695 // See comment for User::isIP. We don't just call that function
1696 // here because it also returns true for things like
1697 // 300.300.300.300 that are neither valid usernames nor valid IP
1700 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1704 return IP
::sanitizeIP( $value );
1707 $this->dieWithError(
1708 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1709 "baduser_{$encParamName}"
1715 /************************************************************************//**
1716 * @name Utility methods
1721 * Set a watch (or unwatch) based the based on a watchlist parameter.
1722 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1723 * @param Title $titleObj The article's title to change
1724 * @param string|null $userOption The user option to consider when $watch=preferences
1726 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1727 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1728 if ( $value === null ) {
1732 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1736 * Gets the user for whom to get the watchlist
1738 * @param array $params
1741 public function getWatchlistUser( $params ) {
1742 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1743 $user = User
::newFromName( $params['owner'], false );
1744 if ( !( $user && $user->getId() ) ) {
1745 $this->dieWithError(
1746 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1749 $token = $user->getOption( 'watchlisttoken' );
1750 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1751 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1754 if ( !$this->getUser()->isLoggedIn() ) {
1755 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1757 $this->checkUserRightsAny( 'viewmywatchlist' );
1758 $user = $this->getUser();
1765 * Create a Message from a string or array
1767 * A string is used as a message key. An array has the message key as the
1768 * first value and message parameters as subsequent values.
1771 * @param string|array|Message $msg
1772 * @param IContextSource $context
1773 * @param array|null $params
1774 * @return Message|null
1776 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1777 if ( is_string( $msg ) ) {
1778 $msg = wfMessage( $msg );
1779 } elseif ( is_array( $msg ) ) {
1780 $msg = wfMessage( ...$msg );
1782 if ( !$msg instanceof Message
) {
1786 $msg->setContext( $context );
1788 $msg->params( $params );
1795 * Turn an array of message keys or key+param arrays into a Status
1797 * @param array $errors
1798 * @param User|null $user
1801 public function errorArrayToStatus( array $errors, User
$user = null ) {
1802 if ( $user === null ) {
1803 $user = $this->getUser();
1806 $status = Status
::newGood();
1807 foreach ( $errors as $error ) {
1808 if ( is_array( $error ) && isset( self
::$blockMsgMap[$error[0]] ) && $user->getBlock() ) {
1809 list( $msg, $code ) = self
::$blockMsgMap[$error[0]];
1810 $status->fatal( ApiMessage
::create( $msg, $code,
1811 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1814 $status->fatal( ...(array)$error );
1821 * Add block info to block messages in a Status
1823 * @param StatusValue $status
1824 * @param User|null $user
1826 public function addBlockInfoToStatus( StatusValue
$status, User
$user = null ) {
1827 if ( $user === null ) {
1828 $user = $this->getUser();
1831 foreach ( self
::$blockMsgMap as $msg => list( $apiMsg, $code ) ) {
1832 if ( $status->hasMessage( $msg ) && $user->getBlock() ) {
1833 $status->replaceMessage( $msg, ApiMessage
::create( $apiMsg, $code,
1834 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1841 * Call wfTransactionalTimeLimit() if this request was POSTed
1844 protected function useTransactionalTimeLimit() {
1845 if ( $this->getRequest()->wasPosted() ) {
1846 wfTransactionalTimeLimit();
1851 * Filter out-of-range values from a list of positive integer IDs
1853 * @param array $fields Array of pairs of table and field to check
1854 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1855 * expected to be stringified ints.
1856 * @return (string|int)[] Filtered IDs.
1858 protected function filterIDs( $fields, array $ids ) {
1861 foreach ( $fields as list( $table, $field ) ) {
1862 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1863 $row = self
::$filterIDsCache[$table][$field];
1865 $row = $this->getDB()->selectRow(
1868 'min_id' => "MIN($field)",
1869 'max_id' => "MAX($field)",
1874 self
::$filterIDsCache[$table][$field] = $row;
1876 $min = min( $min, $row->min_id
);
1877 $max = max( $max, $row->max_id
);
1879 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1880 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1881 && $id >= $min && $id <= $max;
1887 /************************************************************************//**
1888 * @name Warning and error reporting
1893 * Add a warning for this module.
1895 * Users should monitor this section to notice any changes in API. Multiple
1896 * calls to this function will result in multiple warning messages.
1898 * If $msg is not an ApiMessage, the message code will be derived from the
1899 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1902 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1903 * @param string|null $code See ApiErrorFormatter::addWarning()
1904 * @param array|null $data See ApiErrorFormatter::addWarning()
1906 public function addWarning( $msg, $code = null, $data = null ) {
1907 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1911 * Add a deprecation warning for this module.
1913 * A combination of $this->addWarning() and $this->logFeatureUsage()
1916 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1917 * @param string|null $feature See ApiBase::logFeatureUsage()
1918 * @param array|null $data See ApiErrorFormatter::addWarning()
1920 public function addDeprecation( $msg, $feature, $data = [] ) {
1921 $data = (array)$data;
1922 if ( $feature !== null ) {
1923 $data['feature'] = $feature;
1924 $this->logFeatureUsage( $feature );
1926 $this->addWarning( $msg, 'deprecation', $data );
1928 // No real need to deduplicate here, ApiErrorFormatter does that for
1929 // us (assuming the hook is deterministic).
1930 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1931 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1932 if ( count( $msgs ) > 1 ) {
1933 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1934 $msg = ( new RawMessage( $key ) )->params( $msgs );
1936 $msg = reset( $msgs );
1938 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1942 * Add an error for this module without aborting
1944 * If $msg is not an ApiMessage, the message code will be derived from the
1945 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1947 * @note If you want to abort processing, use self::dieWithError() instead.
1949 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1950 * @param string|null $code See ApiErrorFormatter::addError()
1951 * @param array|null $data See ApiErrorFormatter::addError()
1953 public function addError( $msg, $code = null, $data = null ) {
1954 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1958 * Add warnings and/or errors from a Status
1960 * @note If you want to abort processing, use self::dieStatus() instead.
1962 * @param StatusValue $status
1963 * @param string[] $types 'warning' and/or 'error'
1964 * @param string[] $filter Message keys to filter out (since 1.33)
1966 public function addMessagesFromStatus(
1967 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1969 $this->getErrorFormatter()->addMessagesFromStatus(
1970 $this->getModulePath(), $status, $types, $filter
1975 * Abort execution with an error
1977 * If $msg is not an ApiMessage, the message code will be derived from the
1978 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1981 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1982 * @param string|null $code See ApiErrorFormatter::addError()
1983 * @param array|null $data See ApiErrorFormatter::addError()
1984 * @param int|null $httpCode HTTP error code to use
1985 * @throws ApiUsageException always
1987 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1988 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1992 * Abort execution with an error derived from an exception
1995 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1996 * @param array $options See ApiErrorFormatter::getMessageFromException()
1997 * @throws ApiUsageException always
1999 public function dieWithException( $exception, array $options = [] ) {
2000 $this->dieWithError(
2001 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
2006 * Adds a warning to the output, else dies
2008 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2009 * @param bool $enforceLimits Whether this is an enforce (die)
2011 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2012 if ( $enforceLimits ) {
2013 $this->dieWithError( $msg );
2015 $this->addWarning( $msg );
2020 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2021 * error handler and die with an error message including block info.
2024 * @param Block $block The block used to generate the ApiUsageException
2025 * @throws ApiUsageException always
2027 public function dieBlocked( Block
$block ) {
2028 // Die using the appropriate message depending on block type
2029 if ( $block->getType() == Block
::TYPE_AUTO
) {
2030 $this->dieWithError(
2031 'apierror-autoblocked',
2033 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2035 } elseif ( !$block->isSitewide() ) {
2036 $this->dieWithError(
2037 'apierror-blocked-partial',
2039 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2042 $this->dieWithError(
2045 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2051 * Throw an ApiUsageException based on the Status object.
2054 * @since 1.29 Accepts a StatusValue
2055 * @param StatusValue $status
2056 * @throws ApiUsageException always
2058 public function dieStatus( StatusValue
$status ) {
2059 if ( $status->isGood() ) {
2060 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2063 // ApiUsageException needs a fatal status, but this method has
2064 // historically accepted any non-good status. Convert it if necessary.
2065 $status->setOK( false );
2066 if ( !$status->getErrorsByType( 'error' ) ) {
2067 $newStatus = Status
::newGood();
2068 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2069 $newStatus->fatal( $err['message'], ...$err['params'] );
2071 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2072 $newStatus->fatal( 'unknownerror-nocode' );
2074 $status = $newStatus;
2077 $this->addBlockInfoToStatus( $status );
2078 throw new ApiUsageException( $this, $status );
2082 * Helper function for readonly errors
2084 * @throws ApiUsageException always
2086 public function dieReadOnly() {
2087 $this->dieWithError(
2088 'apierror-readonly',
2090 [ 'readonlyreason' => wfReadOnlyReason() ]
2095 * Helper function for permission-denied errors
2097 * @param string|string[] $rights
2098 * @param User|null $user
2099 * @throws ApiUsageException if the user doesn't have any of the rights.
2100 * The error message is based on $rights[0].
2102 public function checkUserRightsAny( $rights, $user = null ) {
2104 $user = $this->getUser();
2106 $rights = (array)$rights;
2107 if ( !$user->isAllowedAny( ...$rights ) ) {
2108 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2113 * Helper function for permission-denied errors
2115 * @since 1.33 Changed the third parameter from $user to $options.
2116 * @param Title $title
2117 * @param string|string[] $actions
2118 * @param array $options Additional options
2119 * - user: (User) User to use rather than $this->getUser()
2120 * - autoblock: (bool, default false) Whether to spread autoblocks
2121 * For compatibility, passing a User object is treated as the value for the 'user' option.
2122 * @throws ApiUsageException if the user doesn't have all of the rights.
2124 public function checkTitleUserPermissions( Title
$title, $actions, $options = [] ) {
2125 if ( !is_array( $options ) ) {
2126 wfDeprecated( '$user as the third parameter to ' . __METHOD__
, '1.33' );
2127 $options = [ 'user' => $options ];
2129 $user = $options['user'] ??
$this->getUser();
2132 foreach ( (array)$actions as $action ) {
2133 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2137 // track block notices
2138 if ( $this->getConfig()->get( 'EnableBlockNoticeStats' ) ) {
2139 $this->trackBlockNotices( $errors );
2142 if ( !empty( $options['autoblock'] ) ) {
2143 $user->spreadAnyEditBlock();
2146 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2151 * Keep track of errors messages resulting from a block
2153 * @param array $errors
2155 private function trackBlockNotices( array $errors ) {
2156 $errorMessageKeys = [
2158 'blockedtext-partial',
2160 'systemblockedtext',
2163 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
2165 foreach ( $errors as $error ) {
2166 if ( in_array( $error[0], $errorMessageKeys ) ) {
2167 $wiki = $this->getConfig()->get( 'DBname' );
2168 $statsd->increment( 'BlockNotices.' . $wiki . '.MediaWikiApi.returned' );
2175 * Will only set a warning instead of failing if the global $wgDebugAPI
2176 * is set to true. Otherwise behaves exactly as self::dieWithError().
2179 * @param string|array|Message $msg
2180 * @param string|null $code
2181 * @param array|null $data
2182 * @param int|null $httpCode
2183 * @throws ApiUsageException
2185 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2186 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2187 $this->dieWithError( $msg, $code, $data, $httpCode );
2189 $this->addWarning( $msg, $code, $data );
2194 * Die with the 'badcontinue' error.
2196 * This call is common enough to make it into the base method.
2198 * @param bool $condition Will only die if this value is true
2199 * @throws ApiUsageException
2202 protected function dieContinueUsageIf( $condition ) {
2204 $this->dieWithError( 'apierror-badcontinue' );
2209 * Internal code errors should be reported with this method
2210 * @param string $method Method or function name
2211 * @param string $message Error message
2212 * @throws MWException always
2214 protected static function dieDebug( $method, $message ) {
2215 throw new MWException( "Internal error in $method: $message" );
2219 * Write logging information for API features to a debug log, for usage
2221 * @note Consider using $this->addDeprecation() instead to both warn and log.
2222 * @param string $feature Feature being used.
2224 public function logFeatureUsage( $feature ) {
2225 $request = $this->getRequest();
2226 $s = '"' . addslashes( $feature ) . '"' .
2227 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2228 ' "' . $request->getIP() . '"' .
2229 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2230 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2231 wfDebugLog( 'api-feature-usage', $s, 'private' );
2236 /************************************************************************//**
2237 * @name Help message generation
2242 * Return the summary message.
2244 * This is a one-line description of the module, suitable for display in a
2248 * @return string|array|Message
2250 protected function getSummaryMessage() {
2251 return "apihelp-{$this->getModulePath()}-summary";
2255 * Return the extended help text message.
2257 * This is additional text to display at the top of the help section, below
2261 * @return string|array|Message
2263 protected function getExtendedDescription() {
2265 "apihelp-{$this->getModulePath()}-extended-description",
2266 'api-help-no-extended-description',
2271 * Get final module summary
2276 public function getFinalSummary() {
2277 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2278 $this->getModulePrefix(),
2279 $this->getModuleName(),
2280 $this->getModulePath(),
2286 * Get final module description, after hooks have had a chance to tweak it as
2289 * @since 1.25, returns Message[] rather than string[]
2292 public function getFinalDescription() {
2293 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2294 $this->getModulePrefix(),
2295 $this->getModuleName(),
2296 $this->getModulePath(),
2298 $extendedDescription = self
::makeMessage(
2299 $this->getExtendedDescription(), $this->getContext(), [
2300 $this->getModulePrefix(),
2301 $this->getModuleName(),
2302 $this->getModulePath(),
2306 $msgs = [ $summary, $extendedDescription ];
2308 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2314 * Get final list of parameters, after hooks have had a chance to
2315 * tweak it as needed.
2317 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2318 * @return array|bool False on no parameters
2319 * @since 1.21 $flags param added
2321 public function getFinalParams( $flags = 0 ) {
2322 $params = $this->getAllowedParams( $flags );
2327 if ( $this->needsToken() ) {
2328 $params['token'] = [
2329 self
::PARAM_TYPE
=> 'string',
2330 self
::PARAM_REQUIRED
=> true,
2331 self
::PARAM_SENSITIVE
=> true,
2332 self
::PARAM_HELP_MSG
=> [
2333 'api-help-param-token',
2334 $this->needsToken(),
2336 ] +
( $params['token'] ??
[] );
2339 // Avoid PHP 7.1 warning of passing $this by reference
2341 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2347 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2350 * @since 1.25, returns array of Message[] rather than array of string[]
2351 * @return array Keys are parameter names, values are arrays of Message objects
2353 public function getFinalParamDescription() {
2354 $prefix = $this->getModulePrefix();
2355 $name = $this->getModuleName();
2356 $path = $this->getModulePath();
2358 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2360 foreach ( $params as $param => $settings ) {
2361 if ( !is_array( $settings ) ) {
2365 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2366 $msg = $settings[self
::PARAM_HELP_MSG
];
2368 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2370 $msg = self
::makeMessage( $msg, $this->getContext(),
2371 [ $prefix, $param, $name, $path ] );
2373 self
::dieDebug( __METHOD__
,
2374 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2376 $msgs[$param] = [ $msg ];
2378 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2379 $settings[self
::PARAM_TYPE
] === 'submodule'
2381 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2382 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2384 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2386 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2387 $map[$submoduleName] = $prefix . $submoduleName;
2392 $deprecatedSubmodules = [];
2393 foreach ( $map as $v => $m ) {
2394 $arr = &$submodules;
2395 $isDeprecated = false;
2398 $submod = $this->getModuleFromPath( $m );
2400 $summary = $submod->getFinalSummary();
2401 $isDeprecated = $submod->isDeprecated();
2402 if ( $isDeprecated ) {
2403 $arr = &$deprecatedSubmodules;
2406 } catch ( ApiUsageException
$ex ) {
2410 $key = $summary->getKey();
2411 $params = $summary->getParams();
2413 $key = 'api-help-undocumented-module';
2416 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2417 $arr[] = $m->setContext( $this->getContext() );
2419 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2420 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2421 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2422 self
::dieDebug( __METHOD__
,
2423 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2425 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2426 self
::dieDebug( __METHOD__
,
2427 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2428 'ApiBase::PARAM_TYPE is an array' );
2431 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2432 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2434 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2435 if ( isset( $valueMsgs[$value] ) ) {
2436 $msg = $valueMsgs[$value];
2438 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2440 $m = self
::makeMessage( $msg, $this->getContext(),
2441 [ $prefix, $param, $name, $path, $value ] );
2443 $m = new ApiHelpParamValueMessage(
2445 [ $m->getKey(), 'api-help-param-no-description' ],
2447 isset( $deprecatedValues[$value] )
2449 $msgs[$param][] = $m->setContext( $this->getContext() );
2451 self
::dieDebug( __METHOD__
,
2452 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2457 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2458 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2459 self
::dieDebug( __METHOD__
,
2460 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2462 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2463 $m = self
::makeMessage( $m, $this->getContext(),
2464 [ $prefix, $param, $name, $path ] );
2466 $msgs[$param][] = $m;
2468 self
::dieDebug( __METHOD__
,
2469 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2475 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2481 * Generates the list of flags for the help screen and for action=paraminfo
2483 * Corresponding messages: api-help-flag-deprecated,
2484 * api-help-flag-internal, api-help-flag-readrights,
2485 * api-help-flag-writerights, api-help-flag-mustbeposted
2489 protected function getHelpFlags() {
2492 if ( $this->isDeprecated() ) {
2493 $flags[] = 'deprecated';
2495 if ( $this->isInternal() ) {
2496 $flags[] = 'internal';
2498 if ( $this->isReadMode() ) {
2499 $flags[] = 'readrights';
2501 if ( $this->isWriteMode() ) {
2502 $flags[] = 'writerights';
2504 if ( $this->mustBePosted() ) {
2505 $flags[] = 'mustbeposted';
2512 * Returns information about the source of this module, if known
2514 * Returned array is an array with the following keys:
2515 * - path: Install path
2516 * - name: Extension name, or "MediaWiki" for core
2517 * - namemsg: (optional) i18n message key for a display name
2518 * - license-name: (optional) Name of license
2520 * @return array|null
2522 protected function getModuleSourceInfo() {
2525 if ( $this->mModuleSource
!== false ) {
2526 return $this->mModuleSource
;
2529 // First, try to find where the module comes from...
2530 $rClass = new ReflectionClass( $this );
2531 $path = $rClass->getFileName();
2534 $this->mModuleSource
= null;
2537 $path = realpath( $path ) ?
: $path;
2539 // Build map of extension directories to extension info
2540 if ( self
::$extensionInfo === null ) {
2541 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2542 self
::$extensionInfo = [
2543 realpath( __DIR__
) ?
: __DIR__
=> [
2545 'name' => 'MediaWiki',
2546 'license-name' => 'GPL-2.0-or-later',
2548 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2549 realpath( $extDir ) ?
: $extDir => null,
2555 'license-name' => null,
2557 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2558 foreach ( $group as $ext ) {
2559 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2560 // This shouldn't happen, but does anyway.
2564 $extpath = $ext['path'];
2565 if ( !is_dir( $extpath ) ) {
2566 $extpath = dirname( $extpath );
2568 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2569 array_intersect_key( $ext, $keep );
2572 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2573 $extpath = $ext['path'];
2574 if ( !is_dir( $extpath ) ) {
2575 $extpath = dirname( $extpath );
2577 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2578 array_intersect_key( $ext, $keep );
2582 // Now traverse parent directories until we find a match or run out of
2585 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2587 $this->mModuleSource
= self
::$extensionInfo[$path];
2588 return $this->mModuleSource
;
2592 $path = dirname( $path );
2593 } while ( $path !== $oldpath );
2595 // No idea what extension this might be.
2596 $this->mModuleSource
= null;
2601 * Called from ApiHelp before the pieces are joined together and returned.
2603 * This exists mainly for ApiMain to add the Permissions and Credits
2604 * sections. Other modules probably don't need it.
2606 * @param string[] &$help Array of help data
2607 * @param array $options Options passed to ApiHelp::getHelp
2608 * @param array &$tocData If a TOC is being generated, this array has keys
2609 * as anchors in the page and values as for Linker::generateTOC().
2611 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2616 /************************************************************************//**
2622 * Returns the description string for this module
2624 * Ignored if an i18n message exists for
2625 * "apihelp-{$this->getModulePath()}-description".
2627 * @deprecated since 1.25
2628 * @return Message|string|array|false
2630 protected function getDescription() {
2631 wfDeprecated( __METHOD__
, '1.25' );
2636 * Returns an array of parameter descriptions.
2638 * For each parameter, ignored if an i18n message exists for the parameter.
2639 * By default that message is
2640 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2641 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2642 * self::getFinalParams().
2644 * @deprecated since 1.25
2645 * @return array|bool False on no parameter descriptions
2647 protected function getParamDescription() {
2648 wfDeprecated( __METHOD__
, '1.25' );
2653 * Returns usage examples for this module.
2655 * Return value as an array is either:
2656 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2658 * - sequential numeric keys with even-numbered keys being display-text
2659 * and odd-numbered keys being partial urls
2660 * - partial URLs as keys with display-text (string or array-to-be-joined)
2662 * Return value as a string is the same as an array with a numeric key and
2663 * that value, and boolean false means "no examples".
2665 * @deprecated since 1.25, use getExamplesMessages() instead
2666 * @return bool|string|array
2668 protected function getExamples() {
2669 wfDeprecated( __METHOD__
, '1.25' );
2674 * Return the description message.
2676 * This is additional text to display on the help page after the summary.
2678 * @deprecated since 1.30
2679 * @return string|array|Message
2681 protected function getDescriptionMessage() {
2682 wfDeprecated( __METHOD__
, '1.30' );
2684 "apihelp-{$this->getModulePath()}-description",
2685 "apihelp-{$this->getModulePath()}-summary",
2690 * Truncate an array to a certain length.
2691 * @deprecated since 1.32, no replacement
2692 * @param array &$arr Array to truncate
2693 * @param int $limit Maximum length
2694 * @return bool True if the array was truncated, false otherwise
2696 public static function truncateArray( &$arr, $limit ) {
2697 wfDeprecated( __METHOD__
, '1.32' );
2699 while ( count( $arr ) > $limit ) {
2711 * For really cool vim folding this needs to be at the end:
2712 * vim: foldmarker=@{,@} foldmethod=marker