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\Linker\LinkTarget
;
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Permissions\PermissionManager
;
28 use Wikimedia\Rdbms\IDatabase
;
31 * This abstract class implements many basic API functions, and is the base of
33 * The class functions are divided into several areas of functionality:
35 * Module parameters: Derived classes can define getAllowedParams() to specify
36 * which parameters to expect, how to parse and validate them.
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
44 use ApiBlockInfoTrait
;
47 * @name Constants for ::getAllowedParams() arrays
48 * These constants are keys in the arrays returned by ::getAllowedParams()
49 * and accepted by ::getParameterFromSettings() that define how the
50 * parameters coming in from the request are to be interpreted.
54 /** (null|boolean|integer|string) Default value of the parameter. */
57 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
58 const PARAM_ISMULTI
= 1;
61 * (string|string[]) Either an array of allowed value strings, or a string
62 * type as described below. If not specified, will be determined from the
65 * Supported string types are:
66 * - boolean: A boolean parameter, returned as false if the parameter is
67 * omitted and true if present (even with a falsey value, i.e. it works
68 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
69 * Cannot be used with PARAM_ISMULTI.
70 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
71 * PARAM_RANGE_ENFORCE.
72 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
73 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
74 * specified. Cannot be used with PARAM_ISMULTI.
75 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
76 * support easily specifying all namespaces.
78 * - password: Any non-empty string. Input value is private or sensitive.
79 * <input type="password"> would be an appropriate HTML form field.
80 * - string: Any non-empty string, not expected to be very long or contain newlines.
81 * <input type="text"> would be an appropriate HTML form field.
82 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
83 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
84 * used with PARAM_ISMULTI.
85 * - text: Any non-empty string, expected to be very long or contain newlines.
86 * <textarea> would be an appropriate HTML form field.
87 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
88 * string 'now' representing the current timestamp. Will be returned in
90 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
91 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
92 * Cannot be used with PARAM_ISMULTI.
96 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
100 * (integer) Max value allowed for the parameter for users with the
101 * apihighlimits right, for PARAM_TYPE 'limit'.
103 const PARAM_MAX2
= 4;
105 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
108 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
109 const PARAM_ALLOW_DUPLICATES
= 6;
111 /** (boolean) Is the parameter deprecated (will show a warning)? */
112 const PARAM_DEPRECATED
= 7;
115 * (boolean) Is the parameter required?
118 const PARAM_REQUIRED
= 8;
121 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
124 const PARAM_RANGE_ENFORCE
= 9;
127 * (string|array|Message) Specify an alternative i18n documentation message
128 * for this parameter. Default is apihelp-{$path}-param-{$param}.
131 const PARAM_HELP_MSG
= 10;
134 * ((string|array|Message)[]) Specify additional i18n messages to append to
135 * the normal message for this parameter.
138 const PARAM_HELP_MSG_APPEND
= 11;
141 * (array) Specify additional information tags for the parameter. Value is
142 * an array of arrays, with the first member being the 'tag' for the info
143 * and the remaining members being the values. In the help, this is
144 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
145 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
148 const PARAM_HELP_MSG_INFO
= 12;
151 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
152 * those values to page titles which will be linked in the help.
155 const PARAM_VALUE_LINKS
= 13;
158 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
159 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
160 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
161 * Specify an empty array to use the default message key for all values.
164 const PARAM_HELP_MSG_PER_VALUE
= 14;
167 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
168 * submodule paths. Default is to use all modules in
169 * $this->getModuleManager() in the group matching the parameter name.
172 const PARAM_SUBMODULE_MAP
= 15;
175 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
176 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
179 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
182 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
183 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
184 * every possible value. If a string is set, it will be used in place of the asterisk.
187 const PARAM_ALL
= 17;
190 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
193 const PARAM_EXTRA_NAMESPACES
= 18;
196 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
197 * always sensitive regardless of the value of this field.
200 const PARAM_SENSITIVE
= 19;
203 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
204 * Keys are the deprecated parameter values, values define the warning
205 * message to emit: either boolean true (to use a default message) or a
206 * $msg for ApiBase::makeMessage().
209 const PARAM_DEPRECATED_VALUES
= 20;
212 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
215 const PARAM_ISMULTI_LIMIT1
= 21;
218 * (integer) Maximum number of values, for users with the apihighimits right.
219 * Must be used with PARAM_ISMULTI.
222 const PARAM_ISMULTI_LIMIT2
= 22;
225 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
228 const PARAM_MAX_BYTES
= 23;
231 * (integer) Maximum length of a string in characters (unicode codepoints).
234 const PARAM_MAX_CHARS
= 24;
237 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
238 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
239 * which the replacement values are taken.
241 * For example, a parameter "foo-{ns}-{title}" could be defined with
242 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
243 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
245 * All placeholders must be present in the parameter's name. Each target parameter must have
246 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
247 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
248 * A parameter cannot target itself.
252 const PARAM_TEMPLATE_VARS
= 25;
256 const ALL_DEFAULT_STRING
= '*';
258 /** Fast query, standard limit. */
259 const LIMIT_BIG1
= 500;
260 /** Fast query, apihighlimits limit. */
261 const LIMIT_BIG2
= 5000;
262 /** Slow query, standard limit. */
263 const LIMIT_SML1
= 50;
264 /** Slow query, apihighlimits limit. */
265 const LIMIT_SML2
= 500;
268 * getAllowedParams() flag: When set, the result could take longer to generate,
269 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
272 const GET_VALUES_FOR_HELP
= 1;
274 /** @var array Maps extension paths to info arrays */
275 private static $extensionInfo = null;
277 /** @var int[][][] Cache for self::filterIDs() */
278 private static $filterIDsCache = [];
280 /** $var array Map of web UI block messages to corresponding API messages and codes */
281 private static $blockMsgMap = [
282 'blockedtext' => [ 'apierror-blocked', 'blocked' ],
283 'blockedtext-partial' => [ 'apierror-blocked', 'blocked' ],
284 'autoblockedtext' => [ 'apierror-autoblocked', 'autoblocked' ],
285 'systemblockedtext' => [ 'apierror-systemblocked', 'blocked' ],
289 private $mMainModule;
291 private $mModuleName, $mModulePrefix;
292 private $mReplicaDB = null;
293 private $mParamCache = [];
294 /** @var array|null|bool */
295 private $mModuleSource = false;
298 * @param ApiMain $mainModule
299 * @param string $moduleName Name of this module
300 * @param string $modulePrefix Prefix to use for parameter names
302 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
303 $this->mMainModule
= $mainModule;
304 $this->mModuleName
= $moduleName;
305 $this->mModulePrefix
= $modulePrefix;
307 if ( !$this->isMain() ) {
308 $this->setContext( $mainModule->getContext() );
312 /************************************************************************//**
313 * @name Methods to implement
318 * Evaluates the parameters, performs the requested query, and sets up
319 * the result. Concrete implementations of ApiBase must override this
320 * method to provide whatever functionality their module offers.
321 * Implementations must not produce any output on their own and are not
322 * expected to handle any errors.
324 * The execute() method will be invoked directly by ApiMain immediately
325 * before the result of the module is output. Aside from the
326 * constructor, implementations should assume that no other methods
327 * will be called externally on the module before the result is
330 * The result data should be stored in the ApiResult object available
331 * through getResult().
333 abstract public function execute();
336 * Get the module manager, or null if this module has no sub-modules
338 * @return ApiModuleManager
340 public function getModuleManager() {
345 * If the module may only be used with a certain format module,
346 * it should override this method to return an instance of that formatter.
347 * A value of null means the default format will be used.
348 * @note Do not use this just because you don't want to support non-json
349 * formats. This should be used only when there is a fundamental
350 * requirement for a specific format.
351 * @return mixed Instance of a derived class of ApiFormatBase, or null
353 public function getCustomPrinter() {
358 * Returns usage examples for this module.
360 * Return value has query strings as keys, with values being either strings
361 * (message key), arrays (message key + parameter), or Message objects.
363 * Do not call this base class implementation when overriding this method.
368 protected function getExamplesMessages() {
373 * Return links to more detailed help pages about the module.
374 * @since 1.25, returning boolean false is deprecated
375 * @return string|array
377 public function getHelpUrls() {
382 * Returns an array of allowed parameters (parameter name) => (default
383 * value) or (parameter name) => (array with PARAM_* constants as keys)
384 * Don't call this function directly: use getFinalParams() to allow
385 * hooks to modify parameters as needed.
387 * Some derived classes may choose to handle an integer $flags parameter
388 * in the overriding methods. Callers of this method can pass zero or
389 * more OR-ed flags like GET_VALUES_FOR_HELP.
393 protected function getAllowedParams( /* $flags = 0 */ ) {
394 // int $flags is not declared because it causes "Strict standards"
395 // warning. Most derived classes do not implement it.
400 * Indicates if this module needs maxlag to be checked
403 public function shouldCheckMaxlag() {
408 * Indicates whether this module requires read rights
411 public function isReadMode() {
416 * Indicates whether this module requires write mode
418 * This should return true for modules that may require synchronous database writes.
419 * Modules that do not need such writes should also not rely on master database access,
420 * since only read queries are needed and each master DB is a single point of failure.
421 * Additionally, requests that only need replica DBs can be efficiently routed to any
422 * datacenter via the Promise-Non-Write-API-Action header.
426 public function isWriteMode() {
431 * Indicates whether this module must be called with a POST request
434 public function mustBePosted() {
435 return $this->needsToken() !== false;
439 * Indicates whether this module is deprecated
443 public function isDeprecated() {
448 * Indicates whether this module is "internal"
449 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
453 public function isInternal() {
458 * Returns the token type this module requires in order to execute.
460 * Modules are strongly encouraged to use the core 'csrf' type unless they
461 * have specialized security needs. If the token type is not one of the
462 * core types, you must use the ApiQueryTokensRegisterTypes hook to
465 * Returning a non-falsey value here will force the addition of an
466 * appropriate 'token' parameter in self::getFinalParams(). Also,
467 * self::mustBePosted() must return true when tokens are used.
469 * In previous versions of MediaWiki, true was a valid return value.
470 * Returning true will generate errors indicating that the API module needs
473 * @return string|false
475 public function needsToken() {
480 * Fetch the salt used in the Web UI corresponding to this module.
482 * Only override this if the Web UI uses a token with a non-constant salt.
485 * @param array $params All supplied parameters for the module
486 * @return string|array|null
488 protected function getWebUITokenSalt( array $params ) {
493 * Returns data for HTTP conditional request mechanisms.
496 * @param string $condition Condition being queried:
497 * - last-modified: Return a timestamp representing the maximum of the
498 * last-modified dates for all resources involved in the request. See
499 * RFC 7232 § 2.2 for semantics.
500 * - etag: Return an entity-tag representing the state of all resources involved
501 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
502 * @return string|bool|null As described above, or null if no value is available.
504 public function getConditionalRequestData( $condition ) {
510 /************************************************************************//**
511 * @name Data access methods
516 * Get the name of the module being executed by this instance
519 public function getModuleName() {
520 return $this->mModuleName
;
524 * Get parameter prefix (usually two letters or an empty string).
527 public function getModulePrefix() {
528 return $this->mModulePrefix
;
532 * Get the main module
535 public function getMain() {
536 return $this->mMainModule
;
540 * Returns true if this module is the main module ($this === $this->mMainModule),
544 public function isMain() {
545 return $this === $this->mMainModule
;
549 * Get the parent of this module
551 * @return ApiBase|null
553 public function getParent() {
554 return $this->isMain() ?
null : $this->getMain();
558 * Returns true if the current request breaks the same-origin policy.
560 * For example, json with callbacks.
562 * https://en.wikipedia.org/wiki/Same-origin_policy
567 public function lacksSameOriginSecurity() {
568 // Main module has this method overridden
569 // Safety - avoid infinite loop:
570 if ( $this->isMain() ) {
571 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
574 return $this->getMain()->lacksSameOriginSecurity();
578 * Get the path to this module
583 public function getModulePath() {
584 if ( $this->isMain() ) {
586 } elseif ( $this->getParent()->isMain() ) {
587 return $this->getModuleName();
589 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
594 * Get a module from its module path
597 * @param string $path
598 * @return ApiBase|null
599 * @throws ApiUsageException
601 public function getModuleFromPath( $path ) {
602 $module = $this->getMain();
603 if ( $path === 'main' ) {
607 $parts = explode( '+', $path );
608 if ( count( $parts ) === 1 ) {
609 // In case the '+' was typed into URL, it resolves as a space
610 $parts = explode( ' ', $path );
613 $count = count( $parts );
614 for ( $i = 0; $i < $count; $i++
) {
616 $manager = $parent->getModuleManager();
617 if ( $manager === null ) {
618 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
619 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
621 $module = $manager->getModule( $parts[$i] );
623 if ( $module === null ) {
624 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
626 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
636 * Get the result object
639 public function getResult() {
640 // Main module has getResult() method overridden
641 // Safety - avoid infinite loop:
642 if ( $this->isMain() ) {
643 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
646 return $this->getMain()->getResult();
650 * Get the error formatter
651 * @return ApiErrorFormatter
653 public function getErrorFormatter() {
654 // Main module has getErrorFormatter() method overridden
655 // Safety - avoid infinite loop:
656 if ( $this->isMain() ) {
657 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
660 return $this->getMain()->getErrorFormatter();
664 * Gets a default replica DB connection object
667 protected function getDB() {
668 if ( !isset( $this->mReplicaDB
) ) {
669 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
672 return $this->mReplicaDB
;
676 * Get the continuation manager
677 * @return ApiContinuationManager|null
679 public function getContinuationManager() {
680 // Main module has getContinuationManager() method overridden
681 // Safety - avoid infinite loop:
682 if ( $this->isMain() ) {
683 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
686 return $this->getMain()->getContinuationManager();
690 * Set the continuation manager
691 * @param ApiContinuationManager|null $manager
693 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
694 // Main module has setContinuationManager() method overridden
695 // Safety - avoid infinite loop:
696 if ( $this->isMain() ) {
697 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
700 $this->getMain()->setContinuationManager( $manager );
704 * Obtain a PermissionManager instance that subclasses may use in their authorization checks.
707 * @return PermissionManager
709 protected function getPermissionManager(): PermissionManager
{
710 return MediaWikiServices
::getInstance()->getPermissionManager();
715 /************************************************************************//**
716 * @name Parameter handling
721 * Indicate if the module supports dynamically-determined parameters that
722 * cannot be included in self::getAllowedParams().
723 * @return string|array|Message|null Return null if the module does not
724 * support additional dynamic parameters, otherwise return a message
727 public function dynamicParameterDocumentation() {
732 * This method mangles parameter name based on the prefix supplied to the constructor.
733 * Override this method to change parameter name during runtime
734 * @param string|string[] $paramName Parameter name
735 * @return string|string[] Prefixed parameter name
736 * @since 1.29 accepts an array of strings
738 public function encodeParamName( $paramName ) {
739 if ( is_array( $paramName ) ) {
740 return array_map( function ( $name ) {
741 return $this->mModulePrefix
. $name;
744 return $this->mModulePrefix
. $paramName;
749 * Using getAllowedParams(), this function makes an array of the values
750 * provided by the user, with key being the name of the variable, and
751 * value - validated value from user or default. limits will not be
752 * parsed if $parseLimit is set to false; use this when the max
753 * limit is not definitive yet, e.g. when getting revisions.
754 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
755 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
756 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
757 * Returned parameter values might be ApiUsageException instances.
760 public function extractRequestParams( $options = [] ) {
761 if ( is_bool( $options ) ) {
762 $options = [ 'parseLimit' => $options ];
765 'parseLimit' => true,
769 $parseLimit = (bool)$options['parseLimit'];
771 // Cache parameters, for performance and to avoid T26564.
772 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
773 $params = $this->getFinalParams() ?
: [];
777 // Process all non-templates and save templates for secondary
780 foreach ( $params as $paramName => $paramSettings ) {
781 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
782 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
785 $results[$paramName] = $this->getParameterFromSettings(
786 $paramName, $paramSettings, $parseLimit
788 } catch ( ApiUsageException
$ex ) {
789 $results[$paramName] = $ex;
794 // Now process all the templates by successively replacing the
795 // placeholders with all client-supplied values.
796 // This bit duplicates JavaScript logic in
797 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
798 // If you update this, see if that needs updating too.
799 while ( $toProcess ) {
800 list( $name, $targets, $settings ) = array_shift( $toProcess );
802 foreach ( $targets as $placeholder => $target ) {
803 if ( !array_key_exists( $target, $results ) ) {
804 // The target wasn't processed yet, try the next one.
805 // If all hit this case, the parameter has no expansions.
808 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
809 // The target was processed but has no (valid) values.
810 // That means it has no expansions.
814 // Expand this target in the name and all other targets,
815 // then requeue if there are more targets left or put in
816 // $results if all are done.
817 unset( $targets[$placeholder] );
818 $placeholder = '{' . $placeholder . '}';
819 // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
820 foreach ( $results[$target] as $value ) {
821 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
822 // Skip values that make invalid parameter names.
823 $encTargetName = $this->encodeParamName( $target );
824 if ( !isset( $warned[$encTargetName][$value] ) ) {
825 $warned[$encTargetName][$value] = true;
827 'apiwarn-ignoring-invalid-templated-value',
828 wfEscapeWikiText( $encTargetName ),
829 wfEscapeWikiText( $value ),
835 $newName = str_replace( $placeholder, $value, $name );
838 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
839 } catch ( ApiUsageException
$ex ) {
840 $results[$newName] = $ex;
844 foreach ( $targets as $k => $v ) {
845 $newTargets[$k] = str_replace( $placeholder, $value, $v );
847 $toProcess[] = [ $newName, $newTargets, $settings ];
854 $this->mParamCache
[$parseLimit] = $results;
857 $ret = $this->mParamCache
[$parseLimit];
858 if ( !$options['safeMode'] ) {
859 foreach ( $ret as $v ) {
860 if ( $v instanceof ApiUsageException
) {
866 return $this->mParamCache
[$parseLimit];
870 * Get a value for the given parameter
871 * @param string $paramName Parameter name
872 * @param bool $parseLimit See extractRequestParams()
873 * @return mixed Parameter value
875 protected function getParameter( $paramName, $parseLimit = true ) {
876 $ret = $this->extractRequestParams( [
877 'parseLimit' => $parseLimit,
880 if ( $ret instanceof ApiUsageException
) {
887 * Die if none or more than one of a certain set of parameters is set and not false.
889 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
890 * @param string $required,... Names of parameters of which exactly one must be set
892 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
893 $required = func_get_args();
894 array_shift( $required );
896 $intersection = array_intersect( array_keys( array_filter( $params,
897 [ $this, 'parameterNotEmpty' ] ) ), $required );
899 if ( count( $intersection ) > 1 ) {
900 $this->dieWithError( [
901 'apierror-invalidparammix',
902 Message
::listParam( array_map(
904 return '<var>' . $this->encodeParamName( $p ) . '</var>';
906 array_values( $intersection )
908 count( $intersection ),
910 } elseif ( count( $intersection ) == 0 ) {
911 $this->dieWithError( [
912 'apierror-missingparam-one-of',
913 Message
::listParam( array_map(
915 return '<var>' . $this->encodeParamName( $p ) . '</var>';
917 array_values( $required )
925 * Die if more than one of a certain set of parameters is set and not false.
927 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
928 * @param string $required,... Names of parameters of which at most one must be set
930 public function requireMaxOneParameter( $params, $required /*...*/ ) {
931 $required = func_get_args();
932 array_shift( $required );
934 $intersection = array_intersect( array_keys( array_filter( $params,
935 [ $this, 'parameterNotEmpty' ] ) ), $required );
937 if ( count( $intersection ) > 1 ) {
938 $this->dieWithError( [
939 'apierror-invalidparammix',
940 Message
::listParam( array_map(
942 return '<var>' . $this->encodeParamName( $p ) . '</var>';
944 array_values( $intersection )
946 count( $intersection ),
952 * Die if none of a certain set of parameters is set and not false.
955 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
956 * @param string $required,... Names of parameters of which at least one must be set
958 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
959 $required = func_get_args();
960 array_shift( $required );
962 $intersection = array_intersect(
963 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
967 if ( count( $intersection ) == 0 ) {
968 $this->dieWithError( [
969 'apierror-missingparam-at-least-one-of',
970 Message
::listParam( array_map(
972 return '<var>' . $this->encodeParamName( $p ) . '</var>';
974 array_values( $required )
982 * Die if any of the specified parameters were found in the query part of
983 * the URL rather than the post body.
985 * @param string[] $params Parameters to check
986 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
988 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
989 // Skip if $wgDebugAPI is set or we're in internal mode
990 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
994 $queryValues = $this->getRequest()->getQueryValues();
996 foreach ( $params as $param ) {
997 if ( $prefix !== 'noprefix' ) {
998 $param = $this->encodeParamName( $param );
1000 if ( array_key_exists( $param, $queryValues ) ) {
1001 $badParams[] = $param;
1006 $this->dieWithError(
1007 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
1013 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
1015 * @param object $x Parameter to check is not null/false
1018 private function parameterNotEmpty( $x ) {
1019 return !is_null( $x ) && $x !== false;
1023 * Get a WikiPage object from a title or pageid param, if possible.
1024 * Can die, if no param is set or if the title or page id is not valid.
1026 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1027 * @param bool|string $load Whether load the object's state from the database:
1028 * - false: don't load (if the pageid is given, it will still be loaded)
1029 * - 'fromdb': load from a replica DB
1030 * - 'fromdbmaster': load from the master database
1033 public function getTitleOrPageId( $params, $load = false ) {
1034 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1037 if ( isset( $params['title'] ) ) {
1038 $titleObj = Title
::newFromText( $params['title'] );
1039 if ( !$titleObj ||
$titleObj->isExternal() ) {
1040 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1042 if ( !$titleObj->canExist() ) {
1043 $this->dieWithError( 'apierror-pagecannotexist' );
1045 $pageObj = WikiPage
::factory( $titleObj );
1046 if ( $load !== false ) {
1047 $pageObj->loadPageData( $load );
1049 } elseif ( isset( $params['pageid'] ) ) {
1050 if ( $load === false ) {
1053 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1055 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1063 * Get a Title object from a title or pageid param, if possible.
1064 * Can die, if no param is set or if the title or page id is not valid.
1067 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1070 public function getTitleFromTitleOrPageId( $params ) {
1071 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1074 if ( isset( $params['title'] ) ) {
1075 $titleObj = Title
::newFromText( $params['title'] );
1076 if ( !$titleObj ||
$titleObj->isExternal() ) {
1077 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1080 } elseif ( isset( $params['pageid'] ) ) {
1081 $titleObj = Title
::newFromID( $params['pageid'] );
1083 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1091 * Return true if we're to watch the page, false if not, null if no change.
1092 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1093 * @param Title $titleObj The page under consideration
1094 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1095 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1098 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1099 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1101 switch ( $watchlist ) {
1109 # If the user is already watching, don't bother checking
1110 if ( $userWatching ) {
1113 # If no user option was passed, use watchdefault and watchcreations
1114 if ( is_null( $userOption ) ) {
1115 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1116 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1119 # Watch the article based on the user preference
1120 return $this->getUser()->getBoolOption( $userOption );
1123 return $userWatching;
1126 return $userWatching;
1131 * Using the settings determine the value for the given parameter
1133 * @param string $paramName Parameter name
1134 * @param array|mixed $paramSettings Default value or an array of settings
1135 * using PARAM_* constants.
1136 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1137 * @return mixed Parameter value
1139 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1140 // Some classes may decide to change parameter names
1141 $encParamName = $this->encodeParamName( $paramName );
1144 if ( !is_array( $paramSettings ) ) {
1146 self
::PARAM_DFLT
=> $paramSettings,
1150 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1151 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1152 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1153 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1154 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1155 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1156 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1157 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1158 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1159 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1161 // When type is not given, and no choices, the type is the same as $default
1162 if ( !isset( $type ) ) {
1163 if ( isset( $default ) ) {
1164 $type = gettype( $default );
1166 $type = 'NULL'; // allow everything
1170 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1171 $this->getMain()->markParamsSensitive( $encParamName );
1174 if ( $type == 'boolean' ) {
1175 if ( isset( $default ) && $default !== false ) {
1176 // Having a default value of anything other than 'false' is not allowed
1179 "Boolean param $encParamName's default is set to '$default'. " .
1180 'Boolean parameters must default to false.'
1184 $value = $this->getMain()->getCheck( $encParamName );
1186 } elseif ( $type == 'upload' ) {
1187 if ( isset( $default ) ) {
1188 // Having a default value is not allowed
1191 "File upload param $encParamName's default is set to " .
1192 "'$default'. File upload parameters may not have a default." );
1195 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1197 $value = $this->getMain()->getUpload( $encParamName );
1198 $provided = $value->exists();
1199 if ( !$value->exists() ) {
1200 // This will get the value without trying to normalize it
1201 // (because trying to normalize a large binary file
1202 // accidentally uploaded as a field fails spectacularly)
1203 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1204 if ( $value !== null ) {
1205 $this->dieWithError(
1206 [ 'apierror-badupload', $encParamName ],
1207 "badupload_{$encParamName}"
1212 $value = $this->getMain()->getVal( $encParamName, $default );
1213 $provided = $this->getMain()->getCheck( $encParamName );
1215 if ( isset( $value ) && $type == 'namespace' ) {
1216 $type = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1217 getValidNamespaces();
1218 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1219 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1221 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1223 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1224 // specify all namespaces irrespective of PARAM_ALL.
1227 if ( isset( $value ) && $type == 'submodule' ) {
1228 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1229 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1231 $type = $this->getModuleManager()->getNames( $paramName );
1235 $request = $this->getMain()->getRequest();
1236 $rawValue = $request->getRawVal( $encParamName );
1237 if ( $rawValue === null ) {
1238 $rawValue = $default;
1241 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1242 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1244 // This loses the potential checkTitleEncoding() transformation done by
1245 // WebRequest for $_GET. Let's call that a feature.
1246 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1248 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1252 // Check for NFC normalization, and warn
1253 if ( $rawValue !== $value ) {
1254 $this->handleParamNormalization( $paramName, $value, $rawValue );
1258 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1259 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1262 "For param $encParamName, PARAM_ALL collides with a possible value" );
1264 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1265 $value = $this->parseMultiValue(
1269 is_array( $type ) ?
$type : null,
1270 $allowAll ?
$allSpecifier : null,
1276 if ( isset( $value ) ) {
1277 // More validation only when choices were not given
1278 // choices were validated in parseMultiValue()
1279 if ( !is_array( $type ) ) {
1281 case 'NULL': // nothing to do
1286 if ( $required && $value === '' ) {
1287 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1290 case 'integer': // Force everything using intval() and optionally validate limits
1291 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1292 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1293 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1295 if ( is_array( $value ) ) {
1296 $value = array_map( 'intval', $value );
1297 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1298 foreach ( $value as &$v ) {
1299 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1303 $value = (int)$value;
1304 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1305 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1310 if ( !$parseLimit ) {
1311 // Don't do any validation whatsoever
1314 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1315 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1319 "MAX1 or MAX2 are not defined for the limit $encParamName"
1323 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1325 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1326 if ( $value == 'max' ) {
1327 $value = $this->getMain()->canApiHighLimits()
1328 ?
$paramSettings[self
::PARAM_MAX2
]
1329 : $paramSettings[self
::PARAM_MAX
];
1330 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1332 $value = (int)$value;
1333 $this->validateLimit(
1337 $paramSettings[self
::PARAM_MAX
],
1338 $paramSettings[self
::PARAM_MAX2
]
1344 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1348 if ( is_array( $value ) ) {
1349 foreach ( $value as $key => $val ) {
1350 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1353 $value = $this->validateTimestamp( $value, $encParamName );
1357 if ( is_array( $value ) ) {
1358 foreach ( $value as $key => $val ) {
1359 $value[$key] = $this->validateUser( $val, $encParamName );
1362 $value = $this->validateUser( $value, $encParamName );
1365 case 'upload': // nothing to do
1368 // If change tagging was requested, check that the tags are valid.
1369 if ( !is_array( $value ) && !$multi ) {
1370 $value = [ $value ];
1372 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1373 if ( !$tagsStatus->isGood() ) {
1374 $this->dieStatus( $tagsStatus );
1378 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1382 // Throw out duplicates if requested
1383 if ( !$dupes && is_array( $value ) ) {
1384 $value = array_unique( $value );
1387 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1388 foreach ( (array)$value as $val ) {
1389 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1390 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1392 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1393 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1395 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1396 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1398 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1399 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1404 // Set a warning if a deprecated parameter has been passed
1405 if ( $deprecated && $provided ) {
1406 $feature = $encParamName;
1408 while ( !$m->isMain() ) {
1409 $p = $m->getParent();
1410 $name = $m->getModuleName();
1411 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1412 $feature = "{$param}={$name}&{$feature}";
1415 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1418 // Set a warning if a deprecated parameter value has been passed
1419 $usedDeprecatedValues = $deprecatedValues && $provided
1420 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1422 if ( $usedDeprecatedValues ) {
1423 $feature = "$encParamName=";
1425 while ( !$m->isMain() ) {
1426 $p = $m->getParent();
1427 $name = $m->getModuleName();
1428 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1429 $feature = "{$param}={$name}&{$feature}";
1432 foreach ( $usedDeprecatedValues as $v ) {
1433 $msg = $deprecatedValues[$v];
1434 if ( $msg === true ) {
1435 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1437 $this->addDeprecation( $msg, "$feature$v" );
1440 } elseif ( $required ) {
1441 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1448 * Handle when a parameter was Unicode-normalized
1450 * @param string $paramName Unprefixed parameter name
1451 * @param string $value Input that will be used.
1452 * @param string $rawValue Input before normalization.
1454 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1455 $encParamName = $this->encodeParamName( $paramName );
1456 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1460 * Split a multi-valued parameter string, like explode()
1462 * @param string $value
1466 protected function explodeMultiValue( $value, $limit ) {
1467 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1469 $value = substr( $value, 1 );
1474 return explode( $sep, $value, $limit );
1478 * Return an array of values that were given in a 'a|b|c' notation,
1479 * after it optionally validates them against the list allowed values.
1481 * @param string $valueName The name of the parameter (for error
1483 * @param mixed $value The value being parsed
1484 * @param bool $allowMultiple Can $value contain more than one value
1486 * @param string[]|null $allowedValues An array of values to check against. If
1487 * null, all values are accepted.
1488 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1489 * if this behavior should not be allowed
1490 * @param int|null $limit1 Maximum number of values, for normal users.
1491 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1492 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1494 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1495 $allSpecifier = null, $limit1 = null, $limit2 = null
1497 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1500 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1501 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1503 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1504 // because it unstubs $wgUser
1505 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1506 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1510 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1511 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1513 return $allowedValues;
1516 if ( count( $valuesList ) > $sizeLimit ) {
1517 $this->dieWithError(
1518 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1519 "too-many-$valueName"
1523 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1524 // T35482 - Allow entries with | in them for non-multiple values
1525 if ( in_array( $value, $allowedValues, true ) ) {
1529 $values = array_map( function ( $v ) {
1530 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1531 }, $allowedValues );
1532 $this->dieWithError( [
1533 'apierror-multival-only-one-of',
1535 Message
::listParam( $values ),
1537 ], "multival_$valueName" );
1540 if ( is_array( $allowedValues ) ) {
1541 // Check for unknown values
1542 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1543 if ( count( $unknown ) ) {
1544 if ( $allowMultiple ) {
1545 $this->addWarning( [
1546 'apiwarn-unrecognizedvalues',
1548 Message
::listParam( $unknown, 'comma' ),
1552 $this->dieWithError(
1553 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1554 "unknown_$valueName"
1558 // Now throw them out
1559 $valuesList = array_intersect( $valuesList, $allowedValues );
1562 return $allowMultiple ?
$valuesList : $valuesList[0];
1566 * Validate the value against the minimum and user/bot maximum limits.
1567 * Prints usage info on failure.
1568 * @param string $paramName Parameter name
1569 * @param int &$value Parameter value
1570 * @param int|null $min Minimum value
1571 * @param int|null $max Maximum value for users
1572 * @param int|null $botMax Maximum value for sysops/bots
1573 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1575 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1576 $enforceLimits = false
1578 if ( !is_null( $min ) && $value < $min ) {
1579 $msg = ApiMessage
::create(
1580 [ 'apierror-integeroutofrange-belowminimum',
1581 $this->encodeParamName( $paramName ), $min, $value ],
1582 'integeroutofrange',
1583 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1585 $this->warnOrDie( $msg, $enforceLimits );
1589 // Minimum is always validated, whereas maximum is checked only if not
1590 // running in internal call mode
1591 if ( $this->getMain()->isInternalMode() ) {
1595 // Optimization: do not check user's bot status unless really needed -- skips db query
1596 // assumes $botMax >= $max
1597 if ( !is_null( $max ) && $value > $max ) {
1598 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1599 if ( $value > $botMax ) {
1600 $msg = ApiMessage
::create(
1601 [ 'apierror-integeroutofrange-abovebotmax',
1602 $this->encodeParamName( $paramName ), $botMax, $value ],
1603 'integeroutofrange',
1604 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1606 $this->warnOrDie( $msg, $enforceLimits );
1610 $msg = ApiMessage
::create(
1611 [ 'apierror-integeroutofrange-abovemax',
1612 $this->encodeParamName( $paramName ), $max, $value ],
1613 'integeroutofrange',
1614 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1616 $this->warnOrDie( $msg, $enforceLimits );
1623 * Validate and normalize parameters of type 'timestamp'
1624 * @param string $value Parameter value
1625 * @param string $encParamName Parameter name
1626 * @return string Validated and normalized parameter
1628 protected function validateTimestamp( $value, $encParamName ) {
1629 // Confusing synonyms for the current time accepted by wfTimestamp()
1630 // (wfTimestamp() also accepts various non-strings and the string of 14
1631 // ASCII NUL bytes, but those can't get here)
1633 $this->addDeprecation(
1634 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1635 'unclear-"now"-timestamp'
1637 return wfTimestamp( TS_MW
);
1640 // Explicit synonym for the current time
1641 if ( $value === 'now' ) {
1642 return wfTimestamp( TS_MW
);
1645 $timestamp = wfTimestamp( TS_MW
, $value );
1646 if ( $timestamp === false ) {
1647 $this->dieWithError(
1648 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1649 "badtimestamp_{$encParamName}"
1657 * Validate the supplied token.
1660 * @param string $token Supplied token
1661 * @param array $params All supplied parameters for the module
1663 * @throws MWException
1665 final public function validateToken( $token, array $params ) {
1666 $tokenType = $this->needsToken();
1667 $salts = ApiQueryTokens
::getTokenTypeSalts();
1668 if ( !isset( $salts[$tokenType] ) ) {
1669 throw new MWException(
1670 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1671 'without registering it'
1675 $tokenObj = ApiQueryTokens
::getToken(
1676 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1678 if ( $tokenObj->match( $token ) ) {
1682 $webUiSalt = $this->getWebUITokenSalt( $params );
1683 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1695 * Validate and normalize parameters of type 'user'
1696 * @param string $value Parameter value
1697 * @param string $encParamName Parameter name
1698 * @return string Validated and normalized parameter
1700 private function validateUser( $value, $encParamName ) {
1701 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1705 $name = User
::getCanonicalName( $value, 'valid' );
1706 if ( $name !== false ) {
1711 // We allow ranges as well, for blocks.
1712 IP
::isIPAddress( $value ) ||
1713 // See comment for User::isIP. We don't just call that function
1714 // here because it also returns true for things like
1715 // 300.300.300.300 that are neither valid usernames nor valid IP
1718 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1722 return IP
::sanitizeIP( $value );
1725 $this->dieWithError(
1726 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1727 "baduser_{$encParamName}"
1733 /************************************************************************//**
1734 * @name Utility methods
1739 * Set a watch (or unwatch) based the based on a watchlist parameter.
1740 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1741 * @param Title $titleObj The article's title to change
1742 * @param string|null $userOption The user option to consider when $watch=preferences
1744 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1745 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1746 if ( $value === null ) {
1750 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1754 * Gets the user for whom to get the watchlist
1756 * @param array $params
1759 public function getWatchlistUser( $params ) {
1760 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1761 $user = User
::newFromName( $params['owner'], false );
1762 if ( !( $user && $user->getId() ) ) {
1763 $this->dieWithError(
1764 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1767 $token = $user->getOption( 'watchlisttoken' );
1768 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1769 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1772 if ( !$this->getUser()->isLoggedIn() ) {
1773 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1775 $this->checkUserRightsAny( 'viewmywatchlist' );
1776 $user = $this->getUser();
1783 * Create a Message from a string or array
1785 * A string is used as a message key. An array has the message key as the
1786 * first value and message parameters as subsequent values.
1789 * @param string|array|Message $msg
1790 * @param IContextSource $context
1791 * @param array|null $params
1792 * @return Message|null
1794 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1795 if ( is_string( $msg ) ) {
1796 $msg = wfMessage( $msg );
1797 } elseif ( is_array( $msg ) ) {
1798 $msg = wfMessage( ...$msg );
1800 if ( !$msg instanceof Message
) {
1804 $msg->setContext( $context );
1806 $msg->params( $params );
1813 * Turn an array of message keys or key+param arrays into a Status
1815 * @param array $errors
1816 * @param User|null $user
1819 public function errorArrayToStatus( array $errors, User
$user = null ) {
1820 if ( $user === null ) {
1821 $user = $this->getUser();
1824 $status = Status
::newGood();
1825 foreach ( $errors as $error ) {
1826 if ( !is_array( $error ) ) {
1827 $error = [ $error ];
1829 if ( is_string( $error[0] ) && isset( self
::$blockMsgMap[$error[0]] ) && $user->getBlock() ) {
1830 list( $msg, $code ) = self
::$blockMsgMap[$error[0]];
1831 $status->fatal( ApiMessage
::create( $msg, $code,
1832 [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
1835 $status->fatal( ...$error );
1842 * Add block info to block messages in a Status
1844 * @param StatusValue $status
1845 * @param User|null $user
1847 public function addBlockInfoToStatus( StatusValue
$status, User
$user = null ) {
1848 if ( $user === null ) {
1849 $user = $this->getUser();
1852 foreach ( self
::$blockMsgMap as $msg => list( $apiMsg, $code ) ) {
1853 if ( $status->hasMessage( $msg ) && $user->getBlock() ) {
1854 $status->replaceMessage( $msg, ApiMessage
::create( $apiMsg, $code,
1855 [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
1862 * Call wfTransactionalTimeLimit() if this request was POSTed
1865 protected function useTransactionalTimeLimit() {
1866 if ( $this->getRequest()->wasPosted() ) {
1867 wfTransactionalTimeLimit();
1872 * Filter out-of-range values from a list of positive integer IDs
1874 * @param array $fields Array of pairs of table and field to check
1875 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1876 * expected to be stringified ints.
1877 * @return (string|int)[] Filtered IDs.
1879 protected function filterIDs( $fields, array $ids ) {
1882 foreach ( $fields as list( $table, $field ) ) {
1883 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1884 $row = self
::$filterIDsCache[$table][$field];
1886 $row = $this->getDB()->selectRow(
1889 'min_id' => "MIN($field)",
1890 'max_id' => "MAX($field)",
1895 self
::$filterIDsCache[$table][$field] = $row;
1897 $min = min( $min, $row->min_id
);
1898 $max = max( $max, $row->max_id
);
1900 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1901 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1902 && $id >= $min && $id <= $max;
1908 /************************************************************************//**
1909 * @name Warning and error reporting
1914 * Add a warning for this module.
1916 * Users should monitor this section to notice any changes in API. Multiple
1917 * calls to this function will result in multiple warning messages.
1919 * If $msg is not an ApiMessage, the message code will be derived from the
1920 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1923 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1924 * @param string|null $code See ApiErrorFormatter::addWarning()
1925 * @param array|null $data See ApiErrorFormatter::addWarning()
1927 public function addWarning( $msg, $code = null, $data = null ) {
1928 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1932 * Add a deprecation warning for this module.
1934 * A combination of $this->addWarning() and $this->logFeatureUsage()
1937 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1938 * @param string|null $feature See ApiBase::logFeatureUsage()
1939 * @param array|null $data See ApiErrorFormatter::addWarning()
1941 public function addDeprecation( $msg, $feature, $data = [] ) {
1942 $data = (array)$data;
1943 if ( $feature !== null ) {
1944 $data['feature'] = $feature;
1945 $this->logFeatureUsage( $feature );
1947 $this->addWarning( $msg, 'deprecation', $data );
1949 // No real need to deduplicate here, ApiErrorFormatter does that for
1950 // us (assuming the hook is deterministic).
1951 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1952 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1953 if ( count( $msgs ) > 1 ) {
1954 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1955 $msg = ( new RawMessage( $key ) )->params( $msgs );
1957 $msg = reset( $msgs );
1959 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1963 * Add an error for this module without aborting
1965 * If $msg is not an ApiMessage, the message code will be derived from the
1966 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1968 * @note If you want to abort processing, use self::dieWithError() instead.
1970 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1971 * @param string|null $code See ApiErrorFormatter::addError()
1972 * @param array|null $data See ApiErrorFormatter::addError()
1974 public function addError( $msg, $code = null, $data = null ) {
1975 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1979 * Add warnings and/or errors from a Status
1981 * @note If you want to abort processing, use self::dieStatus() instead.
1983 * @param StatusValue $status
1984 * @param string[] $types 'warning' and/or 'error'
1985 * @param string[] $filter Message keys to filter out (since 1.33)
1987 public function addMessagesFromStatus(
1988 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1990 $this->getErrorFormatter()->addMessagesFromStatus(
1991 $this->getModulePath(), $status, $types, $filter
1996 * Abort execution with an error
1998 * If $msg is not an ApiMessage, the message code will be derived from the
1999 * message key by stripping any "apiwarn-" or "apierror-" prefix.
2002 * @param string|array|Message $msg See ApiErrorFormatter::addError()
2003 * @param string|null $code See ApiErrorFormatter::addError()
2004 * @param array|null $data See ApiErrorFormatter::addError()
2005 * @param int|null $httpCode HTTP error code to use
2006 * @throws ApiUsageException always
2008 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
2009 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
2013 * Abort execution with an error derived from an exception
2016 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
2017 * @param array $options See ApiErrorFormatter::getMessageFromException()
2018 * @throws ApiUsageException always
2020 public function dieWithException( $exception, array $options = [] ) {
2021 $this->dieWithError(
2022 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
2027 * Adds a warning to the output, else dies
2029 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2030 * @param bool $enforceLimits Whether this is an enforce (die)
2032 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2033 if ( $enforceLimits ) {
2034 $this->dieWithError( $msg );
2036 $this->addWarning( $msg );
2041 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2042 * error handler and die with an error message including block info.
2045 * @param AbstractBlock $block The block used to generate the ApiUsageException
2046 * @throws ApiUsageException always
2048 public function dieBlocked( AbstractBlock
$block ) {
2049 // Die using the appropriate message depending on block type
2050 if ( $block->getType() == DatabaseBlock
::TYPE_AUTO
) {
2051 $this->dieWithError(
2052 'apierror-autoblocked',
2054 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2056 } elseif ( !$block->isSitewide() ) {
2057 $this->dieWithError(
2058 'apierror-blocked-partial',
2060 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2063 $this->dieWithError(
2066 [ 'blockinfo' => $this->getBlockDetails( $block ) ]
2072 * Throw an ApiUsageException based on the Status object.
2075 * @since 1.29 Accepts a StatusValue
2076 * @param StatusValue $status
2077 * @throws ApiUsageException always
2079 public function dieStatus( StatusValue
$status ) {
2080 if ( $status->isGood() ) {
2081 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2084 // ApiUsageException needs a fatal status, but this method has
2085 // historically accepted any non-good status. Convert it if necessary.
2086 $status->setOK( false );
2087 if ( !$status->getErrorsByType( 'error' ) ) {
2088 $newStatus = Status
::newGood();
2089 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2090 $newStatus->fatal( $err['message'], ...$err['params'] );
2092 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2093 $newStatus->fatal( 'unknownerror-nocode' );
2095 $status = $newStatus;
2098 $this->addBlockInfoToStatus( $status );
2099 throw new ApiUsageException( $this, $status );
2103 * Helper function for readonly errors
2105 * @throws ApiUsageException always
2107 public function dieReadOnly() {
2108 $this->dieWithError(
2109 'apierror-readonly',
2111 [ 'readonlyreason' => wfReadOnlyReason() ]
2116 * Helper function for permission-denied errors
2118 * @param string|string[] $rights
2119 * @param User|null $user
2120 * @throws ApiUsageException if the user doesn't have any of the rights.
2121 * The error message is based on $rights[0].
2123 public function checkUserRightsAny( $rights, $user = null ) {
2125 $user = $this->getUser();
2127 $rights = (array)$rights;
2128 if ( !$user->isAllowedAny( ...$rights ) ) {
2129 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2134 * Helper function for permission-denied errors
2136 * @param LinkTarget $linkTarget
2137 * @param string|string[] $actions
2138 * @param array $options Additional options
2139 * - user: (User) User to use rather than $this->getUser()
2140 * - autoblock: (bool, default false) Whether to spread autoblocks
2141 * For compatibility, passing a User object is treated as the value for the 'user' option.
2142 * @throws ApiUsageException if the user doesn't have all of the rights.
2145 * @since 1.33 Changed the third parameter from $user to $options.
2147 public function checkTitleUserPermissions( LinkTarget
$linkTarget, $actions, $options = [] ) {
2148 if ( !is_array( $options ) ) {
2149 wfDeprecated( '$user as the third parameter to ' . __METHOD__
, '1.33' );
2150 $options = [ 'user' => $options ];
2152 $user = $options['user'] ??
$this->getUser();
2155 foreach ( (array)$actions as $action ) {
2156 $errors = array_merge(
2158 $this->getPermissionManager()->getPermissionErrors( $action, $user, $linkTarget )
2163 if ( !empty( $options['autoblock'] ) ) {
2164 $user->spreadAnyEditBlock();
2167 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2172 * Will only set a warning instead of failing if the global $wgDebugAPI
2173 * is set to true. Otherwise behaves exactly as self::dieWithError().
2176 * @param string|array|Message $msg
2177 * @param string|null $code
2178 * @param array|null $data
2179 * @param int|null $httpCode
2180 * @throws ApiUsageException
2182 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2183 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2184 $this->dieWithError( $msg, $code, $data, $httpCode );
2186 $this->addWarning( $msg, $code, $data );
2191 * Die with the 'badcontinue' error.
2193 * This call is common enough to make it into the base method.
2195 * @param bool $condition Will only die if this value is true
2196 * @throws ApiUsageException
2199 protected function dieContinueUsageIf( $condition ) {
2201 $this->dieWithError( 'apierror-badcontinue' );
2206 * Internal code errors should be reported with this method
2207 * @param string $method Method or function name
2208 * @param string $message Error message
2209 * @throws MWException always
2211 protected static function dieDebug( $method, $message ) {
2212 throw new MWException( "Internal error in $method: $message" );
2216 * Write logging information for API features to a debug log, for usage
2218 * @note Consider using $this->addDeprecation() instead to both warn and log.
2219 * @param string $feature Feature being used.
2221 public function logFeatureUsage( $feature ) {
2222 static $loggedFeatures = [];
2224 // Only log each feature once per request. We can get multiple calls from calls to
2225 // extractRequestParams() with different values for 'parseLimit', for example.
2226 if ( isset( $loggedFeatures[$feature] ) ) {
2229 $loggedFeatures[$feature] = true;
2231 $request = $this->getRequest();
2233 'feature' => $feature,
2234 // Spaces to underscores in 'username' for historical reasons.
2235 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
2236 'ip' => $request->getIP(),
2237 'referer' => (string)$request->getHeader( 'Referer' ),
2238 'agent' => $this->getMain()->getUserAgent(),
2241 // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
2242 $s = '"' . addslashes( $ctx['feature'] ) . '"' .
2243 ' "' . wfUrlencode( $ctx['username'] ) . '"' .
2244 ' "' . $ctx['ip'] . '"' .
2245 ' "' . addslashes( $ctx['referer'] ) . '"' .
2246 ' "' . addslashes( $ctx['agent'] ) . '"';
2248 wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
2253 /************************************************************************//**
2254 * @name Help message generation
2259 * Return the summary message.
2261 * This is a one-line description of the module, suitable for display in a
2265 * @return string|array|Message
2267 protected function getSummaryMessage() {
2268 return "apihelp-{$this->getModulePath()}-summary";
2272 * Return the extended help text message.
2274 * This is additional text to display at the top of the help section, below
2278 * @return string|array|Message
2280 protected function getExtendedDescription() {
2282 "apihelp-{$this->getModulePath()}-extended-description",
2283 'api-help-no-extended-description',
2288 * Get final module summary
2293 public function getFinalSummary() {
2294 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2295 $this->getModulePrefix(),
2296 $this->getModuleName(),
2297 $this->getModulePath(),
2303 * Get final module description, after hooks have had a chance to tweak it as
2306 * @since 1.25, returns Message[] rather than string[]
2309 public function getFinalDescription() {
2310 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2311 $this->getModulePrefix(),
2312 $this->getModuleName(),
2313 $this->getModulePath(),
2315 $extendedDescription = self
::makeMessage(
2316 $this->getExtendedDescription(), $this->getContext(), [
2317 $this->getModulePrefix(),
2318 $this->getModuleName(),
2319 $this->getModulePath(),
2323 $msgs = [ $summary, $extendedDescription ];
2325 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2331 * Get final list of parameters, after hooks have had a chance to
2332 * tweak it as needed.
2334 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2335 * @return array|bool False on no parameters
2336 * @since 1.21 $flags param added
2338 public function getFinalParams( $flags = 0 ) {
2339 $params = $this->getAllowedParams( $flags );
2344 if ( $this->needsToken() ) {
2345 $params['token'] = [
2346 self
::PARAM_TYPE
=> 'string',
2347 self
::PARAM_REQUIRED
=> true,
2348 self
::PARAM_SENSITIVE
=> true,
2349 self
::PARAM_HELP_MSG
=> [
2350 'api-help-param-token',
2351 $this->needsToken(),
2353 ] +
( $params['token'] ??
[] );
2356 // Avoid PHP 7.1 warning of passing $this by reference
2358 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2364 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2367 * @since 1.25, returns array of Message[] rather than array of string[]
2368 * @return array Keys are parameter names, values are arrays of Message objects
2370 public function getFinalParamDescription() {
2371 $prefix = $this->getModulePrefix();
2372 $name = $this->getModuleName();
2373 $path = $this->getModulePath();
2375 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2377 foreach ( $params as $param => $settings ) {
2378 if ( !is_array( $settings ) ) {
2382 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2383 $msg = $settings[self
::PARAM_HELP_MSG
];
2385 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2387 $msg = self
::makeMessage( $msg, $this->getContext(),
2388 [ $prefix, $param, $name, $path ] );
2390 self
::dieDebug( __METHOD__
,
2391 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2393 $msgs[$param] = [ $msg ];
2395 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2396 $settings[self
::PARAM_TYPE
] === 'submodule'
2398 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2399 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2401 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2403 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2404 $map[$submoduleName] = $prefix . $submoduleName;
2409 $deprecatedSubmodules = [];
2410 foreach ( $map as $v => $m ) {
2411 $arr = &$submodules;
2412 $isDeprecated = false;
2415 $submod = $this->getModuleFromPath( $m );
2417 $summary = $submod->getFinalSummary();
2418 $isDeprecated = $submod->isDeprecated();
2419 if ( $isDeprecated ) {
2420 $arr = &$deprecatedSubmodules;
2423 } catch ( ApiUsageException
$ex ) {
2427 $key = $summary->getKey();
2428 $params = $summary->getParams();
2430 $key = 'api-help-undocumented-module';
2433 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2434 $arr[] = $m->setContext( $this->getContext() );
2436 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2437 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2438 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2439 self
::dieDebug( __METHOD__
,
2440 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2442 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2443 self
::dieDebug( __METHOD__
,
2444 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2445 'ApiBase::PARAM_TYPE is an array' );
2448 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2449 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2451 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2452 if ( isset( $valueMsgs[$value] ) ) {
2453 $msg = $valueMsgs[$value];
2455 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2457 $m = self
::makeMessage( $msg, $this->getContext(),
2458 [ $prefix, $param, $name, $path, $value ] );
2460 $m = new ApiHelpParamValueMessage(
2462 [ $m->getKey(), 'api-help-param-no-description' ],
2464 isset( $deprecatedValues[$value] )
2466 $msgs[$param][] = $m->setContext( $this->getContext() );
2468 self
::dieDebug( __METHOD__
,
2469 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2474 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2475 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2476 self
::dieDebug( __METHOD__
,
2477 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2479 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2480 $m = self
::makeMessage( $m, $this->getContext(),
2481 [ $prefix, $param, $name, $path ] );
2483 $msgs[$param][] = $m;
2485 self
::dieDebug( __METHOD__
,
2486 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2492 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2498 * Generates the list of flags for the help screen and for action=paraminfo
2500 * Corresponding messages: api-help-flag-deprecated,
2501 * api-help-flag-internal, api-help-flag-readrights,
2502 * api-help-flag-writerights, api-help-flag-mustbeposted
2506 protected function getHelpFlags() {
2509 if ( $this->isDeprecated() ) {
2510 $flags[] = 'deprecated';
2512 if ( $this->isInternal() ) {
2513 $flags[] = 'internal';
2515 if ( $this->isReadMode() ) {
2516 $flags[] = 'readrights';
2518 if ( $this->isWriteMode() ) {
2519 $flags[] = 'writerights';
2521 if ( $this->mustBePosted() ) {
2522 $flags[] = 'mustbeposted';
2529 * Returns information about the source of this module, if known
2531 * Returned array is an array with the following keys:
2532 * - path: Install path
2533 * - name: Extension name, or "MediaWiki" for core
2534 * - namemsg: (optional) i18n message key for a display name
2535 * - license-name: (optional) Name of license
2537 * @return array|null
2539 protected function getModuleSourceInfo() {
2542 if ( $this->mModuleSource
!== false ) {
2543 return $this->mModuleSource
;
2546 // First, try to find where the module comes from...
2547 $rClass = new ReflectionClass( $this );
2548 $path = $rClass->getFileName();
2551 $this->mModuleSource
= null;
2554 $path = realpath( $path ) ?
: $path;
2556 // Build map of extension directories to extension info
2557 if ( self
::$extensionInfo === null ) {
2558 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2559 self
::$extensionInfo = [
2560 realpath( __DIR__
) ?
: __DIR__
=> [
2562 'name' => 'MediaWiki',
2563 'license-name' => 'GPL-2.0-or-later',
2565 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2566 realpath( $extDir ) ?
: $extDir => null,
2572 'license-name' => null,
2574 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2575 foreach ( $group as $ext ) {
2576 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2577 // This shouldn't happen, but does anyway.
2581 $extpath = $ext['path'];
2582 if ( !is_dir( $extpath ) ) {
2583 $extpath = dirname( $extpath );
2585 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2586 array_intersect_key( $ext, $keep );
2589 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2590 $extpath = $ext['path'];
2591 if ( !is_dir( $extpath ) ) {
2592 $extpath = dirname( $extpath );
2594 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2595 array_intersect_key( $ext, $keep );
2599 // Now traverse parent directories until we find a match or run out of
2602 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2604 $this->mModuleSource
= self
::$extensionInfo[$path];
2605 return $this->mModuleSource
;
2609 $path = dirname( $path );
2610 } while ( $path !== $oldpath );
2612 // No idea what extension this might be.
2613 $this->mModuleSource
= null;
2618 * Called from ApiHelp before the pieces are joined together and returned.
2620 * This exists mainly for ApiMain to add the Permissions and Credits
2621 * sections. Other modules probably don't need it.
2623 * @param string[] &$help Array of help data
2624 * @param array $options Options passed to ApiHelp::getHelp
2625 * @param array &$tocData If a TOC is being generated, this array has keys
2626 * as anchors in the page and values as for Linker::generateTOC().
2628 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2633 /************************************************************************//**
2639 * Returns the description string for this module
2641 * Ignored if an i18n message exists for
2642 * "apihelp-{$this->getModulePath()}-description".
2644 * @deprecated since 1.25
2645 * @return Message|string|array|false
2647 protected function getDescription() {
2648 wfDeprecated( __METHOD__
, '1.25' );
2653 * Returns an array of parameter descriptions.
2655 * For each parameter, ignored if an i18n message exists for the parameter.
2656 * By default that message is
2657 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2658 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2659 * self::getFinalParams().
2661 * @deprecated since 1.25
2662 * @return array|bool False on no parameter descriptions
2664 protected function getParamDescription() {
2665 wfDeprecated( __METHOD__
, '1.25' );
2670 * Returns usage examples for this module.
2672 * Return value as an array is either:
2673 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2675 * - sequential numeric keys with even-numbered keys being display-text
2676 * and odd-numbered keys being partial urls
2677 * - partial URLs as keys with display-text (string or array-to-be-joined)
2679 * Return value as a string is the same as an array with a numeric key and
2680 * that value, and boolean false means "no examples".
2682 * @deprecated since 1.25, use getExamplesMessages() instead
2683 * @return bool|string|array
2685 protected function getExamples() {
2686 wfDeprecated( __METHOD__
, '1.25' );
2691 * Return the description message.
2693 * This is additional text to display on the help page after the summary.
2695 * @deprecated since 1.30
2696 * @return string|array|Message
2698 protected function getDescriptionMessage() {
2699 wfDeprecated( __METHOD__
, '1.30' );
2701 "apihelp-{$this->getModulePath()}-description",
2702 "apihelp-{$this->getModulePath()}-summary",
2710 * For really cool vim folding this needs to be at the end:
2711 * vim: foldmarker=@{,@} foldmethod=marker