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 $mSlaveDB = 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() {
351 // Fall back to old non-localised method
354 $examples = $this->getExamples();
356 if ( !is_array( $examples ) ) {
357 $examples = [ $examples ];
358 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
359 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
360 !preg_match( '/^\s*api\.php\?/', $examples[0] )
362 // Fix up the ugly "even numbered elements are description, odd
363 // numbered elemts are the link" format (see doc for self::getExamples)
365 $examplesCount = count( $examples );
366 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
367 $tmp[$examples[$i +
1]] = $examples[$i];
372 foreach ( $examples as $k => $v ) {
373 if ( is_numeric( $k ) ) {
378 $msg = self
::escapeWikiText( $v );
379 if ( is_array( $msg ) ) {
380 $msg = implode( ' ', $msg );
384 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
385 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
393 * Return links to more detailed help pages about the module.
394 * @since 1.25, returning boolean false is deprecated
395 * @return string|array
397 public function getHelpUrls() {
402 * Returns an array of allowed parameters (parameter name) => (default
403 * value) or (parameter name) => (array with PARAM_* constants as keys)
404 * Don't call this function directly: use getFinalParams() to allow
405 * hooks to modify parameters as needed.
407 * Some derived classes may choose to handle an integer $flags parameter
408 * in the overriding methods. Callers of this method can pass zero or
409 * more OR-ed flags like GET_VALUES_FOR_HELP.
413 protected function getAllowedParams( /* $flags = 0 */ ) {
414 // int $flags is not declared because it causes "Strict standards"
415 // warning. Most derived classes do not implement it.
420 * Indicates if this module needs maxlag to be checked
423 public function shouldCheckMaxlag() {
428 * Indicates whether this module requires read rights
431 public function isReadMode() {
436 * Indicates whether this module requires write mode
438 * This should return true for modules that may require synchronous database writes.
439 * Modules that do not need such writes should also not rely on master database access,
440 * since only read queries are needed and each master DB is a single point of failure.
441 * Additionally, requests that only need replica DBs can be efficiently routed to any
442 * datacenter via the Promise-Non-Write-API-Action header.
446 public function isWriteMode() {
451 * Indicates whether this module must be called with a POST request
454 public function mustBePosted() {
455 return $this->needsToken() !== false;
459 * Indicates whether this module is deprecated
463 public function isDeprecated() {
468 * Indicates whether this module is "internal"
469 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
473 public function isInternal() {
478 * Returns the token type this module requires in order to execute.
480 * Modules are strongly encouraged to use the core 'csrf' type unless they
481 * have specialized security needs. If the token type is not one of the
482 * core types, you must use the ApiQueryTokensRegisterTypes hook to
485 * Returning a non-falsey value here will force the addition of an
486 * appropriate 'token' parameter in self::getFinalParams(). Also,
487 * self::mustBePosted() must return true when tokens are used.
489 * In previous versions of MediaWiki, true was a valid return value.
490 * Returning true will generate errors indicating that the API module needs
493 * @return string|false
495 public function needsToken() {
500 * Fetch the salt used in the Web UI corresponding to this module.
502 * Only override this if the Web UI uses a token with a non-constant salt.
505 * @param array $params All supplied parameters for the module
506 * @return string|array|null
508 protected function getWebUITokenSalt( array $params ) {
513 * Returns data for HTTP conditional request mechanisms.
516 * @param string $condition Condition being queried:
517 * - last-modified: Return a timestamp representing the maximum of the
518 * last-modified dates for all resources involved in the request. See
519 * RFC 7232 § 2.2 for semantics.
520 * - etag: Return an entity-tag representing the state of all resources involved
521 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
522 * @return string|bool|null As described above, or null if no value is available.
524 public function getConditionalRequestData( $condition ) {
530 /************************************************************************//**
531 * @name Data access methods
536 * Get the name of the module being executed by this instance
539 public function getModuleName() {
540 return $this->mModuleName
;
544 * Get parameter prefix (usually two letters or an empty string).
547 public function getModulePrefix() {
548 return $this->mModulePrefix
;
552 * Get the main module
555 public function getMain() {
556 return $this->mMainModule
;
560 * Returns true if this module is the main module ($this === $this->mMainModule),
564 public function isMain() {
565 return $this === $this->mMainModule
;
569 * Get the parent of this module
571 * @return ApiBase|null
573 public function getParent() {
574 return $this->isMain() ?
null : $this->getMain();
578 * Returns true if the current request breaks the same-origin policy.
580 * For example, json with callbacks.
582 * https://en.wikipedia.org/wiki/Same-origin_policy
587 public function lacksSameOriginSecurity() {
588 // Main module has this method overridden
589 // Safety - avoid infinite loop:
590 if ( $this->isMain() ) {
591 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
594 return $this->getMain()->lacksSameOriginSecurity();
598 * Get the path to this module
603 public function getModulePath() {
604 if ( $this->isMain() ) {
606 } elseif ( $this->getParent()->isMain() ) {
607 return $this->getModuleName();
609 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
614 * Get a module from its module path
617 * @param string $path
618 * @return ApiBase|null
619 * @throws ApiUsageException
621 public function getModuleFromPath( $path ) {
622 $module = $this->getMain();
623 if ( $path === 'main' ) {
627 $parts = explode( '+', $path );
628 if ( count( $parts ) === 1 ) {
629 // In case the '+' was typed into URL, it resolves as a space
630 $parts = explode( ' ', $path );
633 $count = count( $parts );
634 for ( $i = 0; $i < $count; $i++
) {
636 $manager = $parent->getModuleManager();
637 if ( $manager === null ) {
638 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
639 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
641 $module = $manager->getModule( $parts[$i] );
643 if ( $module === null ) {
644 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
646 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
656 * Get the result object
659 public function getResult() {
660 // Main module has getResult() method overridden
661 // Safety - avoid infinite loop:
662 if ( $this->isMain() ) {
663 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
666 return $this->getMain()->getResult();
670 * Get the error formatter
671 * @return ApiErrorFormatter
673 public function getErrorFormatter() {
674 // Main module has getErrorFormatter() method overridden
675 // Safety - avoid infinite loop:
676 if ( $this->isMain() ) {
677 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
680 return $this->getMain()->getErrorFormatter();
684 * Gets a default replica DB connection object
687 protected function getDB() {
688 if ( !isset( $this->mSlaveDB
) ) {
689 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
692 return $this->mSlaveDB
;
696 * Get the continuation manager
697 * @return ApiContinuationManager|null
699 public function getContinuationManager() {
700 // Main module has getContinuationManager() method overridden
701 // Safety - avoid infinite loop:
702 if ( $this->isMain() ) {
703 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
706 return $this->getMain()->getContinuationManager();
710 * Set the continuation manager
711 * @param ApiContinuationManager|null $manager
713 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
714 // Main module has setContinuationManager() method overridden
715 // Safety - avoid infinite loop:
716 if ( $this->isMain() ) {
717 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
720 $this->getMain()->setContinuationManager( $manager );
725 /************************************************************************//**
726 * @name Parameter handling
731 * Indicate if the module supports dynamically-determined parameters that
732 * cannot be included in self::getAllowedParams().
733 * @return string|array|Message|null Return null if the module does not
734 * support additional dynamic parameters, otherwise return a message
737 public function dynamicParameterDocumentation() {
742 * This method mangles parameter name based on the prefix supplied to the constructor.
743 * Override this method to change parameter name during runtime
744 * @param string|string[] $paramName Parameter name
745 * @return string|string[] Prefixed parameter name
746 * @since 1.29 accepts an array of strings
748 public function encodeParamName( $paramName ) {
749 if ( is_array( $paramName ) ) {
750 return array_map( function ( $name ) {
751 return $this->mModulePrefix
. $name;
754 return $this->mModulePrefix
. $paramName;
759 * Using getAllowedParams(), this function makes an array of the values
760 * provided by the user, with key being the name of the variable, and
761 * value - validated value from user or default. limits will not be
762 * parsed if $parseLimit is set to false; use this when the max
763 * limit is not definitive yet, e.g. when getting revisions.
764 * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
765 * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
766 * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
767 * Returned parameter values might be ApiUsageException instances.
770 public function extractRequestParams( $options = [] ) {
771 if ( is_bool( $options ) ) {
772 $options = [ 'parseLimit' => $options ];
775 'parseLimit' => true,
779 $parseLimit = (bool)$options['parseLimit'];
781 // Cache parameters, for performance and to avoid T26564.
782 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
783 $params = $this->getFinalParams() ?
: [];
787 // Process all non-templates and save templates for secondary
790 foreach ( $params as $paramName => $paramSettings ) {
791 if ( isset( $paramSettings[self
::PARAM_TEMPLATE_VARS
] ) ) {
792 $toProcess[] = [ $paramName, $paramSettings[self
::PARAM_TEMPLATE_VARS
], $paramSettings ];
795 $results[$paramName] = $this->getParameterFromSettings(
796 $paramName, $paramSettings, $parseLimit
798 } catch ( ApiUsageException
$ex ) {
799 $results[$paramName] = $ex;
804 // Now process all the templates by successively replacing the
805 // placeholders with all client-supplied values.
806 // This bit duplicates JavaScript logic in
807 // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
808 // If you update this, see if that needs updating too.
809 while ( $toProcess ) {
810 list( $name, $targets, $settings ) = array_shift( $toProcess );
812 foreach ( $targets as $placeholder => $target ) {
813 if ( !array_key_exists( $target, $results ) ) {
814 // The target wasn't processed yet, try the next one.
815 // If all hit this case, the parameter has no expansions.
818 if ( !is_array( $results[$target] ) ||
!$results[$target] ) {
819 // The target was processed but has no (valid) values.
820 // That means it has no expansions.
824 // Expand this target in the name and all other targets,
825 // then requeue if there are more targets left or put in
826 // $results if all are done.
827 unset( $targets[$placeholder] );
828 $placeholder = '{' . $placeholder . '}';
829 foreach ( $results[$target] as $value ) {
830 if ( !preg_match( '/^[^{}]*$/', $value ) ) {
831 // Skip values that make invalid parameter names.
832 $encTargetName = $this->encodeParamName( $target );
833 if ( !isset( $warned[$encTargetName][$value] ) ) {
834 $warned[$encTargetName][$value] = true;
836 'apiwarn-ignoring-invalid-templated-value',
837 wfEscapeWikiText( $encTargetName ),
838 wfEscapeWikiText( $value ),
844 $newName = str_replace( $placeholder, $value, $name );
847 $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
848 } catch ( ApiUsageException
$ex ) {
849 $results[$newName] = $ex;
853 foreach ( $targets as $k => $v ) {
854 $newTargets[$k] = str_replace( $placeholder, $value, $v );
856 $toProcess[] = [ $newName, $newTargets, $settings ];
863 $this->mParamCache
[$parseLimit] = $results;
866 $ret = $this->mParamCache
[$parseLimit];
867 if ( !$options['safeMode'] ) {
868 foreach ( $ret as $v ) {
869 if ( $v instanceof ApiUsageException
) {
875 return $this->mParamCache
[$parseLimit];
879 * Get a value for the given parameter
880 * @param string $paramName Parameter name
881 * @param bool $parseLimit See extractRequestParams()
882 * @return mixed Parameter value
884 protected function getParameter( $paramName, $parseLimit = true ) {
885 $ret = $this->extractRequestParams( [
886 'parseLimit' => $parseLimit,
889 if ( $ret instanceof ApiUsageException
) {
896 * Die if none or 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 exactly one must be set
901 public function requireOnlyOneParameter( $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 ),
919 } elseif ( count( $intersection ) == 0 ) {
920 $this->dieWithError( [
921 'apierror-missingparam-one-of',
922 Message
::listParam( array_map(
924 return '<var>' . $this->encodeParamName( $p ) . '</var>';
926 array_values( $required )
934 * Die if more than one of a certain set of parameters is set and not false.
936 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
937 * @param string $required,... Names of parameters of which at most one must be set
939 public function requireMaxOneParameter( $params, $required /*...*/ ) {
940 $required = func_get_args();
941 array_shift( $required );
943 $intersection = array_intersect( array_keys( array_filter( $params,
944 [ $this, 'parameterNotEmpty' ] ) ), $required );
946 if ( count( $intersection ) > 1 ) {
947 $this->dieWithError( [
948 'apierror-invalidparammix',
949 Message
::listParam( array_map(
951 return '<var>' . $this->encodeParamName( $p ) . '</var>';
953 array_values( $intersection )
955 count( $intersection ),
961 * Die if none of a certain set of parameters is set and not false.
964 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
965 * @param string $required,... Names of parameters of which at least one must be set
967 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
968 $required = func_get_args();
969 array_shift( $required );
971 $intersection = array_intersect(
972 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
976 if ( count( $intersection ) == 0 ) {
977 $this->dieWithError( [
978 'apierror-missingparam-at-least-one-of',
979 Message
::listParam( array_map(
981 return '<var>' . $this->encodeParamName( $p ) . '</var>';
983 array_values( $required )
991 * Die if any of the specified parameters were found in the query part of
992 * the URL rather than the post body.
994 * @param string[] $params Parameters to check
995 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
997 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
998 // Skip if $wgDebugAPI is set or we're in internal mode
999 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
1003 $queryValues = $this->getRequest()->getQueryValues();
1005 foreach ( $params as $param ) {
1006 if ( $prefix !== 'noprefix' ) {
1007 $param = $this->encodeParamName( $param );
1009 if ( array_key_exists( $param, $queryValues ) ) {
1010 $badParams[] = $param;
1015 $this->dieWithError(
1016 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
1022 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
1024 * @param object $x Parameter to check is not null/false
1027 private function parameterNotEmpty( $x ) {
1028 return !is_null( $x ) && $x !== false;
1032 * Get a WikiPage object from a title or pageid param, if possible.
1033 * Can die, if no param is set or if the title or page id is not valid.
1035 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1036 * @param bool|string $load Whether load the object's state from the database:
1037 * - false: don't load (if the pageid is given, it will still be loaded)
1038 * - 'fromdb': load from a replica DB
1039 * - 'fromdbmaster': load from the master database
1042 public function getTitleOrPageId( $params, $load = false ) {
1043 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1046 if ( isset( $params['title'] ) ) {
1047 $titleObj = Title
::newFromText( $params['title'] );
1048 if ( !$titleObj ||
$titleObj->isExternal() ) {
1049 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1051 if ( !$titleObj->canExist() ) {
1052 $this->dieWithError( 'apierror-pagecannotexist' );
1054 $pageObj = WikiPage
::factory( $titleObj );
1055 if ( $load !== false ) {
1056 $pageObj->loadPageData( $load );
1058 } elseif ( isset( $params['pageid'] ) ) {
1059 if ( $load === false ) {
1062 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
1064 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1072 * Get a Title object from a title or pageid param, if possible.
1073 * Can die, if no param is set or if the title or page id is not valid.
1076 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
1079 public function getTitleFromTitleOrPageId( $params ) {
1080 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1083 if ( isset( $params['title'] ) ) {
1084 $titleObj = Title
::newFromText( $params['title'] );
1085 if ( !$titleObj ||
$titleObj->isExternal() ) {
1086 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1089 } elseif ( isset( $params['pageid'] ) ) {
1090 $titleObj = Title
::newFromID( $params['pageid'] );
1092 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1100 * Return true if we're to watch the page, false if not, null if no change.
1101 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1102 * @param Title $titleObj The page under consideration
1103 * @param string $userOption The user option to consider when $watchlist=preferences.
1104 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
1107 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1108 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
1110 switch ( $watchlist ) {
1118 # If the user is already watching, don't bother checking
1119 if ( $userWatching ) {
1122 # If no user option was passed, use watchdefault and watchcreations
1123 if ( is_null( $userOption ) ) {
1124 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1125 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1128 # Watch the article based on the user preference
1129 return $this->getUser()->getBoolOption( $userOption );
1132 return $userWatching;
1135 return $userWatching;
1140 * Using the settings determine the value for the given parameter
1142 * @param string $paramName Parameter name
1143 * @param array|mixed $paramSettings Default value or an array of settings
1144 * using PARAM_* constants.
1145 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1146 * @return mixed Parameter value
1148 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1149 // Some classes may decide to change parameter names
1150 $encParamName = $this->encodeParamName( $paramName );
1153 if ( !is_array( $paramSettings ) ) {
1155 self
::PARAM_DFLT
=> $paramSettings,
1159 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1160 ?
$paramSettings[self
::PARAM_DFLT
]
1162 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1163 ?
$paramSettings[self
::PARAM_ISMULTI
]
1165 $multiLimit1 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] )
1166 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT1
]
1168 $multiLimit2 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] )
1169 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT2
]
1171 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1172 ?
$paramSettings[self
::PARAM_TYPE
]
1174 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1175 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1177 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1178 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1180 $deprecatedValues = isset( $paramSettings[self
::PARAM_DEPRECATED_VALUES
] )
1181 ?
$paramSettings[self
::PARAM_DEPRECATED_VALUES
]
1183 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1184 ?
$paramSettings[self
::PARAM_REQUIRED
]
1186 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1187 ?
$paramSettings[self
::PARAM_ALL
]
1190 // When type is not given, and no choices, the type is the same as $default
1191 if ( !isset( $type ) ) {
1192 if ( isset( $default ) ) {
1193 $type = gettype( $default );
1195 $type = 'NULL'; // allow everything
1199 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1200 $this->getMain()->markParamsSensitive( $encParamName );
1203 if ( $type == 'boolean' ) {
1204 if ( isset( $default ) && $default !== false ) {
1205 // Having a default value of anything other than 'false' is not allowed
1208 "Boolean param $encParamName's default is set to '$default'. " .
1209 'Boolean parameters must default to false.'
1213 $value = $this->getMain()->getCheck( $encParamName );
1214 } elseif ( $type == 'upload' ) {
1215 if ( isset( $default ) ) {
1216 // Having a default value is not allowed
1219 "File upload param $encParamName's default is set to " .
1220 "'$default'. File upload parameters may not have a default." );
1223 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1225 $value = $this->getMain()->getUpload( $encParamName );
1226 if ( !$value->exists() ) {
1227 // This will get the value without trying to normalize it
1228 // (because trying to normalize a large binary file
1229 // accidentally uploaded as a field fails spectacularly)
1230 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1231 if ( $value !== null ) {
1232 $this->dieWithError(
1233 [ 'apierror-badupload', $encParamName ],
1234 "badupload_{$encParamName}"
1239 $value = $this->getMain()->getVal( $encParamName, $default );
1241 if ( isset( $value ) && $type == 'namespace' ) {
1242 $type = MWNamespace
::getValidNamespaces();
1243 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1244 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1246 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1248 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1249 // specify all namespaces irrespective of PARAM_ALL.
1252 if ( isset( $value ) && $type == 'submodule' ) {
1253 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1254 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1256 $type = $this->getModuleManager()->getNames( $paramName );
1260 $request = $this->getMain()->getRequest();
1261 $rawValue = $request->getRawVal( $encParamName );
1262 if ( $rawValue === null ) {
1263 $rawValue = $default;
1266 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1267 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1269 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1270 // done by WebRequest for $_GET. Let's call that a feature.
1271 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1273 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1277 // Check for NFC normalization, and warn
1278 if ( $rawValue !== $value ) {
1279 $this->handleParamNormalization( $paramName, $value, $rawValue );
1283 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1284 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1287 "For param $encParamName, PARAM_ALL collides with a possible value" );
1289 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1290 $value = $this->parseMultiValue(
1294 is_array( $type ) ?
$type : null,
1295 $allowAll ?
$allSpecifier : null,
1301 if ( isset( $value ) ) {
1302 // More validation only when choices were not given
1303 // choices were validated in parseMultiValue()
1304 if ( !is_array( $type ) ) {
1306 case 'NULL': // nothing to do
1311 if ( $required && $value === '' ) {
1312 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1315 case 'integer': // Force everything using intval() and optionally validate limits
1316 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1317 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1318 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1319 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1321 if ( is_array( $value ) ) {
1322 $value = array_map( 'intval', $value );
1323 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1324 foreach ( $value as &$v ) {
1325 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1329 $value = intval( $value );
1330 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1331 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1336 if ( !$parseLimit ) {
1337 // Don't do any validation whatsoever
1340 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1341 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1345 "MAX1 or MAX2 are not defined for the limit $encParamName"
1349 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1351 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1352 if ( $value == 'max' ) {
1353 $value = $this->getMain()->canApiHighLimits()
1354 ?
$paramSettings[self
::PARAM_MAX2
]
1355 : $paramSettings[self
::PARAM_MAX
];
1356 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1358 $value = intval( $value );
1359 $this->validateLimit(
1363 $paramSettings[self
::PARAM_MAX
],
1364 $paramSettings[self
::PARAM_MAX2
]
1370 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1374 if ( is_array( $value ) ) {
1375 foreach ( $value as $key => $val ) {
1376 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1379 $value = $this->validateTimestamp( $value, $encParamName );
1383 if ( is_array( $value ) ) {
1384 foreach ( $value as $key => $val ) {
1385 $value[$key] = $this->validateUser( $val, $encParamName );
1388 $value = $this->validateUser( $value, $encParamName );
1391 case 'upload': // nothing to do
1394 // If change tagging was requested, check that the tags are valid.
1395 if ( !is_array( $value ) && !$multi ) {
1396 $value = [ $value ];
1398 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1399 if ( !$tagsStatus->isGood() ) {
1400 $this->dieStatus( $tagsStatus );
1404 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1408 // Throw out duplicates if requested
1409 if ( !$dupes && is_array( $value ) ) {
1410 $value = array_unique( $value );
1413 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1414 foreach ( (array)$value as $val ) {
1415 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1416 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1418 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1419 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1421 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1422 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1424 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1425 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1430 // Set a warning if a deprecated parameter has been passed
1431 if ( $deprecated && $value !== false ) {
1432 $feature = $encParamName;
1434 while ( !$m->isMain() ) {
1435 $p = $m->getParent();
1436 $name = $m->getModuleName();
1437 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1438 $feature = "{$param}={$name}&{$feature}";
1441 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1444 // Set a warning if a deprecated parameter value has been passed
1445 $usedDeprecatedValues = $deprecatedValues && $value !== false
1446 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1448 if ( $usedDeprecatedValues ) {
1449 $feature = "$encParamName=";
1451 while ( !$m->isMain() ) {
1452 $p = $m->getParent();
1453 $name = $m->getModuleName();
1454 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1455 $feature = "{$param}={$name}&{$feature}";
1458 foreach ( $usedDeprecatedValues as $v ) {
1459 $msg = $deprecatedValues[$v];
1460 if ( $msg === true ) {
1461 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1463 $this->addDeprecation( $msg, "$feature$v" );
1466 } elseif ( $required ) {
1467 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1474 * Handle when a parameter was Unicode-normalized
1476 * @param string $paramName Unprefixed parameter name
1477 * @param string $value Input that will be used.
1478 * @param string $rawValue Input before normalization.
1480 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1481 $encParamName = $this->encodeParamName( $paramName );
1482 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1486 * Split a multi-valued parameter string, like explode()
1488 * @param string $value
1492 protected function explodeMultiValue( $value, $limit ) {
1493 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1495 $value = substr( $value, 1 );
1500 return explode( $sep, $value, $limit );
1504 * Return an array of values that were given in a 'a|b|c' notation,
1505 * after it optionally validates them against the list allowed values.
1507 * @param string $valueName The name of the parameter (for error
1509 * @param mixed $value The value being parsed
1510 * @param bool $allowMultiple Can $value contain more than one value
1512 * @param string[]|null $allowedValues An array of values to check against. If
1513 * null, all values are accepted.
1514 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1515 * if this behavior should not be allowed
1516 * @param int|null $limit1 Maximum number of values, for normal users.
1517 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1518 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1520 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1521 $allSpecifier = null, $limit1 = null, $limit2 = null
1523 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1526 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1527 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1529 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1530 // because it unstubs $wgUser
1531 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1532 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1536 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1537 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1539 return $allowedValues;
1542 if ( count( $valuesList ) > $sizeLimit ) {
1543 $this->dieWithError(
1544 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1545 "too-many-$valueName"
1549 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1550 // T35482 - Allow entries with | in them for non-multiple values
1551 if ( in_array( $value, $allowedValues, true ) ) {
1555 $values = array_map( function ( $v ) {
1556 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1557 }, $allowedValues );
1558 $this->dieWithError( [
1559 'apierror-multival-only-one-of',
1561 Message
::listParam( $values ),
1563 ], "multival_$valueName" );
1566 if ( is_array( $allowedValues ) ) {
1567 // Check for unknown values
1568 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1569 if ( count( $unknown ) ) {
1570 if ( $allowMultiple ) {
1571 $this->addWarning( [
1572 'apiwarn-unrecognizedvalues',
1574 Message
::listParam( $unknown, 'comma' ),
1578 $this->dieWithError(
1579 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1580 "unknown_$valueName"
1584 // Now throw them out
1585 $valuesList = array_intersect( $valuesList, $allowedValues );
1588 return $allowMultiple ?
$valuesList : $valuesList[0];
1592 * Validate the value against the minimum and user/bot maximum limits.
1593 * Prints usage info on failure.
1594 * @param string $paramName Parameter name
1595 * @param int &$value Parameter value
1596 * @param int|null $min Minimum value
1597 * @param int|null $max Maximum value for users
1598 * @param int $botMax Maximum value for sysops/bots
1599 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1601 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1602 $enforceLimits = false
1604 if ( !is_null( $min ) && $value < $min ) {
1605 $msg = ApiMessage
::create(
1606 [ 'apierror-integeroutofrange-belowminimum',
1607 $this->encodeParamName( $paramName ), $min, $value ],
1608 'integeroutofrange',
1609 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1611 $this->warnOrDie( $msg, $enforceLimits );
1615 // Minimum is always validated, whereas maximum is checked only if not
1616 // running in internal call mode
1617 if ( $this->getMain()->isInternalMode() ) {
1621 // Optimization: do not check user's bot status unless really needed -- skips db query
1622 // assumes $botMax >= $max
1623 if ( !is_null( $max ) && $value > $max ) {
1624 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1625 if ( $value > $botMax ) {
1626 $msg = ApiMessage
::create(
1627 [ 'apierror-integeroutofrange-abovebotmax',
1628 $this->encodeParamName( $paramName ), $botMax, $value ],
1629 'integeroutofrange',
1630 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1632 $this->warnOrDie( $msg, $enforceLimits );
1636 $msg = ApiMessage
::create(
1637 [ 'apierror-integeroutofrange-abovemax',
1638 $this->encodeParamName( $paramName ), $max, $value ],
1639 'integeroutofrange',
1640 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1642 $this->warnOrDie( $msg, $enforceLimits );
1649 * Validate and normalize parameters of type 'timestamp'
1650 * @param string $value Parameter value
1651 * @param string $encParamName Parameter name
1652 * @return string Validated and normalized parameter
1654 protected function validateTimestamp( $value, $encParamName ) {
1655 // Confusing synonyms for the current time accepted by wfTimestamp()
1656 // (wfTimestamp() also accepts various non-strings and the string of 14
1657 // ASCII NUL bytes, but those can't get here)
1659 $this->addDeprecation(
1660 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1661 'unclear-"now"-timestamp'
1663 return wfTimestamp( TS_MW
);
1666 // Explicit synonym for the current time
1667 if ( $value === 'now' ) {
1668 return wfTimestamp( TS_MW
);
1671 $timestamp = wfTimestamp( TS_MW
, $value );
1672 if ( $timestamp === false ) {
1673 $this->dieWithError(
1674 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1675 "badtimestamp_{$encParamName}"
1683 * Validate the supplied token.
1686 * @param string $token Supplied token
1687 * @param array $params All supplied parameters for the module
1689 * @throws MWException
1691 final public function validateToken( $token, array $params ) {
1692 $tokenType = $this->needsToken();
1693 $salts = ApiQueryTokens
::getTokenTypeSalts();
1694 if ( !isset( $salts[$tokenType] ) ) {
1695 throw new MWException(
1696 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1697 'without registering it'
1701 $tokenObj = ApiQueryTokens
::getToken(
1702 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1704 if ( $tokenObj->match( $token ) ) {
1708 $webUiSalt = $this->getWebUITokenSalt( $params );
1709 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1721 * Validate and normalize parameters of type 'user'
1722 * @param string $value Parameter value
1723 * @param string $encParamName Parameter name
1724 * @return string Validated and normalized parameter
1726 private function validateUser( $value, $encParamName ) {
1727 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1731 $name = User
::getCanonicalName( $value, 'valid' );
1732 if ( $name !== false ) {
1737 // We allow ranges as well, for blocks.
1738 IP
::isIPAddress( $value ) ||
1739 // See comment for User::isIP. We don't just call that function
1740 // here because it also returns true for things like
1741 // 300.300.300.300 that are neither valid usernames nor valid IP
1744 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1748 return IP
::sanitizeIP( $value );
1751 $this->dieWithError(
1752 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1753 "baduser_{$encParamName}"
1759 /************************************************************************//**
1760 * @name Utility methods
1765 * Set a watch (or unwatch) based the based on a watchlist parameter.
1766 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1767 * @param Title $titleObj The article's title to change
1768 * @param string $userOption The user option to consider when $watch=preferences
1770 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1771 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1772 if ( $value === null ) {
1776 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1780 * Gets the user for whom to get the watchlist
1782 * @param array $params
1785 public function getWatchlistUser( $params ) {
1786 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1787 $user = User
::newFromName( $params['owner'], false );
1788 if ( !( $user && $user->getId() ) ) {
1789 $this->dieWithError(
1790 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1793 $token = $user->getOption( 'watchlisttoken' );
1794 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1795 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1798 if ( !$this->getUser()->isLoggedIn() ) {
1799 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1801 $this->checkUserRightsAny( 'viewmywatchlist' );
1802 $user = $this->getUser();
1809 * A subset of wfEscapeWikiText for BC texts
1812 * @param string|array $v
1813 * @return string|array
1815 private static function escapeWikiText( $v ) {
1816 if ( is_array( $v ) ) {
1817 return array_map( 'self::escapeWikiText', $v );
1820 '__' => '__', '{' => '{', '}' => '}',
1821 '[[Category:' => '[[:Category:',
1822 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1828 * Create a Message from a string or array
1830 * A string is used as a message key. An array has the message key as the
1831 * first value and message parameters as subsequent values.
1834 * @param string|array|Message $msg
1835 * @param IContextSource $context
1836 * @param array $params
1837 * @return Message|null
1839 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1840 if ( is_string( $msg ) ) {
1841 $msg = wfMessage( $msg );
1842 } elseif ( is_array( $msg ) ) {
1843 $msg = call_user_func_array( 'wfMessage', $msg );
1845 if ( !$msg instanceof Message
) {
1849 $msg->setContext( $context );
1851 $msg->params( $params );
1858 * Turn an array of message keys or key+param arrays into a Status
1860 * @param array $errors
1861 * @param User|null $user
1864 public function errorArrayToStatus( array $errors, User
$user = null ) {
1865 if ( $user === null ) {
1866 $user = $this->getUser();
1869 $status = Status
::newGood();
1870 foreach ( $errors as $error ) {
1871 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1872 $status->fatal( ApiMessage
::create(
1875 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1877 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1878 $status->fatal( ApiMessage
::create(
1879 'apierror-autoblocked',
1881 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1883 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1884 $status->fatal( ApiMessage
::create(
1885 'apierror-systemblocked',
1887 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1890 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1898 /************************************************************************//**
1899 * @name Warning and error reporting
1904 * Add a warning for this module.
1906 * Users should monitor this section to notice any changes in API. Multiple
1907 * calls to this function will result in multiple warning messages.
1909 * If $msg is not an ApiMessage, the message code will be derived from the
1910 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1913 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1914 * @param string|null $code See ApiErrorFormatter::addWarning()
1915 * @param array|null $data See ApiErrorFormatter::addWarning()
1917 public function addWarning( $msg, $code = null, $data = null ) {
1918 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1922 * Add a deprecation warning for this module.
1924 * A combination of $this->addWarning() and $this->logFeatureUsage()
1927 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1928 * @param string|null $feature See ApiBase::logFeatureUsage()
1929 * @param array|null $data See ApiErrorFormatter::addWarning()
1931 public function addDeprecation( $msg, $feature, $data = [] ) {
1932 $data = (array)$data;
1933 if ( $feature !== null ) {
1934 $data['feature'] = $feature;
1935 $this->logFeatureUsage( $feature );
1937 $this->addWarning( $msg, 'deprecation', $data );
1939 // No real need to deduplicate here, ApiErrorFormatter does that for
1940 // us (assuming the hook is deterministic).
1941 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1942 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1943 if ( count( $msgs ) > 1 ) {
1944 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1945 $msg = ( new RawMessage( $key ) )->params( $msgs );
1947 $msg = reset( $msgs );
1949 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1953 * Add an error for this module without aborting
1955 * If $msg is not an ApiMessage, the message code will be derived from the
1956 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1958 * @note If you want to abort processing, use self::dieWithError() instead.
1960 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1961 * @param string|null $code See ApiErrorFormatter::addError()
1962 * @param array|null $data See ApiErrorFormatter::addError()
1964 public function addError( $msg, $code = null, $data = null ) {
1965 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1969 * Add warnings and/or errors from a Status
1971 * @note If you want to abort processing, use self::dieStatus() instead.
1973 * @param StatusValue $status
1974 * @param string[] $types 'warning' and/or 'error'
1976 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1977 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1981 * Abort execution with an error
1983 * If $msg is not an ApiMessage, the message code will be derived from the
1984 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1987 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1988 * @param string|null $code See ApiErrorFormatter::addError()
1989 * @param array|null $data See ApiErrorFormatter::addError()
1990 * @param int|null $httpCode HTTP error code to use
1991 * @throws ApiUsageException always
1993 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1994 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1998 * Abort execution with an error derived from an exception
2001 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
2002 * @param array $options See ApiErrorFormatter::getMessageFromException()
2003 * @throws ApiUsageException always
2005 public function dieWithException( $exception, array $options = [] ) {
2006 $this->dieWithError(
2007 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
2012 * Adds a warning to the output, else dies
2014 * @param ApiMessage $msg Message to show as a warning, or error message if dying
2015 * @param bool $enforceLimits Whether this is an enforce (die)
2017 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
2018 if ( $enforceLimits ) {
2019 $this->dieWithError( $msg );
2021 $this->addWarning( $msg );
2026 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2027 * error handler and die with an error message including block info.
2030 * @param Block $block The block used to generate the ApiUsageException
2031 * @throws ApiUsageException always
2033 public function dieBlocked( Block
$block ) {
2034 // Die using the appropriate message depending on block type
2035 if ( $block->getType() == Block
::TYPE_AUTO
) {
2036 $this->dieWithError(
2037 'apierror-autoblocked',
2039 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2042 $this->dieWithError(
2045 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
2051 * Throw an ApiUsageException based on the Status object.
2054 * @since 1.29 Accepts a StatusValue
2055 * @param StatusValue $status
2056 * @throws ApiUsageException always
2058 public function dieStatus( StatusValue
$status ) {
2059 if ( $status->isGood() ) {
2060 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2063 // ApiUsageException needs a fatal status, but this method has
2064 // historically accepted any non-good status. Convert it if necessary.
2065 $status->setOK( false );
2066 if ( !$status->getErrorsByType( 'error' ) ) {
2067 $newStatus = Status
::newGood();
2068 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2069 call_user_func_array(
2070 [ $newStatus, 'fatal' ],
2071 array_merge( [ $err['message'] ], $err['params'] )
2074 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2075 $newStatus->fatal( 'unknownerror-nocode' );
2077 $status = $newStatus;
2080 throw new ApiUsageException( $this, $status );
2084 * Helper function for readonly errors
2086 * @throws ApiUsageException always
2088 public function dieReadOnly() {
2089 $this->dieWithError(
2090 'apierror-readonly',
2092 [ 'readonlyreason' => wfReadOnlyReason() ]
2097 * Helper function for permission-denied errors
2099 * @param string|string[] $rights
2100 * @param User|null $user
2101 * @throws ApiUsageException if the user doesn't have any of the rights.
2102 * The error message is based on $rights[0].
2104 public function checkUserRightsAny( $rights, $user = null ) {
2106 $user = $this->getUser();
2108 $rights = (array)$rights;
2109 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
2110 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2115 * Helper function for permission-denied errors
2117 * @param Title $title
2118 * @param string|string[] $actions
2119 * @param User|null $user
2120 * @throws ApiUsageException if the user doesn't have all of the rights.
2122 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
2124 $user = $this->getUser();
2128 foreach ( (array)$actions as $action ) {
2129 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2132 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2137 * Will only set a warning instead of failing if the global $wgDebugAPI
2138 * is set to true. Otherwise behaves exactly as self::dieWithError().
2141 * @param string|array|Message $msg
2142 * @param string|null $code
2143 * @param array|null $data
2144 * @param int|null $httpCode
2145 * @throws ApiUsageException
2147 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2148 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2149 $this->dieWithError( $msg, $code, $data, $httpCode );
2151 $this->addWarning( $msg, $code, $data );
2156 * Die with the 'badcontinue' error.
2158 * This call is common enough to make it into the base method.
2160 * @param bool $condition Will only die if this value is true
2161 * @throws ApiUsageException
2164 protected function dieContinueUsageIf( $condition ) {
2166 $this->dieWithError( 'apierror-badcontinue' );
2171 * Internal code errors should be reported with this method
2172 * @param string $method Method or function name
2173 * @param string $message Error message
2174 * @throws MWException always
2176 protected static function dieDebug( $method, $message ) {
2177 throw new MWException( "Internal error in $method: $message" );
2181 * Write logging information for API features to a debug log, for usage
2183 * @note Consider using $this->addDeprecation() instead to both warn and log.
2184 * @param string $feature Feature being used.
2186 public function logFeatureUsage( $feature ) {
2187 $request = $this->getRequest();
2188 $s = '"' . addslashes( $feature ) . '"' .
2189 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2190 ' "' . $request->getIP() . '"' .
2191 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2192 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2193 wfDebugLog( 'api-feature-usage', $s, 'private' );
2198 /************************************************************************//**
2199 * @name Help message generation
2204 * Return the summary message.
2206 * This is a one-line description of the module, suitable for display in a
2210 * @return string|array|Message
2212 protected function getSummaryMessage() {
2213 return "apihelp-{$this->getModulePath()}-summary";
2217 * Return the extended help text message.
2219 * This is additional text to display at the top of the help section, below
2223 * @return string|array|Message
2225 protected function getExtendedDescription() {
2227 "apihelp-{$this->getModulePath()}-extended-description",
2228 'api-help-no-extended-description',
2233 * Get final module summary
2235 * Ideally this will just be the getSummaryMessage(). However, for
2236 * backwards compatibility, if that message does not exist then the first
2237 * line of wikitext from the description message will be used instead.
2242 public function getFinalSummary() {
2243 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2244 $this->getModulePrefix(),
2245 $this->getModuleName(),
2246 $this->getModulePath(),
2248 if ( !$msg->exists() ) {
2249 wfDeprecated( 'API help "description" messages', '1.30' );
2250 $msg = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2251 $this->getModulePrefix(),
2252 $this->getModuleName(),
2253 $this->getModulePath(),
2255 $msg = self
::makeMessage( 'rawmessage', $this->getContext(), [
2256 preg_replace( '/\n.*/s', '', $msg->text() )
2263 * Get final module description, after hooks have had a chance to tweak it as
2266 * @since 1.25, returns Message[] rather than string[]
2269 public function getFinalDescription() {
2270 $desc = $this->getDescription();
2272 // Avoid PHP 7.1 warning of passing $this by reference
2274 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2275 $desc = self
::escapeWikiText( $desc );
2276 if ( is_array( $desc ) ) {
2277 $desc = implode( "\n", $desc );
2279 $desc = (string)$desc;
2282 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2283 $this->getModulePrefix(),
2284 $this->getModuleName(),
2285 $this->getModulePath(),
2287 $extendedDescription = self
::makeMessage(
2288 $this->getExtendedDescription(), $this->getContext(), [
2289 $this->getModulePrefix(),
2290 $this->getModuleName(),
2291 $this->getModulePath(),
2295 if ( $summary->exists() ) {
2296 $msgs = [ $summary, $extendedDescription ];
2298 wfDeprecated( 'API help "description" messages', '1.30' );
2299 $description = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2300 $this->getModulePrefix(),
2301 $this->getModuleName(),
2302 $this->getModulePath(),
2304 if ( !$description->exists() ) {
2305 $description = $this->msg( 'api-help-fallback-description', $desc );
2307 $msgs = [ $description ];
2310 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2316 * Get final list of parameters, after hooks have had a chance to
2317 * tweak it as needed.
2319 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2320 * @return array|bool False on no parameters
2321 * @since 1.21 $flags param added
2323 public function getFinalParams( $flags = 0 ) {
2324 $params = $this->getAllowedParams( $flags );
2329 if ( $this->needsToken() ) {
2330 $params['token'] = [
2331 self
::PARAM_TYPE
=> 'string',
2332 self
::PARAM_REQUIRED
=> true,
2333 self
::PARAM_SENSITIVE
=> true,
2334 self
::PARAM_HELP_MSG
=> [
2335 'api-help-param-token',
2336 $this->needsToken(),
2338 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2341 // Avoid PHP 7.1 warning of passing $this by reference
2343 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2349 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2352 * @since 1.25, returns array of Message[] rather than array of string[]
2353 * @return array Keys are parameter names, values are arrays of Message objects
2355 public function getFinalParamDescription() {
2356 $prefix = $this->getModulePrefix();
2357 $name = $this->getModuleName();
2358 $path = $this->getModulePath();
2360 $desc = $this->getParamDescription();
2362 // Avoid PHP 7.1 warning of passing $this by reference
2364 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2369 $desc = self
::escapeWikiText( $desc );
2371 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2373 foreach ( $params as $param => $settings ) {
2374 if ( !is_array( $settings ) ) {
2378 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2379 if ( is_array( $d ) ) {
2380 // Special handling for prop parameters
2381 $d = array_map( function ( $line ) {
2382 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2383 $line = "\n;{$m[1]}:{$m[2]}";
2387 $d = implode( ' ', $d );
2390 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2391 $msg = $settings[self
::PARAM_HELP_MSG
];
2393 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2394 if ( !$msg->exists() ) {
2395 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2398 $msg = self
::makeMessage( $msg, $this->getContext(),
2399 [ $prefix, $param, $name, $path ] );
2401 self
::dieDebug( __METHOD__
,
2402 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2404 $msgs[$param] = [ $msg ];
2406 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2407 $settings[self
::PARAM_TYPE
] === 'submodule'
2409 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2410 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2412 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2414 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2415 $map[$submoduleName] = $prefix . $submoduleName;
2420 $deprecatedSubmodules = [];
2421 foreach ( $map as $v => $m ) {
2422 $arr = &$submodules;
2423 $isDeprecated = false;
2426 $submod = $this->getModuleFromPath( $m );
2428 $summary = $submod->getFinalSummary();
2429 $isDeprecated = $submod->isDeprecated();
2430 if ( $isDeprecated ) {
2431 $arr = &$deprecatedSubmodules;
2434 } catch ( ApiUsageException
$ex ) {
2438 $key = $summary->getKey();
2439 $params = $summary->getParams();
2441 $key = 'api-help-undocumented-module';
2444 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2445 $arr[] = $m->setContext( $this->getContext() );
2447 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2448 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2449 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2450 self
::dieDebug( __METHOD__
,
2451 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2453 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2454 self
::dieDebug( __METHOD__
,
2455 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2456 'ApiBase::PARAM_TYPE is an array' );
2459 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2460 $deprecatedValues = isset( $settings[self
::PARAM_DEPRECATED_VALUES
] )
2461 ?
$settings[self
::PARAM_DEPRECATED_VALUES
]
2464 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2465 if ( isset( $valueMsgs[$value] ) ) {
2466 $msg = $valueMsgs[$value];
2468 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2470 $m = self
::makeMessage( $msg, $this->getContext(),
2471 [ $prefix, $param, $name, $path, $value ] );
2473 $m = new ApiHelpParamValueMessage(
2475 [ $m->getKey(), 'api-help-param-no-description' ],
2477 isset( $deprecatedValues[$value] )
2479 $msgs[$param][] = $m->setContext( $this->getContext() );
2481 self
::dieDebug( __METHOD__
,
2482 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2487 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2488 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2489 self
::dieDebug( __METHOD__
,
2490 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2492 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2493 $m = self
::makeMessage( $m, $this->getContext(),
2494 [ $prefix, $param, $name, $path ] );
2496 $msgs[$param][] = $m;
2498 self
::dieDebug( __METHOD__
,
2499 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2505 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2511 * Generates the list of flags for the help screen and for action=paraminfo
2513 * Corresponding messages: api-help-flag-deprecated,
2514 * api-help-flag-internal, api-help-flag-readrights,
2515 * api-help-flag-writerights, api-help-flag-mustbeposted
2519 protected function getHelpFlags() {
2522 if ( $this->isDeprecated() ) {
2523 $flags[] = 'deprecated';
2525 if ( $this->isInternal() ) {
2526 $flags[] = 'internal';
2528 if ( $this->isReadMode() ) {
2529 $flags[] = 'readrights';
2531 if ( $this->isWriteMode() ) {
2532 $flags[] = 'writerights';
2534 if ( $this->mustBePosted() ) {
2535 $flags[] = 'mustbeposted';
2542 * Returns information about the source of this module, if known
2544 * Returned array is an array with the following keys:
2545 * - path: Install path
2546 * - name: Extension name, or "MediaWiki" for core
2547 * - namemsg: (optional) i18n message key for a display name
2548 * - license-name: (optional) Name of license
2550 * @return array|null
2552 protected function getModuleSourceInfo() {
2555 if ( $this->mModuleSource
!== false ) {
2556 return $this->mModuleSource
;
2559 // First, try to find where the module comes from...
2560 $rClass = new ReflectionClass( $this );
2561 $path = $rClass->getFileName();
2564 $this->mModuleSource
= null;
2567 $path = realpath( $path ) ?
: $path;
2569 // Build map of extension directories to extension info
2570 if ( self
::$extensionInfo === null ) {
2571 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2572 self
::$extensionInfo = [
2573 realpath( __DIR__
) ?
: __DIR__
=> [
2575 'name' => 'MediaWiki',
2576 'license-name' => 'GPL-2.0-or-later',
2578 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2579 realpath( $extDir ) ?
: $extDir => null,
2585 'license-name' => null,
2587 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2588 foreach ( $group as $ext ) {
2589 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2590 // This shouldn't happen, but does anyway.
2594 $extpath = $ext['path'];
2595 if ( !is_dir( $extpath ) ) {
2596 $extpath = dirname( $extpath );
2598 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2599 array_intersect_key( $ext, $keep );
2602 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2603 $extpath = $ext['path'];
2604 if ( !is_dir( $extpath ) ) {
2605 $extpath = dirname( $extpath );
2607 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2608 array_intersect_key( $ext, $keep );
2612 // Now traverse parent directories until we find a match or run out of
2615 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2617 $this->mModuleSource
= self
::$extensionInfo[$path];
2618 return $this->mModuleSource
;
2622 $path = dirname( $path );
2623 } while ( $path !== $oldpath );
2625 // No idea what extension this might be.
2626 $this->mModuleSource
= null;
2631 * Called from ApiHelp before the pieces are joined together and returned.
2633 * This exists mainly for ApiMain to add the Permissions and Credits
2634 * sections. Other modules probably don't need it.
2636 * @param string[] &$help Array of help data
2637 * @param array $options Options passed to ApiHelp::getHelp
2638 * @param array &$tocData If a TOC is being generated, this array has keys
2639 * as anchors in the page and values as for Linker::generateTOC().
2641 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2646 /************************************************************************//**
2652 * Returns the description string for this module
2654 * Ignored if an i18n message exists for
2655 * "apihelp-{$this->getModulePath()}-description".
2657 * @deprecated since 1.25
2658 * @return Message|string|array|false
2660 protected function getDescription() {
2665 * Returns an array of parameter descriptions.
2667 * For each parameter, ignored if an i18n message exists for the parameter.
2668 * By default that message is
2669 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2670 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2671 * self::getFinalParams().
2673 * @deprecated since 1.25
2674 * @return array|bool False on no parameter descriptions
2676 protected function getParamDescription() {
2681 * Returns usage examples for this module.
2683 * Return value as an array is either:
2684 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2686 * - sequential numeric keys with even-numbered keys being display-text
2687 * and odd-numbered keys being partial urls
2688 * - partial URLs as keys with display-text (string or array-to-be-joined)
2690 * Return value as a string is the same as an array with a numeric key and
2691 * that value, and boolean false means "no examples".
2693 * @deprecated since 1.25, use getExamplesMessages() instead
2694 * @return bool|string|array
2696 protected function getExamples() {
2701 * @deprecated since 1.25
2703 public function profileIn() {
2704 // No wfDeprecated() yet because extensions call this and might need to
2705 // keep doing so for BC.
2709 * @deprecated since 1.25
2711 public function profileOut() {
2712 // No wfDeprecated() yet because extensions call this and might need to
2713 // keep doing so for BC.
2717 * @deprecated since 1.25
2719 public function safeProfileOut() {
2720 wfDeprecated( __METHOD__
, '1.25' );
2724 * @deprecated since 1.25
2726 public function profileDBIn() {
2727 wfDeprecated( __METHOD__
, '1.25' );
2731 * @deprecated since 1.25
2733 public function profileDBOut() {
2734 wfDeprecated( __METHOD__
, '1.25' );
2738 * Call wfTransactionalTimeLimit() if this request was POSTed
2741 protected function useTransactionalTimeLimit() {
2742 if ( $this->getRequest()->wasPosted() ) {
2743 wfTransactionalTimeLimit();
2748 * @deprecated since 1.29, use ApiBase::addWarning() instead
2749 * @param string $warning Warning message
2751 public function setWarning( $warning ) {
2752 wfDeprecated( __METHOD__
, '1.29' );
2753 $msg = new ApiRawMessage( $warning, 'warning' );
2754 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2758 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2759 * error handler and die with an error message.
2761 * @deprecated since 1.29, use self::dieWithError() instead
2762 * @param string $description One-line human-readable description of the
2763 * error condition, e.g., "The API requires a valid action parameter"
2764 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2765 * automated identification of the error, e.g., 'unknown_action'
2766 * @param int $httpRespCode HTTP response code
2767 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2768 * @throws ApiUsageException always
2770 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2771 wfDeprecated( __METHOD__
, '1.29' );
2772 $this->dieWithError(
2773 new RawMessage( '$1', [ $description ] ),
2781 * Get error (as code, string) from a Status object.
2784 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2785 * @param Status $status
2786 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2787 * @return array Array of code and error string
2788 * @throws MWException
2790 public function getErrorFromStatus( $status, &$extraData = null ) {
2791 wfDeprecated( __METHOD__
, '1.29' );
2792 if ( $status->isGood() ) {
2793 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2796 $errors = $status->getErrorsByType( 'error' );
2798 // No errors? Assume the warnings should be treated as errors
2799 $errors = $status->getErrorsByType( 'warning' );
2802 // Still no errors? Punt
2803 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2806 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2807 $msg = $errors[0]['message'];
2809 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2811 if ( !$msg instanceof IApiMessage
) {
2812 $key = $msg->getKey();
2813 $params = $msg->getParams();
2814 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2815 $msg = ApiMessage
::create( $params );
2820 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2825 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2826 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2827 * API codes and message texts, and a few interfaces required poking
2828 * something in here. Now we're repurposing it to map those same strings
2829 * to i18n messages, and declaring that any interface that requires poking
2830 * at this is broken and needs replacing ASAP.
2832 private static $messageMap = [
2833 'unknownerror' => 'apierror-unknownerror',
2834 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2835 'ns-specialprotected' => 'ns-specialprotected',
2836 'protectedinterface' => 'protectedinterface',
2837 'namespaceprotected' => 'namespaceprotected',
2838 'customcssprotected' => 'customcssprotected',
2839 'customjsprotected' => 'customjsprotected',
2840 'cascadeprotected' => 'cascadeprotected',
2841 'protectedpagetext' => 'protectedpagetext',
2842 'protect-cantedit' => 'protect-cantedit',
2843 'deleteprotected' => 'deleteprotected',
2844 'badaccess-group0' => 'badaccess-group0',
2845 'badaccess-groups' => 'badaccess-groups',
2846 'titleprotected' => 'titleprotected',
2847 'nocreate-loggedin' => 'nocreate-loggedin',
2848 'nocreatetext' => 'nocreatetext',
2849 'movenologintext' => 'movenologintext',
2850 'movenotallowed' => 'movenotallowed',
2851 'confirmedittext' => 'confirmedittext',
2852 'blockedtext' => 'apierror-blocked',
2853 'autoblockedtext' => 'apierror-autoblocked',
2854 'systemblockedtext' => 'apierror-systemblocked',
2855 'actionthrottledtext' => 'apierror-ratelimited',
2856 'alreadyrolled' => 'alreadyrolled',
2857 'cantrollback' => 'cantrollback',
2858 'readonlytext' => 'readonlytext',
2859 'sessionfailure' => 'sessionfailure',
2860 'cannotdelete' => 'cannotdelete',
2861 'notanarticle' => 'apierror-missingtitle',
2862 'selfmove' => 'selfmove',
2863 'immobile_namespace' => 'apierror-immobilenamespace',
2864 'articleexists' => 'articleexists',
2865 'hookaborted' => 'hookaborted',
2866 'cantmove-titleprotected' => 'cantmove-titleprotected',
2867 'imagenocrossnamespace' => 'imagenocrossnamespace',
2868 'imagetypemismatch' => 'imagetypemismatch',
2869 'ip_range_invalid' => 'ip_range_invalid',
2870 'range_block_disabled' => 'range_block_disabled',
2871 'nosuchusershort' => 'nosuchusershort',
2872 'badipaddress' => 'badipaddress',
2873 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2874 'ipb_already_blocked' => 'ipb_already_blocked',
2875 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2876 'ipb_cant_unblock' => 'ipb_cant_unblock',
2877 'mailnologin' => 'apierror-cantsend',
2878 'ipbblocked' => 'ipbblocked',
2879 'ipbnounblockself' => 'ipbnounblockself',
2880 'usermaildisabled' => 'usermaildisabled',
2881 'blockedemailuser' => 'apierror-blockedfrommail',
2882 'notarget' => 'apierror-notarget',
2883 'noemail' => 'noemail',
2884 'rcpatroldisabled' => 'rcpatroldisabled',
2885 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2886 'delete-toobig' => 'delete-toobig',
2887 'movenotallowedfile' => 'movenotallowedfile',
2888 'userrights-no-interwiki' => 'userrights-no-interwiki',
2889 'userrights-nodatabase' => 'userrights-nodatabase',
2890 'nouserspecified' => 'nouserspecified',
2891 'noname' => 'noname',
2892 'summaryrequired' => 'apierror-summaryrequired',
2893 'import-rootpage-invalid' => 'import-rootpage-invalid',
2894 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2895 'readrequired' => 'apierror-readapidenied',
2896 'writedisabled' => 'apierror-noapiwrite',
2897 'writerequired' => 'apierror-writeapidenied',
2898 'missingparam' => 'apierror-missingparam',
2899 'invalidtitle' => 'apierror-invalidtitle',
2900 'nosuchpageid' => 'apierror-nosuchpageid',
2901 'nosuchrevid' => 'apierror-nosuchrevid',
2902 'nosuchuser' => 'nosuchusershort',
2903 'invaliduser' => 'apierror-invaliduser',
2904 'invalidexpiry' => 'apierror-invalidexpiry',
2905 'pastexpiry' => 'apierror-pastexpiry',
2906 'create-titleexists' => 'apierror-create-titleexists',
2907 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2908 'cantblock' => 'apierror-cantblock',
2909 'canthide' => 'apierror-canthide',
2910 'cantblock-email' => 'apierror-cantblock-email',
2911 'cantunblock' => 'apierror-permissiondenied-generic',
2912 'cannotundelete' => 'cannotundelete',
2913 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2914 'createonly-exists' => 'apierror-articleexists',
2915 'nocreate-missing' => 'apierror-missingtitle',
2916 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2917 'nosuchrcid' => 'apierror-nosuchrcid',
2918 'nosuchlogid' => 'apierror-nosuchlogid',
2919 'protect-invalidaction' => 'apierror-protect-invalidaction',
2920 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2921 'toofewexpiries' => 'apierror-toofewexpiries',
2922 'cantimport' => 'apierror-cantimport',
2923 'cantimport-upload' => 'apierror-cantimport-upload',
2924 'importnofile' => 'importnofile',
2925 'importuploaderrorsize' => 'importuploaderrorsize',
2926 'importuploaderrorpartial' => 'importuploaderrorpartial',
2927 'importuploaderrortemp' => 'importuploaderrortemp',
2928 'importcantopen' => 'importcantopen',
2929 'import-noarticle' => 'import-noarticle',
2930 'importbadinterwiki' => 'importbadinterwiki',
2931 'import-unknownerror' => 'apierror-import-unknownerror',
2932 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2933 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2934 'mustbeposted' => 'apierror-mustbeposted',
2935 'show' => 'apierror-show',
2936 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2937 'invalidoldimage' => 'apierror-invalidoldimage',
2938 'nodeleteablefile' => 'apierror-nodeleteablefile',
2939 'fileexists-forbidden' => 'fileexists-forbidden',
2940 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2941 'filerevert-badversion' => 'filerevert-badversion',
2942 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2943 'noimageredirect-logged' => 'apierror-noimageredirect',
2944 'spamdetected' => 'apierror-spamdetected',
2945 'contenttoobig' => 'apierror-contenttoobig',
2946 'noedit-anon' => 'apierror-noedit-anon',
2947 'noedit' => 'apierror-noedit',
2948 'wasdeleted' => 'apierror-pagedeleted',
2949 'blankpage' => 'apierror-emptypage',
2950 'editconflict' => 'editconflict',
2951 'hashcheckfailed' => 'apierror-badmd5',
2952 'missingtext' => 'apierror-notext',
2953 'emptynewsection' => 'apierror-emptynewsection',
2954 'revwrongpage' => 'apierror-revwrongpage',
2955 'undo-failure' => 'undo-failure',
2956 'content-not-allowed-here' => 'content-not-allowed-here',
2957 'edit-hook-aborted' => 'edit-hook-aborted',
2958 'edit-gone-missing' => 'edit-gone-missing',
2959 'edit-conflict' => 'edit-conflict',
2960 'edit-already-exists' => 'edit-already-exists',
2961 'invalid-file-key' => 'apierror-invalid-file-key',
2962 'nouploadmodule' => 'apierror-nouploadmodule',
2963 'uploaddisabled' => 'uploaddisabled',
2964 'copyuploaddisabled' => 'copyuploaddisabled',
2965 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2966 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2967 'filename-tooshort' => 'filename-tooshort',
2968 'filename-toolong' => 'filename-toolong',
2969 'illegal-filename' => 'illegal-filename',
2970 'filetype-missing' => 'filetype-missing',
2971 'mustbeloggedin' => 'apierror-mustbeloggedin',
2975 * @deprecated do not use
2976 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2977 * @return ApiMessage
2979 private function parseMsgInternal( $error ) {
2980 $msg = Message
::newFromSpecifier( $error );
2981 if ( !$msg instanceof IApiMessage
) {
2982 $key = $msg->getKey();
2983 if ( isset( self
::$messageMap[$key] ) ) {
2984 $params = $msg->getParams();
2985 array_unshift( $params, self
::$messageMap[$key] );
2987 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2989 $msg = ApiMessage
::create( $params );
2995 * Return the error message related to a certain array
2996 * @deprecated since 1.29
2997 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2998 * @return array [ 'code' => code, 'info' => info ]
3000 public function parseMsg( $error ) {
3001 wfDeprecated( __METHOD__
, '1.29' );
3002 // Check whether someone passed the whole array, instead of one element as
3003 // documented. This breaks if it's actually an array of fallback keys, but
3004 // that's long-standing misbehavior introduced in r87627 to incorrectly
3006 if ( is_array( $error ) ) {
3007 $first = reset( $error );
3008 if ( is_array( $first ) ) {
3009 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
3014 $msg = $this->parseMsgInternal( $error );
3016 'code' => $msg->getApiCode(),
3017 'info' => ApiErrorFormatter
::stripMarkup(
3018 $msg->inLanguage( 'en' )->useDatabase( false )->text()
3020 'data' => $msg->getApiData()
3025 * Output the error message related to a certain array
3026 * @deprecated since 1.29, use ApiBase::dieWithError() instead
3027 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
3028 * @throws ApiUsageException always
3030 public function dieUsageMsg( $error ) {
3031 wfDeprecated( __METHOD__
, '1.29' );
3032 $this->dieWithError( $this->parseMsgInternal( $error ) );
3036 * Will only set a warning instead of failing if the global $wgDebugAPI
3037 * is set to true. Otherwise behaves exactly as dieUsageMsg().
3038 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
3039 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
3040 * @throws ApiUsageException
3043 public function dieUsageMsgOrDebug( $error ) {
3044 wfDeprecated( __METHOD__
, '1.29' );
3045 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
3049 * Return the description message.
3051 * This is additional text to display on the help page after the summary.
3053 * @deprecated since 1.30
3054 * @return string|array|Message
3056 protected function getDescriptionMessage() {
3058 "apihelp-{$this->getModulePath()}-description",
3059 "apihelp-{$this->getModulePath()}-summary",
3064 * Truncate an array to a certain length.
3065 * @deprecated since 1.32, no replacement
3066 * @param array &$arr Array to truncate
3067 * @param int $limit Maximum length
3068 * @return bool True if the array was truncated, false otherwise
3070 public static function truncateArray( &$arr, $limit ) {
3071 wfDeprecated( __METHOD__
, '1.32' );
3073 while ( count( $arr ) > $limit ) {
3085 * For really cool vim folding this needs to be at the end:
3086 * vim: foldmarker=@{,@} foldmethod=marker