3 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\IDatabase
;
26 * This abstract class implements many basic API functions, and is the base of
28 * The class functions are divided into several areas of functionality:
30 * Module parameters: Derived classes can define getAllowedParams() to specify
31 * which parameters to expect, how to parse and validate them.
33 * Self-documentation: code to allow the API to document its own state
37 abstract class ApiBase
extends ContextSource
{
40 * @name Constants for ::getAllowedParams() arrays
41 * These constants are keys in the arrays returned by ::getAllowedParams()
42 * and accepted by ::getParameterFromSettings() that define how the
43 * parameters coming in from the request are to be interpreted.
47 /** (null|boolean|integer|string) Default value of the parameter. */
50 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
51 const PARAM_ISMULTI
= 1;
54 * (string|string[]) Either an array of allowed value strings, or a string
55 * type as described below. If not specified, will be determined from the
58 * Supported string types are:
59 * - boolean: A boolean parameter, returned as false if the parameter is
60 * omitted and true if present (even with a falsey value, i.e. it works
61 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
62 * Cannot be used with PARAM_ISMULTI.
63 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
64 * PARAM_RANGE_ENFORCE.
65 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
66 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
67 * specified. Cannot be used with PARAM_ISMULTI.
68 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
69 * support easily specifying all namespaces.
71 * - password: Any non-empty string. Input value is private or sensitive.
72 * <input type="password"> would be an appropriate HTML form field.
73 * - string: Any non-empty string, not expected to be very long or contain newlines.
74 * <input type="text"> would be an appropriate HTML form field.
75 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
76 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
77 * used with PARAM_ISMULTI.
78 * - text: Any non-empty string, expected to be very long or contain newlines.
79 * <textarea> would be an appropriate HTML form field.
80 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
81 * string 'now' representing the current timestamp. Will be returned in
83 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
84 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
85 * Cannot be used with PARAM_ISMULTI.
89 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
93 * (integer) Max value allowed for the parameter for users with the
94 * apihighlimits right, for PARAM_TYPE 'limit'.
98 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
101 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
102 const PARAM_ALLOW_DUPLICATES
= 6;
104 /** (boolean) Is the parameter deprecated (will show a warning)? */
105 const PARAM_DEPRECATED
= 7;
108 * (boolean) Is the parameter required?
111 const PARAM_REQUIRED
= 8;
114 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
117 const PARAM_RANGE_ENFORCE
= 9;
120 * (string|array|Message) Specify an alternative i18n documentation message
121 * for this parameter. Default is apihelp-{$path}-param-{$param}.
124 const PARAM_HELP_MSG
= 10;
127 * ((string|array|Message)[]) Specify additional i18n messages to append to
128 * the normal message for this parameter.
131 const PARAM_HELP_MSG_APPEND
= 11;
134 * (array) Specify additional information tags for the parameter. Value is
135 * an array of arrays, with the first member being the 'tag' for the info
136 * and the remaining members being the values. In the help, this is
137 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
138 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
141 const PARAM_HELP_MSG_INFO
= 12;
144 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
145 * those values to page titles which will be linked in the help.
148 const PARAM_VALUE_LINKS
= 13;
151 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
152 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
153 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
154 * Specify an empty array to use the default message key for all values.
157 const PARAM_HELP_MSG_PER_VALUE
= 14;
160 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
161 * submodule paths. Default is to use all modules in
162 * $this->getModuleManager() in the group matching the parameter name.
165 const PARAM_SUBMODULE_MAP
= 15;
168 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
169 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
172 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
175 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
176 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
177 * every possible value. If a string is set, it will be used in place of the asterisk.
180 const PARAM_ALL
= 17;
183 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
186 const PARAM_EXTRA_NAMESPACES
= 18;
189 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
190 * always sensitive regardless of the value of this field.
193 const PARAM_SENSITIVE
= 19;
196 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
197 * Keys are the deprecated parameter values, values define the warning
198 * message to emit: either boolean true (to use a default message) or a
199 * $msg for ApiBase::makeMessage().
202 const PARAM_DEPRECATED_VALUES
= 20;
205 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
208 const PARAM_ISMULTI_LIMIT1
= 21;
211 * (integer) Maximum number of values, for users with the apihighimits right.
212 * Must be used with PARAM_ISMULTI.
215 const PARAM_ISMULTI_LIMIT2
= 22;
218 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
221 const PARAM_MAX_BYTES
= 23;
224 * (integer) Maximum length of a string in characters (unicode codepoints).
227 const PARAM_MAX_CHARS
= 24;
230 * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
231 * placeholders in the parameter name and values are the names of (unprefixed) parameters from
232 * which the replacement values are taken.
234 * For example, a parameter "foo-{ns}-{title}" could be defined with
235 * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
236 * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
238 * All placeholders must be present in the parameter's name. Each target parameter must have
239 * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
240 * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
241 * A parameter cannot target itself.
245 const PARAM_TEMPLATE_VARS
= 25;
249 const ALL_DEFAULT_STRING
= '*';
251 /** Fast query, standard limit. */
252 const LIMIT_BIG1
= 500;
253 /** Fast query, apihighlimits limit. */
254 const LIMIT_BIG2
= 5000;
255 /** Slow query, standard limit. */
256 const LIMIT_SML1
= 50;
257 /** Slow query, apihighlimits limit. */
258 const LIMIT_SML2
= 500;
261 * getAllowedParams() flag: When set, the result could take longer to generate,
262 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
265 const GET_VALUES_FOR_HELP
= 1;
267 /** @var array Maps extension paths to info arrays */
268 private static $extensionInfo = null;
271 private $mMainModule;
273 private $mModuleName, $mModulePrefix;
274 private $mReplicaDB = null;
275 private $mParamCache = [];
276 /** @var array|null|bool */
277 private $mModuleSource = false;
280 * @param ApiMain $mainModule
281 * @param string $moduleName Name of this module
282 * @param string $modulePrefix Prefix to use for parameter names
284 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
285 $this->mMainModule
= $mainModule;
286 $this->mModuleName
= $moduleName;
287 $this->mModulePrefix
= $modulePrefix;
289 if ( !$this->isMain() ) {
290 $this->setContext( $mainModule->getContext() );
294 /************************************************************************//**
295 * @name Methods to implement
300 * Evaluates the parameters, performs the requested query, and sets up
301 * the result. Concrete implementations of ApiBase must override this
302 * method to provide whatever functionality their module offers.
303 * Implementations must not produce any output on their own and are not
304 * expected to handle any errors.
306 * The execute() method will be invoked directly by ApiMain immediately
307 * before the result of the module is output. Aside from the
308 * constructor, implementations should assume that no other methods
309 * will be called externally on the module before the result is
312 * The result data should be stored in the ApiResult object available
313 * through getResult().
315 abstract public function execute();
318 * Get the module manager, or null if this module has no sub-modules
320 * @return ApiModuleManager
322 public function getModuleManager() {
327 * If the module may only be used with a certain format module,
328 * it should override this method to return an instance of that formatter.
329 * A value of null means the default format will be used.
330 * @note Do not use this just because you don't want to support non-json
331 * formats. This should be used only when there is a fundamental
332 * requirement for a specific format.
333 * @return mixed Instance of a derived class of ApiFormatBase, or null
335 public function getCustomPrinter() {
340 * Returns usage examples for this module.
342 * Return value has query strings as keys, with values being either strings
343 * (message key), arrays (message key + parameter), or Message objects.
345 * Do not call this base class implementation when overriding this method.
350 protected function getExamplesMessages() {
355 * Return links to more detailed help pages about the module.
356 * @since 1.25, returning boolean false is deprecated
357 * @return string|array
359 public function getHelpUrls() {
364 * Returns an array of allowed parameters (parameter name) => (default
365 * value) or (parameter name) => (array with PARAM_* constants as keys)
366 * Don't call this function directly: use getFinalParams() to allow
367 * hooks to modify parameters as needed.
369 * Some derived classes may choose to handle an integer $flags parameter
370 * in the overriding methods. Callers of this method can pass zero or
371 * more OR-ed flags like GET_VALUES_FOR_HELP.
375 protected function getAllowedParams( /* $flags = 0 */ ) {
376 // int $flags is not declared because it causes "Strict standards"
377 // warning. Most derived classes do not implement it.
382 * Indicates if this module needs maxlag to be checked
385 public function shouldCheckMaxlag() {
390 * Indicates whether this module requires read rights
393 public function isReadMode() {
398 * Indicates whether this module requires write mode
400 * This should return true for modules that may require synchronous database writes.
401 * Modules that do not need such writes should also not rely on master database access,
402 * since only read queries are needed and each master DB is a single point of failure.
403 * Additionally, requests that only need replica DBs can be efficiently routed to any
404 * datacenter via the Promise-Non-Write-API-Action header.
408 public function isWriteMode() {
413 * Indicates whether this module must be called with a POST request
416 public function mustBePosted() {
417 return $this->needsToken() !== false;
421 * Indicates whether this module is deprecated
425 public function isDeprecated() {
430 * Indicates whether this module is "internal"
431 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
435 public function isInternal() {
440 * Returns the token type this module requires in order to execute.
442 * Modules are strongly encouraged to use the core 'csrf' type unless they
443 * have specialized security needs. If the token type is not one of the
444 * core types, you must use the ApiQueryTokensRegisterTypes hook to
447 * Returning a non-falsey value here will force the addition of an
448 * appropriate 'token' parameter in self::getFinalParams(). Also,
449 * self::mustBePosted() must return true when tokens are used.
451 * In previous versions of MediaWiki, true was a valid return value.
452 * Returning true will generate errors indicating that the API module needs
455 * @return string|false
457 public function needsToken() {
462 * Fetch the salt used in the Web UI corresponding to this module.
464 * Only override this if the Web UI uses a token with a non-constant salt.
467 * @param array $params All supplied parameters for the module
468 * @return string|array|null
470 protected function getWebUITokenSalt( array $params ) {
475 * Returns data for HTTP conditional request mechanisms.
478 * @param string $condition Condition being queried:
479 * - last-modified: Return a timestamp representing the maximum of the
480 * last-modified dates for all resources involved in the request. See
481 * RFC 7232 § 2.2 for semantics.
482 * - etag: Return an entity-tag representing the state of all resources involved
483 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
484 * @return string|bool|null As described above, or null if no value is available.
486 public function getConditionalRequestData( $condition ) {
492 /************************************************************************//**
493 * @name Data access methods
498 * Get the name of the module being executed by this instance
501 public function getModuleName() {
502 return $this->mModuleName
;
506 * Get parameter prefix (usually two letters or an empty string).
509 public function getModulePrefix() {
510 return $this->mModulePrefix
;
514 * Get the main module
517 public function getMain() {
518 return $this->mMainModule
;
522 * Returns true if this module is the main module ($this === $this->mMainModule),
526 public function isMain() {
527 return $this === $this->mMainModule
;
531 * Get the parent of this module
533 * @return ApiBase|null
535 public function getParent() {
536 return $this->isMain() ?
null : $this->getMain();
540 * Returns true if the current request breaks the same-origin policy.
542 * For example, json with callbacks.
544 * https://en.wikipedia.org/wiki/Same-origin_policy
549 public function lacksSameOriginSecurity() {
550 // Main module has this method overridden
551 // Safety - avoid infinite loop:
552 if ( $this->isMain() ) {
553 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
556 return $this->getMain()->lacksSameOriginSecurity();
560 * Get the path to this module
565 public function getModulePath() {
566 if ( $this->isMain() ) {
568 } elseif ( $this->getParent()->isMain() ) {
569 return $this->getModuleName();
571 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
576 * Get a module from its module path
579 * @param string $path
580 * @return ApiBase|null
581 * @throws ApiUsageException
583 public function getModuleFromPath( $path ) {
584 $module = $this->getMain();
585 if ( $path === 'main' ) {
589 $parts = explode( '+', $path );
590 if ( count( $parts ) === 1 ) {
591 // In case the '+' was typed into URL, it resolves as a space
592 $parts = explode( ' ', $path );
595 $count = count( $parts );
596 for ( $i = 0; $i < $count; $i++
) {
598 $manager = $parent->getModuleManager();
599 if ( $manager === null ) {
600 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
601 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
603 $module = $manager->getModule( $parts[$i] );
605 if ( $module === null ) {
606 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
608 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
618 * Get the result object
621 public function getResult() {
622 // Main module has getResult() method overridden
623 // Safety - avoid infinite loop:
624 if ( $this->isMain() ) {
625 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
628 return $this->getMain()->getResult();
632 * Get the error formatter
633 * @return ApiErrorFormatter
635 public function getErrorFormatter() {
636 // Main module has getErrorFormatter() method overridden
637 // Safety - avoid infinite loop:
638 if ( $this->isMain() ) {
639 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
642 return $this->getMain()->getErrorFormatter();
646 * Gets a default replica DB connection object
649 protected function getDB() {
650 if ( !isset( $this->mReplicaDB
) ) {
651 $this->mReplicaDB
= wfGetDB( DB_REPLICA
, 'api' );
654 return $this->mReplicaDB
;
658 * Get the continuation manager
659 * @return ApiContinuationManager|null
661 public function getContinuationManager() {
662 // Main module has getContinuationManager() method overridden
663 // Safety - avoid infinite loop:
664 if ( $this->isMain() ) {
665 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
668 return $this->getMain()->getContinuationManager();
672 * Set the continuation manager
673 * @param ApiContinuationManager|null $manager
675 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
676 // Main module has setContinuationManager() method overridden
677 // Safety - avoid infinite loop:
678 if ( $this->isMain() ) {
679 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
682 $this->getMain()->setContinuationManager( $manager );
687 /************************************************************************//**
688 * @name Parameter handling
693 * Indicate if the module supports dynamically-determined parameters that
694 * cannot be included in self::getAllowedParams().
695 * @return string|array|Message|null Return null if the module does not
696 * support additional dynamic parameters, otherwise return a message
699 public function dynamicParameterDocumentation() {
704 * This method mangles parameter name based on the prefix supplied to the constructor.
705 * Override this method to change parameter name during runtime
706 * @param string|string[] $paramName Parameter name
707 * @return string|string[] Prefixed parameter name
708 * @since 1.29 accepts an array of strings
710 public function encodeParamName( $paramName ) {
711 if ( is_array( $paramName ) ) {
712 return array_map( function ( $name ) {
713 return $this->mModulePrefix
. $name;
716 return $this->mModulePrefix
. $paramName;
721 * Using getAllowedParams(), this function makes an array of the values
722 * provided by the user, with key being the name of the variable, and
723 * value - validated value from user or default. limits will not be
724 * parsed if $parseLimit is set to false; use this when the max
725 * limit is not definitive yet, e.g. when getting revisions.
726 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
727 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
728 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
729 * Returned parameter values might be ApiUsageException instances.
732 public function extractRequestParams( $options = [] ) {
733 if ( is_bool( $options ) ) {
734 $options = [ 'parseLimit' => $options ];
737 'parseLimit' => true,
741 $parseLimit = (bool)$options['parseLimit'];
743 // Cache parameters, for performance and to avoid T26564.
744 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
745 $params = $this->getFinalParams() ?
: [];
749 // Process all non-templates and save templates for secondary
752 foreach ( $params as $paramName => $paramSettings ) {
753 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
754 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
757 $results[$paramName] = $this->getParameterFromSettings(
758 $paramName, $paramSettings, $parseLimit
760 } catch ( ApiUsageException
$ex ) {
761 $results[$paramName] = $ex;
766 // Now process all the templates by successively replacing the
767 // placeholders with all client-supplied values.
768 // This bit duplicates JavaScript logic in
769 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
770 // If you update this, see if that needs updating too.
771 while ( $toProcess ) {
772 list( $name, $targets, $settings ) = array_shift( $toProcess );
774 foreach ( $targets as $placeholder => $target ) {
775 if ( !array_key_exists( $target, $results ) ) {
776 // The target wasn't processed yet, try the next one.
777 // If all hit this case, the parameter has no expansions.
780 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
781 // The target was processed but has no (valid) values.
782 // That means it has no expansions.
786 // Expand this target in the name and all other targets,
787 // then requeue if there are more targets left or put in
788 // $results if all are done.
789 unset( $targets[$placeholder] );
790 $placeholder = '{' . $placeholder . '}';
791 foreach ( $results[$target] as $value ) {
792 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
793 // Skip values that make invalid parameter names.
794 $encTargetName = $this->encodeParamName( $target );
795 if ( !isset( $warned[$encTargetName][$value] ) ) {
796 $warned[$encTargetName][$value] = true;
798 'apiwarn-ignoring-invalid-templated-value',
799 wfEscapeWikiText( $encTargetName ),
800 wfEscapeWikiText( $value ),
806 $newName = str_replace( $placeholder, $value, $name );
809 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
810 } catch ( ApiUsageException
$ex ) {
811 $results[$newName] = $ex;
815 foreach ( $targets as $k => $v ) {
816 $newTargets[$k] = str_replace( $placeholder, $value, $v );
818 $toProcess[] = [ $newName, $newTargets, $settings ];
825 $this->mParamCache
[$parseLimit] = $results;
828 $ret = $this->mParamCache
[$parseLimit];
829 if ( !$options['safeMode'] ) {
830 foreach ( $ret as $v ) {
831 if ( $v instanceof ApiUsageException
) {
837 return $this->mParamCache
[$parseLimit];
841 * Get a value for the given parameter
842 * @param string $paramName Parameter name
843 * @param bool $parseLimit See extractRequestParams()
844 * @return mixed Parameter value
846 protected function getParameter( $paramName, $parseLimit = true ) {
847 $ret = $this->extractRequestParams( [
848 'parseLimit' => $parseLimit,
851 if ( $ret instanceof ApiUsageException
) {
858 * Die if none or more than one of a certain set of parameters is set and not false.
860 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
861 * @param string $required,... Names of parameters of which exactly one must be set
863 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
864 $required = func_get_args();
865 array_shift( $required );
867 $intersection = array_intersect( array_keys( array_filter( $params,
868 [ $this, 'parameterNotEmpty' ] ) ), $required );
870 if ( count( $intersection ) > 1 ) {
871 $this->dieWithError( [
872 'apierror-invalidparammix',
873 Message
::listParam( array_map(
875 return '<var>' . $this->encodeParamName( $p ) . '</var>';
877 array_values( $intersection )
879 count( $intersection ),
881 } elseif ( count( $intersection ) == 0 ) {
882 $this->dieWithError( [
883 'apierror-missingparam-one-of',
884 Message
::listParam( array_map(
886 return '<var>' . $this->encodeParamName( $p ) . '</var>';
888 array_values( $required )
896 * Die if more than one of a certain set of parameters is set and not false.
898 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
899 * @param string $required,... Names of parameters of which at most one must be set
901 public function requireMaxOneParameter( $params, $required /*...*/ ) {
902 $required = func_get_args();
903 array_shift( $required );
905 $intersection = array_intersect( array_keys( array_filter( $params,
906 [ $this, 'parameterNotEmpty' ] ) ), $required );
908 if ( count( $intersection ) > 1 ) {
909 $this->dieWithError( [
910 'apierror-invalidparammix',
911 Message
::listParam( array_map(
913 return '<var>' . $this->encodeParamName( $p ) . '</var>';
915 array_values( $intersection )
917 count( $intersection ),
923 * Die if none of a certain set of parameters is set and not false.
926 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
927 * @param string $required,... Names of parameters of which at least one must be set
929 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
930 $required = func_get_args();
931 array_shift( $required );
933 $intersection = array_intersect(
934 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
938 if ( count( $intersection ) == 0 ) {
939 $this->dieWithError( [
940 'apierror-missingparam-at-least-one-of',
941 Message
::listParam( array_map(
943 return '<var>' . $this->encodeParamName( $p ) . '</var>';
945 array_values( $required )
953 * Die if any of the specified parameters were found in the query part of
954 * the URL rather than the post body.
956 * @param string[] $params Parameters to check
957 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
959 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
960 // Skip if $wgDebugAPI is set or we're in internal mode
961 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
965 $queryValues = $this->getRequest()->getQueryValues();
967 foreach ( $params as $param ) {
968 if ( $prefix !== 'noprefix' ) {
969 $param = $this->encodeParamName( $param );
971 if ( array_key_exists( $param, $queryValues ) ) {
972 $badParams[] = $param;
978 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
984 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
986 * @param object $x Parameter to check is not null/false
989 private function parameterNotEmpty( $x ) {
990 return !is_null( $x ) && $x !== false;
994 * Get a WikiPage object from a title or pageid param, if possible.
995 * Can die, if no param is set or if the title or page id is not valid.
997 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
998 * @param bool|string $load Whether load the object's state from the database:
999 * - false: don't load (if the pageid is given, it will still be loaded)
1000 * - 'fromdb': load from a replica DB
1001 * - 'fromdbmaster': load from the master database
1004 public function getTitleOrPageId( $params, $load = false ) {
1005 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1008 if ( isset( $params['title'] ) ) {
1009 $titleObj = Title
::newFromText( $params['title'] );
1010 if ( !$titleObj ||
$titleObj->isExternal() ) {
1011 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1013 if ( !$titleObj->canExist() ) {
1014 $this->dieWithError( 'apierror-pagecannotexist' );
1016 $pageObj = WikiPage
::factory( $titleObj );
1017 if ( $load !== false ) {
1018 $pageObj->loadPageData( $load );
1020 } elseif ( isset( $params['pageid'] ) ) {
1021 if ( $load === false ) {
1024 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1026 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1034 * Get a Title object from a title or pageid param, if possible.
1035 * Can die, if no param is set or if the title or page id is not valid.
1038 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1041 public function getTitleFromTitleOrPageId( $params ) {
1042 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1045 if ( isset( $params['title'] ) ) {
1046 $titleObj = Title
::newFromText( $params['title'] );
1047 if ( !$titleObj ||
$titleObj->isExternal() ) {
1048 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1051 } elseif ( isset( $params['pageid'] ) ) {
1052 $titleObj = Title
::newFromID( $params['pageid'] );
1054 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1062 * Return true if we're to watch the page, false if not, null if no change.
1063 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1064 * @param Title $titleObj The page under consideration
1065 * @param string|null $userOption The user option to consider when $watchlist=preferences.
1066 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1069 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1070 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1072 switch ( $watchlist ) {
1080 # If the user is already watching, don't bother checking
1081 if ( $userWatching ) {
1084 # If no user option was passed, use watchdefault and watchcreations
1085 if ( is_null( $userOption ) ) {
1086 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1087 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1090 # Watch the article based on the user preference
1091 return $this->getUser()->getBoolOption( $userOption );
1094 return $userWatching;
1097 return $userWatching;
1102 * Using the settings determine the value for the given parameter
1104 * @param string $paramName Parameter name
1105 * @param array|mixed $paramSettings Default value or an array of settings
1106 * using PARAM_* constants.
1107 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1108 * @return mixed Parameter value
1110 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1111 // Some classes may decide to change parameter names
1112 $encParamName = $this->encodeParamName( $paramName );
1115 if ( !is_array( $paramSettings ) ) {
1117 self
::PARAM_DFLT
=> $paramSettings,
1121 $default = $paramSettings[self
::PARAM_DFLT
] ??
null;
1122 $multi = $paramSettings[self
::PARAM_ISMULTI
] ??
false;
1123 $multiLimit1 = $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] ??
null;
1124 $multiLimit2 = $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] ??
null;
1125 $type = $paramSettings[self
::PARAM_TYPE
] ??
null;
1126 $dupes = $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ??
false;
1127 $deprecated = $paramSettings[self
::PARAM_DEPRECATED
] ??
false;
1128 $deprecatedValues = $paramSettings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
1129 $required = $paramSettings[self
::PARAM_REQUIRED
] ??
false;
1130 $allowAll = $paramSettings[self
::PARAM_ALL
] ??
false;
1132 // When type is not given, and no choices, the type is the same as $default
1133 if ( !isset( $type ) ) {
1134 if ( isset( $default ) ) {
1135 $type = gettype( $default );
1137 $type = 'NULL'; // allow everything
1141 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1142 $this->getMain()->markParamsSensitive( $encParamName );
1145 if ( $type == 'boolean' ) {
1146 if ( isset( $default ) && $default !== false ) {
1147 // Having a default value of anything other than 'false' is not allowed
1150 "Boolean param $encParamName's default is set to '$default'. " .
1151 'Boolean parameters must default to false.'
1155 $value = $this->getMain()->getCheck( $encParamName );
1156 } elseif ( $type == 'upload' ) {
1157 if ( isset( $default ) ) {
1158 // Having a default value is not allowed
1161 "File upload param $encParamName's default is set to " .
1162 "'$default'. File upload parameters may not have a default." );
1165 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1167 $value = $this->getMain()->getUpload( $encParamName );
1168 if ( !$value->exists() ) {
1169 // This will get the value without trying to normalize it
1170 // (because trying to normalize a large binary file
1171 // accidentally uploaded as a field fails spectacularly)
1172 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1173 if ( $value !== null ) {
1174 $this->dieWithError(
1175 [ 'apierror-badupload', $encParamName ],
1176 "badupload_{$encParamName}"
1181 $value = $this->getMain()->getVal( $encParamName, $default );
1183 if ( isset( $value ) && $type == 'namespace' ) {
1184 $type = MWNamespace
::getValidNamespaces();
1185 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1186 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1188 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1190 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1191 // specify all namespaces irrespective of PARAM_ALL.
1194 if ( isset( $value ) && $type == 'submodule' ) {
1195 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1196 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1198 $type = $this->getModuleManager()->getNames( $paramName );
1202 $request = $this->getMain()->getRequest();
1203 $rawValue = $request->getRawVal( $encParamName );
1204 if ( $rawValue === null ) {
1205 $rawValue = $default;
1208 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1209 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1211 // This loses the potential checkTitleEncoding() transformation done by
1212 // WebRequest for $_GET. Let's call that a feature.
1213 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1215 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1219 // Check for NFC normalization, and warn
1220 if ( $rawValue !== $value ) {
1221 $this->handleParamNormalization( $paramName, $value, $rawValue );
1225 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1226 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1229 "For param $encParamName, PARAM_ALL collides with a possible value" );
1231 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1232 $value = $this->parseMultiValue(
1236 is_array( $type ) ?
$type : null,
1237 $allowAll ?
$allSpecifier : null,
1243 if ( isset( $value ) ) {
1244 // More validation only when choices were not given
1245 // choices were validated in parseMultiValue()
1246 if ( !is_array( $type ) ) {
1248 case 'NULL': // nothing to do
1253 if ( $required && $value === '' ) {
1254 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1257 case 'integer': // Force everything using intval() and optionally validate limits
1258 $min = $paramSettings[self
::PARAM_MIN
] ??
null;
1259 $max = $paramSettings[self
::PARAM_MAX
] ??
null;
1260 $enforceLimits = $paramSettings[self
::PARAM_RANGE_ENFORCE
] ??
false;
1262 if ( is_array( $value ) ) {
1263 $value = array_map( 'intval', $value );
1264 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1265 foreach ( $value as &$v ) {
1266 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1270 $value = intval( $value );
1271 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1272 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1277 if ( !$parseLimit ) {
1278 // Don't do any validation whatsoever
1281 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1282 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1286 "MAX1 or MAX2 are not defined for the limit $encParamName"
1290 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1292 $min = $paramSettings[self
::PARAM_MIN
] ??
0;
1293 if ( $value == 'max' ) {
1294 $value = $this->getMain()->canApiHighLimits()
1295 ?
$paramSettings[self
::PARAM_MAX2
]
1296 : $paramSettings[self
::PARAM_MAX
];
1297 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1299 $value = intval( $value );
1300 $this->validateLimit(
1304 $paramSettings[self
::PARAM_MAX
],
1305 $paramSettings[self
::PARAM_MAX2
]
1311 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1315 if ( is_array( $value ) ) {
1316 foreach ( $value as $key => $val ) {
1317 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1320 $value = $this->validateTimestamp( $value, $encParamName );
1324 if ( is_array( $value ) ) {
1325 foreach ( $value as $key => $val ) {
1326 $value[$key] = $this->validateUser( $val, $encParamName );
1329 $value = $this->validateUser( $value, $encParamName );
1332 case 'upload': // nothing to do
1335 // If change tagging was requested, check that the tags are valid.
1336 if ( !is_array( $value ) && !$multi ) {
1337 $value = [ $value ];
1339 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1340 if ( !$tagsStatus->isGood() ) {
1341 $this->dieStatus( $tagsStatus );
1345 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1349 // Throw out duplicates if requested
1350 if ( !$dupes && is_array( $value ) ) {
1351 $value = array_unique( $value );
1354 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1355 foreach ( (array)$value as $val ) {
1356 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1357 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1359 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1360 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1362 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1363 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1365 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1366 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1371 // Set a warning if a deprecated parameter has been passed
1372 if ( $deprecated && $value !== false ) {
1373 $feature = $encParamName;
1375 while ( !$m->isMain() ) {
1376 $p = $m->getParent();
1377 $name = $m->getModuleName();
1378 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1379 $feature = "{$param}={$name}&{$feature}";
1382 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1385 // Set a warning if a deprecated parameter value has been passed
1386 $usedDeprecatedValues = $deprecatedValues && $value !== false
1387 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1389 if ( $usedDeprecatedValues ) {
1390 $feature = "$encParamName=";
1392 while ( !$m->isMain() ) {
1393 $p = $m->getParent();
1394 $name = $m->getModuleName();
1395 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1396 $feature = "{$param}={$name}&{$feature}";
1399 foreach ( $usedDeprecatedValues as $v ) {
1400 $msg = $deprecatedValues[$v];
1401 if ( $msg === true ) {
1402 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1404 $this->addDeprecation( $msg, "$feature$v" );
1407 } elseif ( $required ) {
1408 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1415 * Handle when a parameter was Unicode-normalized
1417 * @param string $paramName Unprefixed parameter name
1418 * @param string $value Input that will be used.
1419 * @param string $rawValue Input before normalization.
1421 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1422 $encParamName = $this->encodeParamName( $paramName );
1423 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1427 * Split a multi-valued parameter string, like explode()
1429 * @param string $value
1433 protected function explodeMultiValue( $value, $limit ) {
1434 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1436 $value = substr( $value, 1 );
1441 return explode( $sep, $value, $limit );
1445 * Return an array of values that were given in a 'a|b|c' notation,
1446 * after it optionally validates them against the list allowed values.
1448 * @param string $valueName The name of the parameter (for error
1450 * @param mixed $value The value being parsed
1451 * @param bool $allowMultiple Can $value contain more than one value
1453 * @param string[]|null $allowedValues An array of values to check against. If
1454 * null, all values are accepted.
1455 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1456 * if this behavior should not be allowed
1457 * @param int|null $limit1 Maximum number of values, for normal users.
1458 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1459 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1461 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1462 $allSpecifier = null, $limit1 = null, $limit2 = null
1464 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1467 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1468 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1470 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1471 // because it unstubs $wgUser
1472 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1473 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1477 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1478 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1480 return $allowedValues;
1483 if ( count( $valuesList ) > $sizeLimit ) {
1484 $this->dieWithError(
1485 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1486 "too-many-$valueName"
1490 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1491 // T35482 - Allow entries with | in them for non-multiple values
1492 if ( in_array( $value, $allowedValues, true ) ) {
1496 $values = array_map( function ( $v ) {
1497 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1498 }, $allowedValues );
1499 $this->dieWithError( [
1500 'apierror-multival-only-one-of',
1502 Message
::listParam( $values ),
1504 ], "multival_$valueName" );
1507 if ( is_array( $allowedValues ) ) {
1508 // Check for unknown values
1509 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1510 if ( count( $unknown ) ) {
1511 if ( $allowMultiple ) {
1512 $this->addWarning( [
1513 'apiwarn-unrecognizedvalues',
1515 Message
::listParam( $unknown, 'comma' ),
1519 $this->dieWithError(
1520 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1521 "unknown_$valueName"
1525 // Now throw them out
1526 $valuesList = array_intersect( $valuesList, $allowedValues );
1529 return $allowMultiple ?
$valuesList : $valuesList[0];
1533 * Validate the value against the minimum and user/bot maximum limits.
1534 * Prints usage info on failure.
1535 * @param string $paramName Parameter name
1536 * @param int &$value Parameter value
1537 * @param int|null $min Minimum value
1538 * @param int|null $max Maximum value for users
1539 * @param int|null $botMax Maximum value for sysops/bots
1540 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1542 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1543 $enforceLimits = false
1545 if ( !is_null( $min ) && $value < $min ) {
1546 $msg = ApiMessage
::create(
1547 [ 'apierror-integeroutofrange-belowminimum',
1548 $this->encodeParamName( $paramName ), $min, $value ],
1549 'integeroutofrange',
1550 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1552 $this->warnOrDie( $msg, $enforceLimits );
1556 // Minimum is always validated, whereas maximum is checked only if not
1557 // running in internal call mode
1558 if ( $this->getMain()->isInternalMode() ) {
1562 // Optimization: do not check user's bot status unless really needed -- skips db query
1563 // assumes $botMax >= $max
1564 if ( !is_null( $max ) && $value > $max ) {
1565 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1566 if ( $value > $botMax ) {
1567 $msg = ApiMessage
::create(
1568 [ 'apierror-integeroutofrange-abovebotmax',
1569 $this->encodeParamName( $paramName ), $botMax, $value ],
1570 'integeroutofrange',
1571 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1573 $this->warnOrDie( $msg, $enforceLimits );
1577 $msg = ApiMessage
::create(
1578 [ 'apierror-integeroutofrange-abovemax',
1579 $this->encodeParamName( $paramName ), $max, $value ],
1580 'integeroutofrange',
1581 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1583 $this->warnOrDie( $msg, $enforceLimits );
1590 * Validate and normalize parameters of type 'timestamp'
1591 * @param string $value Parameter value
1592 * @param string $encParamName Parameter name
1593 * @return string Validated and normalized parameter
1595 protected function validateTimestamp( $value, $encParamName ) {
1596 // Confusing synonyms for the current time accepted by wfTimestamp()
1597 // (wfTimestamp() also accepts various non-strings and the string of 14
1598 // ASCII NUL bytes, but those can't get here)
1600 $this->addDeprecation(
1601 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1602 'unclear-"now"-timestamp'
1604 return wfTimestamp( TS_MW
);
1607 // Explicit synonym for the current time
1608 if ( $value === 'now' ) {
1609 return wfTimestamp( TS_MW
);
1612 $timestamp = wfTimestamp( TS_MW
, $value );
1613 if ( $timestamp === false ) {
1614 $this->dieWithError(
1615 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1616 "badtimestamp_{$encParamName}"
1624 * Validate the supplied token.
1627 * @param string $token Supplied token
1628 * @param array $params All supplied parameters for the module
1630 * @throws MWException
1632 final public function validateToken( $token, array $params ) {
1633 $tokenType = $this->needsToken();
1634 $salts = ApiQueryTokens
::getTokenTypeSalts();
1635 if ( !isset( $salts[$tokenType] ) ) {
1636 throw new MWException(
1637 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1638 'without registering it'
1642 $tokenObj = ApiQueryTokens
::getToken(
1643 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1645 if ( $tokenObj->match( $token ) ) {
1649 $webUiSalt = $this->getWebUITokenSalt( $params );
1650 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1662 * Validate and normalize parameters of type 'user'
1663 * @param string $value Parameter value
1664 * @param string $encParamName Parameter name
1665 * @return string Validated and normalized parameter
1667 private function validateUser( $value, $encParamName ) {
1668 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1672 $name = User
::getCanonicalName( $value, 'valid' );
1673 if ( $name !== false ) {
1678 // We allow ranges as well, for blocks.
1679 IP
::isIPAddress( $value ) ||
1680 // See comment for User::isIP. We don't just call that function
1681 // here because it also returns true for things like
1682 // 300.300.300.300 that are neither valid usernames nor valid IP
1685 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1689 return IP
::sanitizeIP( $value );
1692 $this->dieWithError(
1693 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1694 "baduser_{$encParamName}"
1700 /************************************************************************//**
1701 * @name Utility methods
1706 * Set a watch (or unwatch) based the based on a watchlist parameter.
1707 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1708 * @param Title $titleObj The article's title to change
1709 * @param string|null $userOption The user option to consider when $watch=preferences
1711 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1712 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1713 if ( $value === null ) {
1717 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1721 * Gets the user for whom to get the watchlist
1723 * @param array $params
1726 public function getWatchlistUser( $params ) {
1727 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1728 $user = User
::newFromName( $params['owner'], false );
1729 if ( !( $user && $user->getId() ) ) {
1730 $this->dieWithError(
1731 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1734 $token = $user->getOption( 'watchlisttoken' );
1735 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1736 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1739 if ( !$this->getUser()->isLoggedIn() ) {
1740 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1742 $this->checkUserRightsAny( 'viewmywatchlist' );
1743 $user = $this->getUser();
1750 * Create a Message from a string or array
1752 * A string is used as a message key. An array has the message key as the
1753 * first value and message parameters as subsequent values.
1756 * @param string|array|Message $msg
1757 * @param IContextSource $context
1758 * @param array|null $params
1759 * @return Message|null
1761 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1762 if ( is_string( $msg ) ) {
1763 $msg = wfMessage( $msg );
1764 } elseif ( is_array( $msg ) ) {
1765 $msg = wfMessage( ...$msg );
1767 if ( !$msg instanceof Message
) {
1771 $msg->setContext( $context );
1773 $msg->params( $params );
1780 * Turn an array of message keys or key+param arrays into a Status
1782 * @param array $errors
1783 * @param User|null $user
1786 public function errorArrayToStatus( array $errors, User
$user = null ) {
1787 if ( $user === null ) {
1788 $user = $this->getUser();
1791 $status = Status
::newGood();
1792 foreach ( $errors as $error ) {
1793 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1794 $status->fatal( ApiMessage
::create(
1797 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1799 } elseif ( is_array( $error ) && $error[0] === 'blockedtext-partial' && $user->getBlock() ) {
1800 $status->fatal( ApiMessage
::create(
1801 'apierror-blocked-partial',
1803 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1805 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1806 $status->fatal( ApiMessage
::create(
1807 'apierror-autoblocked',
1809 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1811 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1812 $status->fatal( ApiMessage
::create(
1813 'apierror-systemblocked',
1815 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1818 $status->fatal( ...(array)$error );
1825 * Call wfTransactionalTimeLimit() if this request was POSTed
1828 protected function useTransactionalTimeLimit() {
1829 if ( $this->getRequest()->wasPosted() ) {
1830 wfTransactionalTimeLimit();
1836 /************************************************************************//**
1837 * @name Warning and error reporting
1842 * Add a warning for this module.
1844 * Users should monitor this section to notice any changes in API. Multiple
1845 * calls to this function will result in multiple warning messages.
1847 * If $msg is not an ApiMessage, the message code will be derived from the
1848 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1851 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1852 * @param string|null $code See ApiErrorFormatter::addWarning()
1853 * @param array|null $data See ApiErrorFormatter::addWarning()
1855 public function addWarning( $msg, $code = null, $data = null ) {
1856 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1860 * Add a deprecation warning for this module.
1862 * A combination of $this->addWarning() and $this->logFeatureUsage()
1865 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1866 * @param string|null $feature See ApiBase::logFeatureUsage()
1867 * @param array|null $data See ApiErrorFormatter::addWarning()
1869 public function addDeprecation( $msg, $feature, $data = [] ) {
1870 $data = (array)$data;
1871 if ( $feature !== null ) {
1872 $data['feature'] = $feature;
1873 $this->logFeatureUsage( $feature );
1875 $this->addWarning( $msg, 'deprecation', $data );
1877 // No real need to deduplicate here, ApiErrorFormatter does that for
1878 // us (assuming the hook is deterministic).
1879 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1880 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1881 if ( count( $msgs ) > 1 ) {
1882 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1883 $msg = ( new RawMessage( $key ) )->params( $msgs );
1885 $msg = reset( $msgs );
1887 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1891 * Add an error for this module without aborting
1893 * If $msg is not an ApiMessage, the message code will be derived from the
1894 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1896 * @note If you want to abort processing, use self::dieWithError() instead.
1898 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1899 * @param string|null $code See ApiErrorFormatter::addError()
1900 * @param array|null $data See ApiErrorFormatter::addError()
1902 public function addError( $msg, $code = null, $data = null ) {
1903 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1907 * Add warnings and/or errors from a Status
1909 * @note If you want to abort processing, use self::dieStatus() instead.
1911 * @param StatusValue $status
1912 * @param string[] $types 'warning' and/or 'error'
1914 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1915 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1919 * Abort execution with an error
1921 * If $msg is not an ApiMessage, the message code will be derived from the
1922 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1925 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1926 * @param string|null $code See ApiErrorFormatter::addError()
1927 * @param array|null $data See ApiErrorFormatter::addError()
1928 * @param int|null $httpCode HTTP error code to use
1929 * @throws ApiUsageException always
1931 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1932 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1936 * Abort execution with an error derived from an exception
1939 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1940 * @param array $options See ApiErrorFormatter::getMessageFromException()
1941 * @throws ApiUsageException always
1943 public function dieWithException( $exception, array $options = [] ) {
1944 $this->dieWithError(
1945 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1950 * Adds a warning to the output, else dies
1952 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1953 * @param bool $enforceLimits Whether this is an enforce (die)
1955 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1956 if ( $enforceLimits ) {
1957 $this->dieWithError( $msg );
1959 $this->addWarning( $msg );
1964 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1965 * error handler and die with an error message including block info.
1968 * @param Block $block The block used to generate the ApiUsageException
1969 * @throws ApiUsageException always
1971 public function dieBlocked( Block
$block ) {
1972 // Die using the appropriate message depending on block type
1973 if ( $block->getType() == Block
::TYPE_AUTO
) {
1974 $this->dieWithError(
1975 'apierror-autoblocked',
1977 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1979 } elseif ( !$block->isSitewide() ) {
1980 $this->dieWithError(
1981 'apierror-blocked-partial',
1983 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1986 $this->dieWithError(
1989 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1995 * Throw an ApiUsageException based on the Status object.
1998 * @since 1.29 Accepts a StatusValue
1999 * @param StatusValue $status
2000 * @throws ApiUsageException always
2002 public function dieStatus( StatusValue
$status ) {
2003 if ( $status->isGood() ) {
2004 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2007 // ApiUsageException needs a fatal status, but this method has
2008 // historically accepted any non-good status. Convert it if necessary.
2009 $status->setOK( false );
2010 if ( !$status->getErrorsByType( 'error' ) ) {
2011 $newStatus = Status
::newGood();
2012 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2013 $newStatus->fatal( $err['message'], ...$err['params'] );
2015 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2016 $newStatus->fatal( 'unknownerror-nocode' );
2018 $status = $newStatus;
2021 throw new ApiUsageException( $this, $status );
2025 * Helper function for readonly errors
2027 * @throws ApiUsageException always
2029 public function dieReadOnly() {
2030 $this->dieWithError(
2031 'apierror-readonly',
2033 [ 'readonlyreason' => wfReadOnlyReason() ]
2038 * Helper function for permission-denied errors
2040 * @param string|string[] $rights
2041 * @param User|null $user
2042 * @throws ApiUsageException if the user doesn't have any of the rights.
2043 * The error message is based on $rights[0].
2045 public function checkUserRightsAny( $rights, $user = null ) {
2047 $user = $this->getUser();
2049 $rights = (array)$rights;
2050 if ( !$user->isAllowedAny( ...$rights ) ) {
2051 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2056 * Helper function for permission-denied errors
2058 * @param Title $title
2059 * @param string|string[] $actions
2060 * @param User|null $user
2061 * @throws ApiUsageException if the user doesn't have all of the rights.
2063 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
2065 $user = $this->getUser();
2069 foreach ( (array)$actions as $action ) {
2070 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2073 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2078 * Will only set a warning instead of failing if the global $wgDebugAPI
2079 * is set to true. Otherwise behaves exactly as self::dieWithError().
2082 * @param string|array|Message $msg
2083 * @param string|null $code
2084 * @param array|null $data
2085 * @param int|null $httpCode
2086 * @throws ApiUsageException
2088 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2089 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2090 $this->dieWithError( $msg, $code, $data, $httpCode );
2092 $this->addWarning( $msg, $code, $data );
2097 * Die with the 'badcontinue' error.
2099 * This call is common enough to make it into the base method.
2101 * @param bool $condition Will only die if this value is true
2102 * @throws ApiUsageException
2105 protected function dieContinueUsageIf( $condition ) {
2107 $this->dieWithError( 'apierror-badcontinue' );
2112 * Internal code errors should be reported with this method
2113 * @param string $method Method or function name
2114 * @param string $message Error message
2115 * @throws MWException always
2117 protected static function dieDebug( $method, $message ) {
2118 throw new MWException( "Internal error in $method: $message" );
2122 * Write logging information for API features to a debug log, for usage
2124 * @note Consider using $this->addDeprecation() instead to both warn and log.
2125 * @param string $feature Feature being used.
2127 public function logFeatureUsage( $feature ) {
2128 $request = $this->getRequest();
2129 $s = '"' . addslashes( $feature ) . '"' .
2130 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2131 ' "' . $request->getIP() . '"' .
2132 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2133 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2134 wfDebugLog( 'api-feature-usage', $s, 'private' );
2139 /************************************************************************//**
2140 * @name Help message generation
2145 * Return the summary message.
2147 * This is a one-line description of the module, suitable for display in a
2151 * @return string|array|Message
2153 protected function getSummaryMessage() {
2154 return "apihelp-{$this->getModulePath()}-summary";
2158 * Return the extended help text message.
2160 * This is additional text to display at the top of the help section, below
2164 * @return string|array|Message
2166 protected function getExtendedDescription() {
2168 "apihelp-{$this->getModulePath()}-extended-description",
2169 'api-help-no-extended-description',
2174 * Get final module summary
2179 public function getFinalSummary() {
2180 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2181 $this->getModulePrefix(),
2182 $this->getModuleName(),
2183 $this->getModulePath(),
2189 * Get final module description, after hooks have had a chance to tweak it as
2192 * @since 1.25, returns Message[] rather than string[]
2195 public function getFinalDescription() {
2196 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2197 $this->getModulePrefix(),
2198 $this->getModuleName(),
2199 $this->getModulePath(),
2201 $extendedDescription = self
::makeMessage(
2202 $this->getExtendedDescription(), $this->getContext(), [
2203 $this->getModulePrefix(),
2204 $this->getModuleName(),
2205 $this->getModulePath(),
2209 $msgs = [ $summary, $extendedDescription ];
2211 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2217 * Get final list of parameters, after hooks have had a chance to
2218 * tweak it as needed.
2220 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2221 * @return array|bool False on no parameters
2222 * @since 1.21 $flags param added
2224 public function getFinalParams( $flags = 0 ) {
2225 $params = $this->getAllowedParams( $flags );
2230 if ( $this->needsToken() ) {
2231 $params['token'] = [
2232 self
::PARAM_TYPE
=> 'string',
2233 self
::PARAM_REQUIRED
=> true,
2234 self
::PARAM_SENSITIVE
=> true,
2235 self
::PARAM_HELP_MSG
=> [
2236 'api-help-param-token',
2237 $this->needsToken(),
2239 ] +
( $params['token'] ??
[] );
2242 // Avoid PHP 7.1 warning of passing $this by reference
2244 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2250 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2253 * @since 1.25, returns array of Message[] rather than array of string[]
2254 * @return array Keys are parameter names, values are arrays of Message objects
2256 public function getFinalParamDescription() {
2257 $prefix = $this->getModulePrefix();
2258 $name = $this->getModuleName();
2259 $path = $this->getModulePath();
2261 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2263 foreach ( $params as $param => $settings ) {
2264 if ( !is_array( $settings ) ) {
2268 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2269 $msg = $settings[self
::PARAM_HELP_MSG
];
2271 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2273 $msg = self
::makeMessage( $msg, $this->getContext(),
2274 [ $prefix, $param, $name, $path ] );
2276 self
::dieDebug( __METHOD__
,
2277 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2279 $msgs[$param] = [ $msg ];
2281 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2282 $settings[self
::PARAM_TYPE
] === 'submodule'
2284 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2285 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2287 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2289 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2290 $map[$submoduleName] = $prefix . $submoduleName;
2295 $deprecatedSubmodules = [];
2296 foreach ( $map as $v => $m ) {
2297 $arr = &$submodules;
2298 $isDeprecated = false;
2301 $submod = $this->getModuleFromPath( $m );
2303 $summary = $submod->getFinalSummary();
2304 $isDeprecated = $submod->isDeprecated();
2305 if ( $isDeprecated ) {
2306 $arr = &$deprecatedSubmodules;
2309 } catch ( ApiUsageException
$ex ) {
2313 $key = $summary->getKey();
2314 $params = $summary->getParams();
2316 $key = 'api-help-undocumented-module';
2319 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2320 $arr[] = $m->setContext( $this->getContext() );
2322 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2323 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2324 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2325 self
::dieDebug( __METHOD__
,
2326 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2328 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2329 self
::dieDebug( __METHOD__
,
2330 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2331 'ApiBase::PARAM_TYPE is an array' );
2334 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2335 $deprecatedValues = $settings[self
::PARAM_DEPRECATED_VALUES
] ??
[];
2337 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2338 if ( isset( $valueMsgs[$value] ) ) {
2339 $msg = $valueMsgs[$value];
2341 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2343 $m = self
::makeMessage( $msg, $this->getContext(),
2344 [ $prefix, $param, $name, $path, $value ] );
2346 $m = new ApiHelpParamValueMessage(
2348 [ $m->getKey(), 'api-help-param-no-description' ],
2350 isset( $deprecatedValues[$value] )
2352 $msgs[$param][] = $m->setContext( $this->getContext() );
2354 self
::dieDebug( __METHOD__
,
2355 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2360 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2361 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2362 self
::dieDebug( __METHOD__
,
2363 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2365 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2366 $m = self
::makeMessage( $m, $this->getContext(),
2367 [ $prefix, $param, $name, $path ] );
2369 $msgs[$param][] = $m;
2371 self
::dieDebug( __METHOD__
,
2372 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2378 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2384 * Generates the list of flags for the help screen and for action=paraminfo
2386 * Corresponding messages: api-help-flag-deprecated,
2387 * api-help-flag-internal, api-help-flag-readrights,
2388 * api-help-flag-writerights, api-help-flag-mustbeposted
2392 protected function getHelpFlags() {
2395 if ( $this->isDeprecated() ) {
2396 $flags[] = 'deprecated';
2398 if ( $this->isInternal() ) {
2399 $flags[] = 'internal';
2401 if ( $this->isReadMode() ) {
2402 $flags[] = 'readrights';
2404 if ( $this->isWriteMode() ) {
2405 $flags[] = 'writerights';
2407 if ( $this->mustBePosted() ) {
2408 $flags[] = 'mustbeposted';
2415 * Returns information about the source of this module, if known
2417 * Returned array is an array with the following keys:
2418 * - path: Install path
2419 * - name: Extension name, or "MediaWiki" for core
2420 * - namemsg: (optional) i18n message key for a display name
2421 * - license-name: (optional) Name of license
2423 * @return array|null
2425 protected function getModuleSourceInfo() {
2428 if ( $this->mModuleSource
!== false ) {
2429 return $this->mModuleSource
;
2432 // First, try to find where the module comes from...
2433 $rClass = new ReflectionClass( $this );
2434 $path = $rClass->getFileName();
2437 $this->mModuleSource
= null;
2440 $path = realpath( $path ) ?
: $path;
2442 // Build map of extension directories to extension info
2443 if ( self
::$extensionInfo === null ) {
2444 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2445 self
::$extensionInfo = [
2446 realpath( __DIR__
) ?
: __DIR__
=> [
2448 'name' => 'MediaWiki',
2449 'license-name' => 'GPL-2.0-or-later',
2451 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2452 realpath( $extDir ) ?
: $extDir => null,
2458 'license-name' => null,
2460 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2461 foreach ( $group as $ext ) {
2462 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2463 // This shouldn't happen, but does anyway.
2467 $extpath = $ext['path'];
2468 if ( !is_dir( $extpath ) ) {
2469 $extpath = dirname( $extpath );
2471 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2472 array_intersect_key( $ext, $keep );
2475 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2476 $extpath = $ext['path'];
2477 if ( !is_dir( $extpath ) ) {
2478 $extpath = dirname( $extpath );
2480 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2481 array_intersect_key( $ext, $keep );
2485 // Now traverse parent directories until we find a match or run out of
2488 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2490 $this->mModuleSource
= self
::$extensionInfo[$path];
2491 return $this->mModuleSource
;
2495 $path = dirname( $path );
2496 } while ( $path !== $oldpath );
2498 // No idea what extension this might be.
2499 $this->mModuleSource
= null;
2504 * Called from ApiHelp before the pieces are joined together and returned.
2506 * This exists mainly for ApiMain to add the Permissions and Credits
2507 * sections. Other modules probably don't need it.
2509 * @param string[] &$help Array of help data
2510 * @param array $options Options passed to ApiHelp::getHelp
2511 * @param array &$tocData If a TOC is being generated, this array has keys
2512 * as anchors in the page and values as for Linker::generateTOC().
2514 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2519 /************************************************************************//**
2525 * Returns the description string for this module
2527 * Ignored if an i18n message exists for
2528 * "apihelp-{$this->getModulePath()}-description".
2530 * @deprecated since 1.25
2531 * @return Message|string|array|false
2533 protected function getDescription() {
2534 wfDeprecated( __METHOD__
, '1.25' );
2539 * Returns an array of parameter descriptions.
2541 * For each parameter, ignored if an i18n message exists for the parameter.
2542 * By default that message is
2543 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2544 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2545 * self::getFinalParams().
2547 * @deprecated since 1.25
2548 * @return array|bool False on no parameter descriptions
2550 protected function getParamDescription() {
2551 wfDeprecated( __METHOD__
, '1.25' );
2556 * Returns usage examples for this module.
2558 * Return value as an array is either:
2559 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2561 * - sequential numeric keys with even-numbered keys being display-text
2562 * and odd-numbered keys being partial urls
2563 * - partial URLs as keys with display-text (string or array-to-be-joined)
2565 * Return value as a string is the same as an array with a numeric key and
2566 * that value, and boolean false means "no examples".
2568 * @deprecated since 1.25, use getExamplesMessages() instead
2569 * @return bool|string|array
2571 protected function getExamples() {
2572 wfDeprecated( __METHOD__
, '1.25' );
2577 * Return the description message.
2579 * This is additional text to display on the help page after the summary.
2581 * @deprecated since 1.30
2582 * @return string|array|Message
2584 protected function getDescriptionMessage() {
2585 wfDeprecated( __METHOD__
, '1.30' );
2587 "apihelp-{$this->getModulePath()}-description",
2588 "apihelp-{$this->getModulePath()}-summary",
2593 * Truncate an array to a certain length.
2594 * @deprecated since 1.32, no replacement
2595 * @param array &$arr Array to truncate
2596 * @param int $limit Maximum length
2597 * @return bool True if the array was truncated, false otherwise
2599 public static function truncateArray( &$arr, $limit ) {
2600 wfDeprecated( __METHOD__
, '1.32' );
2602 while ( count( $arr ) > $limit ) {
2614 * For really cool vim folding this needs to be at the end:
2615 * vim: foldmarker=@{,@} foldmethod=marker