3 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\IDatabase
;
24 use MediaWiki\MediaWikiServices
;
27 * This abstract class implements many basic API functions, and is the base of
29 * The class functions are divided into several areas of functionality:
31 * Module parameters: Derived classes can define getAllowedParams() to specify
32 * which parameters to expect, how to parse and validate them.
34 * Self-documentation: code to allow the API to document its own state
38 abstract class ApiBase
extends ContextSource
{
41 * @name Constants for ::getAllowedParams() arrays
42 * These constants are keys in the arrays returned by ::getAllowedParams()
43 * and accepted by ::getParameterFromSettings() that define how the
44 * parameters coming in from the request are to be interpreted.
48 /** (null|boolean|integer|string) Default value of the parameter. */
51 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
52 const PARAM_ISMULTI
= 1;
55 * (string|string[]) Either an array of allowed value strings, or a string
56 * type as described below. If not specified, will be determined from the
59 * Supported string types are:
60 * - boolean: A boolean parameter, returned as false if the parameter is
61 * omitted and true if present (even with a falsey value, i.e. it works
62 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
63 * Cannot be used with PARAM_ISMULTI.
64 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
65 * PARAM_RANGE_ENFORCE.
66 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
67 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
68 * specified. Cannot be used with PARAM_ISMULTI.
69 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
70 * support easily specifying all namespaces.
72 * - password: Any non-empty string. Input value is private or sensitive.
73 * <input type="password"> would be an appropriate HTML form field.
74 * - string: Any non-empty string, not expected to be very long or contain newlines.
75 * <input type="text"> would be an appropriate HTML form field.
76 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
77 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
78 * used with PARAM_ISMULTI.
79 * - text: Any non-empty string, expected to be very long or contain newlines.
80 * <textarea> would be an appropriate HTML form field.
81 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
82 * string 'now' representing the current timestamp. Will be returned in
84 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
85 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
86 * Cannot be used with PARAM_ISMULTI.
90 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
94 * (integer) Max value allowed for the parameter for users with the
95 * apihighlimits right, for PARAM_TYPE 'limit'.
99 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
102 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
103 const PARAM_ALLOW_DUPLICATES
= 6;
105 /** (boolean) Is the parameter deprecated (will show a warning)? */
106 const PARAM_DEPRECATED
= 7;
109 * (boolean) Is the parameter required?
112 const PARAM_REQUIRED
= 8;
115 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
118 const PARAM_RANGE_ENFORCE
= 9;
121 * (string|array|Message) Specify an alternative i18n documentation message
122 * for this parameter. Default is apihelp-{$path}-param-{$param}.
125 const PARAM_HELP_MSG
= 10;
128 * ((string|array|Message)[]) Specify additional i18n messages to append to
129 * the normal message for this parameter.
132 const PARAM_HELP_MSG_APPEND
= 11;
135 * (array) Specify additional information tags for the parameter. Value is
136 * an array of arrays, with the first member being the 'tag' for the info
137 * and the remaining members being the values. In the help, this is
138 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
139 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
142 const PARAM_HELP_MSG_INFO
= 12;
145 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
146 * those values to page titles which will be linked in the help.
149 const PARAM_VALUE_LINKS
= 13;
152 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
153 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
154 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
155 * Specify an empty array to use the default message key for all values.
158 const PARAM_HELP_MSG_PER_VALUE
= 14;
161 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
162 * submodule paths. Default is to use all modules in
163 * $this->getModuleManager() in the group matching the parameter name.
166 const PARAM_SUBMODULE_MAP
= 15;
169 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
170 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
173 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
176 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
177 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
178 * every possible value. If a string is set, it will be used in place of the asterisk.
181 const PARAM_ALL
= 17;
184 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
187 const PARAM_EXTRA_NAMESPACES
= 18;
190 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
191 * always sensitive regardless of the value of this field.
194 const PARAM_SENSITIVE
= 19;
197 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
198 * Keys are the deprecated parameter values, values define the warning
199 * message to emit: either boolean true (to use a default message) or a
200 * $msg for ApiBase::makeMessage().
203 const PARAM_DEPRECATED_VALUES
= 20;
206 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
209 const PARAM_ISMULTI_LIMIT1
= 21;
212 * (integer) Maximum number of values, for users with the apihighimits right.
213 * Must be used with PARAM_ISMULTI.
216 const PARAM_ISMULTI_LIMIT2
= 22;
219 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
222 const PARAM_MAX_BYTES
= 23;
225 * (integer) Maximum length of a string in characters (unicode codepoints).
228 const PARAM_MAX_CHARS
= 24;
231 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
232 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
233 * which the replacement values are taken.
235 * For example, a parameter "foo-{ns}-{title}" could be defined with
236 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
237 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
239 * All placeholders must be present in the parameter's name. Each target parameter must have
240 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
241 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
242 * A parameter cannot target itself.
246 const PARAM_TEMPLATE_VARS
= 25;
250 const ALL_DEFAULT_STRING
= '*';
252 /** Fast query, standard limit. */
253 const LIMIT_BIG1
= 500;
254 /** Fast query, apihighlimits limit. */
255 const LIMIT_BIG2
= 5000;
256 /** Slow query, standard limit. */
257 const LIMIT_SML1
= 50;
258 /** Slow query, apihighlimits limit. */
259 const LIMIT_SML2
= 500;
262 * getAllowedParams() flag: When set, the result could take longer to generate,
263 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
266 const GET_VALUES_FOR_HELP
= 1;
268 /** @var array Maps extension paths to info arrays */
269 private static $extensionInfo = null;
271 /** @var int[][][] Cache for self::filterIDs() */
272 private static $filterIDsCache = [];
275 private $mMainModule;
277 private $mModuleName, $mModulePrefix;
278 private $mReplicaDB = null;
279 private $mParamCache = [];
280 /** @var array|null|bool */
281 private $mModuleSource = false;
284 * @param ApiMain $mainModule
285 * @param string $moduleName Name of this module
286 * @param string $modulePrefix Prefix to use for parameter names
288 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
289 $this->mMainModule
= $mainModule;
290 $this->mModuleName
= $moduleName;
291 $this->mModulePrefix
= $modulePrefix;
293 if ( !$this->isMain() ) {
294 $this->setContext( $mainModule->getContext() );
298 /************************************************************************//**
299 * @name Methods to implement
304 * Evaluates the parameters, performs the requested query, and sets up
305 * the result. Concrete implementations of ApiBase must override this
306 * method to provide whatever functionality their module offers.
307 * Implementations must not produce any output on their own and are not
308 * expected to handle any errors.
310 * The execute() method will be invoked directly by ApiMain immediately
311 * before the result of the module is output. Aside from the
312 * constructor, implementations should assume that no other methods
313 * will be called externally on the module before the result is
316 * The result data should be stored in the ApiResult object available
317 * through getResult().
319 abstract public function execute();
322 * Get the module manager, or null if this module has no sub-modules
324 * @return ApiModuleManager
326 public function getModuleManager() {
331 * If the module may only be used with a certain format module,
332 * it should override this method to return an instance of that formatter.
333 * A value of null means the default format will be used.
334 * @note Do not use this just because you don't want to support non-json
335 * formats. This should be used only when there is a fundamental
336 * requirement for a specific format.
337 * @return mixed Instance of a derived class of ApiFormatBase, or null
339 public function getCustomPrinter() {
344 * Returns usage examples for this module.
346 * Return value has query strings as keys, with values being either strings
347 * (message key), arrays (message key + parameter), or Message objects.
349 * Do not call this base class implementation when overriding this method.
354 protected function getExamplesMessages() {
359 * Return links to more detailed help pages about the module.
360 * @since 1.25, returning boolean false is deprecated
361 * @return string|array
363 public function getHelpUrls() {
368 * Returns an array of allowed parameters (parameter name) => (default
369 * value) or (parameter name) => (array with PARAM_* constants as keys)
370 * Don't call this function directly: use getFinalParams() to allow
371 * hooks to modify parameters as needed.
373 * Some derived classes may choose to handle an integer $flags parameter
374 * in the overriding methods. Callers of this method can pass zero or
375 * more OR-ed flags like GET_VALUES_FOR_HELP.
379 protected function getAllowedParams( /* $flags = 0 */ ) {
380 // int $flags is not declared because it causes "Strict standards"
381 // warning. Most derived classes do not implement it.
386 * Indicates if this module needs maxlag to be checked
389 public function shouldCheckMaxlag() {
394 * Indicates whether this module requires read rights
397 public function isReadMode() {
402 * Indicates whether this module requires write mode
404 * This should return true for modules that may require synchronous database writes.
405 * Modules that do not need such writes should also not rely on master database access,
406 * since only read queries are needed and each master DB is a single point of failure.
407 * Additionally, requests that only need replica DBs can be efficiently routed to any
408 * datacenter via the Promise-Non-Write-API-Action header.
412 public function isWriteMode() {
417 * Indicates whether this module must be called with a POST request
420 public function mustBePosted() {
421 return $this->needsToken() !== false;
425 * Indicates whether this module is deprecated
429 public function isDeprecated() {
434 * Indicates whether this module is "internal"
435 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
439 public function isInternal() {
444 * Returns the token type this module requires in order to execute.
446 * Modules are strongly encouraged to use the core 'csrf' type unless they
447 * have specialized security needs. If the token type is not one of the
448 * core types, you must use the ApiQueryTokensRegisterTypes hook to
451 * Returning a non-falsey value here will force the addition of an
452 * appropriate 'token' parameter in self::getFinalParams(). Also,
453 * self::mustBePosted() must return true when tokens are used.
455 * In previous versions of MediaWiki, true was a valid return value.
456 * Returning true will generate errors indicating that the API module needs
459 * @return string|false
461 public function needsToken() {
466 * Fetch the salt used in the Web UI corresponding to this module.
468 * Only override this if the Web UI uses a token with a non-constant salt.
471 * @param array $params All supplied parameters for the module
472 * @return string|array|null
474 protected function getWebUITokenSalt( array $params ) {
479 * Returns data for HTTP conditional request mechanisms.
482 * @param string $condition Condition being queried:
483 * - last-modified: Return a timestamp representing the maximum of the
484 * last-modified dates for all resources involved in the request. See
485 * RFC 7232 § 2.2 for semantics.
486 * - etag: Return an entity-tag representing the state of all resources involved
487 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
488 * @return string|bool|null As described above, or null if no value is available.
490 public function getConditionalRequestData( $condition ) {
496 /************************************************************************//**
497 * @name Data access methods
502 * Get the name of the module being executed by this instance
505 public function getModuleName() {
506 return $this->mModuleName
;
510 * Get parameter prefix (usually two letters or an empty string).
513 public function getModulePrefix() {
514 return $this->mModulePrefix
;
518 * Get the main module
521 public function getMain() {
522 return $this->mMainModule
;
526 * Returns true if this module is the main module ($this === $this->mMainModule),
530 public function isMain() {
531 return $this === $this->mMainModule
;
535 * Get the parent of this module
537 * @return ApiBase|null
539 public function getParent() {
540 return $this->isMain() ?
null : $this->getMain();
544 * Returns true if the current request breaks the same-origin policy.
546 * For example, json with callbacks.
548 * https://en.wikipedia.org/wiki/Same-origin_policy
553 public function lacksSameOriginSecurity() {
554 // Main module has this method overridden
555 // Safety - avoid infinite loop:
556 if ( $this->isMain() ) {
557 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
560 return $this->getMain()->lacksSameOriginSecurity();
564 * Get the path to this module
569 public function getModulePath() {
570 if ( $this->isMain() ) {
572 } elseif ( $this->getParent()->isMain() ) {
573 return $this->getModuleName();
575 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
580 * Get a module from its module path
583 * @param string $path
584 * @return ApiBase|null
585 * @throws ApiUsageException
587 public function getModuleFromPath( $path ) {
588 $module = $this->getMain();
589 if ( $path === 'main' ) {
593 $parts = explode( '+', $path );
594 if ( count( $parts ) === 1 ) {
595 // In case the '+' was typed into URL, it resolves as a space
596 $parts = explode( ' ', $path );
599 $count = count( $parts );
600 for ( $i = 0; $i < $count; $i++
) {
602 $manager = $parent->getModuleManager();
603 if ( $manager === null ) {
604 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
605 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
607 $module = $manager->getModule( $parts[$i] );
609 if ( $module === null ) {
610 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
612 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
622 * Get the result object
625 public function getResult() {
626 // Main module has getResult() method overridden
627 // Safety - avoid infinite loop:
628 if ( $this->isMain() ) {
629 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
632 return $this->getMain()->getResult();
636 * Get the error formatter
637 * @return ApiErrorFormatter
639 public function getErrorFormatter() {
640 // Main module has getErrorFormatter() 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()->getErrorFormatter();
650 * Gets a default replica DB connection object
653 protected function getDB() {
654 if ( !isset( $this->mReplicaDB
) ) {
655 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
658 return $this->mReplicaDB
;
662 * Get the continuation manager
663 * @return ApiContinuationManager|null
665 public function getContinuationManager() {
666 // Main module has getContinuationManager() method overridden
667 // Safety - avoid infinite loop:
668 if ( $this->isMain() ) {
669 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
672 return $this->getMain()->getContinuationManager();
676 * Set the continuation manager
677 * @param ApiContinuationManager|null $manager
679 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
680 // Main module has setContinuationManager() method overridden
681 // Safety - avoid infinite loop:
682 if ( $this->isMain() ) {
683 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
686 $this->getMain()->setContinuationManager( $manager );
691 /************************************************************************//**
692 * @name Parameter handling
697 * Indicate if the module supports dynamically-determined parameters that
698 * cannot be included in self::getAllowedParams().
699 * @return string|array|Message|null Return null if the module does not
700 * support additional dynamic parameters, otherwise return a message
703 public function dynamicParameterDocumentation() {
708 * This method mangles parameter name based on the prefix supplied to the constructor.
709 * Override this method to change parameter name during runtime
710 * @param string|string[] $paramName Parameter name
711 * @return string|string[] Prefixed parameter name
712 * @since 1.29 accepts an array of strings
714 public function encodeParamName( $paramName ) {
715 if ( is_array( $paramName ) ) {
716 return array_map( function ( $name ) {
717 return $this->mModulePrefix
. $name;
720 return $this->mModulePrefix
. $paramName;
725 * Using getAllowedParams(), this function makes an array of the values
726 * provided by the user, with key being the name of the variable, and
727 * value - validated value from user or default. limits will not be
728 * parsed if $parseLimit is set to false; use this when the max
729 * limit is not definitive yet, e.g. when getting revisions.
730 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
731 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
732 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
733 * Returned parameter values might be ApiUsageException instances.
736 public function extractRequestParams( $options = [] ) {
737 if ( is_bool( $options ) ) {
738 $options = [ 'parseLimit' => $options ];
741 'parseLimit' => true,
745 $parseLimit = (bool)$options['parseLimit'];
747 // Cache parameters, for performance and to avoid T26564.
748 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
749 $params = $this->getFinalParams() ?
: [];
753 // Process all non-templates and save templates for secondary
756 foreach ( $params as $paramName => $paramSettings ) {
757 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
758 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
761 $results[$paramName] = $this->getParameterFromSettings(
762 $paramName, $paramSettings, $parseLimit
764 } catch ( ApiUsageException
$ex ) {
765 $results[$paramName] = $ex;
770 // Now process all the templates by successively replacing the
771 // placeholders with all client-supplied values.
772 // This bit duplicates JavaScript logic in
773 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
774 // If you update this, see if that needs updating too.
775 while ( $toProcess ) {
776 list( $name, $targets, $settings ) = array_shift( $toProcess );
778 foreach ( $targets as $placeholder => $target ) {
779 if ( !array_key_exists( $target, $results ) ) {
780 // The target wasn't processed yet, try the next one.
781 // If all hit this case, the parameter has no expansions.
784 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
785 // The target was processed but has no (valid) values.
786 // That means it has no expansions.
790 // Expand this target in the name and all other targets,
791 // then requeue if there are more targets left or put in
792 // $results if all are done.
793 unset( $targets[$placeholder] );
794 $placeholder = '{' . $placeholder . '}';
795 foreach ( $results[$target] as $value ) {
796 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
797 // Skip values that make invalid parameter names.
798 $encTargetName = $this->encodeParamName( $target );
799 if ( !isset( $warned[$encTargetName][$value] ) ) {
800 $warned[$encTargetName][$value] = true;
802 'apiwarn-ignoring-invalid-templated-value',
803 wfEscapeWikiText( $encTargetName ),
804 wfEscapeWikiText( $value ),
810 $newName = str_replace( $placeholder, $value, $name );
813 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
814 } catch ( ApiUsageException
$ex ) {
815 $results[$newName] = $ex;
819 foreach ( $targets as $k => $v ) {
820 $newTargets[$k] = str_replace( $placeholder, $value, $v );
822 $toProcess[] = [ $newName, $newTargets, $settings ];
829 $this->mParamCache
[$parseLimit] = $results;
832 $ret = $this->mParamCache
[$parseLimit];
833 if ( !$options['safeMode'] ) {
834 foreach ( $ret as $v ) {
835 if ( $v instanceof ApiUsageException
) {
841 return $this->mParamCache
[$parseLimit];
845 * Get a value for the given parameter
846 * @param string $paramName Parameter name
847 * @param bool $parseLimit See extractRequestParams()
848 * @return mixed Parameter value
850 protected function getParameter( $paramName, $parseLimit = true ) {
851 $ret = $this->extractRequestParams( [
852 'parseLimit' => $parseLimit,
855 if ( $ret instanceof ApiUsageException
) {
862 * Die if none or more than one of a certain set of parameters is set and not false.
864 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
865 * @param string $required,... Names of parameters of which exactly one must be set
867 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
868 $required = func_get_args();
869 array_shift( $required );
871 $intersection = array_intersect( array_keys( array_filter( $params,
872 [ $this, 'parameterNotEmpty' ] ) ), $required );
874 if ( count( $intersection ) > 1 ) {
875 $this->dieWithError( [
876 'apierror-invalidparammix',
877 Message
::listParam( array_map(
879 return '<var>' . $this->encodeParamName( $p ) . '</var>';
881 array_values( $intersection )
883 count( $intersection ),
885 } elseif ( count( $intersection ) == 0 ) {
886 $this->dieWithError( [
887 'apierror-missingparam-one-of',
888 Message
::listParam( array_map(
890 return '<var>' . $this->encodeParamName( $p ) . '</var>';
892 array_values( $required )
900 * Die if more than one of a certain set of parameters is set and not false.
902 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
903 * @param string $required,... Names of parameters of which at most one must be set
905 public function requireMaxOneParameter( $params, $required /*...*/ ) {
906 $required = func_get_args();
907 array_shift( $required );
909 $intersection = array_intersect( array_keys( array_filter( $params,
910 [ $this, 'parameterNotEmpty' ] ) ), $required );
912 if ( count( $intersection ) > 1 ) {
913 $this->dieWithError( [
914 'apierror-invalidparammix',
915 Message
::listParam( array_map(
917 return '<var>' . $this->encodeParamName( $p ) . '</var>';
919 array_values( $intersection )
921 count( $intersection ),
927 * Die if none of a certain set of parameters is set and not false.
930 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
931 * @param string $required,... Names of parameters of which at least one must be set
933 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
934 $required = func_get_args();
935 array_shift( $required );
937 $intersection = array_intersect(
938 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
942 if ( count( $intersection ) == 0 ) {
943 $this->dieWithError( [
944 'apierror-missingparam-at-least-one-of',
945 Message
::listParam( array_map(
947 return '<var>' . $this->encodeParamName( $p ) . '</var>';
949 array_values( $required )
957 * Die if any of the specified parameters were found in the query part of
958 * the URL rather than the post body.
960 * @param string[] $params Parameters to check
961 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
963 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
964 // Skip if $wgDebugAPI is set or we're in internal mode
965 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
969 $queryValues = $this->getRequest()->getQueryValues();
971 foreach ( $params as $param ) {
972 if ( $prefix !== 'noprefix' ) {
973 $param = $this->encodeParamName( $param );
975 if ( array_key_exists( $param, $queryValues ) ) {
976 $badParams[] = $param;
982 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
988 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
990 * @param object $x Parameter to check is not null/false
993 private function parameterNotEmpty( $x ) {
994 return !is_null( $x ) && $x !== false;
998 * Get a WikiPage object from a title or pageid param, if possible.
999 * Can die, if no param is set or if the title or page id is not valid.
1001 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1002 * @param bool|string $load Whether load the object's state from the database:
1003 * - false: don't load (if the pageid is given, it will still be loaded)
1004 * - 'fromdb': load from a replica DB
1005 * - 'fromdbmaster': load from the master database
1008 public function getTitleOrPageId( $params, $load = false ) {
1009 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1012 if ( isset( $params['title'] ) ) {
1013 $titleObj = Title
::newFromText( $params['title'] );
1014 if ( !$titleObj ||
$titleObj->isExternal() ) {
1015 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1017 if ( !$titleObj->canExist() ) {
1018 $this->dieWithError( 'apierror-pagecannotexist' );
1020 $pageObj = WikiPage
::factory( $titleObj );
1021 if ( $load !== false ) {
1022 $pageObj->loadPageData( $load );
1024 } elseif ( isset( $params['pageid'] ) ) {
1025 if ( $load === false ) {
1028 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1030 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1038 * Get a Title object from a title or pageid param, if possible.
1039 * Can die, if no param is set or if the title or page id is not valid.
1042 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1045 public function getTitleFromTitleOrPageId( $params ) {
1046 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1049 if ( isset( $params['title'] ) ) {
1050 $titleObj = Title
::newFromText( $params['title'] );
1051 if ( !$titleObj ||
$titleObj->isExternal() ) {
1052 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1055 } elseif ( isset( $params['pageid'] ) ) {
1056 $titleObj = Title
::newFromID( $params['pageid'] );
1058 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1066 * Return true if we're to watch the page, false if not, null if no change.
1067 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1068 * @param Title $titleObj The page under consideration
1069 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1070 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1073 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1074 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1076 switch ( $watchlist ) {
1084 # If the user is already watching, don't bother checking
1085 if ( $userWatching ) {
1088 # If no user option was passed, use watchdefault and watchcreations
1089 if ( is_null( $userOption ) ) {
1090 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1091 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1094 # Watch the article based on the user preference
1095 return $this->getUser()->getBoolOption( $userOption );
1098 return $userWatching;
1101 return $userWatching;
1106 * Using the settings determine the value for the given parameter
1108 * @param string $paramName Parameter name
1109 * @param array|mixed $paramSettings Default value or an array of settings
1110 * using PARAM_* constants.
1111 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1112 * @return mixed Parameter value
1114 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1115 // Some classes may decide to change parameter names
1116 $encParamName = $this->encodeParamName( $paramName );
1119 if ( !is_array( $paramSettings ) ) {
1121 self
::PARAM_DFLT
=> $paramSettings,
1125 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1126 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1127 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1128 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1129 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1130 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1131 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1132 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1133 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1134 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1136 // When type is not given, and no choices, the type is the same as $default
1137 if ( !isset( $type ) ) {
1138 if ( isset( $default ) ) {
1139 $type = gettype( $default );
1141 $type = 'NULL'; // allow everything
1145 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1146 $this->getMain()->markParamsSensitive( $encParamName );
1149 if ( $type == 'boolean' ) {
1150 if ( isset( $default ) && $default !== false ) {
1151 // Having a default value of anything other than 'false' is not allowed
1154 "Boolean param $encParamName's default is set to '$default'. " .
1155 'Boolean parameters must default to false.'
1159 $value = $this->getMain()->getCheck( $encParamName );
1161 } elseif ( $type == 'upload' ) {
1162 if ( isset( $default ) ) {
1163 // Having a default value is not allowed
1166 "File upload param $encParamName's default is set to " .
1167 "'$default'. File upload parameters may not have a default." );
1170 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1172 $value = $this->getMain()->getUpload( $encParamName );
1173 $provided = $value->exists();
1174 if ( !$value->exists() ) {
1175 // This will get the value without trying to normalize it
1176 // (because trying to normalize a large binary file
1177 // accidentally uploaded as a field fails spectacularly)
1178 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1179 if ( $value !== null ) {
1180 $this->dieWithError(
1181 [ 'apierror-badupload', $encParamName ],
1182 "badupload_{$encParamName}"
1187 $value = $this->getMain()->getVal( $encParamName, $default );
1188 $provided = $this->getMain()->getCheck( $encParamName );
1190 if ( isset( $value ) && $type == 'namespace' ) {
1191 $type = MWNamespace
::getValidNamespaces();
1192 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1193 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1195 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1197 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1198 // specify all namespaces irrespective of PARAM_ALL.
1201 if ( isset( $value ) && $type == 'submodule' ) {
1202 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1203 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1205 $type = $this->getModuleManager()->getNames( $paramName );
1209 $request = $this->getMain()->getRequest();
1210 $rawValue = $request->getRawVal( $encParamName );
1211 if ( $rawValue === null ) {
1212 $rawValue = $default;
1215 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1216 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1218 // This loses the potential checkTitleEncoding() transformation done by
1219 // WebRequest for $_GET. Let's call that a feature.
1220 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1222 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1226 // Check for NFC normalization, and warn
1227 if ( $rawValue !== $value ) {
1228 $this->handleParamNormalization( $paramName, $value, $rawValue );
1232 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1233 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1236 "For param $encParamName, PARAM_ALL collides with a possible value" );
1238 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1239 $value = $this->parseMultiValue(
1243 is_array( $type ) ?
$type : null,
1244 $allowAll ?
$allSpecifier : null,
1250 if ( isset( $value ) ) {
1251 // More validation only when choices were not given
1252 // choices were validated in parseMultiValue()
1253 if ( !is_array( $type ) ) {
1255 case 'NULL': // nothing to do
1260 if ( $required && $value === '' ) {
1261 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1264 case 'integer': // Force everything using intval() and optionally validate limits
1265 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1266 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1267 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1269 if ( is_array( $value ) ) {
1270 $value = array_map( 'intval', $value );
1271 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1272 foreach ( $value as &$v ) {
1273 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1277 $value = intval( $value );
1278 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1279 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1284 if ( !$parseLimit ) {
1285 // Don't do any validation whatsoever
1288 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1289 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1293 "MAX1 or MAX2 are not defined for the limit $encParamName"
1297 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1299 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1300 if ( $value == 'max' ) {
1301 $value = $this->getMain()->canApiHighLimits()
1302 ?
$paramSettings[self
::PARAM_MAX2
]
1303 : $paramSettings[self
::PARAM_MAX
];
1304 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1306 $value = intval( $value );
1307 $this->validateLimit(
1311 $paramSettings[self
::PARAM_MAX
],
1312 $paramSettings[self
::PARAM_MAX2
]
1318 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1322 if ( is_array( $value ) ) {
1323 foreach ( $value as $key => $val ) {
1324 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1327 $value = $this->validateTimestamp( $value, $encParamName );
1331 if ( is_array( $value ) ) {
1332 foreach ( $value as $key => $val ) {
1333 $value[$key] = $this->validateUser( $val, $encParamName );
1336 $value = $this->validateUser( $value, $encParamName );
1339 case 'upload': // nothing to do
1342 // If change tagging was requested, check that the tags are valid.
1343 if ( !is_array( $value ) && !$multi ) {
1344 $value = [ $value ];
1346 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1347 if ( !$tagsStatus->isGood() ) {
1348 $this->dieStatus( $tagsStatus );
1352 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1356 // Throw out duplicates if requested
1357 if ( !$dupes && is_array( $value ) ) {
1358 $value = array_unique( $value );
1361 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1362 foreach ( (array)$value as $val ) {
1363 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1364 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1366 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1367 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1369 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1370 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1372 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1373 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1378 // Set a warning if a deprecated parameter has been passed
1379 if ( $deprecated && $provided ) {
1380 $feature = $encParamName;
1382 while ( !$m->isMain() ) {
1383 $p = $m->getParent();
1384 $name = $m->getModuleName();
1385 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1386 $feature = "{$param}={$name}&{$feature}";
1389 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1392 // Set a warning if a deprecated parameter value has been passed
1393 $usedDeprecatedValues = $deprecatedValues && $provided
1394 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1396 if ( $usedDeprecatedValues ) {
1397 $feature = "$encParamName=";
1399 while ( !$m->isMain() ) {
1400 $p = $m->getParent();
1401 $name = $m->getModuleName();
1402 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1403 $feature = "{$param}={$name}&{$feature}";
1406 foreach ( $usedDeprecatedValues as $v ) {
1407 $msg = $deprecatedValues[$v];
1408 if ( $msg === true ) {
1409 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1411 $this->addDeprecation( $msg, "$feature$v" );
1414 } elseif ( $required ) {
1415 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1422 * Handle when a parameter was Unicode-normalized
1424 * @param string $paramName Unprefixed parameter name
1425 * @param string $value Input that will be used.
1426 * @param string $rawValue Input before normalization.
1428 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1429 $encParamName = $this->encodeParamName( $paramName );
1430 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1434 * Split a multi-valued parameter string, like explode()
1436 * @param string $value
1440 protected function explodeMultiValue( $value, $limit ) {
1441 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1443 $value = substr( $value, 1 );
1448 return explode( $sep, $value, $limit );
1452 * Return an array of values that were given in a 'a|b|c' notation,
1453 * after it optionally validates them against the list allowed values.
1455 * @param string $valueName The name of the parameter (for error
1457 * @param mixed $value The value being parsed
1458 * @param bool $allowMultiple Can $value contain more than one value
1460 * @param string[]|null $allowedValues An array of values to check against. If
1461 * null, all values are accepted.
1462 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1463 * if this behavior should not be allowed
1464 * @param int|null $limit1 Maximum number of values, for normal users.
1465 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1466 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1468 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1469 $allSpecifier = null, $limit1 = null, $limit2 = null
1471 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1474 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1475 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1477 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1478 // because it unstubs $wgUser
1479 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1480 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1484 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1485 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1487 return $allowedValues;
1490 if ( count( $valuesList ) > $sizeLimit ) {
1491 $this->dieWithError(
1492 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1493 "too-many-$valueName"
1497 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1498 // T35482 - Allow entries with | in them for non-multiple values
1499 if ( in_array( $value, $allowedValues, true ) ) {
1503 $values = array_map( function ( $v ) {
1504 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1505 }, $allowedValues );
1506 $this->dieWithError( [
1507 'apierror-multival-only-one-of',
1509 Message
::listParam( $values ),
1511 ], "multival_$valueName" );
1514 if ( is_array( $allowedValues ) ) {
1515 // Check for unknown values
1516 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1517 if ( count( $unknown ) ) {
1518 if ( $allowMultiple ) {
1519 $this->addWarning( [
1520 'apiwarn-unrecognizedvalues',
1522 Message
::listParam( $unknown, 'comma' ),
1526 $this->dieWithError(
1527 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1528 "unknown_$valueName"
1532 // Now throw them out
1533 $valuesList = array_intersect( $valuesList, $allowedValues );
1536 return $allowMultiple ?
$valuesList : $valuesList[0];
1540 * Validate the value against the minimum and user/bot maximum limits.
1541 * Prints usage info on failure.
1542 * @param string $paramName Parameter name
1543 * @param int &$value Parameter value
1544 * @param int|null $min Minimum value
1545 * @param int|null $max Maximum value for users
1546 * @param int|null $botMax Maximum value for sysops/bots
1547 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1549 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1550 $enforceLimits = false
1552 if ( !is_null( $min ) && $value < $min ) {
1553 $msg = ApiMessage
::create(
1554 [ 'apierror-integeroutofrange-belowminimum',
1555 $this->encodeParamName( $paramName ), $min, $value ],
1556 'integeroutofrange',
1557 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1559 $this->warnOrDie( $msg, $enforceLimits );
1563 // Minimum is always validated, whereas maximum is checked only if not
1564 // running in internal call mode
1565 if ( $this->getMain()->isInternalMode() ) {
1569 // Optimization: do not check user's bot status unless really needed -- skips db query
1570 // assumes $botMax >= $max
1571 if ( !is_null( $max ) && $value > $max ) {
1572 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1573 if ( $value > $botMax ) {
1574 $msg = ApiMessage
::create(
1575 [ 'apierror-integeroutofrange-abovebotmax',
1576 $this->encodeParamName( $paramName ), $botMax, $value ],
1577 'integeroutofrange',
1578 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1580 $this->warnOrDie( $msg, $enforceLimits );
1584 $msg = ApiMessage
::create(
1585 [ 'apierror-integeroutofrange-abovemax',
1586 $this->encodeParamName( $paramName ), $max, $value ],
1587 'integeroutofrange',
1588 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1590 $this->warnOrDie( $msg, $enforceLimits );
1597 * Validate and normalize parameters of type 'timestamp'
1598 * @param string $value Parameter value
1599 * @param string $encParamName Parameter name
1600 * @return string Validated and normalized parameter
1602 protected function validateTimestamp( $value, $encParamName ) {
1603 // Confusing synonyms for the current time accepted by wfTimestamp()
1604 // (wfTimestamp() also accepts various non-strings and the string of 14
1605 // ASCII NUL bytes, but those can't get here)
1607 $this->addDeprecation(
1608 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1609 'unclear-"now"-timestamp'
1611 return wfTimestamp( TS_MW
);
1614 // Explicit synonym for the current time
1615 if ( $value === 'now' ) {
1616 return wfTimestamp( TS_MW
);
1619 $timestamp = wfTimestamp( TS_MW
, $value );
1620 if ( $timestamp === false ) {
1621 $this->dieWithError(
1622 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1623 "badtimestamp_{$encParamName}"
1631 * Validate the supplied token.
1634 * @param string $token Supplied token
1635 * @param array $params All supplied parameters for the module
1637 * @throws MWException
1639 final public function validateToken( $token, array $params ) {
1640 $tokenType = $this->needsToken();
1641 $salts = ApiQueryTokens
::getTokenTypeSalts();
1642 if ( !isset( $salts[$tokenType] ) ) {
1643 throw new MWException(
1644 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1645 'without registering it'
1649 $tokenObj = ApiQueryTokens
::getToken(
1650 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1652 if ( $tokenObj->match( $token ) ) {
1656 $webUiSalt = $this->getWebUITokenSalt( $params );
1657 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1669 * Validate and normalize parameters of type 'user'
1670 * @param string $value Parameter value
1671 * @param string $encParamName Parameter name
1672 * @return string Validated and normalized parameter
1674 private function validateUser( $value, $encParamName ) {
1675 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1679 $name = User
::getCanonicalName( $value, 'valid' );
1680 if ( $name !== false ) {
1685 // We allow ranges as well, for blocks.
1686 IP
::isIPAddress( $value ) ||
1687 // See comment for User::isIP. We don't just call that function
1688 // here because it also returns true for things like
1689 // 300.300.300.300 that are neither valid usernames nor valid IP
1692 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1696 return IP
::sanitizeIP( $value );
1699 $this->dieWithError(
1700 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1701 "baduser_{$encParamName}"
1707 /************************************************************************//**
1708 * @name Utility methods
1713 * Set a watch (or unwatch) based the based on a watchlist parameter.
1714 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1715 * @param Title $titleObj The article's title to change
1716 * @param string|null $userOption The user option to consider when $watch=preferences
1718 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1719 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1720 if ( $value === null ) {
1724 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1728 * Gets the user for whom to get the watchlist
1730 * @param array $params
1733 public function getWatchlistUser( $params ) {
1734 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1735 $user = User
::newFromName( $params['owner'], false );
1736 if ( !( $user && $user->getId() ) ) {
1737 $this->dieWithError(
1738 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1741 $token = $user->getOption( 'watchlisttoken' );
1742 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1743 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1746 if ( !$this->getUser()->isLoggedIn() ) {
1747 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1749 $this->checkUserRightsAny( 'viewmywatchlist' );
1750 $user = $this->getUser();
1757 * Create a Message from a string or array
1759 * A string is used as a message key. An array has the message key as the
1760 * first value and message parameters as subsequent values.
1763 * @param string|array|Message $msg
1764 * @param IContextSource $context
1765 * @param array|null $params
1766 * @return Message|null
1768 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1769 if ( is_string( $msg ) ) {
1770 $msg = wfMessage( $msg );
1771 } elseif ( is_array( $msg ) ) {
1772 $msg = wfMessage( ...$msg );
1774 if ( !$msg instanceof Message
) {
1778 $msg->setContext( $context );
1780 $msg->params( $params );
1787 * Turn an array of message keys or key+param arrays into a Status
1789 * @param array $errors
1790 * @param User|null $user
1793 public function errorArrayToStatus( array $errors, User
$user = null ) {
1794 if ( $user === null ) {
1795 $user = $this->getUser();
1798 $status = Status
::newGood();
1799 foreach ( $errors as $error ) {
1800 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1801 $status->fatal( ApiMessage
::create(
1804 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1806 } elseif ( is_array( $error ) && $error[0] === 'blockedtext-partial' && $user->getBlock() ) {
1807 $status->fatal( ApiMessage
::create(
1808 'apierror-blocked-partial',
1810 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1812 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1813 $status->fatal( ApiMessage
::create(
1814 'apierror-autoblocked',
1816 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1818 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1819 $status->fatal( ApiMessage
::create(
1820 'apierror-systemblocked',
1822 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1825 $status->fatal( ...(array)$error );
1832 * Call wfTransactionalTimeLimit() if this request was POSTed
1835 protected function useTransactionalTimeLimit() {
1836 if ( $this->getRequest()->wasPosted() ) {
1837 wfTransactionalTimeLimit();
1842 * Filter out-of-range values from a list of positive integer IDs
1844 * @param array $fields Array of pairs of table and field to check
1845 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1846 * expected to be stringified ints.
1847 * @return (string|int)[] Filtered IDs.
1849 protected function filterIDs( $fields, array $ids ) {
1852 foreach ( $fields as list( $table, $field ) ) {
1853 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1854 $row = self
::$filterIDsCache[$table][$field];
1856 $row = $this->getDB()->selectRow(
1859 'min_id' => "MIN($field)",
1860 'max_id' => "MAX($field)",
1865 self
::$filterIDsCache[$table][$field] = $row;
1867 $min = min( $min, $row->min_id
);
1868 $max = max( $max, $row->max_id
);
1870 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1871 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1872 && $id >= $min && $id <= $max;
1878 /************************************************************************//**
1879 * @name Warning and error reporting
1884 * Add a warning for this module.
1886 * Users should monitor this section to notice any changes in API. Multiple
1887 * calls to this function will result in multiple warning messages.
1889 * If $msg is not an ApiMessage, the message code will be derived from the
1890 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1893 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1894 * @param string|null $code See ApiErrorFormatter::addWarning()
1895 * @param array|null $data See ApiErrorFormatter::addWarning()
1897 public function addWarning( $msg, $code = null, $data = null ) {
1898 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1902 * Add a deprecation warning for this module.
1904 * A combination of $this->addWarning() and $this->logFeatureUsage()
1907 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1908 * @param string|null $feature See ApiBase::logFeatureUsage()
1909 * @param array|null $data See ApiErrorFormatter::addWarning()
1911 public function addDeprecation( $msg, $feature, $data = [] ) {
1912 $data = (array)$data;
1913 if ( $feature !== null ) {
1914 $data['feature'] = $feature;
1915 $this->logFeatureUsage( $feature );
1917 $this->addWarning( $msg, 'deprecation', $data );
1919 // No real need to deduplicate here, ApiErrorFormatter does that for
1920 // us (assuming the hook is deterministic).
1921 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1922 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1923 if ( count( $msgs ) > 1 ) {
1924 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1925 $msg = ( new RawMessage( $key ) )->params( $msgs );
1927 $msg = reset( $msgs );
1929 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1933 * Add an error for this module without aborting
1935 * If $msg is not an ApiMessage, the message code will be derived from the
1936 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1938 * @note If you want to abort processing, use self::dieWithError() instead.
1940 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1941 * @param string|null $code See ApiErrorFormatter::addError()
1942 * @param array|null $data See ApiErrorFormatter::addError()
1944 public function addError( $msg, $code = null, $data = null ) {
1945 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1949 * Add warnings and/or errors from a Status
1951 * @note If you want to abort processing, use self::dieStatus() instead.
1953 * @param StatusValue $status
1954 * @param string[] $types 'warning' and/or 'error'
1955 * @param string[] $filter Message keys to filter out (since 1.33)
1957 public function addMessagesFromStatus(
1958 StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
1960 $this->getErrorFormatter()->addMessagesFromStatus(
1961 $this->getModulePath(), $status, $types, $filter
1966 * Abort execution with an error
1968 * If $msg is not an ApiMessage, the message code will be derived from the
1969 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1972 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1973 * @param string|null $code See ApiErrorFormatter::addError()
1974 * @param array|null $data See ApiErrorFormatter::addError()
1975 * @param int|null $httpCode HTTP error code to use
1976 * @throws ApiUsageException always
1978 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1979 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1983 * Abort execution with an error derived from an exception
1986 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1987 * @param array $options See ApiErrorFormatter::getMessageFromException()
1988 * @throws ApiUsageException always
1990 public function dieWithException( $exception, array $options = [] ) {
1991 $this->dieWithError(
1992 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1997 * Adds a warning to the output, else dies
1999 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2000 * @param bool $enforceLimits Whether this is an enforce (die)
2002 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2003 if ( $enforceLimits ) {
2004 $this->dieWithError( $msg );
2006 $this->addWarning( $msg );
2011 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2012 * error handler and die with an error message including block info.
2015 * @param Block $block The block used to generate the ApiUsageException
2016 * @throws ApiUsageException always
2018 public function dieBlocked( Block
$block ) {
2019 // Die using the appropriate message depending on block type
2020 if ( $block->getType() == Block
::TYPE_AUTO
) {
2021 $this->dieWithError(
2022 'apierror-autoblocked',
2024 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2026 } elseif ( !$block->isSitewide() ) {
2027 $this->dieWithError(
2028 'apierror-blocked-partial',
2030 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2033 $this->dieWithError(
2036 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2042 * Throw an ApiUsageException based on the Status object.
2045 * @since 1.29 Accepts a StatusValue
2046 * @param StatusValue $status
2047 * @throws ApiUsageException always
2049 public function dieStatus( StatusValue
$status ) {
2050 if ( $status->isGood() ) {
2051 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2054 // ApiUsageException needs a fatal status, but this method has
2055 // historically accepted any non-good status. Convert it if necessary.
2056 $status->setOK( false );
2057 if ( !$status->getErrorsByType( 'error' ) ) {
2058 $newStatus = Status
::newGood();
2059 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2060 $newStatus->fatal( $err['message'], ...$err['params'] );
2062 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2063 $newStatus->fatal( 'unknownerror-nocode' );
2065 $status = $newStatus;
2068 throw new ApiUsageException( $this, $status );
2072 * Helper function for readonly errors
2074 * @throws ApiUsageException always
2076 public function dieReadOnly() {
2077 $this->dieWithError(
2078 'apierror-readonly',
2080 [ 'readonlyreason' => wfReadOnlyReason() ]
2085 * Helper function for permission-denied errors
2087 * @param string|string[] $rights
2088 * @param User|null $user
2089 * @throws ApiUsageException if the user doesn't have any of the rights.
2090 * The error message is based on $rights[0].
2092 public function checkUserRightsAny( $rights, $user = null ) {
2094 $user = $this->getUser();
2096 $rights = (array)$rights;
2097 if ( !$user->isAllowedAny( ...$rights ) ) {
2098 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2103 * Helper function for permission-denied errors
2105 * @param Title $title
2106 * @param string|string[] $actions
2107 * @param User|null $user
2108 * @throws ApiUsageException if the user doesn't have all of the rights.
2110 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
2112 $user = $this->getUser();
2116 foreach ( (array)$actions as $action ) {
2117 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2121 // track block notices
2122 if ( $this->getConfig()->get( 'EnableBlockNoticeStats' ) ) {
2123 $this->trackBlockNotices( $errors );
2126 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2131 * Keep track of errors messages resulting from a block
2133 * @param array $errors
2135 private function trackBlockNotices( array $errors ) {
2136 $errorMessageKeys = [
2138 'blockedtext-partial',
2140 'systemblockedtext',
2143 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
2145 foreach ( $errors as $error ) {
2146 if ( in_array( $error[0], $errorMessageKeys ) ) {
2147 $wiki = $this->getConfig()->get( 'DBname' );
2148 $statsd->increment( 'BlockNotices.' . $wiki . '.MediaWikiApi.returned' );
2155 * Will only set a warning instead of failing if the global $wgDebugAPI
2156 * is set to true. Otherwise behaves exactly as self::dieWithError().
2159 * @param string|array|Message $msg
2160 * @param string|null $code
2161 * @param array|null $data
2162 * @param int|null $httpCode
2163 * @throws ApiUsageException
2165 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2166 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2167 $this->dieWithError( $msg, $code, $data, $httpCode );
2169 $this->addWarning( $msg, $code, $data );
2174 * Die with the 'badcontinue' error.
2176 * This call is common enough to make it into the base method.
2178 * @param bool $condition Will only die if this value is true
2179 * @throws ApiUsageException
2182 protected function dieContinueUsageIf( $condition ) {
2184 $this->dieWithError( 'apierror-badcontinue' );
2189 * Internal code errors should be reported with this method
2190 * @param string $method Method or function name
2191 * @param string $message Error message
2192 * @throws MWException always
2194 protected static function dieDebug( $method, $message ) {
2195 throw new MWException( "Internal error in $method: $message" );
2199 * Write logging information for API features to a debug log, for usage
2201 * @note Consider using $this->addDeprecation() instead to both warn and log.
2202 * @param string $feature Feature being used.
2204 public function logFeatureUsage( $feature ) {
2205 $request = $this->getRequest();
2206 $s = '"' . addslashes( $feature ) . '"' .
2207 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2208 ' "' . $request->getIP() . '"' .
2209 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2210 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2211 wfDebugLog( 'api-feature-usage', $s, 'private' );
2216 /************************************************************************//**
2217 * @name Help message generation
2222 * Return the summary message.
2224 * This is a one-line description of the module, suitable for display in a
2228 * @return string|array|Message
2230 protected function getSummaryMessage() {
2231 return "apihelp-{$this->getModulePath()}-summary";
2235 * Return the extended help text message.
2237 * This is additional text to display at the top of the help section, below
2241 * @return string|array|Message
2243 protected function getExtendedDescription() {
2245 "apihelp-{$this->getModulePath()}-extended-description",
2246 'api-help-no-extended-description',
2251 * Get final module summary
2256 public function getFinalSummary() {
2257 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2258 $this->getModulePrefix(),
2259 $this->getModuleName(),
2260 $this->getModulePath(),
2266 * Get final module description, after hooks have had a chance to tweak it as
2269 * @since 1.25, returns Message[] rather than string[]
2272 public function getFinalDescription() {
2273 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2274 $this->getModulePrefix(),
2275 $this->getModuleName(),
2276 $this->getModulePath(),
2278 $extendedDescription = self
::makeMessage(
2279 $this->getExtendedDescription(), $this->getContext(), [
2280 $this->getModulePrefix(),
2281 $this->getModuleName(),
2282 $this->getModulePath(),
2286 $msgs = [ $summary, $extendedDescription ];
2288 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2294 * Get final list of parameters, after hooks have had a chance to
2295 * tweak it as needed.
2297 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2298 * @return array|bool False on no parameters
2299 * @since 1.21 $flags param added
2301 public function getFinalParams( $flags = 0 ) {
2302 $params = $this->getAllowedParams( $flags );
2307 if ( $this->needsToken() ) {
2308 $params['token'] = [
2309 self
::PARAM_TYPE
=> 'string',
2310 self
::PARAM_REQUIRED
=> true,
2311 self
::PARAM_SENSITIVE
=> true,
2312 self
::PARAM_HELP_MSG
=> [
2313 'api-help-param-token',
2314 $this->needsToken(),
2316 ] +
( $params['token'] ??
[] );
2319 // Avoid PHP 7.1 warning of passing $this by reference
2321 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2327 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2330 * @since 1.25, returns array of Message[] rather than array of string[]
2331 * @return array Keys are parameter names, values are arrays of Message objects
2333 public function getFinalParamDescription() {
2334 $prefix = $this->getModulePrefix();
2335 $name = $this->getModuleName();
2336 $path = $this->getModulePath();
2338 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2340 foreach ( $params as $param => $settings ) {
2341 if ( !is_array( $settings ) ) {
2345 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2346 $msg = $settings[self
::PARAM_HELP_MSG
];
2348 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2350 $msg = self
::makeMessage( $msg, $this->getContext(),
2351 [ $prefix, $param, $name, $path ] );
2353 self
::dieDebug( __METHOD__
,
2354 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2356 $msgs[$param] = [ $msg ];
2358 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2359 $settings[self
::PARAM_TYPE
] === 'submodule'
2361 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2362 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2364 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2366 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2367 $map[$submoduleName] = $prefix . $submoduleName;
2372 $deprecatedSubmodules = [];
2373 foreach ( $map as $v => $m ) {
2374 $arr = &$submodules;
2375 $isDeprecated = false;
2378 $submod = $this->getModuleFromPath( $m );
2380 $summary = $submod->getFinalSummary();
2381 $isDeprecated = $submod->isDeprecated();
2382 if ( $isDeprecated ) {
2383 $arr = &$deprecatedSubmodules;
2386 } catch ( ApiUsageException
$ex ) {
2390 $key = $summary->getKey();
2391 $params = $summary->getParams();
2393 $key = 'api-help-undocumented-module';
2396 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2397 $arr[] = $m->setContext( $this->getContext() );
2399 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2400 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2401 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2402 self
::dieDebug( __METHOD__
,
2403 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2405 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2406 self
::dieDebug( __METHOD__
,
2407 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2408 'ApiBase::PARAM_TYPE is an array' );
2411 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2412 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2414 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2415 if ( isset( $valueMsgs[$value] ) ) {
2416 $msg = $valueMsgs[$value];
2418 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2420 $m = self
::makeMessage( $msg, $this->getContext(),
2421 [ $prefix, $param, $name, $path, $value ] );
2423 $m = new ApiHelpParamValueMessage(
2425 [ $m->getKey(), 'api-help-param-no-description' ],
2427 isset( $deprecatedValues[$value] )
2429 $msgs[$param][] = $m->setContext( $this->getContext() );
2431 self
::dieDebug( __METHOD__
,
2432 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2437 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2438 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2439 self
::dieDebug( __METHOD__
,
2440 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2442 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2443 $m = self
::makeMessage( $m, $this->getContext(),
2444 [ $prefix, $param, $name, $path ] );
2446 $msgs[$param][] = $m;
2448 self
::dieDebug( __METHOD__
,
2449 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2455 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2461 * Generates the list of flags for the help screen and for action=paraminfo
2463 * Corresponding messages: api-help-flag-deprecated,
2464 * api-help-flag-internal, api-help-flag-readrights,
2465 * api-help-flag-writerights, api-help-flag-mustbeposted
2469 protected function getHelpFlags() {
2472 if ( $this->isDeprecated() ) {
2473 $flags[] = 'deprecated';
2475 if ( $this->isInternal() ) {
2476 $flags[] = 'internal';
2478 if ( $this->isReadMode() ) {
2479 $flags[] = 'readrights';
2481 if ( $this->isWriteMode() ) {
2482 $flags[] = 'writerights';
2484 if ( $this->mustBePosted() ) {
2485 $flags[] = 'mustbeposted';
2492 * Returns information about the source of this module, if known
2494 * Returned array is an array with the following keys:
2495 * - path: Install path
2496 * - name: Extension name, or "MediaWiki" for core
2497 * - namemsg: (optional) i18n message key for a display name
2498 * - license-name: (optional) Name of license
2500 * @return array|null
2502 protected function getModuleSourceInfo() {
2505 if ( $this->mModuleSource
!== false ) {
2506 return $this->mModuleSource
;
2509 // First, try to find where the module comes from...
2510 $rClass = new ReflectionClass( $this );
2511 $path = $rClass->getFileName();
2514 $this->mModuleSource
= null;
2517 $path = realpath( $path ) ?
: $path;
2519 // Build map of extension directories to extension info
2520 if ( self
::$extensionInfo === null ) {
2521 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2522 self
::$extensionInfo = [
2523 realpath( __DIR__
) ?
: __DIR__
=> [
2525 'name' => 'MediaWiki',
2526 'license-name' => 'GPL-2.0-or-later',
2528 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2529 realpath( $extDir ) ?
: $extDir => null,
2535 'license-name' => null,
2537 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2538 foreach ( $group as $ext ) {
2539 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2540 // This shouldn't happen, but does anyway.
2544 $extpath = $ext['path'];
2545 if ( !is_dir( $extpath ) ) {
2546 $extpath = dirname( $extpath );
2548 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2549 array_intersect_key( $ext, $keep );
2552 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2553 $extpath = $ext['path'];
2554 if ( !is_dir( $extpath ) ) {
2555 $extpath = dirname( $extpath );
2557 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2558 array_intersect_key( $ext, $keep );
2562 // Now traverse parent directories until we find a match or run out of
2565 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2567 $this->mModuleSource
= self
::$extensionInfo[$path];
2568 return $this->mModuleSource
;
2572 $path = dirname( $path );
2573 } while ( $path !== $oldpath );
2575 // No idea what extension this might be.
2576 $this->mModuleSource
= null;
2581 * Called from ApiHelp before the pieces are joined together and returned.
2583 * This exists mainly for ApiMain to add the Permissions and Credits
2584 * sections. Other modules probably don't need it.
2586 * @param string[] &$help Array of help data
2587 * @param array $options Options passed to ApiHelp::getHelp
2588 * @param array &$tocData If a TOC is being generated, this array has keys
2589 * as anchors in the page and values as for Linker::generateTOC().
2591 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2596 /************************************************************************//**
2602 * Returns the description string for this module
2604 * Ignored if an i18n message exists for
2605 * "apihelp-{$this->getModulePath()}-description".
2607 * @deprecated since 1.25
2608 * @return Message|string|array|false
2610 protected function getDescription() {
2611 wfDeprecated( __METHOD__
, '1.25' );
2616 * Returns an array of parameter descriptions.
2618 * For each parameter, ignored if an i18n message exists for the parameter.
2619 * By default that message is
2620 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2621 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2622 * self::getFinalParams().
2624 * @deprecated since 1.25
2625 * @return array|bool False on no parameter descriptions
2627 protected function getParamDescription() {
2628 wfDeprecated( __METHOD__
, '1.25' );
2633 * Returns usage examples for this module.
2635 * Return value as an array is either:
2636 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2638 * - sequential numeric keys with even-numbered keys being display-text
2639 * and odd-numbered keys being partial urls
2640 * - partial URLs as keys with display-text (string or array-to-be-joined)
2642 * Return value as a string is the same as an array with a numeric key and
2643 * that value, and boolean false means "no examples".
2645 * @deprecated since 1.25, use getExamplesMessages() instead
2646 * @return bool|string|array
2648 protected function getExamples() {
2649 wfDeprecated( __METHOD__
, '1.25' );
2654 * Return the description message.
2656 * This is additional text to display on the help page after the summary.
2658 * @deprecated since 1.30
2659 * @return string|array|Message
2661 protected function getDescriptionMessage() {
2662 wfDeprecated( __METHOD__
, '1.30' );
2664 "apihelp-{$this->getModulePath()}-description",
2665 "apihelp-{$this->getModulePath()}-summary",
2670 * Truncate an array to a certain length.
2671 * @deprecated since 1.32, no replacement
2672 * @param array &$arr Array to truncate
2673 * @param int $limit Maximum length
2674 * @return bool True if the array was truncated, false otherwise
2676 public static function truncateArray( &$arr, $limit ) {
2677 wfDeprecated( __METHOD__
, '1.32' );
2679 while ( count( $arr ) > $limit ) {
2691 * For really cool vim folding this needs to be at the end:
2692 * vim: foldmarker=@{,@} foldmethod=marker