3 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Block\AbstractBlock
;
24 use MediaWiki\Block\DatabaseBlock
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Rdbms\IDatabase
;
29 * This abstract class implements many basic API functions, and is the base of
31 * The class functions are divided into several areas of functionality:
33 * Module parameters: Derived classes can define getAllowedParams() to specify
34 * which parameters to expect, how to parse and validate them.
36 * Self-documentation: code to allow the API to document its own state
40 abstract class ApiBase
extends ContextSource
{
42 use ApiBlockInfoTrait
;
45 * @name Constants for ::getAllowedParams() arrays
46 * These constants are keys in the arrays returned by ::getAllowedParams()
47 * and accepted by ::getParameterFromSettings() that define how the
48 * parameters coming in from the request are to be interpreted.
52 /** (null|boolean|integer|string) Default value of the parameter. */
55 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
56 const PARAM_ISMULTI
= 1;
59 * (string|string[]) Either an array of allowed value strings, or a string
60 * type as described below. If not specified, will be determined from the
63 * Supported string types are:
64 * - boolean: A boolean parameter, returned as false if the parameter is
65 * omitted and true if present (even with a falsey value, i.e. it works
66 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
67 * Cannot be used with PARAM_ISMULTI.
68 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
69 * PARAM_RANGE_ENFORCE.
70 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
71 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
72 * specified. Cannot be used with PARAM_ISMULTI.
73 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
74 * support easily specifying all namespaces.
76 * - password: Any non-empty string. Input value is private or sensitive.
77 * <input type="password"> would be an appropriate HTML form field.
78 * - string: Any non-empty string, not expected to be very long or contain newlines.
79 * <input type="text"> would be an appropriate HTML form field.
80 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
81 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
82 * used with PARAM_ISMULTI.
83 * - text: Any non-empty string, expected to be very long or contain newlines.
84 * <textarea> would be an appropriate HTML form field.
85 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
86 * string 'now' representing the current timestamp. Will be returned in
88 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
89 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
90 * Cannot be used with PARAM_ISMULTI.
94 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
98 * (integer) Max value allowed for the parameter for users with the
99 * apihighlimits right, for PARAM_TYPE 'limit'.
101 const PARAM_MAX2
= 4;
103 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
106 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
107 const PARAM_ALLOW_DUPLICATES
= 6;
109 /** (boolean) Is the parameter deprecated (will show a warning)? */
110 const PARAM_DEPRECATED
= 7;
113 * (boolean) Is the parameter required?
116 const PARAM_REQUIRED
= 8;
119 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
122 const PARAM_RANGE_ENFORCE
= 9;
125 * (string|array|Message) Specify an alternative i18n documentation message
126 * for this parameter. Default is apihelp-{$path}-param-{$param}.
129 const PARAM_HELP_MSG
= 10;
132 * ((string|array|Message)[]) Specify additional i18n messages to append to
133 * the normal message for this parameter.
136 const PARAM_HELP_MSG_APPEND
= 11;
139 * (array) Specify additional information tags for the parameter. Value is
140 * an array of arrays, with the first member being the 'tag' for the info
141 * and the remaining members being the values. In the help, this is
142 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
143 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
146 const PARAM_HELP_MSG_INFO
= 12;
149 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
150 * those values to page titles which will be linked in the help.
153 const PARAM_VALUE_LINKS
= 13;
156 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
157 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
158 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
159 * Specify an empty array to use the default message key for all values.
162 const PARAM_HELP_MSG_PER_VALUE
= 14;
165 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
166 * submodule paths. Default is to use all modules in
167 * $this->getModuleManager() in the group matching the parameter name.
170 const PARAM_SUBMODULE_MAP
= 15;
173 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
174 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
177 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
180 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
181 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
182 * every possible value. If a string is set, it will be used in place of the asterisk.
185 const PARAM_ALL
= 17;
188 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
191 const PARAM_EXTRA_NAMESPACES
= 18;
194 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
195 * always sensitive regardless of the value of this field.
198 const PARAM_SENSITIVE
= 19;
201 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
202 * Keys are the deprecated parameter values, values define the warning
203 * message to emit: either boolean true (to use a default message) or a
204 * $msg for ApiBase::makeMessage().
207 const PARAM_DEPRECATED_VALUES
= 20;
210 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
213 const PARAM_ISMULTI_LIMIT1
= 21;
216 * (integer) Maximum number of values, for users with the apihighimits right.
217 * Must be used with PARAM_ISMULTI.
220 const PARAM_ISMULTI_LIMIT2
= 22;
223 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
226 const PARAM_MAX_BYTES
= 23;
229 * (integer) Maximum length of a string in characters (unicode codepoints).
232 const PARAM_MAX_CHARS
= 24;
235 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
236 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
237 * which the replacement values are taken.
239 * For example, a parameter "foo-{ns}-{title}" could be defined with
240 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
241 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
243 * All placeholders must be present in the parameter's name. Each target parameter must have
244 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
245 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
246 * A parameter cannot target itself.
250 const PARAM_TEMPLATE_VARS
= 25;
254 const ALL_DEFAULT_STRING
= '*';
256 /** Fast query, standard limit. */
257 const LIMIT_BIG1
= 500;
258 /** Fast query, apihighlimits limit. */
259 const LIMIT_BIG2
= 5000;
260 /** Slow query, standard limit. */
261 const LIMIT_SML1
= 50;
262 /** Slow query, apihighlimits limit. */
263 const LIMIT_SML2
= 500;
266 * getAllowedParams() flag: When set, the result could take longer to generate,
267 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
270 const GET_VALUES_FOR_HELP
= 1;
272 /** @var array Maps extension paths to info arrays */
273 private static $extensionInfo = null;
275 /** @var int[][][] Cache for self::filterIDs() */
276 private static $filterIDsCache = [];
278 /** $var array Map of web UI block messages to corresponding API messages and codes */
279 private static $blockMsgMap = [
280 'blockedtext' => [ 'apierror-blocked', 'blocked' ],
281 'blockedtext-partial' => [ 'apierror-blocked', 'blocked' ],
282 'autoblockedtext' => [ 'apierror-autoblocked', 'autoblocked' ],
283 'systemblockedtext' => [ 'apierror-systemblocked', 'blocked' ],
287 private $mMainModule;
289 private $mModuleName, $mModulePrefix;
290 private $mReplicaDB = null;
291 private $mParamCache = [];
292 /** @var array|null|bool */
293 private $mModuleSource = false;
296 * @param ApiMain $mainModule
297 * @param string $moduleName Name of this module
298 * @param string $modulePrefix Prefix to use for parameter names
300 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
301 $this->mMainModule
= $mainModule;
302 $this->mModuleName
= $moduleName;
303 $this->mModulePrefix
= $modulePrefix;
305 if ( !$this->isMain() ) {
306 $this->setContext( $mainModule->getContext() );
310 /************************************************************************//**
311 * @name Methods to implement
316 * Evaluates the parameters, performs the requested query, and sets up
317 * the result. Concrete implementations of ApiBase must override this
318 * method to provide whatever functionality their module offers.
319 * Implementations must not produce any output on their own and are not
320 * expected to handle any errors.
322 * The execute() method will be invoked directly by ApiMain immediately
323 * before the result of the module is output. Aside from the
324 * constructor, implementations should assume that no other methods
325 * will be called externally on the module before the result is
328 * The result data should be stored in the ApiResult object available
329 * through getResult().
331 abstract public function execute();
334 * Get the module manager, or null if this module has no sub-modules
336 * @return ApiModuleManager
338 public function getModuleManager() {
343 * If the module may only be used with a certain format module,
344 * it should override this method to return an instance of that formatter.
345 * A value of null means the default format will be used.
346 * @note Do not use this just because you don't want to support non-json
347 * formats. This should be used only when there is a fundamental
348 * requirement for a specific format.
349 * @return mixed Instance of a derived class of ApiFormatBase, or null
351 public function getCustomPrinter() {
356 * Returns usage examples for this module.
358 * Return value has query strings as keys, with values being either strings
359 * (message key), arrays (message key + parameter), or Message objects.
361 * Do not call this base class implementation when overriding this method.
366 protected function getExamplesMessages() {
371 * Return links to more detailed help pages about the module.
372 * @since 1.25, returning boolean false is deprecated
373 * @return string|array
375 public function getHelpUrls() {
380 * Returns an array of allowed parameters (parameter name) => (default
381 * value) or (parameter name) => (array with PARAM_* constants as keys)
382 * Don't call this function directly: use getFinalParams() to allow
383 * hooks to modify parameters as needed.
385 * Some derived classes may choose to handle an integer $flags parameter
386 * in the overriding methods. Callers of this method can pass zero or
387 * more OR-ed flags like GET_VALUES_FOR_HELP.
391 protected function getAllowedParams( /* $flags = 0 */ ) {
392 // int $flags is not declared because it causes "Strict standards"
393 // warning. Most derived classes do not implement it.
398 * Indicates if this module needs maxlag to be checked
401 public function shouldCheckMaxlag() {
406 * Indicates whether this module requires read rights
409 public function isReadMode() {
414 * Indicates whether this module requires write mode
416 * This should return true for modules that may require synchronous database writes.
417 * Modules that do not need such writes should also not rely on master database access,
418 * since only read queries are needed and each master DB is a single point of failure.
419 * Additionally, requests that only need replica DBs can be efficiently routed to any
420 * datacenter via the Promise-Non-Write-API-Action header.
424 public function isWriteMode() {
429 * Indicates whether this module must be called with a POST request
432 public function mustBePosted() {
433 return $this->needsToken() !== false;
437 * Indicates whether this module is deprecated
441 public function isDeprecated() {
446 * Indicates whether this module is "internal"
447 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
451 public function isInternal() {
456 * Returns the token type this module requires in order to execute.
458 * Modules are strongly encouraged to use the core 'csrf' type unless they
459 * have specialized security needs. If the token type is not one of the
460 * core types, you must use the ApiQueryTokensRegisterTypes hook to
463 * Returning a non-falsey value here will force the addition of an
464 * appropriate 'token' parameter in self::getFinalParams(). Also,
465 * self::mustBePosted() must return true when tokens are used.
467 * In previous versions of MediaWiki, true was a valid return value.
468 * Returning true will generate errors indicating that the API module needs
471 * @return string|false
473 public function needsToken() {
478 * Fetch the salt used in the Web UI corresponding to this module.
480 * Only override this if the Web UI uses a token with a non-constant salt.
483 * @param array $params All supplied parameters for the module
484 * @return string|array|null
486 protected function getWebUITokenSalt( array $params ) {
491 * Returns data for HTTP conditional request mechanisms.
494 * @param string $condition Condition being queried:
495 * - last-modified: Return a timestamp representing the maximum of the
496 * last-modified dates for all resources involved in the request. See
497 * RFC 7232 § 2.2 for semantics.
498 * - etag: Return an entity-tag representing the state of all resources involved
499 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
500 * @return string|bool|null As described above, or null if no value is available.
502 public function getConditionalRequestData( $condition ) {
508 /************************************************************************//**
509 * @name Data access methods
514 * Get the name of the module being executed by this instance
517 public function getModuleName() {
518 return $this->mModuleName
;
522 * Get parameter prefix (usually two letters or an empty string).
525 public function getModulePrefix() {
526 return $this->mModulePrefix
;
530 * Get the main module
533 public function getMain() {
534 return $this->mMainModule
;
538 * Returns true if this module is the main module ($this === $this->mMainModule),
542 public function isMain() {
543 return $this === $this->mMainModule
;
547 * Get the parent of this module
549 * @return ApiBase|null
551 public function getParent() {
552 return $this->isMain() ?
null : $this->getMain();
556 * Returns true if the current request breaks the same-origin policy.
558 * For example, json with callbacks.
560 * https://en.wikipedia.org/wiki/Same-origin_policy
565 public function lacksSameOriginSecurity() {
566 // Main module has this method overridden
567 // Safety - avoid infinite loop:
568 if ( $this->isMain() ) {
569 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
572 return $this->getMain()->lacksSameOriginSecurity();
576 * Get the path to this module
581 public function getModulePath() {
582 if ( $this->isMain() ) {
584 } elseif ( $this->getParent()->isMain() ) {
585 return $this->getModuleName();
587 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
592 * Get a module from its module path
595 * @param string $path
596 * @return ApiBase|null
597 * @throws ApiUsageException
599 public function getModuleFromPath( $path ) {
600 $module = $this->getMain();
601 if ( $path === 'main' ) {
605 $parts = explode( '+', $path );
606 if ( count( $parts ) === 1 ) {
607 // In case the '+' was typed into URL, it resolves as a space
608 $parts = explode( ' ', $path );
611 $count = count( $parts );
612 for ( $i = 0; $i < $count; $i++
) {
614 $manager = $parent->getModuleManager();
615 if ( $manager === null ) {
616 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
617 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
619 $module = $manager->getModule( $parts[$i] );
621 if ( $module === null ) {
622 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
624 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
634 * Get the result object
637 public function getResult() {
638 // Main module has getResult() method overridden
639 // Safety - avoid infinite loop:
640 if ( $this->isMain() ) {
641 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
644 return $this->getMain()->getResult();
648 * Get the error formatter
649 * @return ApiErrorFormatter
651 public function getErrorFormatter() {
652 // Main module has getErrorFormatter() method overridden
653 // Safety - avoid infinite loop:
654 if ( $this->isMain() ) {
655 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
658 return $this->getMain()->getErrorFormatter();
662 * Gets a default replica DB connection object
665 protected function getDB() {
666 if ( !isset( $this->mReplicaDB
) ) {
667 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
670 return $this->mReplicaDB
;
674 * Get the continuation manager
675 * @return ApiContinuationManager|null
677 public function getContinuationManager() {
678 // Main module has getContinuationManager() method overridden
679 // Safety - avoid infinite loop:
680 if ( $this->isMain() ) {
681 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
684 return $this->getMain()->getContinuationManager();
688 * Set the continuation manager
689 * @param ApiContinuationManager|null $manager
691 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
692 // Main module has setContinuationManager() method overridden
693 // Safety - avoid infinite loop:
694 if ( $this->isMain() ) {
695 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
698 $this->getMain()->setContinuationManager( $manager );
703 /************************************************************************//**
704 * @name Parameter handling
709 * Indicate if the module supports dynamically-determined parameters that
710 * cannot be included in self::getAllowedParams().
711 * @return string|array|Message|null Return null if the module does not
712 * support additional dynamic parameters, otherwise return a message
715 public function dynamicParameterDocumentation() {
720 * This method mangles parameter name based on the prefix supplied to the constructor.
721 * Override this method to change parameter name during runtime
722 * @param string|string[] $paramName Parameter name
723 * @return string|string[] Prefixed parameter name
724 * @since 1.29 accepts an array of strings
726 public function encodeParamName( $paramName ) {
727 if ( is_array( $paramName ) ) {
728 return array_map( function ( $name ) {
729 return $this->mModulePrefix
. $name;
732 return $this->mModulePrefix
. $paramName;
737 * Using getAllowedParams(), this function makes an array of the values
738 * provided by the user, with key being the name of the variable, and
739 * value - validated value from user or default. limits will not be
740 * parsed if $parseLimit is set to false; use this when the max
741 * limit is not definitive yet, e.g. when getting revisions.
742 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
743 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
744 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
745 * Returned parameter values might be ApiUsageException instances.
748 public function extractRequestParams( $options = [] ) {
749 if ( is_bool( $options ) ) {
750 $options = [ 'parseLimit' => $options ];
753 'parseLimit' => true,
757 $parseLimit = (bool)$options['parseLimit'];
759 // Cache parameters, for performance and to avoid T26564.
760 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
761 $params = $this->getFinalParams() ?
: [];
765 // Process all non-templates and save templates for secondary
768 foreach ( $params as $paramName => $paramSettings ) {
769 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
770 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
773 $results[$paramName] = $this->getParameterFromSettings(
774 $paramName, $paramSettings, $parseLimit
776 } catch ( ApiUsageException
$ex ) {
777 $results[$paramName] = $ex;
782 // Now process all the templates by successively replacing the
783 // placeholders with all client-supplied values.
784 // This bit duplicates JavaScript logic in
785 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
786 // If you update this, see if that needs updating too.
787 while ( $toProcess ) {
788 list( $name, $targets, $settings ) = array_shift( $toProcess );
790 foreach ( $targets as $placeholder => $target ) {
791 if ( !array_key_exists( $target, $results ) ) {
792 // The target wasn't processed yet, try the next one.
793 // If all hit this case, the parameter has no expansions.
796 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
797 // The target was processed but has no (valid) values.
798 // That means it has no expansions.
802 // Expand this target in the name and all other targets,
803 // then requeue if there are more targets left or put in
804 // $results if all are done.
805 unset( $targets[$placeholder] );
806 $placeholder = '{' . $placeholder . '}';
807 // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
808 foreach ( $results[$target] as $value ) {
809 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
810 // Skip values that make invalid parameter names.
811 $encTargetName = $this->encodeParamName( $target );
812 if ( !isset( $warned[$encTargetName][$value] ) ) {
813 $warned[$encTargetName][$value] = true;
815 'apiwarn-ignoring-invalid-templated-value',
816 wfEscapeWikiText( $encTargetName ),
817 wfEscapeWikiText( $value ),
823 $newName = str_replace( $placeholder, $value, $name );
826 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
827 } catch ( ApiUsageException
$ex ) {
828 $results[$newName] = $ex;
832 foreach ( $targets as $k => $v ) {
833 $newTargets[$k] = str_replace( $placeholder, $value, $v );
835 $toProcess[] = [ $newName, $newTargets, $settings ];
842 $this->mParamCache
[$parseLimit] = $results;
845 $ret = $this->mParamCache
[$parseLimit];
846 if ( !$options['safeMode'] ) {
847 foreach ( $ret as $v ) {
848 if ( $v instanceof ApiUsageException
) {
854 return $this->mParamCache
[$parseLimit];
858 * Get a value for the given parameter
859 * @param string $paramName Parameter name
860 * @param bool $parseLimit See extractRequestParams()
861 * @return mixed Parameter value
863 protected function getParameter( $paramName, $parseLimit = true ) {
864 $ret = $this->extractRequestParams( [
865 'parseLimit' => $parseLimit,
868 if ( $ret instanceof ApiUsageException
) {
875 * Die if none or more than one of a certain set of parameters is set and not false.
877 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
878 * @param string $required,... Names of parameters of which exactly one must be set
880 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
881 $required = func_get_args();
882 array_shift( $required );
884 $intersection = array_intersect( array_keys( array_filter( $params,
885 [ $this, 'parameterNotEmpty' ] ) ), $required );
887 if ( count( $intersection ) > 1 ) {
888 $this->dieWithError( [
889 'apierror-invalidparammix',
890 Message
::listParam( array_map(
892 return '<var>' . $this->encodeParamName( $p ) . '</var>';
894 array_values( $intersection )
896 count( $intersection ),
898 } elseif ( count( $intersection ) == 0 ) {
899 $this->dieWithError( [
900 'apierror-missingparam-one-of',
901 Message
::listParam( array_map(
903 return '<var>' . $this->encodeParamName( $p ) . '</var>';
905 array_values( $required )
913 * Die if more than one of a certain set of parameters is set and not false.
915 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
916 * @param string $required,... Names of parameters of which at most one must be set
918 public function requireMaxOneParameter( $params, $required /*...*/ ) {
919 $required = func_get_args();
920 array_shift( $required );
922 $intersection = array_intersect( array_keys( array_filter( $params,
923 [ $this, 'parameterNotEmpty' ] ) ), $required );
925 if ( count( $intersection ) > 1 ) {
926 $this->dieWithError( [
927 'apierror-invalidparammix',
928 Message
::listParam( array_map(
930 return '<var>' . $this->encodeParamName( $p ) . '</var>';
932 array_values( $intersection )
934 count( $intersection ),
940 * Die if none of a certain set of parameters is set and not false.
943 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
944 * @param string $required,... Names of parameters of which at least one must be set
946 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
947 $required = func_get_args();
948 array_shift( $required );
950 $intersection = array_intersect(
951 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
955 if ( count( $intersection ) == 0 ) {
956 $this->dieWithError( [
957 'apierror-missingparam-at-least-one-of',
958 Message
::listParam( array_map(
960 return '<var>' . $this->encodeParamName( $p ) . '</var>';
962 array_values( $required )
970 * Die if any of the specified parameters were found in the query part of
971 * the URL rather than the post body.
973 * @param string[] $params Parameters to check
974 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
976 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
977 // Skip if $wgDebugAPI is set or we're in internal mode
978 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
982 $queryValues = $this->getRequest()->getQueryValues();
984 foreach ( $params as $param ) {
985 if ( $prefix !== 'noprefix' ) {
986 $param = $this->encodeParamName( $param );
988 if ( array_key_exists( $param, $queryValues ) ) {
989 $badParams[] = $param;
995 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
1001 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
1003 * @param object $x Parameter to check is not null/false
1006 private function parameterNotEmpty( $x ) {
1007 return !is_null( $x ) && $x !== false;
1011 * Get a WikiPage object from a title or pageid param, if possible.
1012 * Can die, if no param is set or if the title or page id is not valid.
1014 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1015 * @param bool|string $load Whether load the object's state from the database:
1016 * - false: don't load (if the pageid is given, it will still be loaded)
1017 * - 'fromdb': load from a replica DB
1018 * - 'fromdbmaster': load from the master database
1021 public function getTitleOrPageId( $params, $load = false ) {
1022 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1025 if ( isset( $params['title'] ) ) {
1026 $titleObj = Title
::newFromText( $params['title'] );
1027 if ( !$titleObj ||
$titleObj->isExternal() ) {
1028 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1030 if ( !$titleObj->canExist() ) {
1031 $this->dieWithError( 'apierror-pagecannotexist' );
1033 $pageObj = WikiPage
::factory( $titleObj );
1034 if ( $load !== false ) {
1035 $pageObj->loadPageData( $load );
1037 } elseif ( isset( $params['pageid'] ) ) {
1038 if ( $load === false ) {
1041 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1043 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1051 * Get a Title object from a title or pageid param, if possible.
1052 * Can die, if no param is set or if the title or page id is not valid.
1055 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1058 public function getTitleFromTitleOrPageId( $params ) {
1059 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1062 if ( isset( $params['title'] ) ) {
1063 $titleObj = Title
::newFromText( $params['title'] );
1064 if ( !$titleObj ||
$titleObj->isExternal() ) {
1065 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1068 } elseif ( isset( $params['pageid'] ) ) {
1069 $titleObj = Title
::newFromID( $params['pageid'] );
1071 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1079 * Return true if we're to watch the page, false if not, null if no change.
1080 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1081 * @param Title $titleObj The page under consideration
1082 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1083 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1086 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1087 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1089 switch ( $watchlist ) {
1097 # If the user is already watching, don't bother checking
1098 if ( $userWatching ) {
1101 # If no user option was passed, use watchdefault and watchcreations
1102 if ( is_null( $userOption ) ) {
1103 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1104 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1107 # Watch the article based on the user preference
1108 return $this->getUser()->getBoolOption( $userOption );
1111 return $userWatching;
1114 return $userWatching;
1119 * Using the settings determine the value for the given parameter
1121 * @param string $paramName Parameter name
1122 * @param array|mixed $paramSettings Default value or an array of settings
1123 * using PARAM_* constants.
1124 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1125 * @return mixed Parameter value
1127 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1128 // Some classes may decide to change parameter names
1129 $encParamName = $this->encodeParamName( $paramName );
1132 if ( !is_array( $paramSettings ) ) {
1134 self
::PARAM_DFLT
=> $paramSettings,
1138 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1139 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1140 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1141 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1142 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1143 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1144 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1145 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1146 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1147 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1149 // When type is not given, and no choices, the type is the same as $default
1150 if ( !isset( $type ) ) {
1151 if ( isset( $default ) ) {
1152 $type = gettype( $default );
1154 $type = 'NULL'; // allow everything
1158 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1159 $this->getMain()->markParamsSensitive( $encParamName );
1162 if ( $type == 'boolean' ) {
1163 if ( isset( $default ) && $default !== false ) {
1164 // Having a default value of anything other than 'false' is not allowed
1167 "Boolean param $encParamName's default is set to '$default'. " .
1168 'Boolean parameters must default to false.'
1172 $value = $this->getMain()->getCheck( $encParamName );
1174 } elseif ( $type == 'upload' ) {
1175 if ( isset( $default ) ) {
1176 // Having a default value is not allowed
1179 "File upload param $encParamName's default is set to " .
1180 "'$default'. File upload parameters may not have a default." );
1183 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1185 $value = $this->getMain()->getUpload( $encParamName );
1186 $provided = $value->exists();
1187 if ( !$value->exists() ) {
1188 // This will get the value without trying to normalize it
1189 // (because trying to normalize a large binary file
1190 // accidentally uploaded as a field fails spectacularly)
1191 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1192 if ( $value !== null ) {
1193 $this->dieWithError(
1194 [ 'apierror-badupload', $encParamName ],
1195 "badupload_{$encParamName}"
1200 $value = $this->getMain()->getVal( $encParamName, $default );
1201 $provided = $this->getMain()->getCheck( $encParamName );
1203 if ( isset( $value ) && $type == 'namespace' ) {
1204 $type = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1205 getValidNamespaces();
1206 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1207 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1209 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1211 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1212 // specify all namespaces irrespective of PARAM_ALL.
1215 if ( isset( $value ) && $type == 'submodule' ) {
1216 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1217 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1219 $type = $this->getModuleManager()->getNames( $paramName );
1223 $request = $this->getMain()->getRequest();
1224 $rawValue = $request->getRawVal( $encParamName );
1225 if ( $rawValue === null ) {
1226 $rawValue = $default;
1229 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1230 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1232 // This loses the potential checkTitleEncoding() transformation done by
1233 // WebRequest for $_GET. Let's call that a feature.
1234 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1236 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1240 // Check for NFC normalization, and warn
1241 if ( $rawValue !== $value ) {
1242 $this->handleParamNormalization( $paramName, $value, $rawValue );
1246 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1247 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1250 "For param $encParamName, PARAM_ALL collides with a possible value" );
1252 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1253 $value = $this->parseMultiValue(
1257 is_array( $type ) ?
$type : null,
1258 $allowAll ?
$allSpecifier : null,
1264 if ( isset( $value ) ) {
1265 // More validation only when choices were not given
1266 // choices were validated in parseMultiValue()
1267 if ( !is_array( $type ) ) {
1269 case 'NULL': // nothing to do
1274 if ( $required && $value === '' ) {
1275 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1278 case 'integer': // Force everything using intval() and optionally validate limits
1279 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1280 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1281 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1283 if ( is_array( $value ) ) {
1284 $value = array_map( 'intval', $value );
1285 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1286 foreach ( $value as &$v ) {
1287 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1291 $value = (int)$value;
1292 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1293 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1298 if ( !$parseLimit ) {
1299 // Don't do any validation whatsoever
1302 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1303 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1307 "MAX1 or MAX2 are not defined for the limit $encParamName"
1311 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1313 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1314 if ( $value == 'max' ) {
1315 $value = $this->getMain()->canApiHighLimits()
1316 ?
$paramSettings[self
::PARAM_MAX2
]
1317 : $paramSettings[self
::PARAM_MAX
];
1318 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1320 $value = (int)$value;
1321 $this->validateLimit(
1325 $paramSettings[self
::PARAM_MAX
],
1326 $paramSettings[self
::PARAM_MAX2
]
1332 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1336 if ( is_array( $value ) ) {
1337 foreach ( $value as $key => $val ) {
1338 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1341 $value = $this->validateTimestamp( $value, $encParamName );
1345 if ( is_array( $value ) ) {
1346 foreach ( $value as $key => $val ) {
1347 $value[$key] = $this->validateUser( $val, $encParamName );
1350 $value = $this->validateUser( $value, $encParamName );
1353 case 'upload': // nothing to do
1356 // If change tagging was requested, check that the tags are valid.
1357 if ( !is_array( $value ) && !$multi ) {
1358 $value = [ $value ];
1360 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1361 if ( !$tagsStatus->isGood() ) {
1362 $this->dieStatus( $tagsStatus );
1366 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1370 // Throw out duplicates if requested
1371 if ( !$dupes && is_array( $value ) ) {
1372 $value = array_unique( $value );
1375 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1376 foreach ( (array)$value as $val ) {
1377 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1378 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1380 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1381 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1383 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1384 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1386 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1387 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1392 // Set a warning if a deprecated parameter has been passed
1393 if ( $deprecated && $provided ) {
1394 $feature = $encParamName;
1396 while ( !$m->isMain() ) {
1397 $p = $m->getParent();
1398 $name = $m->getModuleName();
1399 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1400 $feature = "{$param}={$name}&{$feature}";
1403 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1406 // Set a warning if a deprecated parameter value has been passed
1407 $usedDeprecatedValues = $deprecatedValues && $provided
1408 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1410 if ( $usedDeprecatedValues ) {
1411 $feature = "$encParamName=";
1413 while ( !$m->isMain() ) {
1414 $p = $m->getParent();
1415 $name = $m->getModuleName();
1416 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1417 $feature = "{$param}={$name}&{$feature}";
1420 foreach ( $usedDeprecatedValues as $v ) {
1421 $msg = $deprecatedValues[$v];
1422 if ( $msg === true ) {
1423 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1425 $this->addDeprecation( $msg, "$feature$v" );
1428 } elseif ( $required ) {
1429 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1436 * Handle when a parameter was Unicode-normalized
1438 * @param string $paramName Unprefixed parameter name
1439 * @param string $value Input that will be used.
1440 * @param string $rawValue Input before normalization.
1442 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1443 $encParamName = $this->encodeParamName( $paramName );
1444 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1448 * Split a multi-valued parameter string, like explode()
1450 * @param string $value
1454 protected function explodeMultiValue( $value, $limit ) {
1455 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1457 $value = substr( $value, 1 );
1462 return explode( $sep, $value, $limit );
1466 * Return an array of values that were given in a 'a|b|c' notation,
1467 * after it optionally validates them against the list allowed values.
1469 * @param string $valueName The name of the parameter (for error
1471 * @param mixed $value The value being parsed
1472 * @param bool $allowMultiple Can $value contain more than one value
1474 * @param string[]|null $allowedValues An array of values to check against. If
1475 * null, all values are accepted.
1476 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1477 * if this behavior should not be allowed
1478 * @param int|null $limit1 Maximum number of values, for normal users.
1479 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1480 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1482 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1483 $allSpecifier = null, $limit1 = null, $limit2 = null
1485 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1488 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1489 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1491 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1492 // because it unstubs $wgUser
1493 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1494 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1498 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1499 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1501 return $allowedValues;
1504 if ( count( $valuesList ) > $sizeLimit ) {
1505 $this->dieWithError(
1506 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1507 "too-many-$valueName"
1511 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1512 // T35482 - Allow entries with | in them for non-multiple values
1513 if ( in_array( $value, $allowedValues, true ) ) {
1517 $values = array_map( function ( $v ) {
1518 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1519 }, $allowedValues );
1520 $this->dieWithError( [
1521 'apierror-multival-only-one-of',
1523 Message
::listParam( $values ),
1525 ], "multival_$valueName" );
1528 if ( is_array( $allowedValues ) ) {
1529 // Check for unknown values
1530 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1531 if ( count( $unknown ) ) {
1532 if ( $allowMultiple ) {
1533 $this->addWarning( [
1534 'apiwarn-unrecognizedvalues',
1536 Message
::listParam( $unknown, 'comma' ),
1540 $this->dieWithError(
1541 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1542 "unknown_$valueName"
1546 // Now throw them out
1547 $valuesList = array_intersect( $valuesList, $allowedValues );
1550 return $allowMultiple ?
$valuesList : $valuesList[0];
1554 * Validate the value against the minimum and user/bot maximum limits.
1555 * Prints usage info on failure.
1556 * @param string $paramName Parameter name
1557 * @param int &$value Parameter value
1558 * @param int|null $min Minimum value
1559 * @param int|null $max Maximum value for users
1560 * @param int|null $botMax Maximum value for sysops/bots
1561 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1563 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1564 $enforceLimits = false
1566 if ( !is_null( $min ) && $value < $min ) {
1567 $msg = ApiMessage
::create(
1568 [ 'apierror-integeroutofrange-belowminimum',
1569 $this->encodeParamName( $paramName ), $min, $value ],
1570 'integeroutofrange',
1571 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1573 $this->warnOrDie( $msg, $enforceLimits );
1577 // Minimum is always validated, whereas maximum is checked only if not
1578 // running in internal call mode
1579 if ( $this->getMain()->isInternalMode() ) {
1583 // Optimization: do not check user's bot status unless really needed -- skips db query
1584 // assumes $botMax >= $max
1585 if ( !is_null( $max ) && $value > $max ) {
1586 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1587 if ( $value > $botMax ) {
1588 $msg = ApiMessage
::create(
1589 [ 'apierror-integeroutofrange-abovebotmax',
1590 $this->encodeParamName( $paramName ), $botMax, $value ],
1591 'integeroutofrange',
1592 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1594 $this->warnOrDie( $msg, $enforceLimits );
1598 $msg = ApiMessage
::create(
1599 [ 'apierror-integeroutofrange-abovemax',
1600 $this->encodeParamName( $paramName ), $max, $value ],
1601 'integeroutofrange',
1602 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1604 $this->warnOrDie( $msg, $enforceLimits );
1611 * Validate and normalize parameters of type 'timestamp'
1612 * @param string $value Parameter value
1613 * @param string $encParamName Parameter name
1614 * @return string Validated and normalized parameter
1616 protected function validateTimestamp( $value, $encParamName ) {
1617 // Confusing synonyms for the current time accepted by wfTimestamp()
1618 // (wfTimestamp() also accepts various non-strings and the string of 14
1619 // ASCII NUL bytes, but those can't get here)
1621 $this->addDeprecation(
1622 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1623 'unclear-"now"-timestamp'
1625 return wfTimestamp( TS_MW
);
1628 // Explicit synonym for the current time
1629 if ( $value === 'now' ) {
1630 return wfTimestamp( TS_MW
);
1633 $timestamp = wfTimestamp( TS_MW
, $value );
1634 if ( $timestamp === false ) {
1635 $this->dieWithError(
1636 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1637 "badtimestamp_{$encParamName}"
1645 * Validate the supplied token.
1648 * @param string $token Supplied token
1649 * @param array $params All supplied parameters for the module
1651 * @throws MWException
1653 final public function validateToken( $token, array $params ) {
1654 $tokenType = $this->needsToken();
1655 $salts = ApiQueryTokens
::getTokenTypeSalts();
1656 if ( !isset( $salts[$tokenType] ) ) {
1657 throw new MWException(
1658 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1659 'without registering it'
1663 $tokenObj = ApiQueryTokens
::getToken(
1664 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1666 if ( $tokenObj->match( $token ) ) {
1670 $webUiSalt = $this->getWebUITokenSalt( $params );
1671 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1683 * Validate and normalize parameters of type 'user'
1684 * @param string $value Parameter value
1685 * @param string $encParamName Parameter name
1686 * @return string Validated and normalized parameter
1688 private function validateUser( $value, $encParamName ) {
1689 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1693 $name = User
::getCanonicalName( $value, 'valid' );
1694 if ( $name !== false ) {
1699 // We allow ranges as well, for blocks.
1700 IP
::isIPAddress( $value ) ||
1701 // See comment for User::isIP. We don't just call that function
1702 // here because it also returns true for things like
1703 // 300.300.300.300 that are neither valid usernames nor valid IP
1706 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1710 return IP
::sanitizeIP( $value );
1713 $this->dieWithError(
1714 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1715 "baduser_{$encParamName}"
1721 /************************************************************************//**
1722 * @name Utility methods
1727 * Set a watch (or unwatch) based the based on a watchlist parameter.
1728 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1729 * @param Title $titleObj The article's title to change
1730 * @param string|null $userOption The user option to consider when $watch=preferences
1732 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1733 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1734 if ( $value === null ) {
1738 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1742 * Gets the user for whom to get the watchlist
1744 * @param array $params
1747 public function getWatchlistUser( $params ) {
1748 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1749 $user = User
::newFromName( $params['owner'], false );
1750 if ( !( $user && $user->getId() ) ) {
1751 $this->dieWithError(
1752 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1755 $token = $user->getOption( 'watchlisttoken' );
1756 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1757 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1760 if ( !$this->getUser()->isLoggedIn() ) {
1761 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1763 $this->checkUserRightsAny( 'viewmywatchlist' );
1764 $user = $this->getUser();
1771 * Create a Message from a string or array
1773 * A string is used as a message key. An array has the message key as the
1774 * first value and message parameters as subsequent values.
1777 * @param string|array|Message $msg
1778 * @param IContextSource $context
1779 * @param array|null $params
1780 * @return Message|null
1782 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1783 if ( is_string( $msg ) ) {
1784 $msg = wfMessage( $msg );
1785 } elseif ( is_array( $msg ) ) {
1786 $msg = wfMessage( ...$msg );
1788 if ( !$msg instanceof Message
) {
1792 $msg->setContext( $context );
1794 $msg->params( $params );
1801 * Turn an array of message keys or key+param arrays into a Status
1803 * @param array $errors
1804 * @param User|null $user
1807 public function errorArrayToStatus( array $errors, User
$user = null ) {
1808 if ( $user === null ) {
1809 $user = $this->getUser();
1812 $status = Status
::newGood();
1813 foreach ( $errors as $error ) {
1814 if ( !is_array( $error ) ) {
1815 $error = [ $error ];
1817 if ( is_string( $error[0] ) && isset( self
::$blockMsgMap[$error[0]] ) && $user->getBlock() ) {
1818 list( $msg, $code ) = self
::$blockMsgMap[$error[0]];
1819 $status->fatal( ApiMessage
::create( $msg, $code,
1820 [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
1823 $status->fatal( ...$error );
1830 * Add block info to block messages in a Status
1832 * @param StatusValue $status
1833 * @param User|null $user
1835 public function addBlockInfoToStatus( StatusValue
$status, User
$user = null ) {
1836 if ( $user === null ) {
1837 $user = $this->getUser();
1840 foreach ( self
::$blockMsgMap as $msg => list( $apiMsg, $code ) ) {
1841 if ( $status->hasMessage( $msg ) && $user->getBlock() ) {
1842 $status->replaceMessage( $msg, ApiMessage
::create( $apiMsg, $code,
1843 [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
1850 * Call wfTransactionalTimeLimit() if this request was POSTed
1853 protected function useTransactionalTimeLimit() {
1854 if ( $this->getRequest()->wasPosted() ) {
1855 wfTransactionalTimeLimit();
1860 * Filter out-of-range values from a list of positive integer IDs
1862 * @param array $fields Array of pairs of table and field to check
1863 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1864 * expected to be stringified ints.
1865 * @return (string|int)[] Filtered IDs.
1867 protected function filterIDs( $fields, array $ids ) {
1870 foreach ( $fields as list( $table, $field ) ) {
1871 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1872 $row = self
::$filterIDsCache[$table][$field];
1874 $row = $this->getDB()->selectRow(
1877 'min_id' => "MIN($field)",
1878 'max_id' => "MAX($field)",
1883 self
::$filterIDsCache[$table][$field] = $row;
1885 $min = min( $min, $row->min_id
);
1886 $max = max( $max, $row->max_id
);
1888 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1889 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1890 && $id >= $min && $id <= $max;
1896 /************************************************************************//**
1897 * @name Warning and error reporting
1902 * Add a warning for this module.
1904 * Users should monitor this section to notice any changes in API. Multiple
1905 * calls to this function will result in multiple warning messages.
1907 * If $msg is not an ApiMessage, the message code will be derived from the
1908 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1911 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1912 * @param string|null $code See ApiErrorFormatter::addWarning()
1913 * @param array|null $data See ApiErrorFormatter::addWarning()
1915 public function addWarning( $msg, $code = null, $data = null ) {
1916 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1920 * Add a deprecation warning for this module.
1922 * A combination of $this->addWarning() and $this->logFeatureUsage()
1925 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1926 * @param string|null $feature See ApiBase::logFeatureUsage()
1927 * @param array|null $data See ApiErrorFormatter::addWarning()
1929 public function addDeprecation( $msg, $feature, $data = [] ) {
1930 $data = (array)$data;
1931 if ( $feature !== null ) {
1932 $data['feature'] = $feature;
1933 $this->logFeatureUsage( $feature );
1935 $this->addWarning( $msg, 'deprecation', $data );
1937 // No real need to deduplicate here, ApiErrorFormatter does that for
1938 // us (assuming the hook is deterministic).
1939 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1940 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1941 if ( count( $msgs ) > 1 ) {
1942 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1943 $msg = ( new RawMessage( $key ) )->params( $msgs );
1945 $msg = reset( $msgs );
1947 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1951 * Add an error for this module without aborting
1953 * If $msg is not an ApiMessage, the message code will be derived from the
1954 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1956 * @note If you want to abort processing, use self::dieWithError() instead.
1958 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1959 * @param string|null $code See ApiErrorFormatter::addError()
1960 * @param array|null $data See ApiErrorFormatter::addError()
1962 public function addError( $msg, $code = null, $data = null ) {
1963 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1967 * Add warnings and/or errors from a Status
1969 * @note If you want to abort processing, use self::dieStatus() instead.
1971 * @param StatusValue $status
1972 * @param string[] $types 'warning' and/or 'error'
1973 * @param string[] $filter Message keys to filter out (since 1.33)
1975 public function addMessagesFromStatus(
1976 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1978 $this->getErrorFormatter()->addMessagesFromStatus(
1979 $this->getModulePath(), $status, $types, $filter
1984 * Abort execution with an error
1986 * If $msg is not an ApiMessage, the message code will be derived from the
1987 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1990 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1991 * @param string|null $code See ApiErrorFormatter::addError()
1992 * @param array|null $data See ApiErrorFormatter::addError()
1993 * @param int|null $httpCode HTTP error code to use
1994 * @throws ApiUsageException always
1996 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1997 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
2001 * Abort execution with an error derived from an exception
2004 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
2005 * @param array $options See ApiErrorFormatter::getMessageFromException()
2006 * @throws ApiUsageException always
2008 public function dieWithException( $exception, array $options = [] ) {
2009 $this->dieWithError(
2010 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
2015 * Adds a warning to the output, else dies
2017 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2018 * @param bool $enforceLimits Whether this is an enforce (die)
2020 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2021 if ( $enforceLimits ) {
2022 $this->dieWithError( $msg );
2024 $this->addWarning( $msg );
2029 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2030 * error handler and die with an error message including block info.
2033 * @param AbstractBlock $block The block used to generate the ApiUsageException
2034 * @throws ApiUsageException always
2036 public function dieBlocked( AbstractBlock
$block ) {
2037 // Die using the appropriate message depending on block type
2038 if ( $block->getType() == DatabaseBlock
::TYPE_AUTO
) {
2039 $this->dieWithError(
2040 'apierror-autoblocked',
2042 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2044 } elseif ( !$block->isSitewide() ) {
2045 $this->dieWithError(
2046 'apierror-blocked-partial',
2048 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2051 $this->dieWithError(
2054 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2060 * Throw an ApiUsageException based on the Status object.
2063 * @since 1.29 Accepts a StatusValue
2064 * @param StatusValue $status
2065 * @throws ApiUsageException always
2067 public function dieStatus( StatusValue
$status ) {
2068 if ( $status->isGood() ) {
2069 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2072 // ApiUsageException needs a fatal status, but this method has
2073 // historically accepted any non-good status. Convert it if necessary.
2074 $status->setOK( false );
2075 if ( !$status->getErrorsByType( 'error' ) ) {
2076 $newStatus = Status
::newGood();
2077 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2078 $newStatus->fatal( $err['message'], ...$err['params'] );
2080 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2081 $newStatus->fatal( 'unknownerror-nocode' );
2083 $status = $newStatus;
2086 $this->addBlockInfoToStatus( $status );
2087 throw new ApiUsageException( $this, $status );
2091 * Helper function for readonly errors
2093 * @throws ApiUsageException always
2095 public function dieReadOnly() {
2096 $this->dieWithError(
2097 'apierror-readonly',
2099 [ 'readonlyreason' => wfReadOnlyReason() ]
2104 * Helper function for permission-denied errors
2106 * @param string|string[] $rights
2107 * @param User|null $user
2108 * @throws ApiUsageException if the user doesn't have any of the rights.
2109 * The error message is based on $rights[0].
2111 public function checkUserRightsAny( $rights, $user = null ) {
2113 $user = $this->getUser();
2115 $rights = (array)$rights;
2116 if ( !$user->isAllowedAny( ...$rights ) ) {
2117 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2122 * Helper function for permission-denied errors
2124 * @since 1.33 Changed the third parameter from $user to $options.
2125 * @param Title $title
2126 * @param string|string[] $actions
2127 * @param array $options Additional options
2128 * - user: (User) User to use rather than $this->getUser()
2129 * - autoblock: (bool, default false) Whether to spread autoblocks
2130 * For compatibility, passing a User object is treated as the value for the 'user' option.
2131 * @throws ApiUsageException if the user doesn't have all of the rights.
2133 public function checkTitleUserPermissions( Title
$title, $actions, $options = [] ) {
2134 if ( !is_array( $options ) ) {
2135 wfDeprecated( '$user as the third parameter to ' . __METHOD__
, '1.33' );
2136 $options = [ 'user' => $options ];
2138 $user = $options['user'] ??
$this->getUser();
2141 foreach ( (array)$actions as $action ) {
2142 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2146 if ( !empty( $options['autoblock'] ) ) {
2147 $user->spreadAnyEditBlock();
2150 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2155 * Will only set a warning instead of failing if the global $wgDebugAPI
2156 * is set to true. Otherwise behaves exactly as self::dieWithError().
2159 * @param string|array|Message $msg
2160 * @param string|null $code
2161 * @param array|null $data
2162 * @param int|null $httpCode
2163 * @throws ApiUsageException
2165 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2166 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2167 $this->dieWithError( $msg, $code, $data, $httpCode );
2169 $this->addWarning( $msg, $code, $data );
2174 * Die with the 'badcontinue' error.
2176 * This call is common enough to make it into the base method.
2178 * @param bool $condition Will only die if this value is true
2179 * @throws ApiUsageException
2182 protected function dieContinueUsageIf( $condition ) {
2184 $this->dieWithError( 'apierror-badcontinue' );
2189 * Internal code errors should be reported with this method
2190 * @param string $method Method or function name
2191 * @param string $message Error message
2192 * @throws MWException always
2194 protected static function dieDebug( $method, $message ) {
2195 throw new MWException( "Internal error in $method: $message" );
2199 * Write logging information for API features to a debug log, for usage
2201 * @note Consider using $this->addDeprecation() instead to both warn and log.
2202 * @param string $feature Feature being used.
2204 public function logFeatureUsage( $feature ) {
2205 static $loggedFeatures = [];
2207 // Only log each feature once per request. We can get multiple calls from calls to
2208 // extractRequestParams() with different values for 'parseLimit', for example.
2209 if ( isset( $loggedFeatures[$feature] ) ) {
2212 $loggedFeatures[$feature] = true;
2214 $request = $this->getRequest();
2216 'feature' => $feature,
2217 // Spaces to underscores in 'username' for historical reasons.
2218 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
2219 'ip' => $request->getIP(),
2220 'referer' => (string)$request->getHeader( 'Referer' ),
2221 'agent' => $this->getMain()->getUserAgent(),
2224 // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
2225 $s = '"' . addslashes( $ctx['feature'] ) . '"' .
2226 ' "' . wfUrlencode( $ctx['username'] ) . '"' .
2227 ' "' . $ctx['ip'] . '"' .
2228 ' "' . addslashes( $ctx['referer'] ) . '"' .
2229 ' "' . addslashes( $ctx['agent'] ) . '"';
2231 wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
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",
2693 * For really cool vim folding this needs to be at the end:
2694 * vim: foldmarker=@{,@} foldmethod=marker