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
;
26 * This abstract class implements many basic API functions, and is the base of
28 * The class functions are divided into several areas of functionality:
30 * Module parameters: Derived classes can define getAllowedParams() to specify
31 * which parameters to expect, how to parse and validate them.
33 * Self-documentation: code to allow the API to document its own state
37 abstract class ApiBase
extends ContextSource
{
39 use ApiBlockInfoTrait
;
42 * @name Constants for ::getAllowedParams() arrays
43 * These constants are keys in the arrays returned by ::getAllowedParams()
44 * and accepted by ::getParameterFromSettings() that define how the
45 * parameters coming in from the request are to be interpreted.
49 /** (null|boolean|integer|string) Default value of the parameter. */
52 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
53 const PARAM_ISMULTI
= 1;
56 * (string|string[]) Either an array of allowed value strings, or a string
57 * type as described below. If not specified, will be determined from the
60 * Supported string types are:
61 * - boolean: A boolean parameter, returned as false if the parameter is
62 * omitted and true if present (even with a falsey value, i.e. it works
63 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
64 * Cannot be used with PARAM_ISMULTI.
65 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
66 * PARAM_RANGE_ENFORCE.
67 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
68 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
69 * specified. Cannot be used with PARAM_ISMULTI.
70 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
71 * support easily specifying all namespaces.
73 * - password: Any non-empty string. Input value is private or sensitive.
74 * <input type="password"> would be an appropriate HTML form field.
75 * - string: Any non-empty string, not expected to be very long or contain newlines.
76 * <input type="text"> would be an appropriate HTML form field.
77 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
78 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
79 * used with PARAM_ISMULTI.
80 * - text: Any non-empty string, expected to be very long or contain newlines.
81 * <textarea> would be an appropriate HTML form field.
82 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
83 * string 'now' representing the current timestamp. Will be returned in
85 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
86 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
87 * Cannot be used with PARAM_ISMULTI.
91 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
95 * (integer) Max value allowed for the parameter for users with the
96 * apihighlimits right, for PARAM_TYPE 'limit'.
100 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
103 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
104 const PARAM_ALLOW_DUPLICATES
= 6;
106 /** (boolean) Is the parameter deprecated (will show a warning)? */
107 const PARAM_DEPRECATED
= 7;
110 * (boolean) Is the parameter required?
113 const PARAM_REQUIRED
= 8;
116 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
119 const PARAM_RANGE_ENFORCE
= 9;
122 * (string|array|Message) Specify an alternative i18n documentation message
123 * for this parameter. Default is apihelp-{$path}-param-{$param}.
126 const PARAM_HELP_MSG
= 10;
129 * ((string|array|Message)[]) Specify additional i18n messages to append to
130 * the normal message for this parameter.
133 const PARAM_HELP_MSG_APPEND
= 11;
136 * (array) Specify additional information tags for the parameter. Value is
137 * an array of arrays, with the first member being the 'tag' for the info
138 * and the remaining members being the values. In the help, this is
139 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
140 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
143 const PARAM_HELP_MSG_INFO
= 12;
146 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
147 * those values to page titles which will be linked in the help.
150 const PARAM_VALUE_LINKS
= 13;
153 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
154 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
155 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
156 * Specify an empty array to use the default message key for all values.
159 const PARAM_HELP_MSG_PER_VALUE
= 14;
162 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
163 * submodule paths. Default is to use all modules in
164 * $this->getModuleManager() in the group matching the parameter name.
167 const PARAM_SUBMODULE_MAP
= 15;
170 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
171 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
174 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
177 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
178 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
179 * every possible value. If a string is set, it will be used in place of the asterisk.
182 const PARAM_ALL
= 17;
185 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
188 const PARAM_EXTRA_NAMESPACES
= 18;
191 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
192 * always sensitive regardless of the value of this field.
195 const PARAM_SENSITIVE
= 19;
198 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
199 * Keys are the deprecated parameter values, values define the warning
200 * message to emit: either boolean true (to use a default message) or a
201 * $msg for ApiBase::makeMessage().
204 const PARAM_DEPRECATED_VALUES
= 20;
207 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
210 const PARAM_ISMULTI_LIMIT1
= 21;
213 * (integer) Maximum number of values, for users with the apihighimits right.
214 * Must be used with PARAM_ISMULTI.
217 const PARAM_ISMULTI_LIMIT2
= 22;
220 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
223 const PARAM_MAX_BYTES
= 23;
226 * (integer) Maximum length of a string in characters (unicode codepoints).
229 const PARAM_MAX_CHARS
= 24;
232 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
233 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
234 * which the replacement values are taken.
236 * For example, a parameter "foo-{ns}-{title}" could be defined with
237 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
238 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
240 * All placeholders must be present in the parameter's name. Each target parameter must have
241 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
242 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
243 * A parameter cannot target itself.
247 const PARAM_TEMPLATE_VARS
= 25;
251 const ALL_DEFAULT_STRING
= '*';
253 /** Fast query, standard limit. */
254 const LIMIT_BIG1
= 500;
255 /** Fast query, apihighlimits limit. */
256 const LIMIT_BIG2
= 5000;
257 /** Slow query, standard limit. */
258 const LIMIT_SML1
= 50;
259 /** Slow query, apihighlimits limit. */
260 const LIMIT_SML2
= 500;
263 * getAllowedParams() flag: When set, the result could take longer to generate,
264 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
267 const GET_VALUES_FOR_HELP
= 1;
269 /** @var array Maps extension paths to info arrays */
270 private static $extensionInfo = null;
272 /** @var int[][][] Cache for self::filterIDs() */
273 private static $filterIDsCache = [];
275 /** $var array Map of web UI block messages to corresponding API messages and codes */
276 private static $blockMsgMap = [
277 'blockedtext' => [ 'apierror-blocked', 'blocked' ],
278 'blockedtext-partial' => [ 'apierror-blocked', 'blocked' ],
279 'autoblockedtext' => [ 'apierror-autoblocked', 'autoblocked' ],
280 'systemblockedtext' => [ 'apierror-systemblocked', 'blocked' ],
284 private $mMainModule;
286 private $mModuleName, $mModulePrefix;
287 private $mReplicaDB = null;
288 private $mParamCache = [];
289 /** @var array|null|bool */
290 private $mModuleSource = false;
293 * @param ApiMain $mainModule
294 * @param string $moduleName Name of this module
295 * @param string $modulePrefix Prefix to use for parameter names
297 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
298 $this->mMainModule
= $mainModule;
299 $this->mModuleName
= $moduleName;
300 $this->mModulePrefix
= $modulePrefix;
302 if ( !$this->isMain() ) {
303 $this->setContext( $mainModule->getContext() );
307 /************************************************************************//**
308 * @name Methods to implement
313 * Evaluates the parameters, performs the requested query, and sets up
314 * the result. Concrete implementations of ApiBase must override this
315 * method to provide whatever functionality their module offers.
316 * Implementations must not produce any output on their own and are not
317 * expected to handle any errors.
319 * The execute() method will be invoked directly by ApiMain immediately
320 * before the result of the module is output. Aside from the
321 * constructor, implementations should assume that no other methods
322 * will be called externally on the module before the result is
325 * The result data should be stored in the ApiResult object available
326 * through getResult().
328 abstract public function execute();
331 * Get the module manager, or null if this module has no sub-modules
333 * @return ApiModuleManager
335 public function getModuleManager() {
340 * If the module may only be used with a certain format module,
341 * it should override this method to return an instance of that formatter.
342 * A value of null means the default format will be used.
343 * @note Do not use this just because you don't want to support non-json
344 * formats. This should be used only when there is a fundamental
345 * requirement for a specific format.
346 * @return mixed Instance of a derived class of ApiFormatBase, or null
348 public function getCustomPrinter() {
353 * Returns usage examples for this module.
355 * Return value has query strings as keys, with values being either strings
356 * (message key), arrays (message key + parameter), or Message objects.
358 * Do not call this base class implementation when overriding this method.
363 protected function getExamplesMessages() {
368 * Return links to more detailed help pages about the module.
369 * @since 1.25, returning boolean false is deprecated
370 * @return string|array
372 public function getHelpUrls() {
377 * Returns an array of allowed parameters (parameter name) => (default
378 * value) or (parameter name) => (array with PARAM_* constants as keys)
379 * Don't call this function directly: use getFinalParams() to allow
380 * hooks to modify parameters as needed.
382 * Some derived classes may choose to handle an integer $flags parameter
383 * in the overriding methods. Callers of this method can pass zero or
384 * more OR-ed flags like GET_VALUES_FOR_HELP.
388 protected function getAllowedParams( /* $flags = 0 */ ) {
389 // int $flags is not declared because it causes "Strict standards"
390 // warning. Most derived classes do not implement it.
395 * Indicates if this module needs maxlag to be checked
398 public function shouldCheckMaxlag() {
403 * Indicates whether this module requires read rights
406 public function isReadMode() {
411 * Indicates whether this module requires write mode
413 * This should return true for modules that may require synchronous database writes.
414 * Modules that do not need such writes should also not rely on master database access,
415 * since only read queries are needed and each master DB is a single point of failure.
416 * Additionally, requests that only need replica DBs can be efficiently routed to any
417 * datacenter via the Promise-Non-Write-API-Action header.
421 public function isWriteMode() {
426 * Indicates whether this module must be called with a POST request
429 public function mustBePosted() {
430 return $this->needsToken() !== false;
434 * Indicates whether this module is deprecated
438 public function isDeprecated() {
443 * Indicates whether this module is "internal"
444 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
448 public function isInternal() {
453 * Returns the token type this module requires in order to execute.
455 * Modules are strongly encouraged to use the core 'csrf' type unless they
456 * have specialized security needs. If the token type is not one of the
457 * core types, you must use the ApiQueryTokensRegisterTypes hook to
460 * Returning a non-falsey value here will force the addition of an
461 * appropriate 'token' parameter in self::getFinalParams(). Also,
462 * self::mustBePosted() must return true when tokens are used.
464 * In previous versions of MediaWiki, true was a valid return value.
465 * Returning true will generate errors indicating that the API module needs
468 * @return string|false
470 public function needsToken() {
475 * Fetch the salt used in the Web UI corresponding to this module.
477 * Only override this if the Web UI uses a token with a non-constant salt.
480 * @param array $params All supplied parameters for the module
481 * @return string|array|null
483 protected function getWebUITokenSalt( array $params ) {
488 * Returns data for HTTP conditional request mechanisms.
491 * @param string $condition Condition being queried:
492 * - last-modified: Return a timestamp representing the maximum of the
493 * last-modified dates for all resources involved in the request. See
494 * RFC 7232 § 2.2 for semantics.
495 * - etag: Return an entity-tag representing the state of all resources involved
496 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
497 * @return string|bool|null As described above, or null if no value is available.
499 public function getConditionalRequestData( $condition ) {
505 /************************************************************************//**
506 * @name Data access methods
511 * Get the name of the module being executed by this instance
514 public function getModuleName() {
515 return $this->mModuleName
;
519 * Get parameter prefix (usually two letters or an empty string).
522 public function getModulePrefix() {
523 return $this->mModulePrefix
;
527 * Get the main module
530 public function getMain() {
531 return $this->mMainModule
;
535 * Returns true if this module is the main module ($this === $this->mMainModule),
539 public function isMain() {
540 return $this === $this->mMainModule
;
544 * Get the parent of this module
546 * @return ApiBase|null
548 public function getParent() {
549 return $this->isMain() ?
null : $this->getMain();
553 * Returns true if the current request breaks the same-origin policy.
555 * For example, json with callbacks.
557 * https://en.wikipedia.org/wiki/Same-origin_policy
562 public function lacksSameOriginSecurity() {
563 // Main module has this method overridden
564 // Safety - avoid infinite loop:
565 if ( $this->isMain() ) {
566 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
569 return $this->getMain()->lacksSameOriginSecurity();
573 * Get the path to this module
578 public function getModulePath() {
579 if ( $this->isMain() ) {
581 } elseif ( $this->getParent()->isMain() ) {
582 return $this->getModuleName();
584 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
589 * Get a module from its module path
592 * @param string $path
593 * @return ApiBase|null
594 * @throws ApiUsageException
596 public function getModuleFromPath( $path ) {
597 $module = $this->getMain();
598 if ( $path === 'main' ) {
602 $parts = explode( '+', $path );
603 if ( count( $parts ) === 1 ) {
604 // In case the '+' was typed into URL, it resolves as a space
605 $parts = explode( ' ', $path );
608 $count = count( $parts );
609 for ( $i = 0; $i < $count; $i++
) {
611 $manager = $parent->getModuleManager();
612 if ( $manager === null ) {
613 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
614 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
616 $module = $manager->getModule( $parts[$i] );
618 if ( $module === null ) {
619 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
621 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
631 * Get the result object
634 public function getResult() {
635 // Main module has getResult() method overridden
636 // Safety - avoid infinite loop:
637 if ( $this->isMain() ) {
638 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
641 return $this->getMain()->getResult();
645 * Get the error formatter
646 * @return ApiErrorFormatter
648 public function getErrorFormatter() {
649 // Main module has getErrorFormatter() method overridden
650 // Safety - avoid infinite loop:
651 if ( $this->isMain() ) {
652 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
655 return $this->getMain()->getErrorFormatter();
659 * Gets a default replica DB connection object
662 protected function getDB() {
663 if ( !isset( $this->mReplicaDB
) ) {
664 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
667 return $this->mReplicaDB
;
671 * Get the continuation manager
672 * @return ApiContinuationManager|null
674 public function getContinuationManager() {
675 // Main module has getContinuationManager() method overridden
676 // Safety - avoid infinite loop:
677 if ( $this->isMain() ) {
678 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
681 return $this->getMain()->getContinuationManager();
685 * Set the continuation manager
686 * @param ApiContinuationManager|null $manager
688 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
689 // Main module has setContinuationManager() method overridden
690 // Safety - avoid infinite loop:
691 if ( $this->isMain() ) {
692 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
695 $this->getMain()->setContinuationManager( $manager );
700 /************************************************************************//**
701 * @name Parameter handling
706 * Indicate if the module supports dynamically-determined parameters that
707 * cannot be included in self::getAllowedParams().
708 * @return string|array|Message|null Return null if the module does not
709 * support additional dynamic parameters, otherwise return a message
712 public function dynamicParameterDocumentation() {
717 * This method mangles parameter name based on the prefix supplied to the constructor.
718 * Override this method to change parameter name during runtime
719 * @param string|string[] $paramName Parameter name
720 * @return string|string[] Prefixed parameter name
721 * @since 1.29 accepts an array of strings
723 public function encodeParamName( $paramName ) {
724 if ( is_array( $paramName ) ) {
725 return array_map( function ( $name ) {
726 return $this->mModulePrefix
. $name;
729 return $this->mModulePrefix
. $paramName;
734 * Using getAllowedParams(), this function makes an array of the values
735 * provided by the user, with key being the name of the variable, and
736 * value - validated value from user or default. limits will not be
737 * parsed if $parseLimit is set to false; use this when the max
738 * limit is not definitive yet, e.g. when getting revisions.
739 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
740 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
741 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
742 * Returned parameter values might be ApiUsageException instances.
745 public function extractRequestParams( $options = [] ) {
746 if ( is_bool( $options ) ) {
747 $options = [ 'parseLimit' => $options ];
750 'parseLimit' => true,
754 $parseLimit = (bool)$options['parseLimit'];
756 // Cache parameters, for performance and to avoid T26564.
757 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
758 $params = $this->getFinalParams() ?
: [];
762 // Process all non-templates and save templates for secondary
765 foreach ( $params as $paramName => $paramSettings ) {
766 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
767 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
770 $results[$paramName] = $this->getParameterFromSettings(
771 $paramName, $paramSettings, $parseLimit
773 } catch ( ApiUsageException
$ex ) {
774 $results[$paramName] = $ex;
779 // Now process all the templates by successively replacing the
780 // placeholders with all client-supplied values.
781 // This bit duplicates JavaScript logic in
782 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
783 // If you update this, see if that needs updating too.
784 while ( $toProcess ) {
785 list( $name, $targets, $settings ) = array_shift( $toProcess );
787 foreach ( $targets as $placeholder => $target ) {
788 if ( !array_key_exists( $target, $results ) ) {
789 // The target wasn't processed yet, try the next one.
790 // If all hit this case, the parameter has no expansions.
793 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
794 // The target was processed but has no (valid) values.
795 // That means it has no expansions.
799 // Expand this target in the name and all other targets,
800 // then requeue if there are more targets left or put in
801 // $results if all are done.
802 unset( $targets[$placeholder] );
803 $placeholder = '{' . $placeholder . '}';
804 // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
805 foreach ( $results[$target] as $value ) {
806 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
807 // Skip values that make invalid parameter names.
808 $encTargetName = $this->encodeParamName( $target );
809 if ( !isset( $warned[$encTargetName][$value] ) ) {
810 $warned[$encTargetName][$value] = true;
812 'apiwarn-ignoring-invalid-templated-value',
813 wfEscapeWikiText( $encTargetName ),
814 wfEscapeWikiText( $value ),
820 $newName = str_replace( $placeholder, $value, $name );
823 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
824 } catch ( ApiUsageException
$ex ) {
825 $results[$newName] = $ex;
829 foreach ( $targets as $k => $v ) {
830 $newTargets[$k] = str_replace( $placeholder, $value, $v );
832 $toProcess[] = [ $newName, $newTargets, $settings ];
839 $this->mParamCache
[$parseLimit] = $results;
842 $ret = $this->mParamCache
[$parseLimit];
843 if ( !$options['safeMode'] ) {
844 foreach ( $ret as $v ) {
845 if ( $v instanceof ApiUsageException
) {
851 return $this->mParamCache
[$parseLimit];
855 * Get a value for the given parameter
856 * @param string $paramName Parameter name
857 * @param bool $parseLimit See extractRequestParams()
858 * @return mixed Parameter value
860 protected function getParameter( $paramName, $parseLimit = true ) {
861 $ret = $this->extractRequestParams( [
862 'parseLimit' => $parseLimit,
865 if ( $ret instanceof ApiUsageException
) {
872 * Die if none or more than one of a certain set of parameters is set and not false.
874 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
875 * @param string $required,... Names of parameters of which exactly one must be set
877 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
878 $required = func_get_args();
879 array_shift( $required );
881 $intersection = array_intersect( array_keys( array_filter( $params,
882 [ $this, 'parameterNotEmpty' ] ) ), $required );
884 if ( count( $intersection ) > 1 ) {
885 $this->dieWithError( [
886 'apierror-invalidparammix',
887 Message
::listParam( array_map(
889 return '<var>' . $this->encodeParamName( $p ) . '</var>';
891 array_values( $intersection )
893 count( $intersection ),
895 } elseif ( count( $intersection ) == 0 ) {
896 $this->dieWithError( [
897 'apierror-missingparam-one-of',
898 Message
::listParam( array_map(
900 return '<var>' . $this->encodeParamName( $p ) . '</var>';
902 array_values( $required )
910 * Die if more than one of a certain set of parameters is set and not false.
912 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
913 * @param string $required,... Names of parameters of which at most one must be set
915 public function requireMaxOneParameter( $params, $required /*...*/ ) {
916 $required = func_get_args();
917 array_shift( $required );
919 $intersection = array_intersect( array_keys( array_filter( $params,
920 [ $this, 'parameterNotEmpty' ] ) ), $required );
922 if ( count( $intersection ) > 1 ) {
923 $this->dieWithError( [
924 'apierror-invalidparammix',
925 Message
::listParam( array_map(
927 return '<var>' . $this->encodeParamName( $p ) . '</var>';
929 array_values( $intersection )
931 count( $intersection ),
937 * Die if none of a certain set of parameters is set and not false.
940 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
941 * @param string $required,... Names of parameters of which at least one must be set
943 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
944 $required = func_get_args();
945 array_shift( $required );
947 $intersection = array_intersect(
948 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
952 if ( count( $intersection ) == 0 ) {
953 $this->dieWithError( [
954 'apierror-missingparam-at-least-one-of',
955 Message
::listParam( array_map(
957 return '<var>' . $this->encodeParamName( $p ) . '</var>';
959 array_values( $required )
967 * Die if any of the specified parameters were found in the query part of
968 * the URL rather than the post body.
970 * @param string[] $params Parameters to check
971 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
973 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
974 // Skip if $wgDebugAPI is set or we're in internal mode
975 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
979 $queryValues = $this->getRequest()->getQueryValues();
981 foreach ( $params as $param ) {
982 if ( $prefix !== 'noprefix' ) {
983 $param = $this->encodeParamName( $param );
985 if ( array_key_exists( $param, $queryValues ) ) {
986 $badParams[] = $param;
992 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
998 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
1000 * @param object $x Parameter to check is not null/false
1003 private function parameterNotEmpty( $x ) {
1004 return !is_null( $x ) && $x !== false;
1008 * Get a WikiPage object from a title or pageid param, if possible.
1009 * Can die, if no param is set or if the title or page id is not valid.
1011 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1012 * @param bool|string $load Whether load the object's state from the database:
1013 * - false: don't load (if the pageid is given, it will still be loaded)
1014 * - 'fromdb': load from a replica DB
1015 * - 'fromdbmaster': load from the master database
1018 public function getTitleOrPageId( $params, $load = false ) {
1019 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1022 if ( isset( $params['title'] ) ) {
1023 $titleObj = Title
::newFromText( $params['title'] );
1024 if ( !$titleObj ||
$titleObj->isExternal() ) {
1025 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1027 if ( !$titleObj->canExist() ) {
1028 $this->dieWithError( 'apierror-pagecannotexist' );
1030 $pageObj = WikiPage
::factory( $titleObj );
1031 if ( $load !== false ) {
1032 $pageObj->loadPageData( $load );
1034 } elseif ( isset( $params['pageid'] ) ) {
1035 if ( $load === false ) {
1038 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1040 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1048 * Get a Title object from a title or pageid param, if possible.
1049 * Can die, if no param is set or if the title or page id is not valid.
1052 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1055 public function getTitleFromTitleOrPageId( $params ) {
1056 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1059 if ( isset( $params['title'] ) ) {
1060 $titleObj = Title
::newFromText( $params['title'] );
1061 if ( !$titleObj ||
$titleObj->isExternal() ) {
1062 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1065 } elseif ( isset( $params['pageid'] ) ) {
1066 $titleObj = Title
::newFromID( $params['pageid'] );
1068 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1076 * Return true if we're to watch the page, false if not, null if no change.
1077 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1078 * @param Title $titleObj The page under consideration
1079 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1080 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1083 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1084 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1086 switch ( $watchlist ) {
1094 # If the user is already watching, don't bother checking
1095 if ( $userWatching ) {
1098 # If no user option was passed, use watchdefault and watchcreations
1099 if ( is_null( $userOption ) ) {
1100 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1101 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1104 # Watch the article based on the user preference
1105 return $this->getUser()->getBoolOption( $userOption );
1108 return $userWatching;
1111 return $userWatching;
1116 * Using the settings determine the value for the given parameter
1118 * @param string $paramName Parameter name
1119 * @param array|mixed $paramSettings Default value or an array of settings
1120 * using PARAM_* constants.
1121 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1122 * @return mixed Parameter value
1124 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1125 // Some classes may decide to change parameter names
1126 $encParamName = $this->encodeParamName( $paramName );
1129 if ( !is_array( $paramSettings ) ) {
1131 self
::PARAM_DFLT
=> $paramSettings,
1135 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1136 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1137 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1138 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1139 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1140 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1141 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1142 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1143 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1144 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1146 // When type is not given, and no choices, the type is the same as $default
1147 if ( !isset( $type ) ) {
1148 if ( isset( $default ) ) {
1149 $type = gettype( $default );
1151 $type = 'NULL'; // allow everything
1155 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1156 $this->getMain()->markParamsSensitive( $encParamName );
1159 if ( $type == 'boolean' ) {
1160 if ( isset( $default ) && $default !== false ) {
1161 // Having a default value of anything other than 'false' is not allowed
1164 "Boolean param $encParamName's default is set to '$default'. " .
1165 'Boolean parameters must default to false.'
1169 $value = $this->getMain()->getCheck( $encParamName );
1171 } elseif ( $type == 'upload' ) {
1172 if ( isset( $default ) ) {
1173 // Having a default value is not allowed
1176 "File upload param $encParamName's default is set to " .
1177 "'$default'. File upload parameters may not have a default." );
1180 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1182 $value = $this->getMain()->getUpload( $encParamName );
1183 $provided = $value->exists();
1184 if ( !$value->exists() ) {
1185 // This will get the value without trying to normalize it
1186 // (because trying to normalize a large binary file
1187 // accidentally uploaded as a field fails spectacularly)
1188 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1189 if ( $value !== null ) {
1190 $this->dieWithError(
1191 [ 'apierror-badupload', $encParamName ],
1192 "badupload_{$encParamName}"
1197 $value = $this->getMain()->getVal( $encParamName, $default );
1198 $provided = $this->getMain()->getCheck( $encParamName );
1200 if ( isset( $value ) && $type == 'namespace' ) {
1201 $type = MWNamespace
::getValidNamespaces();
1202 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1203 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1205 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1207 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1208 // specify all namespaces irrespective of PARAM_ALL.
1211 if ( isset( $value ) && $type == 'submodule' ) {
1212 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1213 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1215 $type = $this->getModuleManager()->getNames( $paramName );
1219 $request = $this->getMain()->getRequest();
1220 $rawValue = $request->getRawVal( $encParamName );
1221 if ( $rawValue === null ) {
1222 $rawValue = $default;
1225 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1226 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1228 // This loses the potential checkTitleEncoding() transformation done by
1229 // WebRequest for $_GET. Let's call that a feature.
1230 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1232 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1236 // Check for NFC normalization, and warn
1237 if ( $rawValue !== $value ) {
1238 $this->handleParamNormalization( $paramName, $value, $rawValue );
1242 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1243 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1246 "For param $encParamName, PARAM_ALL collides with a possible value" );
1248 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1249 $value = $this->parseMultiValue(
1253 is_array( $type ) ?
$type : null,
1254 $allowAll ?
$allSpecifier : null,
1260 if ( isset( $value ) ) {
1261 // More validation only when choices were not given
1262 // choices were validated in parseMultiValue()
1263 if ( !is_array( $type ) ) {
1265 case 'NULL': // nothing to do
1270 if ( $required && $value === '' ) {
1271 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1274 case 'integer': // Force everything using intval() and optionally validate limits
1275 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1276 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1277 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1279 if ( is_array( $value ) ) {
1280 $value = array_map( 'intval', $value );
1281 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1282 foreach ( $value as &$v ) {
1283 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1287 $value = (int)$value;
1288 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1289 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1294 if ( !$parseLimit ) {
1295 // Don't do any validation whatsoever
1298 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1299 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1303 "MAX1 or MAX2 are not defined for the limit $encParamName"
1307 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1309 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1310 if ( $value == 'max' ) {
1311 $value = $this->getMain()->canApiHighLimits()
1312 ?
$paramSettings[self
::PARAM_MAX2
]
1313 : $paramSettings[self
::PARAM_MAX
];
1314 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1316 $value = (int)$value;
1317 $this->validateLimit(
1321 $paramSettings[self
::PARAM_MAX
],
1322 $paramSettings[self
::PARAM_MAX2
]
1328 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1332 if ( is_array( $value ) ) {
1333 foreach ( $value as $key => $val ) {
1334 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1337 $value = $this->validateTimestamp( $value, $encParamName );
1341 if ( is_array( $value ) ) {
1342 foreach ( $value as $key => $val ) {
1343 $value[$key] = $this->validateUser( $val, $encParamName );
1346 $value = $this->validateUser( $value, $encParamName );
1349 case 'upload': // nothing to do
1352 // If change tagging was requested, check that the tags are valid.
1353 if ( !is_array( $value ) && !$multi ) {
1354 $value = [ $value ];
1356 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1357 if ( !$tagsStatus->isGood() ) {
1358 $this->dieStatus( $tagsStatus );
1362 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1366 // Throw out duplicates if requested
1367 if ( !$dupes && is_array( $value ) ) {
1368 $value = array_unique( $value );
1371 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1372 foreach ( (array)$value as $val ) {
1373 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1374 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1376 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1377 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1379 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1380 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1382 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1383 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1388 // Set a warning if a deprecated parameter has been passed
1389 if ( $deprecated && $provided ) {
1390 $feature = $encParamName;
1392 while ( !$m->isMain() ) {
1393 $p = $m->getParent();
1394 $name = $m->getModuleName();
1395 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1396 $feature = "{$param}={$name}&{$feature}";
1399 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1402 // Set a warning if a deprecated parameter value has been passed
1403 $usedDeprecatedValues = $deprecatedValues && $provided
1404 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1406 if ( $usedDeprecatedValues ) {
1407 $feature = "$encParamName=";
1409 while ( !$m->isMain() ) {
1410 $p = $m->getParent();
1411 $name = $m->getModuleName();
1412 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1413 $feature = "{$param}={$name}&{$feature}";
1416 foreach ( $usedDeprecatedValues as $v ) {
1417 $msg = $deprecatedValues[$v];
1418 if ( $msg === true ) {
1419 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1421 $this->addDeprecation( $msg, "$feature$v" );
1424 } elseif ( $required ) {
1425 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1432 * Handle when a parameter was Unicode-normalized
1434 * @param string $paramName Unprefixed parameter name
1435 * @param string $value Input that will be used.
1436 * @param string $rawValue Input before normalization.
1438 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1439 $encParamName = $this->encodeParamName( $paramName );
1440 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1444 * Split a multi-valued parameter string, like explode()
1446 * @param string $value
1450 protected function explodeMultiValue( $value, $limit ) {
1451 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1453 $value = substr( $value, 1 );
1458 return explode( $sep, $value, $limit );
1462 * Return an array of values that were given in a 'a|b|c' notation,
1463 * after it optionally validates them against the list allowed values.
1465 * @param string $valueName The name of the parameter (for error
1467 * @param mixed $value The value being parsed
1468 * @param bool $allowMultiple Can $value contain more than one value
1470 * @param string[]|null $allowedValues An array of values to check against. If
1471 * null, all values are accepted.
1472 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1473 * if this behavior should not be allowed
1474 * @param int|null $limit1 Maximum number of values, for normal users.
1475 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1476 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1478 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1479 $allSpecifier = null, $limit1 = null, $limit2 = null
1481 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1484 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1485 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1487 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1488 // because it unstubs $wgUser
1489 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1490 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1494 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1495 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1497 return $allowedValues;
1500 if ( count( $valuesList ) > $sizeLimit ) {
1501 $this->dieWithError(
1502 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1503 "too-many-$valueName"
1507 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1508 // T35482 - Allow entries with | in them for non-multiple values
1509 if ( in_array( $value, $allowedValues, true ) ) {
1513 $values = array_map( function ( $v ) {
1514 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1515 }, $allowedValues );
1516 $this->dieWithError( [
1517 'apierror-multival-only-one-of',
1519 Message
::listParam( $values ),
1521 ], "multival_$valueName" );
1524 if ( is_array( $allowedValues ) ) {
1525 // Check for unknown values
1526 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1527 if ( count( $unknown ) ) {
1528 if ( $allowMultiple ) {
1529 $this->addWarning( [
1530 'apiwarn-unrecognizedvalues',
1532 Message
::listParam( $unknown, 'comma' ),
1536 $this->dieWithError(
1537 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1538 "unknown_$valueName"
1542 // Now throw them out
1543 $valuesList = array_intersect( $valuesList, $allowedValues );
1546 return $allowMultiple ?
$valuesList : $valuesList[0];
1550 * Validate the value against the minimum and user/bot maximum limits.
1551 * Prints usage info on failure.
1552 * @param string $paramName Parameter name
1553 * @param int &$value Parameter value
1554 * @param int|null $min Minimum value
1555 * @param int|null $max Maximum value for users
1556 * @param int|null $botMax Maximum value for sysops/bots
1557 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1559 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1560 $enforceLimits = false
1562 if ( !is_null( $min ) && $value < $min ) {
1563 $msg = ApiMessage
::create(
1564 [ 'apierror-integeroutofrange-belowminimum',
1565 $this->encodeParamName( $paramName ), $min, $value ],
1566 'integeroutofrange',
1567 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1569 $this->warnOrDie( $msg, $enforceLimits );
1573 // Minimum is always validated, whereas maximum is checked only if not
1574 // running in internal call mode
1575 if ( $this->getMain()->isInternalMode() ) {
1579 // Optimization: do not check user's bot status unless really needed -- skips db query
1580 // assumes $botMax >= $max
1581 if ( !is_null( $max ) && $value > $max ) {
1582 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1583 if ( $value > $botMax ) {
1584 $msg = ApiMessage
::create(
1585 [ 'apierror-integeroutofrange-abovebotmax',
1586 $this->encodeParamName( $paramName ), $botMax, $value ],
1587 'integeroutofrange',
1588 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1590 $this->warnOrDie( $msg, $enforceLimits );
1594 $msg = ApiMessage
::create(
1595 [ 'apierror-integeroutofrange-abovemax',
1596 $this->encodeParamName( $paramName ), $max, $value ],
1597 'integeroutofrange',
1598 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1600 $this->warnOrDie( $msg, $enforceLimits );
1607 * Validate and normalize parameters of type 'timestamp'
1608 * @param string $value Parameter value
1609 * @param string $encParamName Parameter name
1610 * @return string Validated and normalized parameter
1612 protected function validateTimestamp( $value, $encParamName ) {
1613 // Confusing synonyms for the current time accepted by wfTimestamp()
1614 // (wfTimestamp() also accepts various non-strings and the string of 14
1615 // ASCII NUL bytes, but those can't get here)
1617 $this->addDeprecation(
1618 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1619 'unclear-"now"-timestamp'
1621 return wfTimestamp( TS_MW
);
1624 // Explicit synonym for the current time
1625 if ( $value === 'now' ) {
1626 return wfTimestamp( TS_MW
);
1629 $timestamp = wfTimestamp( TS_MW
, $value );
1630 if ( $timestamp === false ) {
1631 $this->dieWithError(
1632 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1633 "badtimestamp_{$encParamName}"
1641 * Validate the supplied token.
1644 * @param string $token Supplied token
1645 * @param array $params All supplied parameters for the module
1647 * @throws MWException
1649 final public function validateToken( $token, array $params ) {
1650 $tokenType = $this->needsToken();
1651 $salts = ApiQueryTokens
::getTokenTypeSalts();
1652 if ( !isset( $salts[$tokenType] ) ) {
1653 throw new MWException(
1654 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1655 'without registering it'
1659 $tokenObj = ApiQueryTokens
::getToken(
1660 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1662 if ( $tokenObj->match( $token ) ) {
1666 $webUiSalt = $this->getWebUITokenSalt( $params );
1667 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1679 * Validate and normalize parameters of type 'user'
1680 * @param string $value Parameter value
1681 * @param string $encParamName Parameter name
1682 * @return string Validated and normalized parameter
1684 private function validateUser( $value, $encParamName ) {
1685 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1689 $name = User
::getCanonicalName( $value, 'valid' );
1690 if ( $name !== false ) {
1695 // We allow ranges as well, for blocks.
1696 IP
::isIPAddress( $value ) ||
1697 // See comment for User::isIP. We don't just call that function
1698 // here because it also returns true for things like
1699 // 300.300.300.300 that are neither valid usernames nor valid IP
1702 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1706 return IP
::sanitizeIP( $value );
1709 $this->dieWithError(
1710 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1711 "baduser_{$encParamName}"
1717 /************************************************************************//**
1718 * @name Utility methods
1723 * Set a watch (or unwatch) based the based on a watchlist parameter.
1724 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1725 * @param Title $titleObj The article's title to change
1726 * @param string|null $userOption The user option to consider when $watch=preferences
1728 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1729 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1730 if ( $value === null ) {
1734 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1738 * Gets the user for whom to get the watchlist
1740 * @param array $params
1743 public function getWatchlistUser( $params ) {
1744 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1745 $user = User
::newFromName( $params['owner'], false );
1746 if ( !( $user && $user->getId() ) ) {
1747 $this->dieWithError(
1748 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1751 $token = $user->getOption( 'watchlisttoken' );
1752 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1753 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1756 if ( !$this->getUser()->isLoggedIn() ) {
1757 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1759 $this->checkUserRightsAny( 'viewmywatchlist' );
1760 $user = $this->getUser();
1767 * Create a Message from a string or array
1769 * A string is used as a message key. An array has the message key as the
1770 * first value and message parameters as subsequent values.
1773 * @param string|array|Message $msg
1774 * @param IContextSource $context
1775 * @param array|null $params
1776 * @return Message|null
1778 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1779 if ( is_string( $msg ) ) {
1780 $msg = wfMessage( $msg );
1781 } elseif ( is_array( $msg ) ) {
1782 $msg = wfMessage( ...$msg );
1784 if ( !$msg instanceof Message
) {
1788 $msg->setContext( $context );
1790 $msg->params( $params );
1797 * Turn an array of message keys or key+param arrays into a Status
1799 * @param array $errors
1800 * @param User|null $user
1803 public function errorArrayToStatus( array $errors, User
$user = null ) {
1804 if ( $user === null ) {
1805 $user = $this->getUser();
1808 $status = Status
::newGood();
1809 foreach ( $errors as $error ) {
1810 if ( !is_array( $error ) ) {
1811 $error = [ $error ];
1813 if ( is_string( $error[0] ) && isset( self
::$blockMsgMap[$error[0]] ) && $user->getBlock() ) {
1814 list( $msg, $code ) = self
::$blockMsgMap[$error[0]];
1815 $status->fatal( ApiMessage
::create( $msg, $code,
1816 [ 'blockinfo' => $this->getBlockInfo( $user->getBlock() ) ]
1819 $status->fatal( ...$error );
1826 * Add block info to block messages in a Status
1828 * @param StatusValue $status
1829 * @param User|null $user
1831 public function addBlockInfoToStatus( StatusValue
$status, User
$user = null ) {
1832 if ( $user === null ) {
1833 $user = $this->getUser();
1836 foreach ( self
::$blockMsgMap as $msg => list( $apiMsg, $code ) ) {
1837 if ( $status->hasMessage( $msg ) && $user->getBlock() ) {
1838 $status->replaceMessage( $msg, ApiMessage
::create( $apiMsg, $code,
1839 [ 'blockinfo' => $this->getBlockInfo( $user->getBlock() ) ]
1846 * Call wfTransactionalTimeLimit() if this request was POSTed
1849 protected function useTransactionalTimeLimit() {
1850 if ( $this->getRequest()->wasPosted() ) {
1851 wfTransactionalTimeLimit();
1856 * Filter out-of-range values from a list of positive integer IDs
1858 * @param array $fields Array of pairs of table and field to check
1859 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1860 * expected to be stringified ints.
1861 * @return (string|int)[] Filtered IDs.
1863 protected function filterIDs( $fields, array $ids ) {
1866 foreach ( $fields as list( $table, $field ) ) {
1867 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1868 $row = self
::$filterIDsCache[$table][$field];
1870 $row = $this->getDB()->selectRow(
1873 'min_id' => "MIN($field)",
1874 'max_id' => "MAX($field)",
1879 self
::$filterIDsCache[$table][$field] = $row;
1881 $min = min( $min, $row->min_id
);
1882 $max = max( $max, $row->max_id
);
1884 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1885 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1886 && $id >= $min && $id <= $max;
1892 /************************************************************************//**
1893 * @name Warning and error reporting
1898 * Add a warning for this module.
1900 * Users should monitor this section to notice any changes in API. Multiple
1901 * calls to this function will result in multiple warning messages.
1903 * If $msg is not an ApiMessage, the message code will be derived from the
1904 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1907 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1908 * @param string|null $code See ApiErrorFormatter::addWarning()
1909 * @param array|null $data See ApiErrorFormatter::addWarning()
1911 public function addWarning( $msg, $code = null, $data = null ) {
1912 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1916 * Add a deprecation warning for this module.
1918 * A combination of $this->addWarning() and $this->logFeatureUsage()
1921 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1922 * @param string|null $feature See ApiBase::logFeatureUsage()
1923 * @param array|null $data See ApiErrorFormatter::addWarning()
1925 public function addDeprecation( $msg, $feature, $data = [] ) {
1926 $data = (array)$data;
1927 if ( $feature !== null ) {
1928 $data['feature'] = $feature;
1929 $this->logFeatureUsage( $feature );
1931 $this->addWarning( $msg, 'deprecation', $data );
1933 // No real need to deduplicate here, ApiErrorFormatter does that for
1934 // us (assuming the hook is deterministic).
1935 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1936 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1937 if ( count( $msgs ) > 1 ) {
1938 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1939 $msg = ( new RawMessage( $key ) )->params( $msgs );
1941 $msg = reset( $msgs );
1943 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1947 * Add an error for this module without aborting
1949 * If $msg is not an ApiMessage, the message code will be derived from the
1950 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1952 * @note If you want to abort processing, use self::dieWithError() instead.
1954 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1955 * @param string|null $code See ApiErrorFormatter::addError()
1956 * @param array|null $data See ApiErrorFormatter::addError()
1958 public function addError( $msg, $code = null, $data = null ) {
1959 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1963 * Add warnings and/or errors from a Status
1965 * @note If you want to abort processing, use self::dieStatus() instead.
1967 * @param StatusValue $status
1968 * @param string[] $types 'warning' and/or 'error'
1969 * @param string[] $filter Message keys to filter out (since 1.33)
1971 public function addMessagesFromStatus(
1972 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1974 $this->getErrorFormatter()->addMessagesFromStatus(
1975 $this->getModulePath(), $status, $types, $filter
1980 * Abort execution with an error
1982 * If $msg is not an ApiMessage, the message code will be derived from the
1983 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1986 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1987 * @param string|null $code See ApiErrorFormatter::addError()
1988 * @param array|null $data See ApiErrorFormatter::addError()
1989 * @param int|null $httpCode HTTP error code to use
1990 * @throws ApiUsageException always
1992 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1993 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1997 * Abort execution with an error derived from an exception
2000 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
2001 * @param array $options See ApiErrorFormatter::getMessageFromException()
2002 * @throws ApiUsageException always
2004 public function dieWithException( $exception, array $options = [] ) {
2005 $this->dieWithError(
2006 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
2011 * Adds a warning to the output, else dies
2013 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2014 * @param bool $enforceLimits Whether this is an enforce (die)
2016 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2017 if ( $enforceLimits ) {
2018 $this->dieWithError( $msg );
2020 $this->addWarning( $msg );
2025 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2026 * error handler and die with an error message including block info.
2029 * @param Block $block The block used to generate the ApiUsageException
2030 * @throws ApiUsageException always
2032 public function dieBlocked( Block
$block ) {
2033 // Die using the appropriate message depending on block type
2034 if ( $block->getType() == Block
::TYPE_AUTO
) {
2035 $this->dieWithError(
2036 'apierror-autoblocked',
2038 [ 'blockinfo' => $this->getBlockInfo( $block ) ]
2040 } elseif ( !$block->isSitewide() ) {
2041 $this->dieWithError(
2042 'apierror-blocked-partial',
2044 [ 'blockinfo' => $this->getBlockInfo( $block ) ]
2047 $this->dieWithError(
2050 [ 'blockinfo' => $this->getBlockInfo( $block ) ]
2056 * Throw an ApiUsageException based on the Status object.
2059 * @since 1.29 Accepts a StatusValue
2060 * @param StatusValue $status
2061 * @throws ApiUsageException always
2063 public function dieStatus( StatusValue
$status ) {
2064 if ( $status->isGood() ) {
2065 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2068 // ApiUsageException needs a fatal status, but this method has
2069 // historically accepted any non-good status. Convert it if necessary.
2070 $status->setOK( false );
2071 if ( !$status->getErrorsByType( 'error' ) ) {
2072 $newStatus = Status
::newGood();
2073 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2074 $newStatus->fatal( $err['message'], ...$err['params'] );
2076 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2077 $newStatus->fatal( 'unknownerror-nocode' );
2079 $status = $newStatus;
2082 $this->addBlockInfoToStatus( $status );
2083 throw new ApiUsageException( $this, $status );
2087 * Helper function for readonly errors
2089 * @throws ApiUsageException always
2091 public function dieReadOnly() {
2092 $this->dieWithError(
2093 'apierror-readonly',
2095 [ 'readonlyreason' => wfReadOnlyReason() ]
2100 * Helper function for permission-denied errors
2102 * @param string|string[] $rights
2103 * @param User|null $user
2104 * @throws ApiUsageException if the user doesn't have any of the rights.
2105 * The error message is based on $rights[0].
2107 public function checkUserRightsAny( $rights, $user = null ) {
2109 $user = $this->getUser();
2111 $rights = (array)$rights;
2112 if ( !$user->isAllowedAny( ...$rights ) ) {
2113 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2118 * Helper function for permission-denied errors
2120 * @since 1.33 Changed the third parameter from $user to $options.
2121 * @param Title $title
2122 * @param string|string[] $actions
2123 * @param array $options Additional options
2124 * - user: (User) User to use rather than $this->getUser()
2125 * - autoblock: (bool, default false) Whether to spread autoblocks
2126 * For compatibility, passing a User object is treated as the value for the 'user' option.
2127 * @throws ApiUsageException if the user doesn't have all of the rights.
2129 public function checkTitleUserPermissions( Title
$title, $actions, $options = [] ) {
2130 if ( !is_array( $options ) ) {
2131 wfDeprecated( '$user as the third parameter to ' . __METHOD__
, '1.33' );
2132 $options = [ 'user' => $options ];
2134 $user = $options['user'] ??
$this->getUser();
2137 foreach ( (array)$actions as $action ) {
2138 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2142 if ( !empty( $options['autoblock'] ) ) {
2143 $user->spreadAnyEditBlock();
2146 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2151 * Will only set a warning instead of failing if the global $wgDebugAPI
2152 * is set to true. Otherwise behaves exactly as self::dieWithError().
2155 * @param string|array|Message $msg
2156 * @param string|null $code
2157 * @param array|null $data
2158 * @param int|null $httpCode
2159 * @throws ApiUsageException
2161 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2162 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2163 $this->dieWithError( $msg, $code, $data, $httpCode );
2165 $this->addWarning( $msg, $code, $data );
2170 * Die with the 'badcontinue' error.
2172 * This call is common enough to make it into the base method.
2174 * @param bool $condition Will only die if this value is true
2175 * @throws ApiUsageException
2178 protected function dieContinueUsageIf( $condition ) {
2180 $this->dieWithError( 'apierror-badcontinue' );
2185 * Internal code errors should be reported with this method
2186 * @param string $method Method or function name
2187 * @param string $message Error message
2188 * @throws MWException always
2190 protected static function dieDebug( $method, $message ) {
2191 throw new MWException( "Internal error in $method: $message" );
2195 * Write logging information for API features to a debug log, for usage
2197 * @note Consider using $this->addDeprecation() instead to both warn and log.
2198 * @param string $feature Feature being used.
2200 public function logFeatureUsage( $feature ) {
2201 static $loggedFeatures = [];
2203 // Only log each feature once per request. We can get multiple calls from calls to
2204 // extractRequestParams() with different values for 'parseLimit', for example.
2205 if ( isset( $loggedFeatures[$feature] ) ) {
2208 $loggedFeatures[$feature] = true;
2210 $request = $this->getRequest();
2212 'feature' => $feature,
2213 // Spaces to underscores in 'username' for historical reasons.
2214 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
2215 'ip' => $request->getIP(),
2216 'referer' => (string)$request->getHeader( 'Referer' ),
2217 'agent' => $this->getMain()->getUserAgent(),
2220 // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
2221 $s = '"' . addslashes( $ctx['feature'] ) . '"' .
2222 ' "' . wfUrlencode( $ctx['username'] ) . '"' .
2223 ' "' . $ctx['ip'] . '"' .
2224 ' "' . addslashes( $ctx['referer'] ) . '"' .
2225 ' "' . addslashes( $ctx['agent'] ) . '"';
2227 wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
2232 /************************************************************************//**
2233 * @name Help message generation
2238 * Return the summary message.
2240 * This is a one-line description of the module, suitable for display in a
2244 * @return string|array|Message
2246 protected function getSummaryMessage() {
2247 return "apihelp-{$this->getModulePath()}-summary";
2251 * Return the extended help text message.
2253 * This is additional text to display at the top of the help section, below
2257 * @return string|array|Message
2259 protected function getExtendedDescription() {
2261 "apihelp-{$this->getModulePath()}-extended-description",
2262 'api-help-no-extended-description',
2267 * Get final module summary
2272 public function getFinalSummary() {
2273 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2274 $this->getModulePrefix(),
2275 $this->getModuleName(),
2276 $this->getModulePath(),
2282 * Get final module description, after hooks have had a chance to tweak it as
2285 * @since 1.25, returns Message[] rather than string[]
2288 public function getFinalDescription() {
2289 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2290 $this->getModulePrefix(),
2291 $this->getModuleName(),
2292 $this->getModulePath(),
2294 $extendedDescription = self
::makeMessage(
2295 $this->getExtendedDescription(), $this->getContext(), [
2296 $this->getModulePrefix(),
2297 $this->getModuleName(),
2298 $this->getModulePath(),
2302 $msgs = [ $summary, $extendedDescription ];
2304 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2310 * Get final list of parameters, after hooks have had a chance to
2311 * tweak it as needed.
2313 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2314 * @return array|bool False on no parameters
2315 * @since 1.21 $flags param added
2317 public function getFinalParams( $flags = 0 ) {
2318 $params = $this->getAllowedParams( $flags );
2323 if ( $this->needsToken() ) {
2324 $params['token'] = [
2325 self
::PARAM_TYPE
=> 'string',
2326 self
::PARAM_REQUIRED
=> true,
2327 self
::PARAM_SENSITIVE
=> true,
2328 self
::PARAM_HELP_MSG
=> [
2329 'api-help-param-token',
2330 $this->needsToken(),
2332 ] +
( $params['token'] ??
[] );
2335 // Avoid PHP 7.1 warning of passing $this by reference
2337 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2343 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2346 * @since 1.25, returns array of Message[] rather than array of string[]
2347 * @return array Keys are parameter names, values are arrays of Message objects
2349 public function getFinalParamDescription() {
2350 $prefix = $this->getModulePrefix();
2351 $name = $this->getModuleName();
2352 $path = $this->getModulePath();
2354 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2356 foreach ( $params as $param => $settings ) {
2357 if ( !is_array( $settings ) ) {
2361 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2362 $msg = $settings[self
::PARAM_HELP_MSG
];
2364 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2366 $msg = self
::makeMessage( $msg, $this->getContext(),
2367 [ $prefix, $param, $name, $path ] );
2369 self
::dieDebug( __METHOD__
,
2370 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2372 $msgs[$param] = [ $msg ];
2374 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2375 $settings[self
::PARAM_TYPE
] === 'submodule'
2377 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2378 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2380 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2382 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2383 $map[$submoduleName] = $prefix . $submoduleName;
2388 $deprecatedSubmodules = [];
2389 foreach ( $map as $v => $m ) {
2390 $arr = &$submodules;
2391 $isDeprecated = false;
2394 $submod = $this->getModuleFromPath( $m );
2396 $summary = $submod->getFinalSummary();
2397 $isDeprecated = $submod->isDeprecated();
2398 if ( $isDeprecated ) {
2399 $arr = &$deprecatedSubmodules;
2402 } catch ( ApiUsageException
$ex ) {
2406 $key = $summary->getKey();
2407 $params = $summary->getParams();
2409 $key = 'api-help-undocumented-module';
2412 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2413 $arr[] = $m->setContext( $this->getContext() );
2415 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2416 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2417 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2418 self
::dieDebug( __METHOD__
,
2419 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2421 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2422 self
::dieDebug( __METHOD__
,
2423 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2424 'ApiBase::PARAM_TYPE is an array' );
2427 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2428 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2430 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2431 if ( isset( $valueMsgs[$value] ) ) {
2432 $msg = $valueMsgs[$value];
2434 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2436 $m = self
::makeMessage( $msg, $this->getContext(),
2437 [ $prefix, $param, $name, $path, $value ] );
2439 $m = new ApiHelpParamValueMessage(
2441 [ $m->getKey(), 'api-help-param-no-description' ],
2443 isset( $deprecatedValues[$value] )
2445 $msgs[$param][] = $m->setContext( $this->getContext() );
2447 self
::dieDebug( __METHOD__
,
2448 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2453 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2454 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2455 self
::dieDebug( __METHOD__
,
2456 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2458 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2459 $m = self
::makeMessage( $m, $this->getContext(),
2460 [ $prefix, $param, $name, $path ] );
2462 $msgs[$param][] = $m;
2464 self
::dieDebug( __METHOD__
,
2465 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2471 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2477 * Generates the list of flags for the help screen and for action=paraminfo
2479 * Corresponding messages: api-help-flag-deprecated,
2480 * api-help-flag-internal, api-help-flag-readrights,
2481 * api-help-flag-writerights, api-help-flag-mustbeposted
2485 protected function getHelpFlags() {
2488 if ( $this->isDeprecated() ) {
2489 $flags[] = 'deprecated';
2491 if ( $this->isInternal() ) {
2492 $flags[] = 'internal';
2494 if ( $this->isReadMode() ) {
2495 $flags[] = 'readrights';
2497 if ( $this->isWriteMode() ) {
2498 $flags[] = 'writerights';
2500 if ( $this->mustBePosted() ) {
2501 $flags[] = 'mustbeposted';
2508 * Returns information about the source of this module, if known
2510 * Returned array is an array with the following keys:
2511 * - path: Install path
2512 * - name: Extension name, or "MediaWiki" for core
2513 * - namemsg: (optional) i18n message key for a display name
2514 * - license-name: (optional) Name of license
2516 * @return array|null
2518 protected function getModuleSourceInfo() {
2521 if ( $this->mModuleSource
!== false ) {
2522 return $this->mModuleSource
;
2525 // First, try to find where the module comes from...
2526 $rClass = new ReflectionClass( $this );
2527 $path = $rClass->getFileName();
2530 $this->mModuleSource
= null;
2533 $path = realpath( $path ) ?
: $path;
2535 // Build map of extension directories to extension info
2536 if ( self
::$extensionInfo === null ) {
2537 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2538 self
::$extensionInfo = [
2539 realpath( __DIR__
) ?
: __DIR__
=> [
2541 'name' => 'MediaWiki',
2542 'license-name' => 'GPL-2.0-or-later',
2544 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2545 realpath( $extDir ) ?
: $extDir => null,
2551 'license-name' => null,
2553 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2554 foreach ( $group as $ext ) {
2555 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2556 // This shouldn't happen, but does anyway.
2560 $extpath = $ext['path'];
2561 if ( !is_dir( $extpath ) ) {
2562 $extpath = dirname( $extpath );
2564 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2565 array_intersect_key( $ext, $keep );
2568 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2569 $extpath = $ext['path'];
2570 if ( !is_dir( $extpath ) ) {
2571 $extpath = dirname( $extpath );
2573 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2574 array_intersect_key( $ext, $keep );
2578 // Now traverse parent directories until we find a match or run out of
2581 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2583 $this->mModuleSource
= self
::$extensionInfo[$path];
2584 return $this->mModuleSource
;
2588 $path = dirname( $path );
2589 } while ( $path !== $oldpath );
2591 // No idea what extension this might be.
2592 $this->mModuleSource
= null;
2597 * Called from ApiHelp before the pieces are joined together and returned.
2599 * This exists mainly for ApiMain to add the Permissions and Credits
2600 * sections. Other modules probably don't need it.
2602 * @param string[] &$help Array of help data
2603 * @param array $options Options passed to ApiHelp::getHelp
2604 * @param array &$tocData If a TOC is being generated, this array has keys
2605 * as anchors in the page and values as for Linker::generateTOC().
2607 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2612 /************************************************************************//**
2618 * Returns the description string for this module
2620 * Ignored if an i18n message exists for
2621 * "apihelp-{$this->getModulePath()}-description".
2623 * @deprecated since 1.25
2624 * @return Message|string|array|false
2626 protected function getDescription() {
2627 wfDeprecated( __METHOD__
, '1.25' );
2632 * Returns an array of parameter descriptions.
2634 * For each parameter, ignored if an i18n message exists for the parameter.
2635 * By default that message is
2636 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2637 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2638 * self::getFinalParams().
2640 * @deprecated since 1.25
2641 * @return array|bool False on no parameter descriptions
2643 protected function getParamDescription() {
2644 wfDeprecated( __METHOD__
, '1.25' );
2649 * Returns usage examples for this module.
2651 * Return value as an array is either:
2652 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2654 * - sequential numeric keys with even-numbered keys being display-text
2655 * and odd-numbered keys being partial urls
2656 * - partial URLs as keys with display-text (string or array-to-be-joined)
2658 * Return value as a string is the same as an array with a numeric key and
2659 * that value, and boolean false means "no examples".
2661 * @deprecated since 1.25, use getExamplesMessages() instead
2662 * @return bool|string|array
2664 protected function getExamples() {
2665 wfDeprecated( __METHOD__
, '1.25' );
2670 * Return the description message.
2672 * This is additional text to display on the help page after the summary.
2674 * @deprecated since 1.30
2675 * @return string|array|Message
2677 protected function getDescriptionMessage() {
2678 wfDeprecated( __METHOD__
, '1.30' );
2680 "apihelp-{$this->getModulePath()}-description",
2681 "apihelp-{$this->getModulePath()}-summary",
2686 * Truncate an array to a certain length.
2687 * @deprecated since 1.32, no replacement
2688 * @param array &$arr Array to truncate
2689 * @param int $limit Maximum length
2690 * @return bool True if the array was truncated, false otherwise
2692 public static function truncateArray( &$arr, $limit ) {
2693 wfDeprecated( __METHOD__
, '1.32' );
2695 while ( count( $arr ) > $limit ) {
2707 * For really cool vim folding this needs to be at the end:
2708 * vim: foldmarker=@{,@} foldmethod=marker