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 );
1160 } elseif ( $type == 'upload' ) {
1161 if ( isset( $default ) ) {
1162 // Having a default value is not allowed
1165 "File upload param $encParamName's default is set to " .
1166 "'$default'. File upload parameters may not have a default." );
1169 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1171 $value = $this->getMain()->getUpload( $encParamName );
1172 if ( !$value->exists() ) {
1173 // This will get the value without trying to normalize it
1174 // (because trying to normalize a large binary file
1175 // accidentally uploaded as a field fails spectacularly)
1176 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1177 if ( $value !== null ) {
1178 $this->dieWithError(
1179 [ 'apierror-badupload', $encParamName ],
1180 "badupload_{$encParamName}"
1185 $value = $this->getMain()->getVal( $encParamName, $default );
1187 if ( isset( $value ) && $type == 'namespace' ) {
1188 $type = MWNamespace
::getValidNamespaces();
1189 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1190 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1192 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1194 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1195 // specify all namespaces irrespective of PARAM_ALL.
1198 if ( isset( $value ) && $type == 'submodule' ) {
1199 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1200 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1202 $type = $this->getModuleManager()->getNames( $paramName );
1206 $request = $this->getMain()->getRequest();
1207 $rawValue = $request->getRawVal( $encParamName );
1208 if ( $rawValue === null ) {
1209 $rawValue = $default;
1212 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1213 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1215 // This loses the potential checkTitleEncoding() transformation done by
1216 // WebRequest for $_GET. Let's call that a feature.
1217 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1219 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1223 // Check for NFC normalization, and warn
1224 if ( $rawValue !== $value ) {
1225 $this->handleParamNormalization( $paramName, $value, $rawValue );
1229 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1230 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1233 "For param $encParamName, PARAM_ALL collides with a possible value" );
1235 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1236 $value = $this->parseMultiValue(
1240 is_array( $type ) ?
$type : null,
1241 $allowAll ?
$allSpecifier : null,
1247 if ( isset( $value ) ) {
1248 // More validation only when choices were not given
1249 // choices were validated in parseMultiValue()
1250 if ( !is_array( $type ) ) {
1252 case 'NULL': // nothing to do
1257 if ( $required && $value === '' ) {
1258 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1261 case 'integer': // Force everything using intval() and optionally validate limits
1262 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1263 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1264 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1266 if ( is_array( $value ) ) {
1267 $value = array_map( 'intval', $value );
1268 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1269 foreach ( $value as &$v ) {
1270 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1274 $value = intval( $value );
1275 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1276 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1281 if ( !$parseLimit ) {
1282 // Don't do any validation whatsoever
1285 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1286 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1290 "MAX1 or MAX2 are not defined for the limit $encParamName"
1294 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1296 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1297 if ( $value == 'max' ) {
1298 $value = $this->getMain()->canApiHighLimits()
1299 ?
$paramSettings[self
::PARAM_MAX2
]
1300 : $paramSettings[self
::PARAM_MAX
];
1301 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1303 $value = intval( $value );
1304 $this->validateLimit(
1308 $paramSettings[self
::PARAM_MAX
],
1309 $paramSettings[self
::PARAM_MAX2
]
1315 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1319 if ( is_array( $value ) ) {
1320 foreach ( $value as $key => $val ) {
1321 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1324 $value = $this->validateTimestamp( $value, $encParamName );
1328 if ( is_array( $value ) ) {
1329 foreach ( $value as $key => $val ) {
1330 $value[$key] = $this->validateUser( $val, $encParamName );
1333 $value = $this->validateUser( $value, $encParamName );
1336 case 'upload': // nothing to do
1339 // If change tagging was requested, check that the tags are valid.
1340 if ( !is_array( $value ) && !$multi ) {
1341 $value = [ $value ];
1343 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1344 if ( !$tagsStatus->isGood() ) {
1345 $this->dieStatus( $tagsStatus );
1349 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1353 // Throw out duplicates if requested
1354 if ( !$dupes && is_array( $value ) ) {
1355 $value = array_unique( $value );
1358 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1359 foreach ( (array)$value as $val ) {
1360 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1361 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1363 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1364 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1366 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1367 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1369 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1370 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1375 // Set a warning if a deprecated parameter has been passed
1376 if ( $deprecated && $value !== false ) {
1377 $feature = $encParamName;
1379 while ( !$m->isMain() ) {
1380 $p = $m->getParent();
1381 $name = $m->getModuleName();
1382 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1383 $feature = "{$param}={$name}&{$feature}";
1386 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1389 // Set a warning if a deprecated parameter value has been passed
1390 $usedDeprecatedValues = $deprecatedValues && $value !== false
1391 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1393 if ( $usedDeprecatedValues ) {
1394 $feature = "$encParamName=";
1396 while ( !$m->isMain() ) {
1397 $p = $m->getParent();
1398 $name = $m->getModuleName();
1399 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1400 $feature = "{$param}={$name}&{$feature}";
1403 foreach ( $usedDeprecatedValues as $v ) {
1404 $msg = $deprecatedValues[$v];
1405 if ( $msg === true ) {
1406 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1408 $this->addDeprecation( $msg, "$feature$v" );
1411 } elseif ( $required ) {
1412 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1419 * Handle when a parameter was Unicode-normalized
1421 * @param string $paramName Unprefixed parameter name
1422 * @param string $value Input that will be used.
1423 * @param string $rawValue Input before normalization.
1425 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1426 $encParamName = $this->encodeParamName( $paramName );
1427 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1431 * Split a multi-valued parameter string, like explode()
1433 * @param string $value
1437 protected function explodeMultiValue( $value, $limit ) {
1438 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1440 $value = substr( $value, 1 );
1445 return explode( $sep, $value, $limit );
1449 * Return an array of values that were given in a 'a|b|c' notation,
1450 * after it optionally validates them against the list allowed values.
1452 * @param string $valueName The name of the parameter (for error
1454 * @param mixed $value The value being parsed
1455 * @param bool $allowMultiple Can $value contain more than one value
1457 * @param string[]|null $allowedValues An array of values to check against. If
1458 * null, all values are accepted.
1459 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1460 * if this behavior should not be allowed
1461 * @param int|null $limit1 Maximum number of values, for normal users.
1462 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1463 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1465 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1466 $allSpecifier = null, $limit1 = null, $limit2 = null
1468 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1471 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1472 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1474 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1475 // because it unstubs $wgUser
1476 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1477 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1481 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1482 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1484 return $allowedValues;
1487 if ( count( $valuesList ) > $sizeLimit ) {
1488 $this->dieWithError(
1489 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1490 "too-many-$valueName"
1494 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1495 // T35482 - Allow entries with | in them for non-multiple values
1496 if ( in_array( $value, $allowedValues, true ) ) {
1500 $values = array_map( function ( $v ) {
1501 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1502 }, $allowedValues );
1503 $this->dieWithError( [
1504 'apierror-multival-only-one-of',
1506 Message
::listParam( $values ),
1508 ], "multival_$valueName" );
1511 if ( is_array( $allowedValues ) ) {
1512 // Check for unknown values
1513 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1514 if ( count( $unknown ) ) {
1515 if ( $allowMultiple ) {
1516 $this->addWarning( [
1517 'apiwarn-unrecognizedvalues',
1519 Message
::listParam( $unknown, 'comma' ),
1523 $this->dieWithError(
1524 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1525 "unknown_$valueName"
1529 // Now throw them out
1530 $valuesList = array_intersect( $valuesList, $allowedValues );
1533 return $allowMultiple ?
$valuesList : $valuesList[0];
1537 * Validate the value against the minimum and user/bot maximum limits.
1538 * Prints usage info on failure.
1539 * @param string $paramName Parameter name
1540 * @param int &$value Parameter value
1541 * @param int|null $min Minimum value
1542 * @param int|null $max Maximum value for users
1543 * @param int|null $botMax Maximum value for sysops/bots
1544 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1546 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1547 $enforceLimits = false
1549 if ( !is_null( $min ) && $value < $min ) {
1550 $msg = ApiMessage
::create(
1551 [ 'apierror-integeroutofrange-belowminimum',
1552 $this->encodeParamName( $paramName ), $min, $value ],
1553 'integeroutofrange',
1554 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1556 $this->warnOrDie( $msg, $enforceLimits );
1560 // Minimum is always validated, whereas maximum is checked only if not
1561 // running in internal call mode
1562 if ( $this->getMain()->isInternalMode() ) {
1566 // Optimization: do not check user's bot status unless really needed -- skips db query
1567 // assumes $botMax >= $max
1568 if ( !is_null( $max ) && $value > $max ) {
1569 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1570 if ( $value > $botMax ) {
1571 $msg = ApiMessage
::create(
1572 [ 'apierror-integeroutofrange-abovebotmax',
1573 $this->encodeParamName( $paramName ), $botMax, $value ],
1574 'integeroutofrange',
1575 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1577 $this->warnOrDie( $msg, $enforceLimits );
1581 $msg = ApiMessage
::create(
1582 [ 'apierror-integeroutofrange-abovemax',
1583 $this->encodeParamName( $paramName ), $max, $value ],
1584 'integeroutofrange',
1585 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1587 $this->warnOrDie( $msg, $enforceLimits );
1594 * Validate and normalize parameters of type 'timestamp'
1595 * @param string $value Parameter value
1596 * @param string $encParamName Parameter name
1597 * @return string Validated and normalized parameter
1599 protected function validateTimestamp( $value, $encParamName ) {
1600 // Confusing synonyms for the current time accepted by wfTimestamp()
1601 // (wfTimestamp() also accepts various non-strings and the string of 14
1602 // ASCII NUL bytes, but those can't get here)
1604 $this->addDeprecation(
1605 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1606 'unclear-"now"-timestamp'
1608 return wfTimestamp( TS_MW
);
1611 // Explicit synonym for the current time
1612 if ( $value === 'now' ) {
1613 return wfTimestamp( TS_MW
);
1616 $timestamp = wfTimestamp( TS_MW
, $value );
1617 if ( $timestamp === false ) {
1618 $this->dieWithError(
1619 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1620 "badtimestamp_{$encParamName}"
1628 * Validate the supplied token.
1631 * @param string $token Supplied token
1632 * @param array $params All supplied parameters for the module
1634 * @throws MWException
1636 final public function validateToken( $token, array $params ) {
1637 $tokenType = $this->needsToken();
1638 $salts = ApiQueryTokens
::getTokenTypeSalts();
1639 if ( !isset( $salts[$tokenType] ) ) {
1640 throw new MWException(
1641 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1642 'without registering it'
1646 $tokenObj = ApiQueryTokens
::getToken(
1647 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1649 if ( $tokenObj->match( $token ) ) {
1653 $webUiSalt = $this->getWebUITokenSalt( $params );
1654 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1666 * Validate and normalize parameters of type 'user'
1667 * @param string $value Parameter value
1668 * @param string $encParamName Parameter name
1669 * @return string Validated and normalized parameter
1671 private function validateUser( $value, $encParamName ) {
1672 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1676 $name = User
::getCanonicalName( $value, 'valid' );
1677 if ( $name !== false ) {
1682 // We allow ranges as well, for blocks.
1683 IP
::isIPAddress( $value ) ||
1684 // See comment for User::isIP. We don't just call that function
1685 // here because it also returns true for things like
1686 // 300.300.300.300 that are neither valid usernames nor valid IP
1689 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1693 return IP
::sanitizeIP( $value );
1696 $this->dieWithError(
1697 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1698 "baduser_{$encParamName}"
1704 /************************************************************************//**
1705 * @name Utility methods
1710 * Set a watch (or unwatch) based the based on a watchlist parameter.
1711 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1712 * @param Title $titleObj The article's title to change
1713 * @param string|null $userOption The user option to consider when $watch=preferences
1715 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1716 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1717 if ( $value === null ) {
1721 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1725 * Gets the user for whom to get the watchlist
1727 * @param array $params
1730 public function getWatchlistUser( $params ) {
1731 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1732 $user = User
::newFromName( $params['owner'], false );
1733 if ( !( $user && $user->getId() ) ) {
1734 $this->dieWithError(
1735 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1738 $token = $user->getOption( 'watchlisttoken' );
1739 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1740 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1743 if ( !$this->getUser()->isLoggedIn() ) {
1744 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1746 $this->checkUserRightsAny( 'viewmywatchlist' );
1747 $user = $this->getUser();
1754 * Create a Message from a string or array
1756 * A string is used as a message key. An array has the message key as the
1757 * first value and message parameters as subsequent values.
1760 * @param string|array|Message $msg
1761 * @param IContextSource $context
1762 * @param array|null $params
1763 * @return Message|null
1765 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1766 if ( is_string( $msg ) ) {
1767 $msg = wfMessage( $msg );
1768 } elseif ( is_array( $msg ) ) {
1769 $msg = wfMessage( ...$msg );
1771 if ( !$msg instanceof Message
) {
1775 $msg->setContext( $context );
1777 $msg->params( $params );
1784 * Turn an array of message keys or key+param arrays into a Status
1786 * @param array $errors
1787 * @param User|null $user
1790 public function errorArrayToStatus( array $errors, User
$user = null ) {
1791 if ( $user === null ) {
1792 $user = $this->getUser();
1795 $status = Status
::newGood();
1796 foreach ( $errors as $error ) {
1797 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1798 $status->fatal( ApiMessage
::create(
1801 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1803 } elseif ( is_array( $error ) && $error[0] === 'blockedtext-partial' && $user->getBlock() ) {
1804 $status->fatal( ApiMessage
::create(
1805 'apierror-blocked-partial',
1807 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1809 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1810 $status->fatal( ApiMessage
::create(
1811 'apierror-autoblocked',
1813 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1815 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1816 $status->fatal( ApiMessage
::create(
1817 'apierror-systemblocked',
1819 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1822 $status->fatal( ...(array)$error );
1829 * Call wfTransactionalTimeLimit() if this request was POSTed
1832 protected function useTransactionalTimeLimit() {
1833 if ( $this->getRequest()->wasPosted() ) {
1834 wfTransactionalTimeLimit();
1839 * Filter out-of-range values from a list of positive integer IDs
1841 * @param array $fields Array of pairs of table and field to check
1842 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1843 * expected to be stringified ints.
1844 * @return (string|int)[] Filtered IDs.
1846 protected function filterIDs( $fields, array $ids ) {
1849 foreach ( $fields as list( $table, $field ) ) {
1850 if ( isset( self
::$filterIDsCache[$table][$field] ) ) {
1851 $row = self
::$filterIDsCache[$table][$field];
1853 $row = $this->getDB()->selectRow(
1856 'min_id' => "MIN($field)",
1857 'max_id' => "MAX($field)",
1862 self
::$filterIDsCache[$table][$field] = $row;
1864 $min = min( $min, $row->min_id
);
1865 $max = max( $max, $row->max_id
);
1867 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1868 return ( is_int( $id ) && $id >= 0 ||
ctype_digit( $id ) )
1869 && $id >= $min && $id <= $max;
1875 /************************************************************************//**
1876 * @name Warning and error reporting
1881 * Add a warning for this module.
1883 * Users should monitor this section to notice any changes in API. Multiple
1884 * calls to this function will result in multiple warning messages.
1886 * If $msg is not an ApiMessage, the message code will be derived from the
1887 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1890 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1891 * @param string|null $code See ApiErrorFormatter::addWarning()
1892 * @param array|null $data See ApiErrorFormatter::addWarning()
1894 public function addWarning( $msg, $code = null, $data = null ) {
1895 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1899 * Add a deprecation warning for this module.
1901 * A combination of $this->addWarning() and $this->logFeatureUsage()
1904 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1905 * @param string|null $feature See ApiBase::logFeatureUsage()
1906 * @param array|null $data See ApiErrorFormatter::addWarning()
1908 public function addDeprecation( $msg, $feature, $data = [] ) {
1909 $data = (array)$data;
1910 if ( $feature !== null ) {
1911 $data['feature'] = $feature;
1912 $this->logFeatureUsage( $feature );
1914 $this->addWarning( $msg, 'deprecation', $data );
1916 // No real need to deduplicate here, ApiErrorFormatter does that for
1917 // us (assuming the hook is deterministic).
1918 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1919 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1920 if ( count( $msgs ) > 1 ) {
1921 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1922 $msg = ( new RawMessage( $key ) )->params( $msgs );
1924 $msg = reset( $msgs );
1926 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1930 * Add an error for this module without aborting
1932 * If $msg is not an ApiMessage, the message code will be derived from the
1933 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1935 * @note If you want to abort processing, use self::dieWithError() instead.
1937 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1938 * @param string|null $code See ApiErrorFormatter::addError()
1939 * @param array|null $data See ApiErrorFormatter::addError()
1941 public function addError( $msg, $code = null, $data = null ) {
1942 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1946 * Add warnings and/or errors from a Status
1948 * @note If you want to abort processing, use self::dieStatus() instead.
1950 * @param StatusValue $status
1951 * @param string[] $types 'warning' and/or 'error'
1953 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1954 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1958 * Abort execution with an error
1960 * If $msg is not an ApiMessage, the message code will be derived from the
1961 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1964 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1965 * @param string|null $code See ApiErrorFormatter::addError()
1966 * @param array|null $data See ApiErrorFormatter::addError()
1967 * @param int|null $httpCode HTTP error code to use
1968 * @throws ApiUsageException always
1970 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1971 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1975 * Abort execution with an error derived from an exception
1978 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1979 * @param array $options See ApiErrorFormatter::getMessageFromException()
1980 * @throws ApiUsageException always
1982 public function dieWithException( $exception, array $options = [] ) {
1983 $this->dieWithError(
1984 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1989 * Adds a warning to the output, else dies
1991 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1992 * @param bool $enforceLimits Whether this is an enforce (die)
1994 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1995 if ( $enforceLimits ) {
1996 $this->dieWithError( $msg );
1998 $this->addWarning( $msg );
2003 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2004 * error handler and die with an error message including block info.
2007 * @param Block $block The block used to generate the ApiUsageException
2008 * @throws ApiUsageException always
2010 public function dieBlocked( Block
$block ) {
2011 // Die using the appropriate message depending on block type
2012 if ( $block->getType() == Block
::TYPE_AUTO
) {
2013 $this->dieWithError(
2014 'apierror-autoblocked',
2016 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2018 } elseif ( !$block->isSitewide() ) {
2019 $this->dieWithError(
2020 'apierror-blocked-partial',
2022 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2025 $this->dieWithError(
2028 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2034 * Throw an ApiUsageException based on the Status object.
2037 * @since 1.29 Accepts a StatusValue
2038 * @param StatusValue $status
2039 * @throws ApiUsageException always
2041 public function dieStatus( StatusValue
$status ) {
2042 if ( $status->isGood() ) {
2043 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2046 // ApiUsageException needs a fatal status, but this method has
2047 // historically accepted any non-good status. Convert it if necessary.
2048 $status->setOK( false );
2049 if ( !$status->getErrorsByType( 'error' ) ) {
2050 $newStatus = Status
::newGood();
2051 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2052 $newStatus->fatal( $err['message'], ...$err['params'] );
2054 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2055 $newStatus->fatal( 'unknownerror-nocode' );
2057 $status = $newStatus;
2060 throw new ApiUsageException( $this, $status );
2064 * Helper function for readonly errors
2066 * @throws ApiUsageException always
2068 public function dieReadOnly() {
2069 $this->dieWithError(
2070 'apierror-readonly',
2072 [ 'readonlyreason' => wfReadOnlyReason() ]
2077 * Helper function for permission-denied errors
2079 * @param string|string[] $rights
2080 * @param User|null $user
2081 * @throws ApiUsageException if the user doesn't have any of the rights.
2082 * The error message is based on $rights[0].
2084 public function checkUserRightsAny( $rights, $user = null ) {
2086 $user = $this->getUser();
2088 $rights = (array)$rights;
2089 if ( !$user->isAllowedAny( ...$rights ) ) {
2090 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2095 * Helper function for permission-denied errors
2097 * @param Title $title
2098 * @param string|string[] $actions
2099 * @param User|null $user
2100 * @throws ApiUsageException if the user doesn't have all of the rights.
2102 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
2104 $user = $this->getUser();
2108 foreach ( (array)$actions as $action ) {
2109 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2113 // track block notices
2114 if ( $this->getConfig()->get( 'EnableBlockNoticeStats' ) ) {
2115 $this->trackBlockNotices( $errors );
2118 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2123 * Keep track of errors messages resulting from a block
2125 * @param array $errors
2127 private function trackBlockNotices( array $errors ) {
2128 $errorMessageKeys = [
2130 'blockedtext-partial',
2132 'systemblockedtext',
2135 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
2137 foreach ( $errors as $error ) {
2138 if ( in_array( $error[0], $errorMessageKeys ) ) {
2139 $wiki = $this->getConfig()->get( 'DBname' );
2140 $statsd->increment( 'BlockNotices.' . $wiki . '.MediaWikiApi.returned' );
2147 * Will only set a warning instead of failing if the global $wgDebugAPI
2148 * is set to true. Otherwise behaves exactly as self::dieWithError().
2151 * @param string|array|Message $msg
2152 * @param string|null $code
2153 * @param array|null $data
2154 * @param int|null $httpCode
2155 * @throws ApiUsageException
2157 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2158 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2159 $this->dieWithError( $msg, $code, $data, $httpCode );
2161 $this->addWarning( $msg, $code, $data );
2166 * Die with the 'badcontinue' error.
2168 * This call is common enough to make it into the base method.
2170 * @param bool $condition Will only die if this value is true
2171 * @throws ApiUsageException
2174 protected function dieContinueUsageIf( $condition ) {
2176 $this->dieWithError( 'apierror-badcontinue' );
2181 * Internal code errors should be reported with this method
2182 * @param string $method Method or function name
2183 * @param string $message Error message
2184 * @throws MWException always
2186 protected static function dieDebug( $method, $message ) {
2187 throw new MWException( "Internal error in $method: $message" );
2191 * Write logging information for API features to a debug log, for usage
2193 * @note Consider using $this->addDeprecation() instead to both warn and log.
2194 * @param string $feature Feature being used.
2196 public function logFeatureUsage( $feature ) {
2197 $request = $this->getRequest();
2198 $s = '"' . addslashes( $feature ) . '"' .
2199 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2200 ' "' . $request->getIP() . '"' .
2201 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2202 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2203 wfDebugLog( 'api-feature-usage', $s, 'private' );
2208 /************************************************************************//**
2209 * @name Help message generation
2214 * Return the summary message.
2216 * This is a one-line description of the module, suitable for display in a
2220 * @return string|array|Message
2222 protected function getSummaryMessage() {
2223 return "apihelp-{$this->getModulePath()}-summary";
2227 * Return the extended help text message.
2229 * This is additional text to display at the top of the help section, below
2233 * @return string|array|Message
2235 protected function getExtendedDescription() {
2237 "apihelp-{$this->getModulePath()}-extended-description",
2238 'api-help-no-extended-description',
2243 * Get final module summary
2248 public function getFinalSummary() {
2249 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2250 $this->getModulePrefix(),
2251 $this->getModuleName(),
2252 $this->getModulePath(),
2258 * Get final module description, after hooks have had a chance to tweak it as
2261 * @since 1.25, returns Message[] rather than string[]
2264 public function getFinalDescription() {
2265 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2266 $this->getModulePrefix(),
2267 $this->getModuleName(),
2268 $this->getModulePath(),
2270 $extendedDescription = self
::makeMessage(
2271 $this->getExtendedDescription(), $this->getContext(), [
2272 $this->getModulePrefix(),
2273 $this->getModuleName(),
2274 $this->getModulePath(),
2278 $msgs = [ $summary, $extendedDescription ];
2280 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2286 * Get final list of parameters, after hooks have had a chance to
2287 * tweak it as needed.
2289 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2290 * @return array|bool False on no parameters
2291 * @since 1.21 $flags param added
2293 public function getFinalParams( $flags = 0 ) {
2294 $params = $this->getAllowedParams( $flags );
2299 if ( $this->needsToken() ) {
2300 $params['token'] = [
2301 self
::PARAM_TYPE
=> 'string',
2302 self
::PARAM_REQUIRED
=> true,
2303 self
::PARAM_SENSITIVE
=> true,
2304 self
::PARAM_HELP_MSG
=> [
2305 'api-help-param-token',
2306 $this->needsToken(),
2308 ] +
( $params['token'] ??
[] );
2311 // Avoid PHP 7.1 warning of passing $this by reference
2313 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2319 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2322 * @since 1.25, returns array of Message[] rather than array of string[]
2323 * @return array Keys are parameter names, values are arrays of Message objects
2325 public function getFinalParamDescription() {
2326 $prefix = $this->getModulePrefix();
2327 $name = $this->getModuleName();
2328 $path = $this->getModulePath();
2330 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2332 foreach ( $params as $param => $settings ) {
2333 if ( !is_array( $settings ) ) {
2337 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2338 $msg = $settings[self
::PARAM_HELP_MSG
];
2340 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2342 $msg = self
::makeMessage( $msg, $this->getContext(),
2343 [ $prefix, $param, $name, $path ] );
2345 self
::dieDebug( __METHOD__
,
2346 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2348 $msgs[$param] = [ $msg ];
2350 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2351 $settings[self
::PARAM_TYPE
] === 'submodule'
2353 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2354 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2356 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2358 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2359 $map[$submoduleName] = $prefix . $submoduleName;
2364 $deprecatedSubmodules = [];
2365 foreach ( $map as $v => $m ) {
2366 $arr = &$submodules;
2367 $isDeprecated = false;
2370 $submod = $this->getModuleFromPath( $m );
2372 $summary = $submod->getFinalSummary();
2373 $isDeprecated = $submod->isDeprecated();
2374 if ( $isDeprecated ) {
2375 $arr = &$deprecatedSubmodules;
2378 } catch ( ApiUsageException
$ex ) {
2382 $key = $summary->getKey();
2383 $params = $summary->getParams();
2385 $key = 'api-help-undocumented-module';
2388 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2389 $arr[] = $m->setContext( $this->getContext() );
2391 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2392 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2393 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2394 self
::dieDebug( __METHOD__
,
2395 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2397 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2398 self
::dieDebug( __METHOD__
,
2399 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2400 'ApiBase::PARAM_TYPE is an array' );
2403 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2404 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2406 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2407 if ( isset( $valueMsgs[$value] ) ) {
2408 $msg = $valueMsgs[$value];
2410 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2412 $m = self
::makeMessage( $msg, $this->getContext(),
2413 [ $prefix, $param, $name, $path, $value ] );
2415 $m = new ApiHelpParamValueMessage(
2417 [ $m->getKey(), 'api-help-param-no-description' ],
2419 isset( $deprecatedValues[$value] )
2421 $msgs[$param][] = $m->setContext( $this->getContext() );
2423 self
::dieDebug( __METHOD__
,
2424 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2429 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2430 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2431 self
::dieDebug( __METHOD__
,
2432 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2434 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2435 $m = self
::makeMessage( $m, $this->getContext(),
2436 [ $prefix, $param, $name, $path ] );
2438 $msgs[$param][] = $m;
2440 self
::dieDebug( __METHOD__
,
2441 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2447 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2453 * Generates the list of flags for the help screen and for action=paraminfo
2455 * Corresponding messages: api-help-flag-deprecated,
2456 * api-help-flag-internal, api-help-flag-readrights,
2457 * api-help-flag-writerights, api-help-flag-mustbeposted
2461 protected function getHelpFlags() {
2464 if ( $this->isDeprecated() ) {
2465 $flags[] = 'deprecated';
2467 if ( $this->isInternal() ) {
2468 $flags[] = 'internal';
2470 if ( $this->isReadMode() ) {
2471 $flags[] = 'readrights';
2473 if ( $this->isWriteMode() ) {
2474 $flags[] = 'writerights';
2476 if ( $this->mustBePosted() ) {
2477 $flags[] = 'mustbeposted';
2484 * Returns information about the source of this module, if known
2486 * Returned array is an array with the following keys:
2487 * - path: Install path
2488 * - name: Extension name, or "MediaWiki" for core
2489 * - namemsg: (optional) i18n message key for a display name
2490 * - license-name: (optional) Name of license
2492 * @return array|null
2494 protected function getModuleSourceInfo() {
2497 if ( $this->mModuleSource
!== false ) {
2498 return $this->mModuleSource
;
2501 // First, try to find where the module comes from...
2502 $rClass = new ReflectionClass( $this );
2503 $path = $rClass->getFileName();
2506 $this->mModuleSource
= null;
2509 $path = realpath( $path ) ?
: $path;
2511 // Build map of extension directories to extension info
2512 if ( self
::$extensionInfo === null ) {
2513 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2514 self
::$extensionInfo = [
2515 realpath( __DIR__
) ?
: __DIR__
=> [
2517 'name' => 'MediaWiki',
2518 'license-name' => 'GPL-2.0-or-later',
2520 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2521 realpath( $extDir ) ?
: $extDir => null,
2527 'license-name' => null,
2529 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2530 foreach ( $group as $ext ) {
2531 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2532 // This shouldn't happen, but does anyway.
2536 $extpath = $ext['path'];
2537 if ( !is_dir( $extpath ) ) {
2538 $extpath = dirname( $extpath );
2540 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2541 array_intersect_key( $ext, $keep );
2544 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2545 $extpath = $ext['path'];
2546 if ( !is_dir( $extpath ) ) {
2547 $extpath = dirname( $extpath );
2549 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2550 array_intersect_key( $ext, $keep );
2554 // Now traverse parent directories until we find a match or run out of
2557 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2559 $this->mModuleSource
= self
::$extensionInfo[$path];
2560 return $this->mModuleSource
;
2564 $path = dirname( $path );
2565 } while ( $path !== $oldpath );
2567 // No idea what extension this might be.
2568 $this->mModuleSource
= null;
2573 * Called from ApiHelp before the pieces are joined together and returned.
2575 * This exists mainly for ApiMain to add the Permissions and Credits
2576 * sections. Other modules probably don't need it.
2578 * @param string[] &$help Array of help data
2579 * @param array $options Options passed to ApiHelp::getHelp
2580 * @param array &$tocData If a TOC is being generated, this array has keys
2581 * as anchors in the page and values as for Linker::generateTOC().
2583 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2588 /************************************************************************//**
2594 * Returns the description string for this module
2596 * Ignored if an i18n message exists for
2597 * "apihelp-{$this->getModulePath()}-description".
2599 * @deprecated since 1.25
2600 * @return Message|string|array|false
2602 protected function getDescription() {
2603 wfDeprecated( __METHOD__
, '1.25' );
2608 * Returns an array of parameter descriptions.
2610 * For each parameter, ignored if an i18n message exists for the parameter.
2611 * By default that message is
2612 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2613 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2614 * self::getFinalParams().
2616 * @deprecated since 1.25
2617 * @return array|bool False on no parameter descriptions
2619 protected function getParamDescription() {
2620 wfDeprecated( __METHOD__
, '1.25' );
2625 * Returns usage examples for this module.
2627 * Return value as an array is either:
2628 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2630 * - sequential numeric keys with even-numbered keys being display-text
2631 * and odd-numbered keys being partial urls
2632 * - partial URLs as keys with display-text (string or array-to-be-joined)
2634 * Return value as a string is the same as an array with a numeric key and
2635 * that value, and boolean false means "no examples".
2637 * @deprecated since 1.25, use getExamplesMessages() instead
2638 * @return bool|string|array
2640 protected function getExamples() {
2641 wfDeprecated( __METHOD__
, '1.25' );
2646 * Return the description message.
2648 * This is additional text to display on the help page after the summary.
2650 * @deprecated since 1.30
2651 * @return string|array|Message
2653 protected function getDescriptionMessage() {
2654 wfDeprecated( __METHOD__
, '1.30' );
2656 "apihelp-{$this->getModulePath()}-description",
2657 "apihelp-{$this->getModulePath()}-summary",
2662 * Truncate an array to a certain length.
2663 * @deprecated since 1.32, no replacement
2664 * @param array &$arr Array to truncate
2665 * @param int $limit Maximum length
2666 * @return bool True if the array was truncated, false otherwise
2668 public static function truncateArray( &$arr, $limit ) {
2669 wfDeprecated( __METHOD__
, '1.32' );
2671 while ( count( $arr ) > $limit ) {
2683 * For really cool vim folding this needs to be at the end:
2684 * vim: foldmarker=@{,@} foldmethod=marker